pax_global_header00006660000000000000000000000064152057545360014526gustar00rootroot0000000000000052 comment=87a9eeace3d8f9a0fcaf11dbb2d18a6921054914 kylin-cloud-ai-engine-plugin-1.1.0.1/000077500000000000000000000000001520575453600172445ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/.clang-format000066400000000000000000000067531520575453600216320ustar00rootroot00000000000000--- Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -4 ConstructorInitializerIndentWidth: 4 AlignEscapedNewlinesLeft: false AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AlwaysBreakTemplateDeclarations: true AlwaysBreakBeforeMultilineStrings: false BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BinPackParameters: true ColumnLimit: 80 ConstructorInitializerAllOnOneLineOrOnePerLine: false DerivePointerAlignment: false ExperimentalAutoDetectBinPacking: false IndentCaseLabels: false IndentWrappedFunctionNames: false IndentFunctionDeclarationAfterType: false MaxEmptyLinesToKeep: 1 KeepEmptyLinesAtTheStartOfBlocks: true NamespaceIndentation: None ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakString: 1000 PenaltyBreakFirstLessLess: 120 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right SpacesBeforeTrailingComments: 1 Cpp11BracedListStyle: true Standard: Cpp11 IndentWidth: 4 TabWidth: 4 UseTab: Never BreakBeforeBraces: Attach SpacesInParentheses: false SpacesInAngles: false SpaceInEmptyParentheses: false SpacesInCStyleCastParentheses: false SpacesInContainerLiterals: true SpaceBeforeAssignmentOperators: true ContinuationIndentWidth: 4 CommentPragmas: '^ IWYU pragma:' ForEachMacros: [ Q_FOREACH, BOOST_FOREACH ] SpaceBeforeParens: ControlStatements DisableFormat: false SortIncludes: true IncludeCategories: # C system headers. - Regex: '^[<"](aio|arpa/inet|assert|complex|cpio|ctype|curses|dirent|dlfcn|errno|fcntl|fenv|float|fmtmsg|fnmatch|ftw|glob|grp|iconv|inttypes|iso646|langinfo|libgen|limits|locale|math|monetary|mqueue|ndbm|netdb|net/if|netinet/in|netinet/tcp|nl_types|poll|pthread|pwd|regex|sched|search|semaphore|setjmp|signal|spawn|stdalign|stdarg|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|strings|stropts|sys/ipc|syslog|sys/mman|sys/msg|sys/resource|sys/select|sys/sem|sys/shm|sys/socket|sys/stat|sys/statvfs|sys/time|sys/times|sys/types|sys/uio|sys/un|sys/utsname|sys/wait|tar|term|termios|tgmath|threads|time|trace|uchar|ulimit|uncntrl|unistd|utime|utmpx|wchar|wctype|wordexp)\.h[">]$' Priority: 20 # C++ system headers (as of C++17). - Regex: '^[<"](algorithm|any|array|atomic|bitset|cassert|ccomplex|cctype|cerrno|cfenv|cfloat|charconv|chrono|cinttypes|ciso646|climits|clocale|cmath|codecvt|complex|condition_variable|csetjmp|csignal|cstdalign|cstdarg|cstdbool|cstddef|cstdint|cstdio|cstdlib|cstring|ctgmath|ctime|cuchar|cwchar|cwctype|deque|exception|execution|filesystem|forward_list|fstream|functional|future|initializer_list|iomanip|ios|iosfwd|iostream|istream|iterator|limits|list|locale|map|memory|memory_resource|mutex|new|numeric|optional|ostream|queue|random|ratio|regex|scoped_allocator|set|shared_mutex|sstream|stack|stdexcept|streambuf|string|string_view|strstream|system_error|thread|tuple|type_traits|typeindex|typeinfo|unordered_map|unordered_set|utility|valarray|variant|vector)[">]$' Priority: 30 # Other libraries' h files (with angles). - Regex: '^<' Priority: 40 # Your project's h files. - Regex: '^[<"]fcitx' Priority: 45 # Other libraries' h files (with quotes). - Regex: '^"' Priority: 50 ... kylin-cloud-ai-engine-plugin-1.1.0.1/.gitignore000066400000000000000000000015101520575453600212310ustar00rootroot00000000000000# This file is used to ignore files which are generated # ---------------------------------------------------------------------------- *~ *.autosave *.a *.core *.moc *.o *.obj *.orig *.rej *.so *.so.* *_pch.h.cpp *_resource.rc *.qm .#* *.*# core !core/ tags .DS_Store .directory *.debug Makefile* *.prl *.app moc_*.cpp ui_*.h qrc_*.cpp Thumbs.db *.res *.rc /.qmake.cache /.qmake.stash # qtcreator generated files *.pro.user* CMakeLists.txt.user* # xemacs temporary files *.flc # Vim temporary files .*.swp # Visual Studio generated files *.ib_pdb_index *.idb *.ilk *.pdb *.sln *.suo *.vcproj *vcproj.*.*.user *.ncb *.sdf *.opensdf *.vcxproj *vcxproj.* # MinGW generated files *.Debug *.Release # Python byte code *.pyc # Binaries # -------- *.dll *.exe build .vscode .cache # third-party third-party/llama.cpp/common/build-info.cppkylin-cloud-ai-engine-plugin-1.1.0.1/CMakeLists.txt000066400000000000000000000147701520575453600220150ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kylin-cloud-ai-engine-plugin LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 17) find_package(KylinAiEngine CONFIG REQUIRED) find_package(PkgConfig REQUIRED) find_package(CURL REQUIRED) pkg_check_modules(FREEIMAGE QUIET freeimage) if(FREEIMAGE_FOUND AND FREEIMAGE_LIBRARIES) set(XUNFEI_FREEIMAGE_LIB ${FREEIMAGE_LIBRARIES}) set(XUNFEI_FREEIMAGE_INCLUDE_DIRS ${FREEIMAGE_INCLUDE_DIRS}) else() find_library(XUNFEI_FREEIMAGE_LIB NAMES freeimage FreeImage libfreeimage-3 libfreeimage REQUIRED) find_path(XUNFEI_FREEIMAGE_INCLUDE_DIR NAMES FreeImage.h REQUIRED) set(XUNFEI_FREEIMAGE_INCLUDE_DIRS ${XUNFEI_FREEIMAGE_INCLUDE_DIR}) endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/cpr/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/base) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/cpputil) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/evpp) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/client) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/ssl) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/util) add_subdirectory(third-party/cpr) kylin_ai_add_engine_plugin(xunfei-engine-plugin AI_ENGINE ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/xunfeiengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/nlp/xunfeinlpengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/nlp/xunfeinlpengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/nlp/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/nlp/token.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/nlp/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/logger.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/xunfeivisionengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/xunfeivisionengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/imageloader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/token.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/vision/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/speech/xunfeispeechengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/speech/xunfeispeechengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/speech/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/xunfei/speech/util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/base/hbase.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/base/hlog.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/base/hsocket.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/base/htime.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/wsdef.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/websocket_parser.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/ssl/openssl.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/ssl/hssl.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/util/base64.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/util/sha1.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event/hloop.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event/hevent.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event/epoll.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event/nio.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/event/unpack.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/cpputil/hstring.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/cpputil/hurl.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/cpputil/ThreadLocalStorage.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/http_parser.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/httpdef.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/multipart_parser.c ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/http_content.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/client/WebSocketClient.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/WebSocketChannel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/WebSocketParser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/HttpMessage.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/HttpParser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/third-party/libhv-v1.3.3/http/Http1Parser.cpp ) target_link_libraries(xunfei-engine-plugin cpr ${CURL_LIBRARIES}) target_link_libraries(xunfei-engine-plugin ${XUNFEI_FREEIMAGE_LIB}) target_include_directories(xunfei-engine-plugin PRIVATE ${CURL_INCLUDE_DIRS} ${XUNFEI_FREEIMAGE_INCLUDE_DIRS}) target_compile_definitions(xunfei-engine-plugin PRIVATE WITH_OPENSSL) kylin_ai_add_engine_plugin(deepseek-engine-plugin AI_ENGINE ${CMAKE_CURRENT_SOURCE_DIR}/deepseek/deepseekengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/deepseek/deepseeknlpengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/deepseek/deepseeknlpengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/deepseek/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/deepseek/util.cpp ) target_link_libraries(deepseek-engine-plugin cpr ${CURL_LIBRARIES}) target_include_directories(deepseek-engine-plugin PRIVATE ${CURL_INCLUDE_DIRS}) kylin_ai_add_engine_plugin(qwen-engine-plugin AI_ENGINE ${CMAKE_CURRENT_SOURCE_DIR}/qwen/qwenengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/qwen/qwennlpengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/qwen/qwennlpengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/qwen/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/qwen/util.cpp ) target_link_libraries(qwen-engine-plugin cpr ${CURL_LIBRARIES}) target_include_directories(qwen-engine-plugin PRIVATE ${CURL_INCLUDE_DIRS}) kylin_ai_add_engine_plugin(custom-engine-plugin AI_ENGINE ${CMAKE_CURRENT_SOURCE_DIR}/custom/customengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom/customnlpengine_p.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom/customnlpengine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom/servererror.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom/util.cpp ) target_link_libraries(custom-engine-plugin cpr ${CURL_LIBRARIES}) target_include_directories(custom-engine-plugin PRIVATE ${CURL_INCLUDE_DIRS}) option(ENABLE_TEST "Build Test" OFF) if (ENABLE_TEST) enable_testing() add_subdirectory(test) endif () kylin-cloud-ai-engine-plugin-1.1.0.1/LICENSE000066400000000000000000001057551520575453600202660ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . kylin-cloud-ai-engine-plugin-1.1.0.1/custom/000077500000000000000000000000001520575453600205565ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customengine.cpp000066400000000000000000000020061520575453600237600ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "customengine.h" #include "custom/customnlpengine.h" std::string CustomAiEngine::name() const { return "custom"; } std::unique_ptr CustomAiEngine::createTextGenerationEngine() { return std::make_unique(); } AI_ENGINE_PLUGIN_FACTORY(CustomAiEngine); kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customengine.h000066400000000000000000000017761520575453600234420ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include class CustomAiEngine : public ai_engine::AbstractAiEnginePluginFactory { public: ~CustomAiEngine() = default; std::string name() const override; std::unique_ptr createTextGenerationEngine() override; }; kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customnlpengine.cpp000066400000000000000000000045451520575453600245040ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "customnlpengine.h" #include "custom/customnlpengine_p.h" CustomNlpEngine::CustomNlpEngine() : d(new CustomNlpEnginePrivate()) {} CustomNlpEngine::~CustomNlpEngine() { delete d; } std::string CustomNlpEngine::engineName() const { return d->engineName(); } std::string CustomNlpEngine::currentModel() const { return d->currentModel(); } std::string CustomNlpEngine::currentModelName() const { return d->currentModelName(); } bool CustomNlpEngine::isCloud() const { return d->isCloud(); } bool CustomNlpEngine::isBuiltInEngine() const { return d->isBuiltInEngine(); } bool CustomNlpEngine::isCustomModelEngine() const { return d->isCustomModelEngine(); } std::string CustomNlpEngine::modelInfo() const { return d->modelInfo(); } void CustomNlpEngine::setConfig(const std::string &config) { d->setConfig(config); } bool CustomNlpEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } void CustomNlpEngine::setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { d->setTextGenerationResultCallback(callback); } ai_engine::result::AiEngineBaseResult CustomNlpEngine::init() { return d->init(); } ai_engine::result::AiEngineBaseResult CustomNlpEngine::generateContent( const std::string &input) { return d->generateContent(input); }; ai_engine::result::AiEngineBaseResult CustomNlpEngine::chat( const std::string &message) { return d->chat(message); } void CustomNlpEngine::stopChat() { d->stopChat(); } void CustomNlpEngine::stopGenerateContent() { d->stopGenerateContent(); } ai_engine::result::AiEngineBaseResult CustomNlpEngine::destroy() { return d->destroy(); } kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customnlpengine.h000066400000000000000000000037141520575453600241460ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef CUSTOMNLPENGINE_H #define CUSTOMNLPENGINE_H #include class CustomNlpEnginePrivate; class CustomNlpEngine : public ai_engine::gen_ai::nlp::AbstractTextGenerationEngine { public: CustomNlpEngine(); ~CustomNlpEngine(); std::string engineName() const override; bool isCloud() const override; bool isBuiltInEngine() const override; bool isCustomModelEngine() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string currentModel() const override; std::string currentModelName() const override; std::string modelInfo() const override; void setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) override; ai_engine::result::AiEngineBaseResult generateContent( const std::string &input) override; ai_engine::result::AiEngineBaseResult chat( const std::string &message) override; void stopGenerateContent() override; void stopChat() override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; private: CustomNlpEnginePrivate *d; }; #endif // CUSTOMNLPENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customnlpengine_p.cpp000066400000000000000000000453121520575453600250200ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "customnlpengine_p.h" #include #include "servererror.h" #include "util.h" namespace { std::vector splitDataString(const std::string &dataStr, const std::string &endStr) { std::vector datas; int oldIndex = 0; int newIndex = 0; while ((newIndex = dataStr.find_first_of(endStr, newIndex)) != std::string::npos) { datas.push_back(dataStr.substr(oldIndex, newIndex - oldIndex)); newIndex += endStr.length(); oldIndex = newIndex; } return datas; } } // namespace bool writeChatData(std::string data, intptr_t userData) { CustomNlpEnginePrivate *engine = (CustomNlpEnginePrivate *)userData; ai_engine::gen_ai::nlp::TextGenerationResultCallback callback = engine->textGenerationResultCallback_; if (engine->isStopped_ || !engine->isChatRunning()) { return false; } Json::Value resultJson = custom_nlp_util::formatJsonFromString(data); if (resultJson.isObject() && !resultJson.isNull() && resultJson.isMember("error")) { fprintf(stderr, "custom chat failed: %s\n", data.c_str()); engine->currentErrorInfo_ = data; return false; } if (data == ": keep-alive\n\n") { return true; } std::string resultString = engine->tempStreamChatData_.data() + data; if (resultString.length() <= 5) { engine->tempStreamChatData_ += data; return true; } if (!engine->isValidResponse(resultString)) { engine->currentErrorInfo_ = "Unrecognized response format, parsing failed, response is \n" + resultString; return false; } if (data.compare(0, 7, "data: {") == 0) { engine->endStr_ = "\n\n"; } if (resultString.substr(resultString.length() - engine->endStr_.length()) != engine->endStr_) { engine->tempStreamChatData_ += data; return true; } engine->tempStreamChatData_.clear(); std::vector dataStrings = splitDataString(resultString, engine->endStr_); for (std::string data : dataStrings) { if (engine->endStr_ == "\n\n") { data = data.substr(6, data.length() - 1); } if (data == "[DONE]") { break; } Json::Value callbackObj = engine->formatResultJsonFromInputString(data); if (callbackObj.isNull()) { continue; } engine->streamChatData_.push_back(callbackObj["result"]); ai_engine::gen_ai::nlp::TextGenerationResult result{ true, ai_engine::EngineError(), engine->currentModelName_, callbackObj.toStyledString()}; callback(result); } return true; } CustomNlpEnginePrivate::CustomNlpEnginePrivate() {} CustomNlpEnginePrivate::~CustomNlpEnginePrivate() { streamChatData_.clear(); } std::string CustomNlpEnginePrivate::engineName() const { return "custom"; } std::string CustomNlpEnginePrivate::modelInfo() const { const char *info = R"( { "vendor": "自定义模型", "models": [ { } ] } )"; return info; } void CustomNlpEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = custom_nlp_util::formatJsonFromString(config); if (configJson.isNull() || !configJson.isMember("apiKey") || !configJson["apiKey"].isString() || !configJson.isMember("apiUrl") || !configJson["apiUrl"].isString() || !configJson.isMember("modelName") || !configJson["modelName"].isString() || !configJson.isMember("modelVersion") || !configJson["modelVersion"].isString()) { std::fprintf(stderr, "Invalid config for custom nlp engine: %s\n", config.c_str()); return; } apiKey_ = configJson["apiKey"].asString(); buildChatAndContentGenerationUrl(configJson["apiUrl"].asString()); currentModel_ = configJson["modelVersion"].asString(); currentModelName_ = configJson["modelName"].asString(); } void CustomNlpEnginePrivate::buildChatAndContentGenerationUrl( const std::string &apiUrl) { const std::string chatStr = "chat/completions"; const std::string generateContentStr = "completions"; generateContentUrl_ = apiUrl; chatUrl_ = apiUrl; if (apiUrl.length() >= generateContentStr.length() && apiUrl.substr(apiUrl.length() - generateContentStr.length()) != generateContentStr) { if (apiUrl.back() == '/') { generateContentUrl_ = apiUrl + generateContentStr; } else { generateContentUrl_ = apiUrl + "/" + generateContentStr; } } if (apiUrl.length() >= chatStr.length() && apiUrl.substr(apiUrl.length() - chatStr.length()) != chatStr) { if (apiUrl.back() == '/') { chatUrl_ = apiUrl + chatStr; } else { chatUrl_ = apiUrl + "/" + chatStr; } } } bool CustomNlpEnginePrivate::setCurrentModel(const std::string &model) { return true; } void CustomNlpEnginePrivate::setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { textGenerationResultCallback_ = std::move(callback); } void CustomNlpEnginePrivate::clearContext() { if (context_.isMember("messages")) { context_["messages"].clear(); } } void CustomNlpEnginePrivate::addContext_(const std::string &role, const std::string &message) { if (role == "system") { if (!message.empty()) { context_["messages"][0]["role"] = role; context_["messages"][0]["content"] = message; } return; } int size = context_["messages"].size(); context_["messages"][size]["role"] = role; context_["messages"][size]["content"] = message; } void CustomNlpEnginePrivate::removeLastContext_() { int size = context_["messages"].size(); if (size - 1 >= 0 && context_["messages"][size - 1]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); return; } if ((size - 1) >= 0 && (size - 2) >= 0 && context_["messages"][size - 1]["role"].asString() == "assistant" && context_["messages"][size - 2]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); context_["messages"].removeIndex(size - 2, &removeValue); return; } } void CustomNlpEnginePrivate::decreaseChatCounter() { if (chatCounter_ > 0) { --chatCounter_; } } void CustomNlpEnginePrivate::increaseChatCounter() { ++chatCounter_; } bool CustomNlpEnginePrivate::isChatRunning() const { return chatCounter_ > 0; } ai_engine::result::AiEngineBaseResult CustomNlpEnginePrivate::init() { currentError_ = ai_engine::EngineError(); context_["model"] = currentModel_; context_["stream"] = true; return {true, ai_engine::EngineError()}; } ai_engine::result::AiEngineBaseResult CustomNlpEnginePrivate::generateContent( const std::string &input) { tempStreamChatData_.clear(); isGenerateContentCalled_ = true; isThinking_ = false; hasReasoningContent_ = false; sentenceId_ = 0; currentError_ = ai_engine::EngineError(); if (!textGenerationResultCallback_) { return {false, currentError_}; } if (input.empty()) { currentError_ = ai_engine::EngineError( (int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } clearContext(); if (!waitForStopped()) { isStopped_ = false; } Json::Value context = custom_nlp_util::formatJsonFromString(input); context_["prompt"] = context["prompt"].asString(); std::string postString = context_.toStyledString(); cpr::Url url{generateContentUrl_}; cpr::Header header{cpr::Header{{"Content-Type", "application/json"}, {"Authorization", "Bearer " + apiKey_}}}; cpr::Body body{cpr::Body{{postString}}}; cpr::Response response = cpr::Post( url, header, body, cpr::WriteCallback{writeChatData, (intptr_t)this}, cpr::LowSpeed{20, 10}); return processChatResponse_(response); } ai_engine::result::AiEngineBaseResult CustomNlpEnginePrivate::chat( const std::string &message) { tempStreamChatData_.clear(); isThinking_ = false; hasReasoningContent_ = false; sentenceId_ = 0; currentError_ = ai_engine::EngineError(); if (!textGenerationResultCallback_) { return {false, currentError_}; } if (message.empty()) { currentError_ = ai_engine::EngineError( (int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } clearContext(); increaseChatCounter(); if (!waitForStopped()) { isStopped_ = false; } if (!isChatRunning()) { printf("CustomNlpEnginePrivate::chat: no chat is running"); return {true, currentError_}; } Json::Value context = custom_nlp_util::formatJsonFromString(message); for (int i = 0; i < context["messages"].size(); i++) { addContext_(context["messages"][i]["role"].asString(), context["messages"][i]["content"].asString()); } if (context.isMember("top_k") && context["top_k"].isInt()) { context_["top_k"] = context["top_k"].asInt(); } std::string postString = context_.toStyledString(); printf("postString: %s", postString.c_str()); cpr::Url url{chatUrl_}; cpr::Header header{cpr::Header{{"Content-Type", "application/json"}, {"Authorization", "Bearer " + apiKey_}}}; cpr::Body body{cpr::Body{{postString}}}; cpr::Response response = cpr::Post( url, header, body, cpr::WriteCallback{writeChatData, (intptr_t)this}, cpr::ConnectTimeout{10000}, // 连接超时10秒 cpr::LowSpeed{20, 10}); return processChatResponse_(response); } bool CustomNlpEnginePrivate::waitForStopped() { auto startTime = std::chrono::steady_clock::now(); while (isStopped_) { if (std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10)) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } void CustomNlpEnginePrivate::stopChat() { if (!isChatRunning()) { printf("CustomNlpEnginePrivate::stopChat: chat is not running"); return; } decreaseChatCounter(); isStopped_ = true; streamChatData_.clear(); ai_engine::gen_ai::nlp::TextGenerationResult result{ true, currentError_, currentModelName_, std::string{R"({"result":"","is_end":true})"}}; if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } void CustomNlpEnginePrivate::stopGenerateContent() { if (isStopped_.exchange(true)) { return; } if (isGenerateContentCalled_) { isGenerateContentCalled_ = false; ai_engine::gen_ai::nlp::TextGenerationResult result{ true, currentError_, currentModelName_, std::string{R"({"result":"","is_end":true})"}}; if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } } ai_engine::result::AiEngineBaseResult CustomNlpEnginePrivate::destroy() { stopChat(); return {true, ai_engine::EngineError()}; } bool CustomNlpEnginePrivate::isValidResponse( const std::string &response) const { if (response.length() >= 9 && response.compare(0, 5, "data:") != 0 && response.compare(0, 6, "\ndata:") != 0 && response.compare(0, 9, R"({"model":)") != 0) { fprintf(stderr, "Invalid response: %s\n", response.c_str()); return false; } return true; } Json::Value CustomNlpEnginePrivate::formatResultJsonFromInputString( const std::string &inputString) { Json::Value inputResultJson = custom_nlp_util::formatJsonFromString(inputString); if (preProcessResultJson(inputResultJson)) { return Json::Value(); } Json::Value resultJson; resultJson["is_end"] = isResultEnd(inputResultJson); if (isThinking()) { resultJson["reasoning_content"] = getThinkingResult(inputResultJson); } else { resultJson["result"] = getResult(inputResultJson); } resultJson["sentence_id"] = sentenceId_; sentenceId_ += 1; return resultJson; } bool CustomNlpEnginePrivate::preProcessResultJson( const Json::Value &inputResultJson) { const std::string startThinkingStr = "\u003cthink\u003e"; const std::string endThinkingStr = "\u003c/think\u003e"; if (isOpenAiApiResult(inputResultJson)) { if (inputResultJson["choices"][0]["delta"].isMember( "reasoning_content") && !inputResultJson["choices"][0]["delta"]["reasoning_content"] .empty()) { isThinking_ = true; hasReasoningContent_ = true; return false; } if (inputResultJson["choices"][0]["delta"].isMember("reasoning") && !inputResultJson["choices"][0]["delta"]["reasoning"].empty()) { isThinking_ = true; hasReasoningContent_ = true; return false; } if (hasReasoningContent_) { hasReasoningContent_ = false; isThinking_ = false; } if (inputResultJson["choices"][0]["delta"]["content"].asString() == startThinkingStr || inputResultJson["choices"][0]["text"].asString() == startThinkingStr) { isThinking_ = true; return true; } if (inputResultJson["choices"][0]["delta"]["content"].asString() == endThinkingStr || inputResultJson["choices"][0]["text"].asString() == endThinkingStr) { isThinking_ = false; return true; } } if (isOllamaApiResult(inputResultJson)) { if (inputResultJson["message"]["content"].asString() == startThinkingStr) { isThinking_ = true; return true; } if (inputResultJson["message"]["content"].asString() == endThinkingStr) { isThinking_ = false; return true; } } return false; } bool CustomNlpEnginePrivate::isOpenAiApiResult( const Json::Value &result) const { return result.isObject() && result.isMember("choices"); } bool CustomNlpEnginePrivate::isOllamaApiResult( const Json::Value &result) const { return result.isObject() && result.isMember("message"); } bool CustomNlpEnginePrivate::isResultEnd(const Json::Value &result) const { if (isOpenAiApiResult(result)) { return result["choices"][0]["finish_reason"] == "stop" || result["choices"][0]["finish_reason"] == "length"; } if (isOllamaApiResult(result)) { return result["done"].asBool(); } return false; } bool CustomNlpEnginePrivate::isThinking() const { return isThinking_; } std::string CustomNlpEnginePrivate::getThinkingResult( const Json::Value &result) const { if (isOpenAiApiResult(result)) { if (!result["choices"][0]["delta"]["reasoning_content"].empty()) { return result["choices"][0]["delta"]["reasoning_content"] .asString(); } if (!result["choices"][0]["delta"]["reasoning"].empty()) { return result["choices"][0]["delta"]["reasoning"].asString(); } if (!result["choices"][0]["text"].empty()) { return result["choices"][0]["text"].asString(); } return result["choices"][0]["delta"]["content"].asString(); } if (isOllamaApiResult(result)) { return result["message"]["content"].asString(); } return ""; } std::string CustomNlpEnginePrivate::getResult(const Json::Value &result) const { if (isOpenAiApiResult(result)) { return result["choices"][0].isMember("delta") ? result["choices"][0]["delta"]["content"].asString() : result["choices"][0].isMember("text") ? result["choices"][0]["text"].asString() : ""; } if (isOllamaApiResult(result)) { return result["message"]["content"].asString(); } return ""; } ai_engine::result::AiEngineBaseResult CustomNlpEnginePrivate::processChatResponse_(cpr::Response &response) { if (isStopped_ || !isChatRunning()) { isStopped_ = false; return {true, ai_engine::EngineError()}; } decreaseChatCounter(); if (response.error.code == cpr::ErrorCode::REQUEST_CANCELLED) { streamChatData_.clear(); auto errorCode = custom_nlp_server_error::errorCode2nlpResult(response.status_code); currentError_ = ai_engine::EngineError(static_cast(errorCode), currentErrorInfo_); return {false, currentError_}; } if (response.error) { streamChatData_.clear(); fprintf(stderr, "net error: %s\n", response.error.message.c_str()); if (response.error.code == cpr::ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR) { currentError_ = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::SslCertificateError), response.error.message); } else { currentError_ = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::NetworkDisconnected), "HTTP response error"); } return {false, currentError_}; } if (response.status_code < 200 || response.status_code >= 300) { streamChatData_.clear(); auto errorCode = custom_nlp_server_error::errorCode2nlpResult(response.status_code); currentError_ = ai_engine::EngineError(static_cast(errorCode), "HTTP status error"); return {false, currentError_}; } streamChatData_.clear(); return {true, currentError_}; }kylin-cloud-ai-engine-plugin-1.1.0.1/custom/customnlpengine_p.h000066400000000000000000000075721520575453600244730ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef CUSTOMNLPENGINE_P_H #define CUSTOMNLPENGINE_P_H #include #include #include #include #include "cpr/cpr.h" class CustomNlpEnginePrivate : public ai_engine::gen_ai::nlp::AbstractTextGenerationEngine { public: CustomNlpEnginePrivate(); ~CustomNlpEnginePrivate(); std::string engineName() const override; bool isCloud() const override { return true; } bool isBuiltInEngine() const override { return false; } bool isCustomModelEngine() const override { return true; } void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string currentModel() const override { return currentModel_; } std::string currentModelName() const override { return currentModelName_; } std::string modelInfo() const override; void setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) override; ai_engine::result::AiEngineBaseResult generateContent( const std::string &input) override; ai_engine::result::AiEngineBaseResult chat( const std::string &message) override; void stopGenerateContent() override; void stopChat() override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; private: bool isValidResponse(const std::string &response) const; Json::Value formatResultJsonFromInputString(const std::string &inputString); bool preProcessResultJson(const Json::Value &inputResultJson); bool isOpenAiApiResult(const Json::Value &result) const; bool isOllamaApiResult(const Json::Value &result) const; bool isResultEnd(const Json::Value &result) const; bool isThinking() const; std::string getThinkingResult(const Json::Value &result) const; std::string getResult(const Json::Value &result) const; void buildChatAndContentGenerationUrl(const std::string &apiUrl); void decreaseChatCounter(); void increaseChatCounter(); bool isChatRunning() const; private: std::string apiKey_; std::string currentModel_; std::string currentModelName_; std::string chatUrl_; std::string generateContentUrl_; ai_engine::gen_ai::nlp::TextGenerationResultCallback textGenerationResultCallback_{nullptr}; Json::Value context_; int sentenceId_{0}; void clearContext(); std::string endStr_ = "\n"; void addContext_(const std::string &role, const std::string &message); void removeLastContext_(); std::vector streamChatData_; std::string tempStreamChatData_; friend bool writeChatData(std::string data, intptr_t userData); ai_engine::result::AiEngineBaseResult processChatResponse_( cpr::Response &response); ai_engine::EngineError currentError_; std::string currentErrorInfo_; bool waitForStopped(); std::atomic isStopped_{false}; std::atomic chatCounter_{0}; bool isGenerateContentCalled_{false}; static std::string systemRole_; bool isThinking_{false}; bool hasReasoningContent_{false}; }; #endif // CUSTOMNLPENGINE_P_H kylin-cloud-ai-engine-plugin-1.1.0.1/custom/servererror.cpp000066400000000000000000000030461520575453600236450ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map nlpChatErrorCodeMap = { {302, ai_engine::NlpEngineErrorCode::NetworkDisconnected}, {400, ai_engine::NlpEngineErrorCode::InvalidWords}, {401, ai_engine::NlpEngineErrorCode::Unauthorized}, {402, ai_engine::NlpEngineErrorCode::Unauthorized}, {404, ai_engine::NlpEngineErrorCode::NetworkDisconnected}, {422, ai_engine::NlpEngineErrorCode::InvalidParamType}, {429, ai_engine::NlpEngineErrorCode::TooFrequentRequest}, {503, ai_engine::NlpEngineErrorCode::ServerNoResponse}, }; }; ai_engine::NlpEngineErrorCode custom_nlp_server_error::errorCode2nlpResult( long errorCode) { if (nlpChatErrorCodeMap.count(errorCode) > 0) { return nlpChatErrorCodeMap.at(errorCode); } return ai_engine::NlpEngineErrorCode::UnknownError; } kylin-cloud-ai-engine-plugin-1.1.0.1/custom/servererror.h000066400000000000000000000016761520575453600233210ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace custom_nlp_server_error { ai_engine::NlpEngineErrorCode errorCode2nlpResult(long errorCode); } // namespace custom_nlp_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/custom/util.cpp000066400000000000000000000021431520575453600222370ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include Json::Value custom_nlp_util::formatJsonFromString( const std::string &stringJson) { Json::Value obj; std::string error; Json::CharReaderBuilder crbuilder; std::unique_ptr reader(crbuilder.newCharReader()); reader->parse(stringJson.c_str(), stringJson.c_str() + stringJson.size(), &obj, &error); return obj; }kylin-cloud-ai-engine-plugin-1.1.0.1/custom/util.h000066400000000000000000000015511520575453600217060ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include namespace custom_nlp_util { Json::Value formatJsonFromString(const std::string &stringJson); } #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/000077500000000000000000000000001520575453600210315ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseekengine.cpp000066400000000000000000000020261520575453600245100ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "deepseekengine.h" #include "deepseek/deepseeknlpengine.h" std::string DeepseekAiEngine::name() const { return "deepseek"; } std::unique_ptr DeepseekAiEngine::createTextGenerationEngine() { return std::make_unique(); } AI_ENGINE_PLUGIN_FACTORY(DeepseekAiEngine) kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseekengine.h000066400000000000000000000020021520575453600241470ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include class DeepseekAiEngine : public ai_engine::AbstractAiEnginePluginFactory { public: ~DeepseekAiEngine() = default; std::string name() const override; std::unique_ptr createTextGenerationEngine() override; }; kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseeknlpengine.cpp000066400000000000000000000042461520575453600252300ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "deepseeknlpengine.h" #include "deepseek/deepseeknlpengine_p.h" DeepseekNlpEngine::DeepseekNlpEngine() : d(new DeepseekNlpEnginePrivate()) {} DeepseekNlpEngine::~DeepseekNlpEngine() { delete d; }; std::string DeepseekNlpEngine::engineName() const { return d->engineName(); } std::string DeepseekNlpEngine::currentModel() const { return d->currentModel(); } std::string DeepseekNlpEngine::currentModelName() const { return d->currentModelName(); } std::string DeepseekNlpEngine::modelInfo() const { return d->modelInfo(); } bool DeepseekNlpEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } void DeepseekNlpEngine::setConfig(const std::string &config) { d->setConfig(config); } void DeepseekNlpEngine::setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { d->setTextGenerationResultCallback(callback); } ai_engine::result::AiEngineBaseResult DeepseekNlpEngine::init() { return d->init(); } ai_engine::result::AiEngineBaseResult DeepseekNlpEngine::destroy() { return d->destroy(); } ai_engine::result::AiEngineBaseResult DeepseekNlpEngine::generateContent( const std::string &input) { return d->generateContent(input); } ai_engine::result::AiEngineBaseResult DeepseekNlpEngine::chat( const std::string &message) { return d->chat(message); } void DeepseekNlpEngine::stopGenerateContent() { d->stopGenerateContent(); } void DeepseekNlpEngine::stopChat() { d->stopChat(); } kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseeknlpengine.h000066400000000000000000000040341520575453600246700ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef DEEPSEEKNLPENGINE_H #define DEEPSEEKNLPENGINE_H #include class DeepseekNlpEnginePrivate; class DeepseekNlpEngine : public ai_engine::gen_ai::nlp::AbstractTextGenerationEngine { public: DeepseekNlpEngine(); ~DeepseekNlpEngine() override; std::string engineName() const override; bool isCloud() const override { return true; } bool isBuiltInEngine() const override { return false; } bool isCustomModelEngine() const override { return false; } std::string modelInfo() const override; bool setCurrentModel(const std::string &model) override; std::string currentModel() const override; std::string currentModelName() const override; void setConfig(const std::string &config) override; void setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; ai_engine::result::AiEngineBaseResult generateContent( const std::string &input) override; ai_engine::result::AiEngineBaseResult chat( const std::string &message) override; void stopGenerateContent() override; void stopChat() override; private: DeepseekNlpEnginePrivate *d; }; #endif // DEEPSEEKNLPENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseeknlpengine_p.cpp000066400000000000000000000312171520575453600255450ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "deepseeknlpengine_p.h" #include #include "servererror.h" #include "util.h" namespace { std::map modelNames = { {"deepseek-chat", "DeepSeek-V3"}, {"deepseek-reasoner", "DeepSeek-R1"}}; } DeepseekNlpEnginePrivate::DeepseekNlpEnginePrivate() : currentModel_("deepseek-chat") {} DeepseekNlpEnginePrivate::~DeepseekNlpEnginePrivate() { streamChatData_.clear(); } std::string DeepseekNlpEnginePrivate::engineName() const { return "deepseek"; } std::string DeepseekNlpEnginePrivate::currentModel() const { return currentModel_; } std::string DeepseekNlpEnginePrivate::currentModelName() const { return modelNames[currentModel_]; } std::string DeepseekNlpEnginePrivate::modelInfo() const { const char *info = R"( { "vendor": "深度求索", "models": [ { "name": "DeepSeek-V3", "model": "deepseek-chat", "subConfig": [ { "name": "deepseek-chat", "config": [ { "friendlyName": "APIKey", "configName": "apiKey" } ] } ], "maxTokens": 8192, "feedbackUrl": "https://platform.deepseek.com/usage" }, { "name": "DeepSeek-R1", "model": "deepseek-reasoner", "subConfig": [ { "name": "deepseek-reasoner", "config": [ { "friendlyName": "APIKey", "configName": "apiKey" } ] } ], "maxTokens": 8192, "feedbackUrl": "https://platform.deepseek.com/usage" } ] } )"; return info; } void DeepseekNlpEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = deepseek_nlp_util::formatJsonFromString(config); if (configJson.isNull() || !configJson.isMember("apiKey") || !configJson["apiKey"].isString() || configJson["apiKey"].asString().empty()) { std::fprintf(stderr, "Invalid config for deepseek nlp engine: %s\n", config.c_str()); return; } apiKey_ = configJson["apiKey"].asString(); } void DeepseekNlpEnginePrivate::setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { textGenerationResultCallback_ = callback; } bool DeepseekNlpEnginePrivate::setCurrentModel(const std::string &model) { if (modelNames.find(model) == modelNames.end()) { return false; } currentModel_ = model; return true; } namespace { std::vector splitDataString(const std::string &dataStr) { std::vector datas; int oldIndex = 0; int newIndex = 0; while ((newIndex = dataStr.find_first_of("\n\n", newIndex)) != std::string::npos) { datas.push_back(dataStr.substr(oldIndex, newIndex - oldIndex)); newIndex += 2; oldIndex = newIndex; } return datas; } } // namespace bool writeChatData(std::string data, intptr_t userData) { DeepseekNlpEnginePrivate *engine = (DeepseekNlpEnginePrivate *)userData; auto callback = engine->textGenerationResultCallback_; if (engine->isStopped_ || !engine->isChatRunning()) { return false; } Json::Value resultJson = deepseek_nlp_util::formatJsonFromString(data); if (resultJson.isObject() && !resultJson.isNull() && resultJson.isMember("error")) { fprintf(stderr, "deepseek chat failed: %s\n", data.c_str()); engine->currentErrorInfo_ = data; return false; } std::string resultString = engine->tempStreamChatData_.data() + data; if (resultString.substr(resultString.length() - 2) != "\n\n") { engine->tempStreamChatData_ += data; return true; } engine->tempStreamChatData_.clear(); std::vector dataStrings = splitDataString(resultString); if (dataStrings[0] == ": keep-alive") { return true; } for (std::string data : dataStrings) { data = data.substr(6, data.length() - 1); if (data == "[DONE]") { break; } Json::Value obj = deepseek_nlp_util::formatJsonFromString(data); Json::Value callbackObj; callbackObj["is_end"] = static_cast(obj["choices"][0]["finish_reason"] == "stop"); if (!obj["choices"][0]["delta"]["reasoning_content"].empty()) { callbackObj["reasoning_content"] = obj["choices"][0]["delta"]["reasoning_content"]; } callbackObj["result"] = obj["choices"][0]["delta"]["content"]; callbackObj["sentence_id"] = engine->sentenceId_; engine->sentenceId_ += 1; engine->streamChatData_.push_back(callbackObj["result"]); ai_engine::gen_ai::nlp::TextGenerationResult result{ true, ai_engine::EngineError(), modelNames[engine->currentModel_], callbackObj.toStyledString()}; callback(result); } return true; } int DeepseekNlpEnginePrivate::getMaxTokens(const std::string &model) { Json::Value modelInfoJson = deepseek_nlp_util::formatJsonFromString(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { maxTokens_ = item["maxTokens"].asInt(); return maxTokens_; } } return -1; } void DeepseekNlpEnginePrivate::clearContext() { if (context_.isMember("messages")) { context_["messages"].clear(); } } void DeepseekNlpEnginePrivate::addContext_(const std::string &role, const std::string &message) { if (role == "system") { if (!message.empty()) { context_["messages"][0]["role"] = role; context_["messages"][0]["content"] = message; } return; } int size = context_["messages"].size(); context_["messages"][size]["role"] = role; context_["messages"][size]["content"] = message; } void DeepseekNlpEnginePrivate::removeLastContext_() { int size = context_["messages"].size(); if (size - 1 >= 0 && context_["messages"][size - 1]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); return; } if ((size - 1) >= 0 && (size - 2) >= 0 && context_["messages"][size - 1]["role"].asString() == "assistant" && context_["messages"][size - 2]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); context_["messages"].removeIndex(size - 2, &removeValue); return; } } void DeepseekNlpEnginePrivate::decreaseChatCounter() { if (chatCounter_ > 0) { --chatCounter_; } } void DeepseekNlpEnginePrivate::increaseChatCounter() { ++chatCounter_; } bool DeepseekNlpEnginePrivate::isChatRunning() const { return chatCounter_ > 0; } ai_engine::result::AiEngineBaseResult DeepseekNlpEnginePrivate::init() { context_["model"] = currentModel_; if (getMaxTokens(currentModel_) != -1) { context_["max_tokens"] = maxTokens_; } context_["stream"] = true; return {true}; } ai_engine::result::AiEngineBaseResult DeepseekNlpEnginePrivate::destroy() { stopChat(); return {true}; } ai_engine::result::AiEngineBaseResult DeepseekNlpEnginePrivate::generateContent( const std::string &input) { ai_engine::EngineError error{ (int)ai_engine::NlpEngineErrorCode::FailedToAnswer, "Unsupported features"}; ai_engine::gen_ai::nlp::TextGenerationResult result{ false, error, modelNames[currentModel_], }; if (textGenerationResultCallback_) { textGenerationResultCallback_(result); } return {false, error}; } ai_engine::result::AiEngineBaseResult DeepseekNlpEnginePrivate::chat( const std::string &message) { tempStreamChatData_.clear(); sentenceId_ = 0; if (!textGenerationResultCallback_) { return {false}; } if (apiKey_.empty()) { ai_engine::EngineError error( (int)ai_engine::NlpEngineErrorCode::Unauthorized, "The apiKey is empty"); return {false, error}; } if (message.empty()) { ai_engine::EngineError error( (int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, error}; } clearContext(); increaseChatCounter(); if (!waitForStopped()) { isStopped_ = false; } if (!isChatRunning()) { printf("DeepseekNlpEnginePrivate::chat: no chat is running"); return {true, currentError_}; } Json::Value context = deepseek_nlp_util::formatJsonFromString(message); for (int i = 0; i < context["messages"].size(); i++) { addContext_(context["messages"][i]["role"].asString(), context["messages"][i]["content"].asString()); } context_["model"] = currentModel_; std::string postString = context_.toStyledString(); cpr::Url url{"https://api.deepseek.com/chat/completions"}; cpr::Header header{cpr::Header{{"Content-Type", "application/json"}, {"Authorization", "Bearer " + apiKey_}}}; cpr::Body body{cpr::Body{{postString}}}; std::fprintf(stderr, "DeepSeek postString: %s\n", postString.c_str()); cpr::Response response = cpr::Post( url, header, body, cpr::WriteCallback{writeChatData, (intptr_t)this}, cpr::LowSpeed(20, 10)); return processChatResponse(response); } void DeepseekNlpEnginePrivate::stopGenerateContent() {} bool DeepseekNlpEnginePrivate::waitForStopped() { auto startTime = std::chrono::steady_clock::now(); while (isStopped_) { if (std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10)) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } void DeepseekNlpEnginePrivate::stopChat() { if (!isChatRunning()) { printf("DeepseekNlpEnginePrivate::stopChat: chat is not running"); return; } decreaseChatCounter(); isStopped_ = true; streamChatData_.clear(); ai_engine::gen_ai::nlp::TextGenerationResult result{ true, {}, modelNames[currentModel_], std::string{R"({"result":"","is_end":true})"}}; if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } ai_engine::result::AiEngineBaseResult DeepseekNlpEnginePrivate::processChatResponse(cpr::Response &response) { if (isStopped_ || !isChatRunning()) { isStopped_ = false; return {true}; }; decreaseChatCounter(); if (response.error.code == cpr::ErrorCode::REQUEST_CANCELLED) { streamChatData_.clear(); ai_engine::EngineError error( (int)deepseek_nlp_server_error::errorCode2nlpResult( response.status_code), currentErrorInfo_); return {false, error}; } if (response.error) { streamChatData_.clear(); fprintf(stderr, "net error: %s\n", response.error.message.c_str()); ai_engine::EngineError error; if (response.error.code == cpr::ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR) { error = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::SslCertificateError), response.error.message); } else { error = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::NetworkDisconnected), response.error.message); } return {false, error}; } streamChatData_.clear(); return {true}; } kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/deepseeknlpengine_p.h000066400000000000000000000053001520575453600252040ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef DEEPSEEKNLPENGINE_P_H #define DEEPSEEKNLPENGINE_P_H #include #include #include #include "third-party/cpr/include/cpr/cpr.h" class DeepseekNlpEnginePrivate { public: DeepseekNlpEnginePrivate(); ~DeepseekNlpEnginePrivate(); std::string engineName() const; std::string currentModel() const; std::string currentModelName() const; void setConfig(const std::string &config); std::string modelInfo() const; void setTextGenerationResultCallback( ai_engine::gen_ai::nlp::TextGenerationResultCallback callback); bool setCurrentModel(const std::string &model); ai_engine::result::AiEngineBaseResult generateContent( const std::string &input); ai_engine::result::AiEngineBaseResult chat(const std::string &message); void stopGenerateContent(); void stopChat(); ai_engine::result::AiEngineBaseResult init(); ai_engine::result::AiEngineBaseResult destroy(); private: std::string apiKey_; ai_engine::gen_ai::nlp::TextGenerationResultCallback textGenerationResultCallback_; Json::Value context_; int sentenceId_{0}; void clearContext(); void addContext_(const std::string &role, const std::string &message); void removeLastContext_(); std::vector streamChatData_; std::string tempStreamChatData_; friend bool writeChatData(std::string data, intptr_t userData); int getMaxTokens(const std::string &model); ai_engine::result::AiEngineBaseResult processChatResponse( cpr::Response &response); void decreaseChatCounter(); void increaseChatCounter(); bool isChatRunning() const; ai_engine::EngineError currentError_; std::string currentErrorInfo_; bool waitForStopped(); std::atomic isStopped_{false}; std::atomic chatCounter_{0}; static std::string systemRole_; std::string currentModel_; int maxTokens_; }; #endif // DEEPSEEKNLPENGINE_P_H kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/servererror.cpp000066400000000000000000000027461520575453600241260ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map nlpChatErrorCodeMap = { {400, ai_engine::NlpEngineErrorCode::InvalidWords}, {401, ai_engine::NlpEngineErrorCode::Unauthorized}, {402, ai_engine::NlpEngineErrorCode::Unauthorized}, {422, ai_engine::NlpEngineErrorCode::InvalidParamType}, {429, ai_engine::NlpEngineErrorCode::TooFrequentRequest}, {500, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {503, ai_engine::NlpEngineErrorCode::ServerNoResponse}, }; }; ai_engine::NlpEngineErrorCode deepseek_nlp_server_error::errorCode2nlpResult( long errorCode) { if (nlpChatErrorCodeMap.count(errorCode) > 0) { return nlpChatErrorCodeMap.at(errorCode); } return ai_engine::NlpEngineErrorCode::UnknownError; } kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/servererror.h000066400000000000000000000017021520575453600235620ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace deepseek_nlp_server_error { ai_engine::NlpEngineErrorCode errorCode2nlpResult(long errorCode); } // namespace deepseek_nlp_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/util.cpp000066400000000000000000000021451520575453600225140ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include Json::Value deepseek_nlp_util::formatJsonFromString( const std::string &stringJson) { Json::Value obj; std::string error; Json::CharReaderBuilder crbuilder; std::unique_ptr reader(crbuilder.newCharReader()); reader->parse(stringJson.c_str(), stringJson.c_str() + stringJson.size(), &obj, &error); return obj; }kylin-cloud-ai-engine-plugin-1.1.0.1/deepseek/util.h000066400000000000000000000015531520575453600221630ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include namespace deepseek_nlp_util { Json::Value formatJsonFromString(const std::string &stringJson); } #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/000077500000000000000000000000001520575453600202165ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/README.md000066400000000000000000000000311520575453600214670ustar00rootroot00000000000000# kylin-qwen-nlp-engine kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwenengine.cpp000066400000000000000000000017661520575453600230740ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "qwenengine.h" #include "qwen/qwennlpengine.h" std::string QwenAiEngine::name() const { return "qwen"; } std::unique_ptr QwenAiEngine::createTextGenerationEngine() { return std::make_unique(); } AI_ENGINE_PLUGIN_FACTORY(QwenAiEngine); kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwenengine.h000066400000000000000000000017721520575453600225360ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include class QwenAiEngine : public ai_engine::AbstractAiEnginePluginFactory { public: ~QwenAiEngine() = default; std::string name() const override; std::unique_ptr createTextGenerationEngine() override; }; kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwennlpengine.cpp000066400000000000000000000044051520575453600235770ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "qwennlpengine.h" #include "qwen/qwennlpengine_p.h" QwenNlpEngine::QwenNlpEngine() : d(new QwenNlpEnginePrivate()) {} QwenNlpEngine::~QwenNlpEngine() = default; std::string QwenNlpEngine::engineName() const { return d->engineName(); } std::string QwenNlpEngine::currentModel() const { return d->currentModel(); } std::string QwenNlpEngine::currentModelName() const { return d->currentModelName(); } bool QwenNlpEngine::isCloud() const { return d->isCloud(); } bool QwenNlpEngine::isBuiltInEngine() const { return d->isBuiltInEngine(); } bool QwenNlpEngine::isCustomModelEngine() const { return d->isCustomModelEngine(); } std::string QwenNlpEngine::modelInfo() const { return d->modelInfo(); } void QwenNlpEngine::setConfig(const std::string &config) { d->setConfig(config); } bool QwenNlpEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } void QwenNlpEngine::setTextGenerationResultCallback(ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { d->setTextGenerationResultCallback(callback); } ai_engine::result::AiEngineBaseResult QwenNlpEngine::generateContent(const std::string &input) { return d->generateContent(input); } ai_engine::result::AiEngineBaseResult QwenNlpEngine::init() { return d->init(); } ai_engine::result::AiEngineBaseResult QwenNlpEngine::chat(const std::string &message) { return d->chat(message); } void QwenNlpEngine::stopChat() { d->stopChat(); } void QwenNlpEngine::stopGenerateContent() { d->stopGenerateContent(); } ai_engine::result::AiEngineBaseResult QwenNlpEngine::destroy() { return d->destroy(); } kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwennlpengine.h000066400000000000000000000036351520575453600232500ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef QWENNLPENGINE_H #define QWENNLPENGINE_H #include class QwenNlpEnginePrivate; class QwenNlpEngine : public ai_engine::gen_ai::nlp::AbstractTextGenerationEngine { public: QwenNlpEngine(); ~QwenNlpEngine(); std::string engineName() const override; bool isCloud() const override; bool isBuiltInEngine() const override; bool isCustomModelEngine() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string currentModel() const override; std::string currentModelName() const override; std::string modelInfo() const override; void setTextGenerationResultCallback(ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) override; ai_engine::result::AiEngineBaseResult generateContent(const std::string &input) override; ai_engine::result::AiEngineBaseResult chat(const std::string &message) override; void stopGenerateContent() override; void stopChat() override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; private: QwenNlpEnginePrivate *d; }; #endif // QWENNLPENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwennlpengine_p.cpp000066400000000000000000000317251520575453600241230ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "qwennlpengine_p.h" #include #include "servererror.h" #include "util.h" QwenNlpEnginePrivate::QwenNlpEnginePrivate() {} QwenNlpEnginePrivate::~QwenNlpEnginePrivate() { streamChatData_.clear(); } std::string QwenNlpEnginePrivate::engineName() const { return "qwen"; } std::string QwenNlpEnginePrivate::modelInfo() const { const char *info = R"( { "vendor": "通义千问", "models": [ { "name": "通义千问-qwen-plus", "model": "qwen-plus", "subConfig": [ { "name": "qwen-plus", "config": [ { "friendlyName": "APIKey", "configName": "apiKey" } ] } ], "maxTokens": 8192, "feedbackUrl": "https://www.aliyun.com/service" } ] } )"; return info; } void QwenNlpEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = qwen_nlp_util::formatJsonFromString(config); if (configJson.isNull() || !configJson.isMember("apiKey") || !configJson["apiKey"].isString()) { std::fprintf(stderr, "Invalid config for qwen nlp engine: %s\n", config.c_str()); return; } apiKey_ = configJson["apiKey"].asString(); } bool QwenNlpEnginePrivate::setCurrentModel(const std::string &model) { const Json::Value modelInfoJson = qwen_nlp_util::formatJsonFromString(modelInfo()); for (const auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { currentModel_ = model; return true; } } fprintf(stderr, "Invalid current model name: %s\n", model.c_str()); return false; } void QwenNlpEnginePrivate::setTextGenerationResultCallback( const ai_engine::gen_ai::nlp::TextGenerationResultCallback &callback) { textGenerationResultCallback_ = callback; } namespace { std::vector splitDataString(const std::string &dataStr) { std::vector datas; int oldIndex = 0; int newIndex = 0; while ((newIndex = dataStr.find_first_of("\n\n", newIndex)) != std::string::npos) { datas.push_back(dataStr.substr(oldIndex, newIndex - oldIndex)); newIndex += 2; oldIndex = newIndex; } return datas; } } // namespace bool writeChatData(std::string data, intptr_t userData) { QwenNlpEnginePrivate *engine = (QwenNlpEnginePrivate *)userData; ai_engine::gen_ai::nlp::TextGenerationResultCallback callback = engine->textGenerationResultCallback_; if (engine->isStopped_ || !engine->isChatRunning()) { return false; } Json::Value resultJson = qwen_nlp_util::formatJsonFromString(data); if (resultJson.isObject() && !resultJson.isNull() && resultJson.isMember("error")) { fprintf(stderr, "qwen chat failed: %s\n", data.c_str()); engine->currentErrorInfo_ = data; return false; } std::string resultString = engine->tempStreamChatData_.data() + data; if (resultString.substr(resultString.length() - 2) != "\n\n") { engine->tempStreamChatData_ += data; return true; } engine->tempStreamChatData_.clear(); std::vector dataStrings = splitDataString(resultString); for (std::string data : dataStrings) { data = data.substr(6, data.length() - 1); if (data == "[DONE]") { break; } Json::Value obj = qwen_nlp_util::formatJsonFromString(data); Json::Value callbackObj; callbackObj["is_end"] = static_cast(obj["choices"][0]["finish_reason"] == "stop"); callbackObj["result"] = obj["choices"][0]["delta"]["content"]; callbackObj["sentence_id"] = engine->sentenceId_; engine->sentenceId_ += 1; engine->streamChatData_.push_back(callbackObj["result"]); ai_engine::gen_ai::nlp::TextGenerationResult result{true, ai_engine::EngineError(), engine->currentModelName_, callbackObj.toStyledString()}; callback(result); } return true; } int QwenNlpEnginePrivate::getMaxTokens(const std::string &model) { Json::Value modelInfoJson = qwen_nlp_util::formatJsonFromString(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { maxTokens_ = item["maxTokens"].asInt(); return maxTokens_; } } return -1; } void QwenNlpEnginePrivate::clearContext() { if (context_.isMember("messages")) { context_["messages"].clear(); } } void QwenNlpEnginePrivate::addContext(const std::string &role, const std::string &content) { if (role.empty() || content.empty()) { return; } if (role == "system") { context_["messages"][0]["role"] = role; context_["messages"][0]["content"] = content; } else { uint32_t size = context_["messages"].size(); context_["messages"][size]["role"] = role; context_["messages"][size]["content"] = content; } } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::buildChatMessage(const std::string &message) { Json::Value context = qwen_nlp_util::stringToJson(message); ai_engine::result::AiEngineBaseResult result; if (!context.isMember("messages")) { result.success = false; result.error = {int(ai_engine::NlpEngineErrorCode::InvalidParamType), "The input information lacks messages content."}; return result; } if (!context["messages"].isArray()) { result.success = false; result.error = {int(ai_engine::NlpEngineErrorCode::InvalidParamType), "The messages is not array."}; return result; } uint32_t size = context["messages"].size(); for (uint32_t i = 0; i < size; ++i) { Json::Value item = context["messages"][i]; if ((!item.isMember("role")) || (!item["role"].isString())) { continue; } if ((!item.isMember("content")) || (!item["content"].isString())) { continue; } std::string role = item["role"].asString(); std::string content = item["content"].asString(); addContext(role, content); } if (context.isMember("top_k") && context["top_k"].isInt()) { context_["top_k"] = context["top_k"].asInt(); } result.success = true; result.error = ai_engine::EngineError{}; return result; } void QwenNlpEnginePrivate::removeLastContext() { int size = context_["messages"].size(); if (size - 1 >= 0 && context_["messages"][size - 1]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); return; } if ((size - 1) >= 0 && (size - 2) >= 0 && context_["messages"][size - 1]["role"].asString() == "assistant" && context_["messages"][size - 2]["role"].asString() == "user") { Json::Value removeValue; context_["messages"].removeIndex(size - 1, &removeValue); context_["messages"].removeIndex(size - 2, &removeValue); return; } } void QwenNlpEnginePrivate::decreaseChatCounter() { if (chatCounter_ > 0) { --chatCounter_; } } void QwenNlpEnginePrivate::increaseChatCounter() { ++chatCounter_; } bool QwenNlpEnginePrivate::isChatRunning() const { return chatCounter_ > 0; } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::init() { currentError_ = ai_engine::EngineError(); context_["model"] = currentModel_; context_["stream"] = true; if (getMaxTokens(currentModel_) != -1) { context_["max_tokens"] = maxTokens_; } context_["enable_search"] = true; return {true, ai_engine::EngineError()}; } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::generateContent(const std::string &input) { Json::Value inputJson = qwen_nlp_util::formatJsonFromString(input); if (input.empty() || inputJson.empty() || !inputJson.isMember("prompt")) { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } std::string promptContent = inputJson["prompt"].asString(); Json::Value messageJson; messageJson["messages"] = Json::Value(Json::arrayValue); Json::Value userMessage; userMessage["role"] = "user"; userMessage["content"] = promptContent; messageJson["messages"].append(userMessage); std::string message = messageJson.toStyledString(); return chat(message); } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::chat(const std::string &message) { tempStreamChatData_.clear(); currentError_ = ai_engine::EngineError(); sentenceId_ = 0; if (!textGenerationResultCallback_) { return {false, currentError_}; } if (message.empty()) { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } clearContext(); increaseChatCounter(); if (!waitForStopped()) { isStopped_ = false; } if (!isChatRunning()) { printf("QwenNlpEnginePrivate::chat: no chat is running"); return {true, currentError_}; } ai_engine::result::AiEngineBaseResult result = buildChatMessage(message); if (!result.success) { return result; } std::string postString = context_.toStyledString(); printf("post string %s", postString.c_str()); cpr::Url url{"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"}; cpr::Header header{cpr::Header{{"Content-Type", "application/json"}, {"Authorization", "Bearer " + apiKey_}}}; cpr::Body body{cpr::Body{{postString}}}; cpr::Response response = cpr::Post(url, header, body, cpr::WriteCallback{writeChatData, (intptr_t)this}, cpr::LowSpeed(20, 10)); return processChatResponse(response); } bool QwenNlpEnginePrivate::waitForStopped() { auto startTime = std::chrono::steady_clock::now(); while (isStopped_) { if (std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10)) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } void QwenNlpEnginePrivate::stopChat() { if (!isChatRunning()) { printf("QwenNlpEnginePrivate::stopChat: chat is not running"); return; } decreaseChatCounter(); isStopped_ = true; streamChatData_.clear(); ai_engine::gen_ai::nlp::TextGenerationResult result{true, currentError_, currentModelName_, std::string{R"({"result":"","is_end":true})"}}; if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } void QwenNlpEnginePrivate::stopGenerateContent() { isStopped_ = true; } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::destroy() { stopChat(); return {true, ai_engine::EngineError()}; } ai_engine::result::AiEngineBaseResult QwenNlpEnginePrivate::processChatResponse(cpr::Response &response) { if (isStopped_ || !isChatRunning()) { isStopped_ = false; return {true, ai_engine::EngineError()}; } decreaseChatCounter(); if (response.error.code == cpr::ErrorCode::REQUEST_CANCELLED) { streamChatData_.clear(); currentError_ = ai_engine::EngineError( (int)qwen_nlp_server_error::errorCode2nlpResult(response.status_code, currentErrorInfo_), currentErrorInfo_); return {false, currentError_}; } if (response.error) { streamChatData_.clear(); fprintf(stderr, "net error: %s\n", response.error.message.c_str()); if (response.error.code == cpr::ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR) { currentError_ = ai_engine::EngineError(int(ai_engine::NlpEngineErrorCode::SslCertificateError), response.error.message); } else { currentError_ = ai_engine::EngineError(int(ai_engine::NlpEngineErrorCode::NetworkDisconnected), response.error.message); } return {false, currentError_}; } streamChatData_.clear(); return {true, currentError_}; }kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/qwennlpengine_p.h000066400000000000000000000057441520575453600235720ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef QWENNLPENGINE_P_H #define QWENNLPENGINE_P_H #include #include #include #include #include "cpr/cpr.h" class QwenNlpEnginePrivate { public: QwenNlpEnginePrivate(); ~QwenNlpEnginePrivate(); std::string engineName() const; bool isCloud() const { return true; } bool isBuiltInEngine() const { return false; } bool isCustomModelEngine() const { return false; } void setConfig(const std::string &config); bool setCurrentModel(const std::string &model); std::string currentModel() const { return currentModel_; } std::string currentModelName() const { return currentModelName_; } std::string modelInfo() const; void setTextGenerationResultCallback(const ai_engine::gen_ai::nlp::TextGenerationResultCallback &callback); ai_engine::result::AiEngineBaseResult generateContent(const std::string &input); ai_engine::result::AiEngineBaseResult chat(const std::string &message); void stopGenerateContent(); void stopChat(); ai_engine::result::AiEngineBaseResult init(); ai_engine::result::AiEngineBaseResult destroy(); private: void addContext(const std::string &role, const std::string &content); ai_engine::result::AiEngineBaseResult buildChatMessage(const std::string &message); void clearContext(); void removeLastContext(); friend bool writeChatData(std::string data, intptr_t userData); int getMaxTokens(const std::string &model); ai_engine::result::AiEngineBaseResult processChatResponse(cpr::Response &response); bool waitForStopped(); void decreaseChatCounter(); void increaseChatCounter(); bool isChatRunning() const; private: std::string apiKey_; std::string currentModel_{"qwen-plus"}; std::string currentModelName_{"通义千问-qwen-plus"}; int maxTokens_; ai_engine::gen_ai::nlp::TextGenerationResultCallback textGenerationResultCallback_{nullptr}; Json::Value context_; int sentenceId_{0}; std::vector streamChatData_; std::string tempStreamChatData_; ai_engine::EngineError currentError_; std::string currentErrorInfo_; std::atomic isStopped_{false}; std::atomic chatCounter_{0}; }; #endif // QWENNLPENGINE_P_H kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/servererror.cpp000066400000000000000000000041211520575453600233000ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map nlpChatErrorCodeMap = { {400, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {401, ai_engine::NlpEngineErrorCode::Unauthorized}, {403, ai_engine::NlpEngineErrorCode::Unauthorized}, {404, ai_engine::NlpEngineErrorCode::Unauthorized}, {408, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {413, ai_engine::NlpEngineErrorCode::TooManyData}, {429, ai_engine::NlpEngineErrorCode::TooFrequentRequest}, {500, ai_engine::NlpEngineErrorCode::ServerNoResponse}, }; }; ai_engine::NlpEngineErrorCode qwen_nlp_server_error::errorCode2nlpResult(long errorCode, const std::string &errorMessage) { if (errorCode == 400) { Json::Value value = qwen_nlp_util::formatJsonFromString(errorMessage); if (value.isMember("error") && value["error"].isObject()) { if (value["error"].isMember("code") && value["error"]["code"].isString()) { if (value["error"]["code"].asString() == "invalid_parameter_error") { return ai_engine::NlpEngineErrorCode::InvalidParamType; } } } } if (nlpChatErrorCodeMap.count(errorCode) > 0) { return nlpChatErrorCodeMap.at(errorCode); } return ai_engine::NlpEngineErrorCode::UnknownError; } kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/servererror.h000066400000000000000000000017331520575453600227530ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace qwen_nlp_server_error { ai_engine::NlpEngineErrorCode errorCode2nlpResult(long errorCode, const std::string &errorMessage); } // namespace qwen_nlp_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/util.cpp000066400000000000000000000027551520575453600217100ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include Json::Value qwen_nlp_util::formatJsonFromString(const std::string &stringJson) { Json::Value obj; std::string error; Json::CharReaderBuilder crbuilder; std::unique_ptr reader(crbuilder.newCharReader()); reader->parse(stringJson.c_str(), stringJson.c_str() + stringJson.size(), &obj, &error); return obj; } std::string qwen_nlp_util::jsonToString(const Json::Value &value) { Json::StreamWriterBuilder builder; builder["emitUTF8"] = true; return Json::writeString(builder, value); } Json::Value qwen_nlp_util::stringToJson(const std::string &string) { Json::Value value; if (Json::Reader reader; reader.parse(string, value)) { return value; } else { return Json::objectValue; } } kylin-cloud-ai-engine-plugin-1.1.0.1/qwen/util.h000066400000000000000000000017561520575453600213550ustar00rootroot00000000000000/* * Copyright 2025 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include namespace qwen_nlp_util { Json::Value formatJsonFromString(const std::string &stringJson); std::string jsonToString(const Json::Value &value); Json::Value stringToJson(const std::string &string); } // namespace qwen_nlp_util #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/test/000077500000000000000000000000001520575453600202235ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/test/16k_10.pcm000066400000000000000000027006001520575453600216320ustar00rootroot00000000000000         $*-.-***)&!     $,231//0146:>BBA?=;91*%     &08?DEB;2(    "$"     '068899=@@<81(   (19ACDB<768<>CHJD?93.*   #%%#  %-0/./111236:960*&"      #'&!"#%'+29>@A@<71(   &.6>BDC?;851,'%*)%"     "" ! !'('% )11,& !(.350&   (2:EMLD;3-)!  !%+-(  )5CJG@4( $&)*("!    (-10(        /=HMPM:#   $! "  $#   & ",024-'&(&%).+! !')&# (:HHBFC/%(149HVSD>.&+8LU]b^RC1'#('""/BGG7 {no{rq 68.)-- -2"91$9DB9'  5HO:  4=/rdo*3<. 3ciL%<Vikb^7(14Uxv3-FZ^2 ;5y~=[d;ARB");CjvS$ ImqnG3@O6Bf_afG(Lo}nV=Nl~l{>LoWJGN@ /z{;2*@F7/'m`qsJQM_oex 4hI2/6:4?F<( zemog}fn 7{sd|.R2kJ>_!<*GonO+0Zic..i~e\gw~pUIt}tmL`yN$  $$oqX+_mX`jy1Gp:KL+ <e~rkR;i~s]T\^epS;.8]~u5uUj .Ue]%%BC(#_WB/( 5I&  2UXB-%87>E+K6! e7V&-B)2,"5C4,!  64Fh`FT{wI7@;0<Tq~}k\QTVSRC;  50$# wAbciC5h=M=*  ?a`7$! 1W]XKTovyzfZNFukJQ[spX;XrgW"uQOWe_s ,/?Nccmsw|nKB;%437,$.OQRD:%:0-: 0?58MtrPI3 " #.-$& --   &+6-UZuyzsUTK7#$5<NcUW\UHVgb]>52$=XpeI*?VBH@4L4 }ypvjPE Mg]mjv?O`U0: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(, rjNLV[#}pj`KLQk|u#M  y w J 9 #rYU34_FJ)XaV93LWw:dagRMYT1P  b Z xq"(iS0R#'qYG:'I'M;  ,Qfq,D_b V+ x z 4  P ,  " 1}t O J|bisZk ez 6ev60F._(% g (  1 [  n { 7 azJ N~hJ!t+jLCyc nB1Ol81Nb')_GwZ. J J A n JB-Nu+<[>vx} |ac.bB2iw`$2Da~X-DjI`.k=\z^T|p[R"zf)7m+r \:(J)~;9rD\b#G5 uI7 +D}K{ 9JK2=x :CRB~[84;VP$72fR&/};Og s o   ] pbTJ.3:K)|sSCLfgq'|S5MLB*r2g5}VS%220y@mO0< Q6\w=a'"}Y430zV CRCZ#&4>.ujNZMer:}R|e-|dc#MQ' _/y}[IMjA.BKfmbc [C |mE4s#e},!,SwVx'&km|d-$ &c1aT X /Rs\cz % | =9]9^~P9EK)z* L)g-k]D:glH0PN!.m4gC:H-d _ OLvQ}2bXVKJ #  ,rnoxWF+d\K#j@rTBB]y?Rl1UZ x 8H' te-kV`0&  &@;_L/Weth w-4[kCt ) . 4DiA8; X ~H\Ijf~h%'Ys    q   o`x4k6ZS7}|Q  Ul#==hl\0f>8 u s<fGS`\Z H M  dp  .e>tP|r);'%?w M  % 8EE :   + 3  ~ 0-^gy-l& ] ~T  ` 0%J{(^?4S ? , #s | fGluSd(,Fa T  ` ) +{` A * 1 U Be -pf[ 3֒MsWKm# q M . i5!{opyKD$?{ d C+ 4:Uih('"nZ  d? (OF  S 4 <  f )  @ 5W>֍<ڲ-C>%?^B$ sm  4js6n4d1) xkdp # @$AKo@ sVb M G  L2F_  0 M zx B?F27& xr,P<֐ 9/I 9 ` @W!jE*ee"r:GcF [ o f"A4u1fa&N#V&_CRUY N!/gL8 M [>fP9+yn W~W'z t w f 4 j*,H}i5i' ' 8 hj $ OlBODDur97i vp;;|QzuL<CQTC  ] ES/KQui+  Z/,jܸ ߍ n5Hm P  :l&%8gy_Sg] W  3 x()?PtRHpR-eA_  . +#Ul3  Ny7Ob> J e$S) 08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,@:8NOd| %16B6EO@KRWjvr{s|eOZH1-"}gZbTERVXVK628"&2/"*-7DEUNSaU^aeonx} #6JBNhwq^LJ,# s{tTXYQOVVWSFUaY^OFK842% *:?KXW]bd~#1-.5MVioafgdd[`et|jXP=;0$0  {gZSXaZfsVVXXgv}uwjyp~{t #9BQRQbICOP^RS^ZmocdbnjTb_dgET`[S><! wuqh^UjgMI>PkFAJHef~)+ 2-;VDLJ;>,!$)+%)=VRWcOses~yuihgi_j{v|s>OI#0,@EG\U<3`soz{&,5+*# $'<B@W\RF<4/-9B<IbakwhR[E,9892BS8?MALVELG1A0!  "*&"23F* #$849:  %/5;PbZSN73OaG=   %7@E# -57/,+  - &39 ./ ! $"%3.$ " %!-9@Ukyp^C2A/NB(6;.7?(!  48=! $<(ICOP^RS^ZmocdbnjTb_dgET`[S><! wuqh^UjgMI>PkFAJHef~)+ 2-;VDLJ;>,!$)+%)=VRWcOses~yuihgi_j{v|s>OI#0,@EG\U<3`soz{&,5+*# $'<B@W\RF<4/-9B<IbakwhR[E,9892BS8?MALVELG1A0!  "*&"23F* #$849:  %/5;PbZSN73OaG=   %7@E# -57/,+  - &39 ./ ! $"%3.$ " %!-9@Ukyp^C2A/NB(6;.7?(!  48=! $<(  ? 6'(38?AWcOd\6)#$(&EA3F5*<<41% ! "#21$   $    *9)/<  +#  ,$ ()G$' 5($1+LC>0?O<1"=>,+/; "'   # . *?*BG,7,*,9+@AA:/7$%9=JB))36>%2LJ:$ 86-2"COLMGT]8/>."01'CS),B@JJ<GLQNRK@@7[{llcB5F;$   ,/$"0=.2;;6.5- H<A[ttJBEAawq\;$   6.# %,+- 3&%%# 7/ vbSh~27  !*9fyvagYZqn]=+!/PScdLS<",99)'68?]`bsp}fdqi}s~~hLGVG-oi\."591(( 6&(F5Mfw*+>W`msw    zMVY<-z~uy{cbfOY_C@A4=/,FHHJ^}yhlvbbkzlXkupwwvkin )VMGf)-7HVlkX,C3gTH@8B6 !%<FHGFBUG"#ukC_ w9~$Dk0j&R8]'':Vh~  *E29R>0' uoQB#  xpnH6>31) \E;$ sqbYeW[ndIMeWj DWP_ !Kat~zl[ORV?Q\@K_QC0 z $+&',:6-&$$$&#&;6662:& '1=E70AH]s|}~deZILhreM@0&!    ' :. " #4 +. 4F.)$   991:(,&$),-(3OE!3#  &%>7$"86/'2?:8+8,/ !;71.6,   (020%0350)6)-;(%88CF) % #    &'      $  )$    $,          $  ",1&      !         .&# &  %$ '"-$"    $     "           #% ' #  "!'  "!'  ''+)          $1%"1"+1"#     !%!'%0  (!"'& &       459*+/ !   %    &$ +'%    -;.#.+"     ! $  "(+3<<82+# +<JOT`I*!! %    '3<6AQ`S716A,+0*>K1'#5ICA>:3(   $$  $  .%?CIC5 %2MPTI11H(+.gH/r<5dbM|ysm'+/2 %/;|H) Ui`vS|sOBy7rQ@ 1%0Z@=8f?33gv~*N*`{'f3 t ^'3cD5r]yO9d. cv\U,{P,PkWuQjG7V+[/&(}RkCg,/xS6g]t8j1 ziku{jvXnW     8 )k (  (  M Z8|L/fIxpkOu:r`@Nt:ZgV9,< ,@ H Lc l ]0We' p D 8 = 8 M Hg>j,D`|u+1 ` ~rqm{@7)X IC:xJmk Z Wl= #F N= g 'lM|ZA.@ LgbeTq;HP*ex2.{eC. A # p g 6 P D Gcf/B.>yObF8Yemtfx &F;Pe.a(  G v r j f  e I \* JC.cSTa',Xod,qqoCb{~neyY tf 8rc5suxYpF  t Z  F <  k:\  #u=`64%<MDX`Mm34 %TT +^C,?mR`= [ 1F W 3k Xj D#56ltA<#x@OkQo[^d >q"*ghX&IJ0 b y E 0 $1 V]  -dmwa`Z '>}rO{TfEyi2&[%MdzU|>#piq)M J  z : # }LR Iymug'D"U_O:  WWF[]eYt_ VCdF(RT0jCY T b  W T,Pw $7 *-IZ.A4j$jWIL] p=wEnse&6gCaNGk`EWv  Y N = zE'4#|ZO H  (p(G  ~ <   F  h  Ek )}e^S: )<&nn xgCe6\ D!Du".5Fk"v{1Q3unr!0"i6tcT.9Z&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9dz P`sIO6.ZCMX`+wm]Wk3f ltxYq-Ge\ X G s  M  - V3Kmvn(t7G 5)]ChVaxU2u; hP&Z9P3- "YAYR# M k ^ / ~  w K KA<8m"vy*CW60]}^hq"O+wFmXkc79 43GB9_\Di{%pVm1rwSfy` 9 ; E ( C 8  ; w f]E$VI~C!tXH8k-,#rC$:HELWIeV; pKLmC$ e  0 ' w # a   23t.b{Zfy F7Na?:cz.  U.!bC5pow G~hQp $%(j sGK $  2 R F W 2 x !,8\Z;t7 Em|gg?@A w U064zky:$~\\tn@3Yi}!Pwj#{  P L  = l &$q-l}oDq>[GZwBD<E#iw N"]?D"L2 tAm!^ 6  i 0  8 -"c'uwls=Q^ fhL~`Kmkf&vwY2LYO1Ygj$]N D m S  RQUBp'w=in@mXTfb =A1cyh BE> vtn:GOpoi `c)}SfW , u 3mp  (31^"y'Fu`aU &=q\X @@&Y@ [cSE1Sp@n~EFc R  D|p0F U nL6GN)m?~nl7:/0 8sutd n$-=[2nhI7XS1QU$5cd  { Y&p: JQPn> |(Dz:G 1{ U'H7)b fWk[V#V\/u}dV"x  X 6  ~ Z (,*QxH!m[=0evGj!X<YH C7fOlL4-iZ$iSNDq;07  5WoK[# _6<;9p'0I5v\6I[eT)}t y_}r!B@TG( s&[ n 'w2 E C+zpW__Ej,iAq-U jp DzW,MD1NoR(+ _GZ[) `( q S . U, v t4/*~Og moiiR,F"*% LZ:y/  8"(dltGRG 3 R  P ; g   0 %  h_I[!zMU69WZw.?|<(J@ZK="s34)Hco=jiE&ON3  % H g d (   b>D 4Fz+&[I_s*`O6|qDY YU~n^9H[ljO ]ql$% 6fsi x  n / Q, uGBST D;e"=^w`>i|q.?k!QQ<\#8_"n!Vyv6P22PHz1XsxQ|yb Y L ~ ?s ~ -z  iE R8 %HiL&/QsaJ\E82 sCN:S3)>Cz 8 F _ I t u d $ g&H;3= =/Ecv@* `z'-$T9E%O ;&-n4tO ? 0 F G Z/ X 39v^5[jd; ]`o/h|i{f2Ju[MNC  7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7'        "$,*+6-09.26+-10.*/( (%"   !     ,)%.-19, $)#-     ((>5 /-(--! !  !( -#&#     " ! )+*#(,3?87;+&-))024-%%      )154#&5034+%  )471,4DFNUJHSW^]P^bZekv~~|y]^^[`J951'      $!&) ):GF621(%(,+.869:((837D8,4>6+&!   !/2.-%"%" "0:/%%)77)+,(' '( $& $"$ (.8KEJ? "( 7;+=RQL1@M$#,00# )AU* "'2-   !9J\Q5>NCKlL.2@YH*8<)25 6X=XW$, >KC  x*tcmi~*8*Kyq ZA%ZH}{o98%![fI/HXKq~ !!Xf<[_CG[v:!{ G\wh~W*,A:FKdMm_w:d\V/f#, WHxbI-"<M' NB^4rkup2 4 u}sCF40 E  vvZ?5bG~wc6HkY 0Dpb v  = Vu_Rv, f&9I= Rv)`  Xj B  7 m k 4W"YXZJ^VxgTgz1x'rap*  - ]  5   59ۦ2W-@SC0'"`ZbnO p e] *Td5O`9Xk\Ph1}v - '3|# HCp pjyW|1 *<oLtv6?I"MY&s@] _i;<4,g &  \ :W4 L} i_Sލ38 po|% ~"+La|:bc| GKn> q u 664*]W F  $IO-^^ 9dB{PlB ]{40 eR_s%4~< YM +yVQ8n{81e{ > H 2N= 5`o" 84rB|s^LP!HM-H%p_k f  G ~ )){, 'jA A,rjSs% aJB7&L7xIb+a LUXL0lCj;ER"@vP Q\ D2 r { E @kLmP _]hr!6"^n@+%*k{KdV+Da3PcM*y)-@>W;;mTA;9 dc-R 1 gfJ/ +(]Z;FOMN7 3Tz 9hy40-oyj^8*m7,wf 0 rr uFS@0b  n8P SAxflf }u(DJ\I'om;+%=5HPCyh n  , z W*  x)  Vz57 %lxr44eioJZVME$P4-'<)k?AN{RWni  )h7} RV&[85 t R;BNw:S%Z;:4[)!pW-> "oo  L p 2AV):Uy!SbY[)+nXJj#CS$~N4NzEwj,>Rs;IQl<bfw!nhjv I M   , /m'oz/j C2~0;s7LNN 7G H$~A'WX0aOzFm I j Z o  y OX_] E v~G!sUzx{7ayqsJgG.y-C,-C dZT*|l7)&+u w m?d:L p |&ly)*[ 'mZ%LE]FwPAx'_;7-E$[} W < L J YI k?p{}/wYl[D5#NSCq  mClH % ] 0  Z  F W YvTN6S_i.&^H0o/J9t,z!<AGJFG|22]M p ( + & h  [ n 8P Lf1JR1? yHAv6 2g&N4$N{y |_fezt2R\M!  ` Z H , } ' b0CoTyS[ mmj E/Le:k1?G cd6n^QN9r^z a / _ 0 g ;  !P6Hv +}n8kSMjz2XM8UG)=*}^ \(-7 0 Y n  W O H ` W  *>d+i*-UAOODZ;(01/>=^>WIO;=pT;/;yX _ o [ K = Y B w8hjR\F[V;!-2(8iy%r%"o& ]O(#Lt)z?[ \ ^ c V 7 ) W]9w6,EX qLYO4DfVQY =''R1^ ap70 -_P; p 7 q z } ~ * T < > ' l w F Ij @y%5*9Y&oq}rlef-e,:yyw'7 Zbr P B C Z G b @ ^  d|gv;=x@LjA>S aAXrqyB*x=emeX> S    # l ' 8 o f ? b@+ +dI1d  '.0mQrg>V!RPe J"\kI8l\IZ| O ? P 8 X  4 p C - 9 ObFyX\d`~{se?90kx8Qpn1yCr]3D^u~L[UD d  ; w %  w [ PLUOXFF ; vX,}"(cILq647{:=o8S p & a s E - o I HNgr6VwttIzD0lV-]Hhs1.d%[qrd1w]B#!({-   C \ ; "  / U fn SS[2] DOVR[6Cl$Z_9: I^ $VWS[{ E  K $ 6 0`. L %b|k$E   H L b Z Y  4 i* e?RpRwz }bT91a<Ro_=8@v94Iu}  ^ izwRG \ fI#G\W p ; ~ ]OmLIK)lBIdk7JwEX{ `lVazT!g^f($!bww`Yw&9 v0Y@c YJ,~ a 4 K UU_(FzN49jNC Pr}x[bq6xyd4ZGE"g)TAc6  ar)\#7 > o g  YbtD%:*uNq`1}0$3!zi.~D)T\!g[ITf(1f"F[P{C  G&.fF|? ( ~ w  yD%%LhZF>S{/YT+Ei3'* =Dj;%3b/ZA(2 4.o n + T o & `Gv H Y v (;t A:b/ORJd[ =W#BItcWO 7n28Xw=X3 WNG=+V/RQl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/-+.!    !.13. "+#    !$*/-      ! "      */64' #%$    %  %062-(  !5=<4,     6A=-*4971 "( %151 "+1,! #)# )#" $"!  $5=;;5& %9AA@=6, %*(.79;5,...* -<@>=3    %@LKA4$  7NRNE6.% %+2:=<4% ")! &((  .73-!     &$ !! 1<?5(    !! $'#*0.  #% $*)" #0( )-'  "# "03-"5AD7$  "3BMND2 $6KPG5 3=4 *-!):B<.  $-& $18>9. 1.+40$ %464.&   '9@9  =JD2#  DTC! $581#.:'IM.&3&8MZE !(VjZ*1^-+ !! BnpR717;. 03:B3 "0% $&>HE5 9,>O`~oB"+' 1FJ9"Sy~X 4/|%Yb& 31"! D7(NvmDTO0NH KOtho4lhB #Cl\lC Ua]^K&jr%MS(  %>`Y@J`Q"0cTWssqY;5, &3,'!" 6LnfRNA$;N:v =c_..120(F:!x(bI<9!9 /# 02KM2d4*7/Opi3G.#>5   ,;Wj:jq5+(-70|<WX3&_dE@TH*..* &!+SH374")CIQ]bu[mM,3 ?hB I|q;w'7: .7RUat!.JIK< %NO"*Z2Jre# 9 \DTT>L;PIX.Opkzem@2$<Y= >Y8 +3502) 4S_B  !QDb\z -+Kwfjj$  1+ "%+' &!'GH*sBJEHPglzGk.@: 28 xe>Xx> 'E71BT)  # $5 7iwjV:rXd Tchw?0g`o9^kFXe\$ .?FhjZZ_.iUtR(-MUXmwA&&3' :f> GF( l%E$$ %IT5/nq+0,Z[ CsFo4] PhF*-2*&5>,5UE,& 8B?bC2G) 6H( PF- yfEs  Dl^HGE -+RH&04=/OhL/-58. -^'50@bgarn>5fohzufmi\XR;&#3OaknaG6/;(R .@?!e VbN?02[(K{o^fwydZf}hPMXa`b|N, \jM$ 3Z ,0 e@7;W}Z;M:5" 7W]TXTFPetz{}~td]hmvV++[zz\8i 9u,5gv`YMH`@:0=STFFT\`q}xxygly{tC :LPJB*P&'=aiD%)\gJBBMw,;>DG;12?Qag`ZboiHAAQ~^-6SUMI:(''xr}{VM]maC3('K}'.+S^TONQakhlww`HA>B^X(4]qndWPKHC:37;85._KIGKcxy|~kD2+ -Rl|)O_J'#9@HON[ryqjrvsm`RQWXcylO$3<;<>?=CJFIOF6&ulvzbVQLJJTi~y(=^~xsrtx{eXMFGLRSD*yehrx{eav"Qv}dPA4*/ATi}dWUTTO@1% cPRb|7HWhuuh]TI5#"AddTB7DYahkaUM;ua`n.6,%29DVU=" -4561'$&-76+"!&(/60&$20" )>OL;." /ET^gnqompk_PJLLJMNE7/  *=ELUROQI9-($"$%)04:>?;-        ! !'3=>4$   $*,, +250+*&'-9;+      (.9GR\^YTMC>@@:<BGKKLNYeou~~}zj^[^`_`gcT>"x]E, !'08=@;* #0DR`orsz-DVckr|&2;A?3%|N'y]> !>Qj 5D[q|cgcI?'tqsd[RTfjdjrknmfnil|uxs[JLSGV__x7%#!('  1B&%-,5 8$3Y/!s,Y#XC:F'%'AD`zpdNn5u,*{{~lSB}c(](2?o{}1{Pn *O:_z N:u< k-9/iwlpL>}>vs72x)>qE@B&UmzZvt63EX56 lnqi9h;9kh uLNiMP*4ua<vgY+WH5Z^6|D pKNvyuVR,k !Byd72nYcNAUwdGtjj+Ld*k t8 ?:;?i+xQ%zW +XZYtm ^^u&nxd$N$j8rz_1TGt! z.p7MG a( K!;[SOxr%j=  c , ? G C  { C%:43;ZQC,TX-?q?q+pR[%Id3d93+ doHw u1+_N7aG# ; 8]d`.yi JxW{q;f7&ublv j(74oo}$ &XBH] D- E v}\=$r+&,e v?m7Mc}nJAOn wz Nl5b x/q6QDs=CQ!, 4M"N=k0oBqi >mo!RT7G6ZC|w ;a P&1 uU?nz]sa|,D'V0BY-FB MCXd { LR6 -t z%BxyW\^3,)c.   h [ } x f d  c E z $k@&b1*`(ewjl:l}w;X g:7  "yEj(1"w~'r+t2LAB#@r5    c / K1 l / 9 A  ?UDn&(a_l7pNg[)hA]nRvTy P)3l.>nvYi?5Oe%\#'%Cv=3 l $ Y g   B ) r 3 C~>]kE+MRM hnC*w[ pnC" zp4B6O?o B7 "l.q^ANm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#efQ"W8 P`j'(<U{2AsI@/<a}nWR1`&th2BW!%_.c-`x_o{yqK 3  QYve " l%BMqHYNEGe1YFz1Z]k+8j5 : DdYoELi 6 j.jqEg,SxlU5Xbt[>ny]>C{n .7 R`%nk&yN/+D>YU\_}TY[&R31r9YN@c) mBl#,1/ Cc#RC%q8 &""]`bDszt$pN*XZaaQJLTSz<_K&Z  b0hyWuG-9S,=zph{rW}2L3 5nz "#[*|4#Q!{1@<`2*kO3 j 9     ^ : X xz]9l Ac]m eN:ey+LPYdo^oz(x'o$\,[<  :S @ G & 9  <0':C[Av{`$,\EIFhghT` aUo>&   L T\_ WVZ x  V d'  uk>vk7: ;k8=fgz4* %3tF T.= =   N5&Wei O   ry s [ _rj\. $Wpg&1x( 4A#F:bwh(tl;t']; ~ 6wert5 .& z }   $  R ~ 3JJ 4 e^hqK MTFX_fS< 72Y5=3[Q(Kn[2s&Gp'uM HABEf n  r  N  P  BTPdY( d 1+K /qfrAMz0C{MP{U2SKga*}zi F   1  b Y $ m  3 % RizSyp9 q H{ !  BD!P%Y(*+*l(`$k aLrOEMۼljӞвΙ[д׺M.G = ) m fkKI' q   h / _CG\%,%P%fkg]RG<1'C 4=֐Գ( FӿӴGܧKsFUhhKB{=Gr@s#I L : > Z ~ i @ { { A RExY*>4su2v ~A70-  &FMAYf'6d 3Y;rHF<YfeS7n1|B Pdg *+Ao '12+?m !Kixw'Qx'FgpuzwP* |[w8%whb?5-td02CG0pCT%` jFT ( B e /yi #j%1c//+b1s !x 1Lv  8sm +"0i%{yA<ߜތޘߘRNGbgn~ln hsb2* o. -?D4 g.M,+w B: J a*r+ҔΰֻF} 4 D WW 5)2-u(gb~r1b0 }#%$T"" ]  D P[.Nuީ.:-y&.$lؾڊ%lu+owxjJ-\|qGG+G"ܱ!AK ?,m9$ ͑R(5%'%Z/._ Yh94j  qg# mo * [O +K,#%p z=7o5*$nZ} R (C$$ 3T}C#3Cp0*2=|Կԣў|.Зֿ0uZ> #4rAvHVF,;+! !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BBZWq'7<$YEyD?{@<G@B^AKLv&zq/z{~Vc]0W[p % J { y g ' TPd 3WMG,8<&|=Zgr>`}A+e`OP402XgT1h`JJuInF =NpB ` X W  } P S > |  X PN_w1q;bu o+h[$E,XGgp7 0ha[L&v1$" Z4J48Yhce8t%n%lnr&vlq[slV[C7u#Iaj YljBm,HbE;uK9kf./U>gkDBi&=z~; c 1 u ; P q=7bJq M^ h+7xU?3'Pnm.  D{9d$Pz 7. xVRspjO?I ec!=ts   3 E  [  U  {  g 7i"=ted\3nJ3yR`b 1U: M?VfST_T`4UB!7(Em#L7y15k x ; ~ f l | 8 Y { x m ,  ]a2?'GAwQw@2T#=)PtG$? @l > 9  16>-C5|IZ(2tcDqE xQFFZ([jyj    Q [ z ( h iE$\M*w%o@>%D'or1oB]DLb)B+TO8Yog~ 2  5 -=+M  JsG.lH*X ;UIya+vz'@ CLw9pZF}!"03 _RVYuJRG8K p R 9=h D \ F8~\F6<0m` dZm~0 J D , TC]<k%RFV`m\\O|,R|V 6 [ q \ z mx^_j |` lMWJ<5~D=MFPCRnP  3 Ahaq{$xL!#r\p Q>!$w`  E ^ 1A%cM #!Up. )z:|bc\[o _ x ]VKU+0XpRD I * I o u ^y Y)# W ~D{ 6R #A?qvf % {  <|k:](-v1Ed{~ ~?H#:{ m s  b vN-4  PsJQ*PGOXVKAn  K ^ g lJXYT OU9Qjn-9qomm2k$Bv n  MG^xjbUiMq d( tI}MOhQ?rIeym%(v Q ) v\xA[dc;Xm|MY$ (a_($b"i` 0z $GC'  # R2*v..BB cG`X^E"  , O  @45k;O7T28WV 5 (Y>9KLN B >6v*eOn<$S"Gr0jD ,Xe z=}wQgm(2Q OR2  p h  u \ 6 l X ] EZ 6o*zSWZII5N] R T S ^'  \ b.'`, 1.v(&*^S S  WjpUq"  ,.K4cVJ!cP[W&2L k e & a|&p6qQHTr:FoB()~_L C &`q& ?W ,H5,AyK/8: ^~9; @`Z_ 'IG5C:ppTa  Z # M L}aqf^[yd`SClKWsXJ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! "!   !!%,-1.+++()04114224.$!#             ##!$%''$ #$$'++($"%&'%"    $&$&(**'&#"!!')))(%!"#"!   $)-/+(   $(#     %372)"   &1<@C?2&!&(#'/4651( ~~| !&.7AJT\]`gge`VMIA5) "#%%),.049CF@7+ ".=GMQRSPB3& *Hbt|vgP;5778<ELMB,~~q_K:2#(5BRau#2BPVZZTLIFHS`ooM%`(2[.Hh@e}hQ1^%s?nL'e7 Ej(ln?A 3JQD(OK b5Gx~@fE0#vX; :Xv  "4>BABA=2"  #?^}-:CGA:. a@zj]N=.!+9AKTTK<,"#*8Op":KZb_RA318Ga/EZfpx}Y5eL0 p@eRE>87;?ABCKWer+Pq+=HS_iqz{z}p:mE'{vx} *9GVl)>KWbjmptreZN@0"  !,6:7/#"),)# "*0562-,+*'! )2=FORNG9)(/36970)#     %18=>;6-$    (.4893$ $(+,./+%      !!%()&#               #*18>;4)           #&%"            !#!             (*..+!)     *#   !  18!H/; 1*! 1. KXP wTcEkmB*:VuRem5#/ LkFv4Jm*@e6"6wwq!g3kYp\s \;nj @I>/=H; ^l^E! JgUhVw"?}pwx572s_ONQGObp `NO4J'CW@1-2h` 6Erp0E`6W,we5 # n1yUyunMmD7{!8z3E2~'w' z}Hi>-^~n_-0;n\|HWfG1G?IFREieSPqrXdue9,mq?0L1?*}d)U_n-z7{ TdM&c?${?vXl8kDY8@ ghR?w 9<TF5/q [^xvQ,,2huk3>ZjMCg 3"h1pE/pU|KQ|' Y18 ^kW|LT#%q]tF} / \hkEpOD< E: 'vB/&e5Fn  '1&L.N!~\9L)r`Dxrov | & !  C _&<JkIB s G\^;p({ KP \C sa"L`BKa=,)*YK~=a!t' H s  3 uJQdZ.uP >  [ ~=k<"<> u2x~,"P>D32*{)h(#!-U 1Z|y5S dVWhjA$.z;q+GTSmUJ9Ox: ) sAU7vL1l<c9Zh$v>w<Kms6/|>q }v\5K(R " zTdZLVc"E<[!F*z%!X$1NIOEp8bk7$ 1-E_ c | O + {  a wz0X`j?xOGP%DJ^FgfR,LI#+\!=Fe|]_s@\da1Za+rJWK9 HVF|wo?d}ACqL r  ] : g A  r tj]Y*L3HF/.eWeO6 D v b0clQ RZ^kua,,4J  ; "  o E .S>|TE2eW<4K@N`X#a G$jdq~*tjb8F O 3P+ - N m  = c . 3 4 p%%Jh$ 0p=@Z3mTIGGv:5BfN k /? ~1h$ZF9bJ;Mx N E  HisNWP@J??=>U}\3[L_`QtJ  IdNuC"MH]] c3gb0 W @ s      $ b?AcX@d n-|)A*JO!v^Wpmnx\$aZUpz>uZ^& WC:;"x]e35wG^x 9 @ w <<kX;V5bl0Vk H\%=xD"yc' 'O.2MW{ VAIenVhuA6*j> > ! 8  + p O   8 /={b__Z@7g{ ;9BW  >PL%(|@DD)*y3j-([   z o  ] a  /x[M_:G >3U`"R;!;E/B%KG``6 n2x(tggOF` n < s .V L A  K<`:D4WY0yqQn'WvzZ+TL -kr|rm0v@*tO K / y  \ <aB / Wl' 63#=;K zREfk#t]^ M d(d;_T*9vZ4=7t 2 a d   7 - &  $"2$ Y;;]*(y fXC!H\q- 4 ;)i"_,"^\DoI1@UW;B  u d L Q"q M y: ^9@ >$<Z3$QUs>cocb^%?nf_?0=r\|IuC`yn 1 5  ;   0Ft w Xd * F q8!Y^2`~:aWn N!  u%<0 yv| H E %Wl] MQC r!RpRGLy[a3EW"UVMP@!V2^)]9yt3KoR P j O 1 b  + Z4Z@u)N!7]j7h2d2/ =Xi;ysoCUs>.r  I  lbK-:T  |} +zKW@If"s"UZ { . r"HR2 ) -Iq+~aQ- Y}?U!fMmm7jR`~E-NmU4G%q8qt n # q J4*gT.MbO _pwFoQn9/z* ?XPr{  VA#2*)87'~|=;W1/z7u3Z98&   `s>((G2I ey~H {x=2:pTi_7 L0Y[9#(.'%%9\CyK>.I F , -Q|T% 7=A_o/:2 :S;"w>GS;hYu#Dv78V0.`dy">@fL5 9 NTa @ 9Ay t[mWrLiTN@CK#r Q"^V.NCH}, :AA^zcQ  j_/R| uL(9Q@J=693[/sl.+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1"%4ia-5c[3),7&  6%$7&. '% -4256 <#E;!"6 Sa9%a5b 3[<%I Tl^- tKVd#E"tp49662mxO-UhBiH(Ew!t4D:u< F DN58(uZ(8,9#;}+S`t Cr\5xMIPxc(%P][yNq .DYE94&aclTqrf.$i J=Jo. -_yXKr ./*Ea`f3~'wnW|+6o|ep#&_F9,[ * s d  nw  o ) -  )T~}fJ YOhG'$z-!6O+? < T  hnq|iBK N N A   4 Y L  B  j # 4~I(5\j1|SAZVj]tn9[Ge5E j m0Cy~,#@  u}T[o4 08}i'/Y8 I2tyw-1b,$FUltZvGD ~ d i,r b?$Sh {] ~7'-u?d 8Vyvl .b<D[;!@t?zzpAuv   O 1 Hm! M,^.zO2b3!$z*-T;B;YK~Y HCm1`#!@aH.3zg{A "  T ` T g H?% H @Fs2M@$Q P8$5U,e`%qSG _/>)1`-l# q : Z   o 5  ,MwY/|z y6X1 A}sro$HJV;<"qQw;Ed"d_ t z K ' * 8 v .N!6 _TYBy$=}sp_PkgS[vjRP.\ljoM}H'dtnVv  >  {O?1 v`5 ;usE?&%A!c= ~E)dz#wOO ) >| C? Y D   :U,v>r&:|A)X5=708<c7=>+BETuJ'O  M f ` &WGT ( ! z) ;3&0cE4[w'\Vdr Ha[c0KKWXZW 3 w   %%g9FO>"??8O6cz^:Ty*H=Dm)_}h ;kN. E 1 k l 2 (` 2  as @[=S4 dm)E vt`{G",^jBiom||JY4k:pf'TID'Pn< B v O & j6. x  @YN0U%D4 Wk>l7qI*p.pu'hNw1 Q 9 K 14vF*-a;!la<,$]n:5K{Ox!WY9 =Z%K1w Zayjt < p  8 | A H ( !56# Ba5J@hKTlI uayn.:>%% SS'!\xoO\v.vFwJ5`i@ # " t <J6H`vu&.oH)hCLsQ8?zVrH_5\}%%*=;(2r_Cw9hM( 9 h ? g 8 RXV ' _7;Qee[,]dg\W)>+O* T 2 SW4*kZb*= `j"U#b ? n:j~K t S   T %   zނ: -ZT C # tY19{cgeM F ]  7/#tSkx25 % <  5Fg[H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  RcCn x.='#I:18][  ueF/.8KqU nmMiqIhY ;\Z%<B? "h~IY6]z4M9^'^n4\oN{ -]&]gxF.v!t)c(A\%r +T_QSSr ',1]P%"cld!S(FDC&edg}p6 K`#@iiF]=]Qb%] #r] 2RYkIASp\kW:sMznZ^nV+q 8P{ +!  t^}wFW> )]z&`/jR<m &ATN`hd&(  %n)(QwB #$!?njT:`sxD [5hd*(s%=e1}ST[$`c q%8Y}hh^\X]R &+TacE5iwx(KxJz2# IaZuq8wR5(lU*KeWen{wyzY5W/ !0k|yS590T-{B~ovknxHs%'$"./$*(8+,0F^tB\e}mI$ wkVK:$)1r&!fdl Ux09\MhiJ1\^8O2@sppP.;_tI]FL_w  =Kh<-OMKice i'hSdz=}p? `_~HU#wL%,Fi*L{'`< 6FF'-LT\aP8-$:QqC\p`@iR0 5v1lU3%*=m V-K /iu4Z3r#BHp.[0bGJA(34 -Tx~E<Vey^LD4'6?<393 )E#-)jH7,fA) ",AVekd^RC3'8Oprcbhz%',,''  -=KXljhpu{J_:i c/&D9-6,tT%277SWXXRWYeqp;z?2a0e><(5H<,9FLJFJ>92! r5z/o= 1ee4  5Rb{3[ &,PppSK80&%- "ofsorule\ZTRYsBd ')?Sbg^dcejeQ8$ %0Sx.FLIN<(b9t0O&j9wAc?+%;Ix%]."#&  o@z9MxTcpKDMECCTae~ De!IwS} 4TU!d~-d10` f9!,884$",#&! ;bD-=m,]o=x#ai3 /Z,rW6\4@OhvwowmS80DPYXNEC<8=:0 fYPB>96( #1/()~Y>'|} 2EO^p *7EV_iwwrlcYTNA6.(   &),&  $%$& #$ !&/421:;8:>CCGB73)"     %1258:@A>?=<DGKVajpqxnhkgjg___YNJMG>2%  ')0*(( "'8<CILKKHJMIPRKFDFC=A@><4,&       "#"              $ '%"&$       !/:"     %   !  &56 2&%5051)0  3?@(& -?h=/L+SW]N FS/z GB38j|U#8HoHj[F.v720 @4NJ&`VUA9\#ln3 |uGYIy0TclBa=q]h$"qEG1 kVLw 7R\plwis$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%3;79< DC4   " , /NA '&   $* '-2'4 $'  )+5)  %15 9*9M2  ?'.0 6,MM 5N6#/ !>#  !& DK8zl5-I6f/,E4 0M. .,>EJ%)*GN?Axl|( #^/E')UQmX 384:a<#$%2B5c=(n;)#.R=,*.@ZE#+ ) DA'(|,yey%qxwo7M%FTH/&&4 N6   MS3mk< 4M8 588DE$'2KU=N4//(%%<5y5<>W~-p]O7mb) g :.G[3$X908!5,B0L "# !40)-)% \b+ * #2) (od!6' /!"  5) 1-1$  &3!)'  : ("%(  " &TP!##" &   ##  7' *) ! )   !$    %  !        !&*($                                       !!!   !(.4BMPTbv}#'.=NTPVeldY]d[C30' _A#X*]Bg[QE:6Thb-vq0A<N\h,VDHr)h-`"+& !'>eT[+>`hz#Wglm|yvq4Cyq_By9&K%\%\L|np8=0F1 <d g!Fi<O]\V-*iWdTxwrip~DIU> K0L_69K;fp[Wm% 2 a#,` ["5T7@_QoI[0muPoMX;\Dt-,(C$ Z :`Cxieh{MpPVRrG['!x= yo _wMX0/B nQyTEry}*Ma  8/1x MV | ^[6=R@B4$SH(EH]:{;t|1RgOk1o%G>* C0Q"H=A@ ~i#b<&_L;f+{T P;2F9)~M4C?O ^< Y;)$QU6mU1|,7iR2 Tn`h296`]JS6/JS%'@@R#9[[EewV7i) 6+5 uG=O'S*cv >=RwlF3 :3fxrp%}g]eT&[O ( 5/:N<%9QVB[gn93D6/&A/?0c"f7R=t=S"b,DnbxKh9p1bJbl<(i' kz1;G |W [G/9+NR,+]:3'T_1Bi?;e3aODW b5Lwm;i@'lJmg7&EG~#80 Jw~OBVYZf^9w?' md 3h?ygGReh =L?}D$b } b%.U'F\ =S@`Ryyxn)[9<|8Wd v8/mEBOR$#k.x5n02%}P_*]YI`B>PK"V_lVS1S\Rr [~!ezN0dO*/Md`3 Wk1E/ Eck7 !X[P[}?wpuj|xmLWOXlZr~tYquz"R|@+GLWs|xr|=M7H`A4<HCDGD[f^dfjp[H;&%/!9[e[s\[jcD & " &//#{~}ldadbl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isVzNvX-n,{:uQviC<8jY(eC4eFM'_R,NR6,,,V"!n20'.UWSmD\sG D(Cg.cb[%i|ljkW8 C# b1s, WI 3:$$T1C- Ba`C>SeY/^I4 a>P!SRa:M! %Y6yN Ht'mX3n ".695(':7+  zV9{P::9878J`_VRLS_t1AS]H+UY&\=uy1v&z{O+:VUJ0uR/}q{~vjfo{ 'Dj'61*(& (?[f]SKE>2+5822( ):@CKSY`l $" {obK4t_M=0" )3A\yzwrg]UG:14EOT[[X_chrv+@\t0?NUUXfs}~~wfM0Z5lM.(>[WR*/'oC]6 f8tjS6%"')*,2::8;DKSVQPSSOIF@::0# %2=>ACAB<;:36:99<;<EHB?;:5+'!#$(,03453.)&!!  !!$*.2/.21.+'*+&%&$&+,05;>BGE?DHB>;;84218;744466/+)+,&"  $'/352/230/-)*(%$'+-15521/-0.*++('#"$'(%&(')'         ##   !" !%$#"   %%%'('&&##&&$$$        *.,.,&'+0.'     ! $'& !-10-% %)$  '%  %+           #*%    -2-8-/.$  (# !*  %4!4<#  " "      " .5+-. 8) %%'270 .).ECGT)  ";)  "67/WeQ 1,39$'6E? $4 - 6IWC!&BI-2 1NF #/ B<  4Q6 /xXNmR40!-%#!,Anl='<*&n{nNA3% &4{y9eVF"E3+KBdfe>.30vp<@ +( 1'0bqH.#bt 21 *0)+V]^J `K$,-;L'0((-# #A`b]wkO5%-R/QV5<,- s@T*Zm[!t6kT\kT/ +"9\l)n:,,)~d c"TXa^5 KEqvaa Ripzj8T7D h$w!U w3uW:J/!%i&3Dl ;P" @`C0z\5!sy[VUtN >C0DBs?o#2 :@7hrZBqw4k'77[-   ,RW.AKC76w[5Hni3g$ c5'=3!48O|m7rjfp`Dk Iwtf !M]:6CP$sWr6x @( t@etm+KRx|Hil^g?}lDiZCa?]X~A\}6#)>\k]uc$ <4:')8+ /Z3 {]0Pq7qYek`J"]\I"b}Co$@6+Xx9f?"Vd H[- '-%sbF4Vk7"A*G6,>Q ~0~E/pZYdrQ:k>uB>!C?C"18%RXQ+)) /6    KD" 80-10   04)ZR&?VgR0 "' MW .Nff?E;w~ "!:;.6/4Q\5 .(BoZ! ( (FE= %:da7% 55 !0 3# ( *++&bcC):$-E@$ CM/'+  OS: (.3) # & &%""+:>>6/!@X\K<*-FR]T8<XjgO)4AE%  -.(   %    %,+'  !                                #,6>IW]`elxxha]XE- tY=(!#7Rfs Gf|>fP.` t5?lv{p\[MBe*`Py7+VA\gv Cxj5Y +Ppv\%*$I7`];K(Ie Ez%IIx+$ESs%sUj$wXk}2cA9UsrU\e*9v@7ClV"_iKcxwv LozjNrcxr$GDjF.P;Rs+ $`^]in $G>(u%gL;@!  =E:>Q>f-TOo]$IKY^rdH*]{A]1?Ac)m1<~2kd ~q K $ | ,S i2OAGvV(z,4p|#IFY^<EBS.'Ny(+R>m  *  v m s c  o; "4Z|u^kL p*f[l^T3w:Z_Pu4 ~Ao;M155;xcV pau- Z  z  V = V| v12;DO_]g_~r}_W&iLJ,}*{HM+N<  U 4   8  A> I5z  a .'mm/ igW}w8~g / V~OK>) sM'kV mXqqB(k_J\SD 0 > { ~ K t  z O f F S U-{Zx$gmod39HxpdHc$w)a]'UZu / e  $i [ _ u z )   '>K9AS#JM[_8g]pD2p;}f{6E@(~0  I  vfW !M   :  d ( rC7!Q;s4lM#mqLI`,OQ*:=K)23yd^ nZ? u k m  J ZmJy TFcJ4) T`^R-cp+o}PxtP]R  HkAA!"!Shn61hpL! Cz_7 8-%MzdT90'SB%a B! j 6 _ B  & 1 < > , h 5 7  L ^u6VxqlcB-0<ZloussoKLO#^pqFrOTz,I08L98`:DUN8mx7&L8z3>.)=]x_W.h<=CY}kaq}`i6U_6u0Gib0u[@\i p3WN*.Z7QTaa$CV fc#n'fOwh,,X=4 #  6 % Md +  S&0D2%aH@nkSUO B-")6--.*%3 DNa fGVikN,/nR7NO B! $5!SF|&'JqM1Zu|TM7;JJ;0ZNo$!]2^>|LZ?;!mvP-.7:c^fK9)    6 o F  @    { DW5pk|N4*I=DV7 !0 u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$FenCs=Vg3"Kt._.cBh @]t~jT7uO'h9mP1 3BUg{m_QD8-# ,;IUdv .:EUcr{trle_[SNHC>:861-)#}{wtsuz#)+,--**,-/36787530//-*&#  !"$$&*.159>CDFIMPTX\][ZXUNHC@@A?>?<951/,)&%#   %,2:AFIKIKIEDDEHHKMNNLLKIDA:61*$!  "$%&%'+-258:9765556787620.*)),./0/.+(#         #$#      ##                   #       "(!!15) 38-"*# '/)         $  !                                                             ')"                                                                        !"          "%+" ,2$ ,1")-!#    $#'! %                   " $   #% "            +.('48/ +,!  #(+*"!"                                                        =E.*BFA)3]X5<opYF7VhWIoD1KR[I:55M;$# #"tjrs_mXlx^T=1 Y Kj#Q[Ld^Qmvv; &AUdksP xTa0|dDw00QWY=[ 4_M=6w\"[()wm9LVjJF\A{<3MJ: [[X C<aP7a[_T }#j/V[&RP :y hd]8V[a `a+MOg T mV J^X1]B:4Q"! *26Iy *-=X]7n>?FVjRW r8#:LID'*C h4M=vF a"|eI dWw}ua gtl6XM9h6I#h\_Xw{<AH?o>S&:B.+4TZJv^$Y6xBv  \z l9_| u:2p4D0x&R^ #.&1s<'Fh\I'e@weF+0}+l  9   Yq-& = JF"2RP yKo](Xo&YU@mv EWtQkpqk= - _ 7{,E!44 Jdni8Ux>OlR(1X0}"H*!k8/nwF!{ ( a wdxy Tdir hcUJ*nb0;"6f*#`=-_:MoLmvZIvf h65C+H15 ;l! "  pF=w w.2Z7N=z}iq{EM ?$vl&:E a $g2 m  }Ez :*;pOdBD$o|WC,|lz\JMMFRJ~5SYNs44/H M : "`| = y{] #MApiUlhXW|:=w;%}K<%:ZJ% 9$-7\R-1$%Z49" }#i aG |4ZpYC< '7XwyM -gZu(oXh|5s$r ope${d ' 2 R Fj Bvq ~ h 8C`i_yU=U>Z:w0#/ q\T::&D!P0n\7:x0k}F [``M-bn~o  c! y  ~ =jN6g;Y'3|c?,8zG>.C[7!L{| UXfk l Y J  # | P ] C l5NpKbGs!z!#j=Y]jJ0 <9y{.p0E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}scQ>,zk]OC7.'!"%*07AJU^k{ !!   (3?JS]goyum`RG<4,!!!&(*+-22//.0/.-+-,&!     #%*,,.3643584321210.-.-+(*))*()))%"$%"!   !%&%&&'++-./002222//.-*&%$     "!  #%&(()**+*++,,*)'$#"!                                !     # &5)79!98/1-6( )6("  ! ' $,.)"   5B+ 0( %&  )3     >J!,XN/ -A-.D@#6%.1$! </0: & )? .' - 0 "/%,!)B( /  ; &!-  JK /)  #'$  &)7$ $1 N@-:5.Ed/  )' :.,/:+ #A;  !$28+?3   / 1&2&5>'<X3  #) -0 /0 2+  (@* .0D-."#1      +       >. (5  +    ) !* * ##      " +,)  "   ,    !9C= &0=+ 4;1- @,!'$$5 (eR|>m>(3.+ B"D:E& 0&3#   " &+( "4EUJ <1&+ %&'K4!(#' &" #)  ( (F*4 #*(     5"4          & ,     $                                                                          4 !$4  "/F? 2?:" B'6P*RH!-D5 /FdvI 0J=1KR,NlM)-#Ux[r!,(>]Dqlu:1K"lk C@!mm5ZZ^Ay_!i?iQ*" 2^RhvUdPQTSG9 ):8#160$EV)0A -!6!3.Gh4s~ BUR6awEru? 6ws9$. Em=7 [$[I@hJ08vP/]xK>@>[TixxK9`0)[{2"0x5"SG#"n9&h(&Phf,Mt WMHL%Akcy4u^6D^;65 [e\+{G5Lr$C|N%;KIPH){<yc]n?wU :SJ"PD_imlCH@ &LevHUqa'1J14CF2  51 IS7=58bP/FE*">< &2!#83! /^]MiQ# #%;0@! DiQ# 8`jR53:sr@^F#'62 ?69N?'v %;JH)  %0?el969Oc .LVG* 08:^kL*,6!D9LtY==?31M`vsXL2 y_~ +* #CipW1-9AIP>5K8&UcdcyuM& "&3H0|s} 02  8OK7*( '7UmHMycKI0RixzgYI0# sP@Nd$ 7SYOVbf`W`aK0,AUetwN3%3DUmiO:0'#2N@ to|jPFSv 4Xb:7_xyfXH;Q{zphea]THFGDGMSTA9@C1AYU0&7>>EOVXWWYQLLXqnB.C^_I1$///) -9D8'>ScZH<- %-&'=JH?1$"1)&   $(%+49GTRF90/8:1/30',<GPQH</""2(0CCCON@99ES[afowwmswjcemswkO97@KOG=9,~or}zi^`a`[OKOS[gmhdbdijo <`nsqqytpxy|wow|qYPO<( yqh_erpheZPUVMECGFM^ijgfjpw%*1EMGGR_o|tg^g{y|m\SIFGHKE3rnghytcbabmyxxspxt{&5:5014:ITROW^\_lsx{vpjsz}{yskb]XVWXUTOG@2%    ( ".6<GMOPLGKQYZOLMJHLPRW^YUUMGA83009@951(!                                              $ !   "                       # ! (!  #-673/-(&!$''%! *8A;1&  0=GRSQPOJFEBBDCDIF@A>;:=??><6.'r[S[l *00$  2H\ktz{tjdabemv~vnf_acjrppi[H1 uhbk~hM606CYo{t++  Bbw{u}vjhoxpW:!i]WSW^htvlaO;*$+8BPfz~tls'/.-6BSaht|p`QD711(zqrple[VI5(  $2;>:102.,/6D[gq-BWm~zzr`M4|o`O;# $! !(5Memons ':=DUizu[Ekylin-cloud-ai-engine-plugin-1.1.0.1/test/CMakeLists.txt000066400000000000000000000015451520575453600227700ustar00rootroot00000000000000configure_file(16k_10.pcm ${CMAKE_CURRENT_BINARY_DIR}/16k_10.pcm COPYONLY) find_package(OpenSSL REQUIRED) include_directories(${CMAKE_SOURCE_DIR}) include_directories(${OPENSSL_INCLUDE_DIR}) add_executable(testspeechengine testspeechengine.cpp ) target_link_libraries(testspeechengine xunfei-engine-plugin ${OPENSSL_LIBRARIES} ) add_test(NAME testspeechengine COMMAND testspeechengine) include_directories(${CMAKE_SOURCE_DIR}) add_executable(testvisionengine testvisionengine.cpp ) target_link_libraries(testvisionengine xunfei-engine-plugin freeimage ${OPENSSL_LIBRARIES} ) add_test(NAME testvisionengine COMMAND testvisionengine) include_directories(${CMAKE_SOURCE_DIR}) add_executable(testnlpengine testnlpengine.cpp ) target_link_libraries(testnlpengine xunfei-engine-plugin ) add_test(NAME testnlpengine COMMAND testnlpengine)kylin-cloud-ai-engine-plugin-1.1.0.1/test/testnlpengine.cpp000066400000000000000000000041141520575453600236060ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include #include #include "xunfeiengine.h" void testNlp() { XunfeiAiEngine xunfeiAiEngine; auto engine = xunfeiAiEngine.createTextGenerationEngine(); const std::string configJson = u8R"({"appId":"fakeAppId", "apiKey":"fakeApiKey", "secretKey":"fakeSecretKey"})"; engine->setConfig(configJson); ai_engine::EngineError error; auto ret = engine->init(); std::cout << "init result: " << error.getMessage() << std::endl; assert(ret.success == true); engine->setTextGenerationResultCallback( [](ai_engine::gen_ai::nlp::TextGenerationResult result) -> void { std::cout << "chat result text: " << result.text << std::endl; std::cout << "char result error message: " << result.error.getMessage() << std::endl; }); const std::string message = R"( { "messages": [ { "role": "assistant", "content": "你是一个ai助手" }, { "role": "user", "content": "今天天气怎么样" } ] } )"; ret = engine->chat(message); std::cout << "chat result: " << error.getMessage() << std::endl; assert(ret.success == true); engine->destroy(); } int main(int argc, char *argv[]) { testNlp(); return 0; }kylin-cloud-ai-engine-plugin-1.1.0.1/test/testspeechengine.cpp000066400000000000000000000136101520575453600242650ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include #include #include #include #include #include #include #include #include "xunfeiengine.h" std::string base64Decode(const std::string &input) { BIO *bio{nullptr}; BIO *b64{nullptr}; char *buffer = new char[input.size()]; std::copy(input.begin(), input.end(), buffer); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new_mem_buf(buffer, static_cast(input.size())); bio = BIO_push(b64, bio); int decodedLength = BIO_read(bio, buffer, static_cast(input.size())); std::string result(buffer, decodedLength); BIO_free_all(bio); delete[] buffer; return result; } void writeBinaryDataToFile(const std::string &filename, const std::vector &data) { std::ofstream outputFile(filename, std::ios::out | std::ios::binary | std::ios::app); if (!outputFile.is_open()) { std::cerr << "Failed to open file for writing." << std::endl; return; } outputFile.write(data.data(), data.size()); if (!outputFile.good()) { std::cerr << "Error occurred while writing to file." << std::endl; } else { std::cout << "Binary data has been written to file: " << filename << std::endl; } outputFile.close(); } std::vector readAudioData(const std::string &filePath) { std::ifstream file(filePath, std::ios::binary); if (!file.is_open()) { std::cerr << "Failed to open file: " << filePath << std::endl; return {}; } file.seekg(0, std::ios::end); std::streampos fileSize = file.tellg(); file.seekg(0, std::ios::beg); std::vector audioData(fileSize); file.read(reinterpret_cast(audioData.data()), fileSize); return audioData; } std::vector> splitAudioData(const std::vector &audioData, size_t chunkSize) { std::vector> chunks; size_t dataSize = audioData.size(); size_t numChunks = dataSize / chunkSize; size_t remainder = dataSize % chunkSize; for (size_t i = 0; i < numChunks; ++i) { chunks.push_back( std::vector(audioData.begin() + i * chunkSize, audioData.begin() + (i + 1) * chunkSize)); } if (remainder != 0) { chunks.push_back( std::vector(audioData.end() - remainder, audioData.end())); } return chunks; } void testSpeech() { XunfeiAiEngine xunfeiAiEngine; auto engine = xunfeiAiEngine.createSpeechEngine(); const std::string configJson = u8R"( {"appId":"fakeAppId", "apiKeyRealTime":"fakeApiKeyRealTime", "apiKeyContinuous":"fakeApiKeyContinuous", "secretKeyContinuous":"fakeSecretKeyContinuous"} )"; engine->setConfig(configJson); auto audioData = readAudioData("16k_10.pcm"); ai_engine::EngineError error; auto ret = engine->initRecognizeOnceModule(); assert(ret.success == true); engine->setRecognitionResultCallback( [](ai_engine::core_ai::speech::RecognitionResult result) { std::cout << "MID_TEXT: " << result.text << std::endl; }); ret = engine->recognizeOnce("\{\"rate\": 16000}", audioData); std::cout << "recongnize once result: " << error.getMessage() << std::endl; assert(ret.success == true); ret = engine->destroyRecognizeOnceModule(); ret = engine->initContinuousRecognitionModule(); assert(ret.success == true); ret = engine->startContinuousRecognition("\{\"rate\": 16000}"); assert(ret.success == true); auto audioDatas = splitAudioData(audioData, 2560); for (auto &data : audioDatas) { std::vector theAudioData(data.begin(), data.end()); ret = engine->writeContinuousRecognitionAudioData(theAudioData); assert(ret.success == true); usleep(80 * 1000); } sleep(5); engine->stopContinuousRecognition(); engine->destroyContinuousRecognitionModule(); ret = engine->initSynthesizeModule(); assert(ret.success == true); std::string text = "看起来像是随机敲击键盘产生的字符组合,没有明确的含义或上下文。\ 它可能是一个错误输入、代码片段的一部分,或者仅仅是随机文本。\ 如果您能提供更多的上下文或信息,我可能能更好地理解它的含义或用途。"; engine->setSynthesisResultCallback( [](ai_engine::core_ai::speech::SynthesisResult result) { std::cout << result.base64AudioData.size() << std::endl; std::string audioData = base64Decode(result.base64AudioData); writeBinaryDataToFile( "test.mp3", std::vector(audioData.begin(), audioData.end())); }); ret = engine->synthesizeText("\{\"speed\": 5}", text); std::cout << "synthesize once result: " << error.getMessage() << std::endl; assert(ret.success == true); ret = engine->destroySynthesizeModule(); assert(ret.success == true); } int main(int argc, char *argv[]) { testSpeech(); return 0; }kylin-cloud-ai-engine-plugin-1.1.0.1/test/testvisionengine.cpp000066400000000000000000000073351520575453600243340ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include #include #include #include #include #include #include "xunfeiengine.h" std::string base64Decode(const std::string &input) { BIO *bio{nullptr}; BIO *b64{nullptr}; char *buffer = new char[input.size()]; std::copy(input.begin(), input.end(), buffer); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new_mem_buf(buffer, static_cast(input.size())); bio = BIO_push(b64, bio); int decodedLength = BIO_read(bio, buffer, static_cast(input.size())); std::string result(buffer, decodedLength); BIO_free_all(bio); delete[] buffer; return result; } void writeBinaryDataToFile(const std::string &filename, const std::vector &data) { std::ofstream outputFile(filename, std::ios::out | std::ios::binary | std::ios::app); if (!outputFile.is_open()) { std::cerr << "Failed to open file for writing." << std::endl; return; } outputFile.write(data.data(), data.size()); if (!outputFile.good()) { std::cerr << "Error occurred while writing to file." << std::endl; } else { std::cout << "Binary data has been written to file: " << filename << std::endl; } outputFile.close(); } void testVision() { XunfeiAiEngine xunfeiAiEngine; auto engine = xunfeiAiEngine.createImageGenerationEngine(); const std::string configJson = u8R"({"appId":"fakeAppId", "apiKey":"fakeApiKey", "secretKey":"fakeSecretKey"})"; engine->setConfig(configJson); engine->setImageNumber(1); engine->setImageStyle("写实风格"); engine->setImageSize(1024, 1024); int imageCount = 0; engine->setGenerationResultCallback( [&imageCount]( ai_engine::gen_ai::vision::ImageGenerationResult imageData) -> void { std::cout << "image format: " << imageData.format << std::endl; std::cout << "image height: " << imageData.height << std::endl; std::cout << "image width: " << imageData.width << std::endl; std::cout << "image index: " << imageData.index << std::endl; std::cout << "image total: " << imageData.total << std::endl; std::cout << "image data size: " << imageData.imageBase64Data.size() << std::endl; std::string imageBase64 = base64Decode(imageData.imageBase64Data); writeBinaryDataToFile( "test" + std::to_string(imageCount++) + ".jpg", std::vector(imageBase64.begin(), imageBase64.end())); std::cout << "image error message: " << imageData.error.getMessage() << std::endl; }); ai_engine::EngineError error; auto ret = engine->generateImage("骑马"); std::cout << "prompt2Image result: " << error.getMessage() << std::endl; assert(ret.success == true); } int main(int argc, char *argv[]) { testVision(); return 0; }kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/000077500000000000000000000000001520575453600215135ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/CMakeLists.txt000066400000000000000000000000251520575453600242500ustar00rootroot00000000000000add_subdirectory(cpr)kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/000077500000000000000000000000001520575453600222775ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/CMakeLists.txt000066400000000000000000000016011520575453600250350ustar00rootroot00000000000000set(MODULE_CPR cpr) add_compile_options(-fPIC) find_package(CURL REQUIRED) include_directories(${CURL_INCLUDE_DIRS}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) set(CPR_SOURCE cpr/accept_encoding.cpp cpr/auth.cpp cpr/async.cpp cpr/bearer.cpp cpr/cert_info.cpp cpr/cookies.cpp cpr/cprtypes.cpp cpr/curl_container.cpp cpr/curlholder.cpp cpr/error.cpp cpr/interceptor.cpp cpr/multipart.cpp cpr/parameters.cpp cpr/payload.cpp cpr/proxies.cpp cpr/proxyauth.cpp cpr/redirect.cpp cpr/response.cpp cpr/session.cpp cpr/ssl_ctx.cpp cpr/threadpool.cpp cpr/timeout.cpp cpr/unix_socket.cpp cpr/util.cpp) add_library(${MODULE_CPR} STATIC ${CPR_SOURCE}) target_link_libraries( cpr PRIVATE pthread ${KYAIDEPENDS_LDFLAGS} ) target_link_libraries(cpr INTERFACE ${CURL_LIBRARIES} pthread) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/CODE_OF_CONDUCT.md000066400000000000000000000121371520575453600251020ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at cc@libcpr.org. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/CONTRIBUTING.md000066400000000000000000000023431520575453600245320ustar00rootroot00000000000000# Contributing to C++ Requests Please fork this repository and contribute back using [pull requests](https://github.com/whoshuu/cpr/pulls). Features can be requested using [issues](https://github.com/whoshuu/cpr/issues). All code, comments, and critiques are greatly appreciated. ## Formatting To avoid unproductive debates on formatting, this project uses `clang-format` to ensure a consistent style across all source files. Currently, `clang-format` 3.8 is the version of `clang-format` we use. The format file can be found [here](https://github.com/whoshuu/cpr/blob/master/.clang-format). To install `clang-format` on Ubuntu, run this: ``` apt-get install clang-format-3.8 ``` To install `clang-format` on OS X, run this: ``` brew install clang-format ``` Note that `brew` might install a later version of `clang-format`, but it should be mostly compatible with what's run on the Travis servers. To run `clang-format` on every source file, run this in the root directory: ``` ./format-check.sh ``` This should indicate which files need formatting and also show a diff of the requested changes. More specific usage instructions can be found on the official [LLVM website](http://releases.llvm.org/3.8.0/tools/clang/docs/ClangFormat.html). kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/LICENSE000066400000000000000000000023151520575453600233050ustar00rootroot00000000000000This license applies to everything except the contents of the "test" directory and its subdirectories. MIT License Copyright (c) 2017-2021 Huu Nguyen Copyright (c) 2022 libcpr and many other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/README.md000066400000000000000000000145071520575453600235650ustar00rootroot00000000000000# C++ Requests: Curl for People [![Documentation](https://img.shields.io/badge/docs-online-informational?style=flat&link=https://docs.libcpr.org/)](https://docs.libcpr.org/) ![CI](https://github.com/libcpr/cpr/workflows/CI/badge.svg) [![Gitter](https://badges.gitter.im/libcpr/community.svg)](https://gitter.im/libcpr/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) ## Announcements * Like you probably have noticed, `cpr` moved to a new home from https://github.com/whoshuu/cpr to https://github.com/libcpr/cpr. Read more [here](https://github.com/libcpr/cpr/issues/636). * This project is being maintained by [Fabian Sauter](https://github.com/com8) and [Kilian Traub](https://github.com/KingKili). * For quick help, and discussion libcpr also offer a [gitter](https://gitter.im/libcpr/community?utm_source=share-link&utm_medium=link&utm_campaign=share-link) chat. ## TLDR C++ Requests is a simple wrapper around [libcurl](http://curl.haxx.se/libcurl) inspired by the excellent [Python Requests](https://github.com/kennethreitz/requests) project. Despite its name, libcurl's easy interface is anything but, and making mistakes misusing it is a common source of error and frustration. Using the more expressive language facilities of C++11, this library captures the essence of making network calls into a few concise idioms. Here's a quick GET request: ```c++ #include int main(int argc, char** argv) { cpr::Response r = cpr::Get(cpr::Url{"https://api.github.com/repos/whoshuu/cpr/contributors"}, cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC}, cpr::Parameters{{"anon", "true"}, {"key", "value"}}); r.status_code; // 200 r.header["content-type"]; // application/json; charset=utf-8 r.text; // JSON text string return 0; } ``` And here's [less functional, more complicated code, without cpr](https://gist.github.com/whoshuu/2dc858b8730079602044). ## Documentation [![Documentation](https://img.shields.io/badge/docs-online-informational?style=for-the-badge&link=https://docs.libcpr.org/)](https://docs.libcpr.org/) You can find the latest documentation [here](https://docs.libcpr.org/). It's a work in progress, but it should give you a better idea of how to use the library than the [tests](https://github.com/libcpr/cpr/tree/master/test) currently do. ## Features C++ Requests currently supports: * Custom headers * Url encoded parameters * Url encoded POST values * Multipart form POST upload * File POST upload * Basic authentication * Bearer authentication * Digest authentication * NTLM authentication * Connection and request timeout specification * Timeout for low speed connection * Asynchronous requests * :cookie: support! * Proxy support * Callback interfaces * PUT methods * DELETE methods * HEAD methods * OPTIONS methods * PATCH methods * Thread Safe access to [libCurl](https://curl.haxx.se/libcurl/c/threadsafe.html) * OpenSSL and WinSSL support for HTTPS requests ## Planned For a quick overview about the planed features, have a look at the next [Milestones](https://github.com/libcpr/cpr/milestones). ## Usage ### CMake If you already have a CMake project you need to integrate C++ Requests with, the primary way is to use `fetch_content`. Add the following to your `CMakeLists.txt`. ```cmake include(FetchContent) FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git GIT_TAG 6ea2dec23c3df14ac3b27b7d2d6bbff0cb7ba1b0) # The commit hash for 1.8.1. Replace with the latest from: https://github.com/libcpr/cpr/releases FetchContent_MakeAvailable(cpr) ``` This will produce the target `cpr::cpr` which you can link against the typical way: ```cmake target_link_libraries(your_target_name PRIVATE cpr::cpr) ``` That should do it! There's no need to handle `libcurl` yourself. All dependencies are taken care of for you. All of this can be found in an example [**here**](https://github.com/libcpr/example-cmake-fetch-content). ### Packages for Linux Distributions Alternatively, you may install a package specific to your Linux distribution. Since so few distributions currently have a package for cpr, most users will not be able to run your program with this approach. Currently, we are aware of packages for the following distributions: * [Arch Linux (AUR)](https://aur.archlinux.org/packages/cpr) If there's no package for your distribution, try making one! If you do, and it is added to your distribution's repositories, please submit a pull request to add it to the list above. However, please only do this if you plan to actively maintain the package. ### NuGet Package For Windows there is also a libcpr NuGet package available. Currently x86 and x64 builds are supported with release and debug configuration. The package can be found here: [NuGet.org](https://www.nuget.org/packages/libcpr/) ## Requirements The only explicit requirements are: * a `C++11` compatible compiler such as Clang or GCC. The minimum required version of GCC is unknown, so if anyone has trouble building this library with a specific version of GCC, do let me know * If you would like to perform https requests `OpenSSL` and its development libraries are required. ## Building cpr - Using vcpkg You can download and install cpr using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: ```Bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install cpr ``` The `cpr` port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. ## Building cpr - Using Conan You can download and install `cpr` using the [Conan](https://conan.io/) package manager. Setup your CMakeLists.txt (see [Conan documentation](https://docs.conan.io/en/latest/integrations/build_system.html) on how to use MSBuild, Meson and others). An example can be found [**here**](https://github.com/libcpr/example-cmake-conan). The `cpr` package in Conan is kept up to date by Conan contributors. If the version is out of date, please [create an issue or pull request](https://github.com/conan-io/conan-center-index) on the `conan-center-index` repository. kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/000077500000000000000000000000001520575453600230635ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/CMakeLists.txt000066400000000000000000000046071520575453600256320ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.15) add_library(cpr accept_encoding.cpp async.cpp auth.cpp bearer.cpp cert_info.cpp cookies.cpp cprtypes.cpp curl_container.cpp curlholder.cpp error.cpp multipart.cpp parameters.cpp payload.cpp proxies.cpp proxyauth.cpp session.cpp threadpool.cpp timeout.cpp unix_socket.cpp util.cpp response.cpp redirect.cpp interceptor.cpp ssl_ctx.cpp) add_library(cpr::cpr ALIAS cpr) target_link_libraries(cpr PUBLIC CURL::libcurl) # todo should be private, but first dependencies in ssl_options need to be removed # Fix missing OpenSSL includes for Windows since in 'ssl_ctx.cpp' we include OpenSSL directly if(SSL_BACKEND_USED STREQUAL "OpenSSL") target_link_libraries(cpr PRIVATE OpenSSL::SSL) target_include_directories(cpr PRIVATE ${OPENSSL_INCLUDE_DIR}) endif() # Set version for shared libraries. set_target_properties(cpr PROPERTIES VERSION ${${PROJECT_NAME}_VERSION} SOVERSION ${${PROJECT_NAME}_VERSION_MAJOR}) # Import GNU common install directory variables include(GNUInstallDirs) install(TARGETS cpr EXPORT cprTargets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) if(CPR_FORCE_USE_SYSTEM_CURL) # Include CMake helpers for package config files # Follow this installation guideline: https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html include(CMakePackageConfigHelpers) write_basic_package_version_file( "${PROJECT_BINARY_DIR}/cpr/cprConfigVersion.cmake" VERSION ${${PROJECT_NAME}_VERSION} COMPATIBILITY ExactVersion) configure_package_config_file(${PROJECT_SOURCE_DIR}/cmake/cprConfig.cmake.in "${PROJECT_BINARY_DIR}/cpr/cprConfig.cmake" INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpr) install(FILES ${PROJECT_BINARY_DIR}/cpr/cprConfig.cmake ${PROJECT_BINARY_DIR}/cpr/cprConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpr) endif() install(EXPORT cprTargets FILE cprTargets.cmake NAMESPACE cpr:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cpr) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/accept_encoding.cpp000066400000000000000000000016041520575453600266750ustar00rootroot00000000000000#include "cpr/accept_encoding.h" #include #include #include namespace cpr { AcceptEncoding::AcceptEncoding(const std::initializer_list& methods) { methods_.clear(); std::transform(methods.begin(), methods.end(), std::back_inserter(methods_), [&](cpr::AcceptEncodingMethods method) { return cpr::AcceptEncodingMethodsStringMap.at(method); }); } AcceptEncoding::AcceptEncoding(const std::initializer_list& string_methods) : methods_{string_methods} {} bool AcceptEncoding::empty() const noexcept { return methods_.empty(); } const std::string AcceptEncoding::getString() const { std::string methodsString = std::accumulate(std::next(methods_.begin()), methods_.end(), methods_[0], [](std::string a, std::string b) { return std::move(a) + ", " + std::move(b); }); return methodsString; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/async.cpp000066400000000000000000000002511520575453600247020ustar00rootroot00000000000000#include "cpr/async.h" namespace cpr { // NOLINTNEXTLINE (cppcoreguidelines-avoid-non-const-global-variables) CPR_SINGLETON_IMPL(GlobalThreadPool) } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/auth.cpp000066400000000000000000000005351520575453600245330ustar00rootroot00000000000000#include "cpr/auth.h" #include "cpr/util.h" namespace cpr { Authentication::~Authentication() noexcept { util::secureStringClear(auth_string_); } const char* Authentication::GetAuthString() const noexcept { return auth_string_.c_str(); } AuthMode Authentication::GetAuthMode() const noexcept { return auth_mode_; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/bearer.cpp000066400000000000000000000006061520575453600250310ustar00rootroot00000000000000#include "cpr/bearer.h" #include "cpr/util.h" namespace cpr { // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 Bearer::~Bearer() noexcept { util::secureStringClear(token_string_); } const char* Bearer::GetToken() const noexcept { return token_string_.c_str(); } #endif } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/cert_info.cpp000066400000000000000000000015341520575453600255420ustar00rootroot00000000000000#include "cpr/cert_info.h" namespace cpr { std::string& CertInfo::operator[](const size_t& pos) { return cert_info_[pos]; } CertInfo::iterator CertInfo::begin() { return cert_info_.begin(); } CertInfo::iterator CertInfo::end() { return cert_info_.end(); } CertInfo::const_iterator CertInfo::begin() const { return cert_info_.begin(); } CertInfo::const_iterator CertInfo::end() const { return cert_info_.end(); } CertInfo::const_iterator CertInfo::cbegin() const { return cert_info_.cbegin(); } CertInfo::const_iterator CertInfo::cend() const { return cert_info_.cend(); } void CertInfo::emplace_back(const std::string& str) { cert_info_.emplace_back(str); } void CertInfo::push_back(const std::string& str) { cert_info_.push_back(str); } void CertInfo::pop_back() { cert_info_.pop_back(); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/cookies.cpp000066400000000000000000000047151520575453600252320ustar00rootroot00000000000000#include "cpr/cookies.h" #include #include namespace cpr { const std::string Cookie::GetDomain() const { return domain_; } bool Cookie::IsIncludingSubdomains() const { return includeSubdomains_; } const std::string Cookie::GetPath() const { return path_; } bool Cookie::IsHttpsOnly() const { return httpsOnly_; } const std::chrono::system_clock::time_point Cookie::GetExpires() const { return expires_; } const std::string Cookie::GetExpiresString() const { std::stringstream ss; std::tm tm{}; const std::time_t tt = std::chrono::system_clock::to_time_t(expires_); #ifdef _WIN32 gmtime_s(&tm, &tt); #else gmtime_r(&tt, &tm); #endif ss << std::put_time(&tm, "%a, %d %b %Y %H:%M:%S GMT"); return ss.str(); } const std::string Cookie::GetName() const { return name_; } const std::string Cookie::GetValue() const { return value_; } const std::string Cookies::GetEncoded(const CurlHolder& holder) const { std::stringstream stream; for (const cpr::Cookie& item : cookies_) { // Depending on if encoding is set to "true", we will URL-encode cookies stream << (encode ? holder.urlEncode(item.GetName()) : item.GetName()) << "="; // special case version 1 cookies, which can be distinguished by // beginning and trailing quotes if (!item.GetValue().empty() && item.GetValue().front() == '"' && item.GetValue().back() == '"') { stream << item.GetValue(); } else { // Depending on if encoding is set to "true", we will URL-encode cookies stream << (encode ? holder.urlEncode(item.GetValue()) : item.GetValue()); } stream << "; "; } return stream.str(); } cpr::Cookie& Cookies::operator[](size_t pos) { return cookies_[pos]; } Cookies::iterator Cookies::begin() { return cookies_.begin(); } Cookies::iterator Cookies::end() { return cookies_.end(); } Cookies::const_iterator Cookies::begin() const { return cookies_.begin(); } Cookies::const_iterator Cookies::end() const { return cookies_.end(); } Cookies::const_iterator Cookies::cbegin() const { return cookies_.cbegin(); } Cookies::const_iterator Cookies::cend() const { return cookies_.cend(); } void Cookies::emplace_back(const Cookie& str) { cookies_.emplace_back(str); } void Cookies::push_back(const Cookie& str) { cookies_.push_back(str); } void Cookies::pop_back() { cookies_.pop_back(); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/cprtypes.cpp000066400000000000000000000005661520575453600254470ustar00rootroot00000000000000#include "cpr/cprtypes.h" #include #include namespace cpr { bool CaseInsensitiveCompare::operator()(const std::string& a, const std::string& b) const noexcept { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](unsigned char ac, unsigned char bc) { return std::tolower(ac) < std::tolower(bc); }); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/curl_container.cpp000066400000000000000000000033551520575453600266040ustar00rootroot00000000000000#include "cpr/curl_container.h" #include #include namespace cpr { template CurlContainer::CurlContainer(const std::initializer_list& containerList) : containerList_(containerList) {} template void CurlContainer::Add(const std::initializer_list& containerList) { std::transform(containerList.begin(), containerList.end(), std::back_inserter(containerList_), [](const T& elem) { return std::move(elem); }); } template void CurlContainer::Add(const T& element) { containerList_.push_back(std::move(element)); } template <> const std::string CurlContainer::GetContent(const CurlHolder& holder) const { std::string content{}; for (const Parameter& parameter : containerList_) { if (!content.empty()) { content += "&"; } const std::string escapedKey = encode ? holder.urlEncode(parameter.key) : parameter.key; if (parameter.value.empty()) { content += escapedKey; } else { const std::string escapedValue = encode ? holder.urlEncode(parameter.value) : parameter.value; content += escapedKey + "="; content += escapedValue; } } return content; } template <> const std::string CurlContainer::GetContent(const CurlHolder& holder) const { std::string content{}; for (const cpr::Pair& element : containerList_) { if (!content.empty()) { content += "&"; } const std::string escaped = encode ? holder.urlEncode(element.value) : element.value; content += element.key + "=" + escaped; } return content; } template class CurlContainer; template class CurlContainer; } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/curlholder.cpp000066400000000000000000000025741520575453600257420ustar00rootroot00000000000000#include "cpr/curlholder.h" #include namespace cpr { CurlHolder::CurlHolder() { /** * Allow multithreaded access to CPR by locking curl_easy_init(). * curl_easy_init() is not thread safe. * References: * https://curl.haxx.se/libcurl/c/curl_easy_init.html * https://curl.haxx.se/libcurl/c/threadsafe.html **/ curl_easy_init_mutex_().lock(); // NOLINTNEXTLINE (cppcoreguidelines-prefer-member-initializer) since we need it to happen inside the lock handle = curl_easy_init(); curl_easy_init_mutex_().unlock(); assert(handle); } // namespace cpr CurlHolder::~CurlHolder() { curl_slist_free_all(chunk); curl_slist_free_all(resolveCurlList); curl_mime_free(multipart); curl_easy_cleanup(handle); } std::string CurlHolder::urlEncode(const std::string& s) const { assert(handle); char* output = curl_easy_escape(handle, s.c_str(), static_cast(s.length())); if (output) { std::string result = output; curl_free(output); return result; } return ""; } std::string CurlHolder::urlDecode(const std::string& s) const { assert(handle); char* output = curl_easy_unescape(handle, s.c_str(), static_cast(s.length()), nullptr); if (output) { std::string result = output; curl_free(output); return result; } return ""; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/error.cpp000066400000000000000000000047051520575453600247260ustar00rootroot00000000000000#include "cpr/error.h" #include namespace cpr { ErrorCode Error::getErrorCodeForCurlError(std::int32_t curl_code) { switch (curl_code) { case CURLE_OK: return ErrorCode::OK; case CURLE_UNSUPPORTED_PROTOCOL: return ErrorCode::UNSUPPORTED_PROTOCOL; case CURLE_URL_MALFORMAT: return ErrorCode::INVALID_URL_FORMAT; case CURLE_COULDNT_RESOLVE_PROXY: return ErrorCode::PROXY_RESOLUTION_FAILURE; case CURLE_COULDNT_RESOLVE_HOST: return ErrorCode::HOST_RESOLUTION_FAILURE; case CURLE_COULDNT_CONNECT: return ErrorCode::CONNECTION_FAILURE; case CURLE_OPERATION_TIMEDOUT: return ErrorCode::OPERATION_TIMEDOUT; case CURLE_SSL_CONNECT_ERROR: return ErrorCode::SSL_CONNECT_ERROR; #if LIBCURL_VERSION_NUM < 0x073e00 case CURLE_PEER_FAILED_VERIFICATION: return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; #endif case CURLE_ABORTED_BY_CALLBACK: case CURLE_WRITE_ERROR: return ErrorCode::REQUEST_CANCELLED; case CURLE_GOT_NOTHING: return ErrorCode::EMPTY_RESPONSE; case CURLE_SSL_ENGINE_NOTFOUND: case CURLE_SSL_ENGINE_SETFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SEND_ERROR: return ErrorCode::NETWORK_SEND_FAILURE; case CURLE_RECV_ERROR: return ErrorCode::NETWORK_RECEIVE_ERROR; case CURLE_SSL_CERTPROBLEM: return ErrorCode::SSL_LOCAL_CERTIFICATE_ERROR; case CURLE_SSL_CIPHER: return ErrorCode::GENERIC_SSL_ERROR; #if LIBCURL_VERSION_NUM >= 0x073e00 case CURLE_PEER_FAILED_VERIFICATION: return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; #else case CURLE_SSL_CACERT: return ErrorCode::SSL_CACERT_ERROR; #endif case CURLE_USE_SSL_FAILED: case CURLE_SSL_ENGINE_INITFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CACERT_BADFILE: return ErrorCode::SSL_CACERT_ERROR; case CURLE_SSL_SHUTDOWN_FAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CRL_BADFILE: case CURLE_SSL_ISSUER_ERROR: return ErrorCode::SSL_CACERT_ERROR; case CURLE_TOO_MANY_REDIRECTS: return ErrorCode::TOO_MANY_REDIRECTS; default: return ErrorCode::INTERNAL_ERROR; } } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/interceptor.cpp000066400000000000000000000031571520575453600261330ustar00rootroot00000000000000#include "cpr/interceptor.h" #include namespace cpr { Response Interceptor::proceed(Session& session) { return session.proceed(); } Response Interceptor::proceed(Session& session, ProceedHttpMethod httpMethod) { switch (httpMethod) { case ProceedHttpMethod::DELETE_REQUEST: return session.Delete(); case ProceedHttpMethod::GET_REQUEST: return session.Get(); case ProceedHttpMethod::HEAD_REQUEST: return session.Head(); case ProceedHttpMethod::OPTIONS_REQUEST: return session.Options(); case ProceedHttpMethod::PATCH_REQUEST: return session.Patch(); case ProceedHttpMethod::POST_REQUEST: return session.Post(); case ProceedHttpMethod::PUT_REQUEST: return session.Put(); default: throw std::invalid_argument{"Can't proceed the session with the provided http method!"}; } } Response Interceptor::proceed(Session& session, ProceedHttpMethod httpMethod, std::ofstream& file) { if (httpMethod == ProceedHttpMethod::DOWNLOAD_FILE_REQUEST) { return session.Download(file); } throw std::invalid_argument{"std::ofstream argument is only valid for ProceedHttpMethod::DOWNLOAD_FILE!"}; } Response Interceptor::proceed(Session& session, ProceedHttpMethod httpMethod, const WriteCallback& write) { if (httpMethod == ProceedHttpMethod::DOWNLOAD_CALLBACK_REQUEST) { return session.Download(write); } throw std::invalid_argument{"WriteCallback argument is only valid for ProceedHttpMethod::DOWNLOAD_CALLBACK!"}; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/multipart.cpp000066400000000000000000000002241520575453600256060ustar00rootroot00000000000000#include "cpr/multipart.h" namespace cpr { Multipart::Multipart(const std::initializer_list& p_parts) : parts{p_parts} {} } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/parameters.cpp000066400000000000000000000001001520575453600257210ustar00rootroot00000000000000#include "cpr/parameters.h" namespace cpr { } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/payload.cpp000066400000000000000000000000751520575453600252220ustar00rootroot00000000000000#include "cpr/payload.h" namespace cpr { } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/proxies.cpp000066400000000000000000000010371520575453600252610ustar00rootroot00000000000000#include "cpr/proxies.h" #include #include #include #include namespace cpr { Proxies::Proxies(const std::initializer_list>& hosts) : hosts_{hosts} {} Proxies::Proxies(const std::map& hosts) : hosts_{hosts} {} bool Proxies::has(const std::string& protocol) const { return hosts_.count(protocol) > 0; } const std::string& Proxies::operator[](const std::string& protocol) { return hosts_[protocol]; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/proxyauth.cpp000066400000000000000000000010261520575453600256310ustar00rootroot00000000000000#include "cpr/proxyauth.h" #include "cpr/util.h" namespace cpr { EncodedAuthentication::~EncodedAuthentication() noexcept { util::secureStringClear(auth_string_); } const char* EncodedAuthentication::GetAuthString() const noexcept { return auth_string_.c_str(); } bool ProxyAuthentication::has(const std::string& protocol) const { return proxyAuth_.count(protocol) > 0; } const char* ProxyAuthentication::operator[](const std::string& protocol) { return proxyAuth_[protocol].GetAuthString(); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/redirect.cpp000066400000000000000000000027161520575453600253760ustar00rootroot00000000000000#include "cpr/redirect.h" namespace cpr { PostRedirectFlags operator|(PostRedirectFlags lhs, PostRedirectFlags rhs) { return static_cast(static_cast(lhs) | static_cast(rhs)); } PostRedirectFlags operator&(PostRedirectFlags lhs, PostRedirectFlags rhs) { return static_cast(static_cast(lhs) & static_cast(rhs)); } PostRedirectFlags operator^(PostRedirectFlags lhs, PostRedirectFlags rhs) { return static_cast(static_cast(lhs) ^ static_cast(rhs)); } PostRedirectFlags operator~(PostRedirectFlags flag) { return static_cast(~static_cast(flag)); } PostRedirectFlags& operator|=(PostRedirectFlags& lhs, PostRedirectFlags rhs) { lhs = static_cast(static_cast(lhs) | static_cast(rhs)); const uint8_t tmp = static_cast(lhs); lhs = static_cast(tmp); return lhs; } PostRedirectFlags& operator&=(PostRedirectFlags& lhs, PostRedirectFlags rhs) { lhs = static_cast(static_cast(lhs) & static_cast(rhs)); return lhs; } PostRedirectFlags& operator^=(PostRedirectFlags& lhs, PostRedirectFlags rhs) { lhs = static_cast(static_cast(lhs) ^ static_cast(rhs)); return lhs; } bool any(PostRedirectFlags flag) { return flag != PostRedirectFlags::NONE; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/response.cpp000066400000000000000000000037331520575453600254330ustar00rootroot00000000000000#include "cpr/response.h" namespace cpr { Response::Response(std::shared_ptr curl, std::string&& p_text, std::string&& p_header_string, Cookies&& p_cookies = Cookies{}, Error&& p_error = Error{}) : curl_(std::move(curl)), text(std::move(p_text)), cookies(std::move(p_cookies)), error(std::move(p_error)), raw_header(std::move(p_header_string)) { header = cpr::util::parseHeader(raw_header, &status_line, &reason); assert(curl_); assert(curl_->handle); curl_easy_getinfo(curl_->handle, CURLINFO_RESPONSE_CODE, &status_code); curl_easy_getinfo(curl_->handle, CURLINFO_TOTAL_TIME, &elapsed); char* url_string{nullptr}; curl_easy_getinfo(curl_->handle, CURLINFO_EFFECTIVE_URL, &url_string); url = Url(url_string); #if LIBCURL_VERSION_NUM >= 0x073700 // 7.55.0 curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_DOWNLOAD_T, &downloaded_bytes); curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_UPLOAD_T, &uploaded_bytes); #else double downloaded_bytes_double, uploaded_bytes_double; curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_DOWNLOAD, &downloaded_bytes_double); curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_UPLOAD, &uploaded_bytes_double); downloaded_bytes = downloaded_bytes_double; uploaded_bytes = uploaded_bytes_double; #endif curl_easy_getinfo(curl_->handle, CURLINFO_REDIRECT_COUNT, &redirect_count); } std::vector Response::GetCertInfos() { assert(curl_); assert(curl_->handle); curl_certinfo* ci{nullptr}; curl_easy_getinfo(curl_->handle, CURLINFO_CERTINFO, &ci); std::vector cert_infos; for (int i = 0; i < ci->num_of_certs; i++) { CertInfo cert_info; // NOLINTNEXTLINE (cppcoreguidelines-pro-bounds-pointer-arithmetic) for (curl_slist* slist = ci->certinfo[i]; slist; slist = slist->next) { cert_info.emplace_back(std::string{slist->data}); } cert_infos.emplace_back(cert_info); } return cert_infos; } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/session.cpp000066400000000000000000001025501520575453600252550ustar00rootroot00000000000000#include "cpr/session.h" #include #include #include #include #include #include #include #include #include "cpr/async.h" #include "cpr/cprtypes.h" #include "cpr/interceptor.h" #include "cpr/util.h" #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION #include "cpr/ssl_ctx.h" #endif namespace cpr { // Ignored here since libcurl reqires a long: // NOLINTNEXTLINE(google-runtime-int) constexpr long ON = 1L; // Ignored here since libcurl reqires a long: // NOLINTNEXTLINE(google-runtime-int) constexpr long OFF = 0L; void Session::SetHeaderInternal() { curl_slist* chunk = nullptr; for (const std::pair& item : header_) { std::string header_string = item.first; if (item.second.empty()) { header_string += ";"; } else { header_string += ": " + item.second; } curl_slist* temp = curl_slist_append(chunk, header_string.c_str()); if (temp) { chunk = temp; } } // Set the chunked transfer encoding in case it does not already exist: if (chunkedTransferEncoding_ && header_.find("Transfer-Encoding") == header_.end()) { curl_slist* temp = curl_slist_append(chunk, "Transfer-Encoding:chunked"); if (temp) { chunk = temp; } } curl_easy_setopt(curl_->handle, CURLOPT_HTTPHEADER, chunk); curl_slist_free_all(curl_->chunk); curl_->chunk = chunk; } // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 void Session::SetBearer(const Bearer& token) { // Ignore here since this has been defined by libcurl. curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); curl_easy_setopt(curl_->handle, CURLOPT_XOAUTH2_BEARER, token.GetToken()); } #endif Session::Session() : curl_(new CurlHolder()) { // Set up some sensible defaults curl_version_info_data* version_info = curl_version_info(CURLVERSION_NOW); const std::string version = "curl/" + std::string{version_info->version}; curl_easy_setopt(curl_->handle, CURLOPT_USERAGENT, version.c_str()); SetRedirect(Redirect()); curl_easy_setopt(curl_->handle, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl_->handle, CURLOPT_ERRORBUFFER, curl_->error.data()); curl_easy_setopt(curl_->handle, CURLOPT_COOKIEFILE, ""); #ifdef CPR_CURL_NOSIGNAL curl_easy_setopt(curl_->handle, CURLOPT_NOSIGNAL, 1L); #endif #if LIBCURL_VERSION_NUM >= 0x071900 // 7.25.0 curl_easy_setopt(curl_->handle, CURLOPT_TCP_KEEPALIVE, 1L); #endif } Response Session::makeDownloadRequest() { assert(curl_->handle); if (!interceptors_.empty()) { const std::shared_ptr interceptor = interceptors_.front(); interceptors_.pop(); return interceptor->intercept(*this); } // Set Header: SetHeaderInternal(); const std::string parametersContent = parameters_.GetContent(*curl_); if (!parametersContent.empty()) { const Url new_url{url_ + "?" + parametersContent}; curl_easy_setopt(curl_->handle, CURLOPT_URL, new_url.c_str()); } else { curl_easy_setopt(curl_->handle, CURLOPT_URL, url_.c_str()); } const std::string protocol = url_.str().substr(0, url_.str().find(':')); if (proxies_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXY, proxies_[protocol].c_str()); if (proxyAuth_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(curl_->handle, CURLOPT_PROXYUSERPWD, proxyAuth_[protocol]); } } curl_->error[0] = '\0'; std::string header_string; if (headercb_.callback) { curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::headerUserFunction); curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &headercb_); } else { curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &header_string); } const CURLcode curl_error = curl_easy_perform(curl_->handle); if (!headercb_.callback) { curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, nullptr); curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, 0); } curl_slist* raw_cookies{nullptr}; curl_easy_getinfo(curl_->handle, CURLINFO_COOKIELIST, &raw_cookies); Cookies cookies = util::parseCookies(raw_cookies); curl_slist_free_all(raw_cookies); std::string errorMsg = curl_->error.data(); return Response(curl_, "", std::move(header_string), std::move(cookies), Error(curl_error, std::move(errorMsg))); } void Session::prepareCommon() { assert(curl_->handle); // Set Header: SetHeaderInternal(); const std::string parametersContent = parameters_.GetContent(*curl_); if (!parametersContent.empty()) { const Url new_url{url_ + "?" + parametersContent}; curl_easy_setopt(curl_->handle, CURLOPT_URL, new_url.c_str()); } else { curl_easy_setopt(curl_->handle, CURLOPT_URL, url_.c_str()); } // Proxy: const std::string protocol = url_.str().substr(0, url_.str().find(':')); if (proxies_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXY, proxies_[protocol].c_str()); if (proxyAuth_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(curl_->handle, CURLOPT_PROXYUSERPWD, proxyAuth_[protocol]); } } #if LIBCURL_VERSION_NUM >= 0x071506 // 7.21.6 if (acceptEncoding_.empty()) { /* enable all supported built-in compressions */ curl_easy_setopt(curl_->handle, CURLOPT_ACCEPT_ENCODING, ""); } else { curl_easy_setopt(curl_->handle, CURLOPT_ACCEPT_ENCODING, acceptEncoding_.getString().c_str()); } #endif #if LIBCURL_VERSION_NUM >= 0x071900 // 7.25.0 #if SUPPORT_SSL_NO_REVOKE // NOLINTNEXTLINE (google-runtime-int) long bitmask{0}; curl_easy_setopt(curl_->handle, CURLOPT_SSL_OPTIONS, &bitmask); const bool noRevoke = bitmask & CURLSSLOPT_NO_REVOKE; #endif // Fix loading certs from Windows cert store when using OpenSSL: // curl_easy_setopt(curl_->handle, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); // Ensure SSL no revoke is still set #if SUPPORT_SSL_NO_REVOKE if (noRevoke) { curl_easy_setopt(curl_->handle, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE); } #endif #endif curl_->error[0] = '\0'; response_string_.clear(); if (response_string_reserve_size_ > 0) { response_string_.reserve(response_string_reserve_size_); } header_string_.clear(); if (!this->writecb_.callback) { curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &response_string_); } if (!this->headercb_.callback) { curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &header_string_); } // Enable so we are able to retrive certificate information: curl_easy_setopt(curl_->handle, CURLOPT_CERTINFO, 1L); } Response Session::makeRequest() { if (!interceptors_.empty()) { // At least one interceptor exists -> Execute its intercept function const std::shared_ptr interceptor = interceptors_.front(); interceptors_.pop(); return interceptor->intercept(*this); } const CURLcode curl_error = curl_easy_perform(curl_->handle); return Complete(curl_error); } void Session::SetLimitRate(const LimitRate& limit_rate) { curl_easy_setopt(curl_->handle, CURLOPT_MAX_RECV_SPEED_LARGE, limit_rate.downrate); curl_easy_setopt(curl_->handle, CURLOPT_MAX_SEND_SPEED_LARGE, limit_rate.uprate); } void Session::SetReadCallback(const ReadCallback& read) { readcb_ = read; curl_easy_setopt(curl_->handle, CURLOPT_INFILESIZE_LARGE, read.size); curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, read.size); curl_easy_setopt(curl_->handle, CURLOPT_READFUNCTION, cpr::util::readUserFunction); curl_easy_setopt(curl_->handle, CURLOPT_READDATA, &readcb_); chunkedTransferEncoding_ = read.size == -1; } void Session::SetHeaderCallback(const HeaderCallback& header) { curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::headerUserFunction); headercb_ = header; curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &headercb_); } void Session::SetWriteCallback(const WriteCallback& write) { curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeUserFunction); writecb_ = write; curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &writecb_); } void Session::SetProgressCallback(const ProgressCallback& progress) { progresscb_ = progress; #if LIBCURL_VERSION_NUM < 0x072000 // 7.32.0 curl_easy_setopt(curl_->handle, CURLOPT_PROGRESSFUNCTION, cpr::util::progressUserFunction); curl_easy_setopt(curl_->handle, CURLOPT_PROGRESSDATA, &progresscb_); #else curl_easy_setopt(curl_->handle, CURLOPT_XFERINFOFUNCTION, cpr::util::progressUserFunction); curl_easy_setopt(curl_->handle, CURLOPT_XFERINFODATA, &progresscb_); #endif curl_easy_setopt(curl_->handle, CURLOPT_NOPROGRESS, 0L); } void Session::SetDebugCallback(const DebugCallback& debug) { curl_easy_setopt(curl_->handle, CURLOPT_DEBUGFUNCTION, cpr::util::debugUserFunction); debugcb_ = debug; curl_easy_setopt(curl_->handle, CURLOPT_DEBUGDATA, &debugcb_); curl_easy_setopt(curl_->handle, CURLOPT_VERBOSE, 1L); } void Session::SetUrl(const Url& url) { url_ = url; } void Session::SetParameters(const Parameters& parameters) { parameters_ = parameters; } void Session::SetParameters(Parameters&& parameters) { parameters_ = std::move(parameters); } void Session::SetHeader(const Header& header) { header_ = header; } void Session::UpdateHeader(const Header& header) { for (const std::pair& item : header) { header_[item.first] = item.second; } } void Session::SetTimeout(const Timeout& timeout) { curl_easy_setopt(curl_->handle, CURLOPT_TIMEOUT_MS, timeout.Milliseconds()); } void Session::SetConnectTimeout(const ConnectTimeout& timeout) { curl_easy_setopt(curl_->handle, CURLOPT_CONNECTTIMEOUT_MS, timeout.Milliseconds()); } void Session::SetAuth(const Authentication& auth) { // Ignore here since this has been defined by libcurl. switch (auth.GetAuthMode()) { case AuthMode::BASIC: curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); break; case AuthMode::DIGEST: curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); break; case AuthMode::NTLM: curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); break; } } void Session::SetUserAgent(const UserAgent& ua) { curl_easy_setopt(curl_->handle, CURLOPT_USERAGENT, ua.c_str()); } void Session::SetPayload(const Payload& payload) { hasBodyOrPayload_ = true; const std::string content = payload.GetContent(*curl_); curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(content.length())); curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, content.c_str()); } void Session::SetPayload(Payload&& payload) { hasBodyOrPayload_ = true; const std::string content = payload.GetContent(*curl_); curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(content.length())); curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, content.c_str()); } void Session::SetProxies(const Proxies& proxies) { proxies_ = proxies; } void Session::SetProxies(Proxies&& proxies) { proxies_ = std::move(proxies); } void Session::SetProxyAuth(ProxyAuthentication&& proxy_auth) { proxyAuth_ = std::move(proxy_auth); } void Session::SetProxyAuth(const ProxyAuthentication& proxy_auth) { proxyAuth_ = proxy_auth; } void Session::SetMultipart(const Multipart& multipart) { // Make sure, we have a empty multipart to start with: if (curl_->multipart) { curl_mime_free(curl_->multipart); } curl_->multipart = curl_mime_init(curl_->handle); // Add all multipart pieces: for (const Part& part : multipart.parts) { if (part.is_file) { curl_mimepart* mimePart = curl_mime_addpart(curl_->multipart); if (!part.content_type.empty()) { curl_mime_type(mimePart, part.content_type.c_str()); } curl_mime_filedata(mimePart, part.value.c_str()); curl_mime_name(mimePart, part.name.c_str()); if (part.has_filename) { curl_mime_filename(mimePart, part.filename.c_str()); } } else { curl_mimepart* mimePart = curl_mime_addpart(curl_->multipart); if (!part.content_type.empty()) { curl_mime_type(mimePart, part.content_type.c_str()); } if (part.is_buffer) { // Do not use formdata, to prevent having to use reinterpreter_cast: curl_mime_name(mimePart, part.name.c_str()); curl_mime_data(mimePart, part.data, part.datalen); curl_mime_filename(mimePart, part.value.c_str()); } else { curl_mime_name(mimePart, part.name.c_str()); curl_mime_data(mimePart, part.value.c_str(), CURL_ZERO_TERMINATED); } } } curl_easy_setopt(curl_->handle, CURLOPT_MIMEPOST, curl_->multipart); hasBodyOrPayload_ = true; } void Session::SetMultipart(Multipart&& multipart) { SetMultipart(multipart); } void Session::SetRedirect(const Redirect& redirect) { curl_easy_setopt(curl_->handle, CURLOPT_FOLLOWLOCATION, redirect.follow ? 1L : 0L); curl_easy_setopt(curl_->handle, CURLOPT_MAXREDIRS, redirect.maximum); curl_easy_setopt(curl_->handle, CURLOPT_UNRESTRICTED_AUTH, redirect.cont_send_cred ? 1L : 0L); // NOLINTNEXTLINE (google-runtime-int) long mask = 0; if (any(redirect.post_flags & PostRedirectFlags::POST_301)) { mask |= CURL_REDIR_POST_301; } if (any(redirect.post_flags & PostRedirectFlags::POST_302)) { mask |= CURL_REDIR_POST_302; } if (any(redirect.post_flags & PostRedirectFlags::POST_303)) { mask |= CURL_REDIR_POST_303; } curl_easy_setopt(curl_->handle, CURLOPT_POSTREDIR, mask); } void Session::SetCookies(const Cookies& cookies) { curl_easy_setopt(curl_->handle, CURLOPT_COOKIELIST, "ALL"); curl_easy_setopt(curl_->handle, CURLOPT_COOKIE, cookies.GetEncoded(*curl_).c_str()); } void Session::SetBody(const Body& body) { hasBodyOrPayload_ = true; curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(body.str().length())); curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, body.c_str()); } void Session::SetBody(Body&& body) { hasBodyOrPayload_ = true; curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(body.str().length())); curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, body.c_str()); } void Session::SetLowSpeed(const LowSpeed& low_speed) { curl_easy_setopt(curl_->handle, CURLOPT_LOW_SPEED_LIMIT, low_speed.limit); curl_easy_setopt(curl_->handle, CURLOPT_LOW_SPEED_TIME, low_speed.time); } void Session::SetVerifySsl(const VerifySsl& verify) { curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYPEER, verify ? ON : OFF); curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYHOST, verify ? 2L : 0L); } void Session::SetUnixSocket(const UnixSocket& unix_socket) { curl_easy_setopt(curl_->handle, CURLOPT_UNIX_SOCKET_PATH, unix_socket.GetUnixSocketString()); } void Session::SetSslOptions(const SslOptions& options) { if (!options.cert_file.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSLCERT, options.cert_file.c_str()); if (!options.cert_type.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSLCERTTYPE, options.cert_type.c_str()); } } if (!options.key_file.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSLKEY, options.key_file.c_str()); if (!options.key_type.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSLKEYTYPE, options.key_type.c_str()); } if (!options.key_pass.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_KEYPASSWD, options.key_pass.c_str()); } #if SUPPORT_CURLOPT_SSLKEY_BLOB } else if (!options.key_blob.empty()) { std::string key_blob(options.key_blob); curl_blob blob{}; // NOLINTNEXTLINE (readability-container-data-pointer) blob.data = &key_blob[0]; blob.len = key_blob.length(); curl_easy_setopt(curl_->handle, CURLOPT_SSLKEY_BLOB, &blob); if (!options.key_type.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSLKEYTYPE, options.key_type.c_str()); } if (!options.key_pass.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_KEYPASSWD, options.key_pass.c_str()); } #endif } if (!options.pinned_public_key.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_PINNEDPUBLICKEY, options.pinned_public_key.c_str()); } #if SUPPORT_ALPN curl_easy_setopt(curl_->handle, CURLOPT_SSL_ENABLE_ALPN, options.enable_alpn ? ON : OFF); #endif #if SUPPORT_NPN curl_easy_setopt(curl_->handle, CURLOPT_SSL_ENABLE_NPN, options.enable_npn ? ON : OFF); #endif curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYPEER, options.verify_peer ? ON : OFF); curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYHOST, options.verify_host ? 2L : 0L); #if LIBCURL_VERSION_NUM >= 0x072900 // 7.41.0 curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYSTATUS, options.verify_status ? ON : OFF); #endif int maxTlsVersion = options.ssl_version; #if SUPPORT_MAX_TLS_VERSION maxTlsVersion |= options.max_version; #endif curl_easy_setopt(curl_->handle, CURLOPT_SSLVERSION, // Ignore here since this has been defined by libcurl. maxTlsVersion); #if SUPPORT_SSL_NO_REVOKE if (options.ssl_no_revoke) { curl_easy_setopt(curl_->handle, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE); } #endif if (!options.ca_info.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_CAINFO, options.ca_info.c_str()); } if (!options.ca_path.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_CAPATH, options.ca_path.c_str()); } #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION #ifdef OPENSSL_BACKEND_USED if (!options.ca_buffer.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSL_CTX_FUNCTION, sslctx_function_load_ca_cert_from_buffer); curl_easy_setopt(curl_->handle, CURLOPT_SSL_CTX_DATA, options.ca_buffer.c_str()); } #endif #endif if (!options.crl_file.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_CRLFILE, options.crl_file.c_str()); } if (!options.ciphers.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_SSL_CIPHER_LIST, options.ciphers.c_str()); } #if SUPPORT_TLSv13_CIPHERS if (!options.tls13_ciphers.empty()) { curl_easy_setopt(curl_->handle, CURLOPT_TLS13_CIPHERS, options.ciphers.c_str()); } #endif #if SUPPORT_SESSIONID_CACHE curl_easy_setopt(curl_->handle, CURLOPT_SSL_SESSIONID_CACHE, options.session_id_cache ? ON : OFF); #endif } void Session::SetVerbose(const Verbose& verbose) { curl_easy_setopt(curl_->handle, CURLOPT_VERBOSE, verbose.verbose ? ON : OFF); } void Session::SetInterface(const Interface& iface) { if (iface.str().empty()) { curl_easy_setopt(curl_->handle, CURLOPT_INTERFACE, nullptr); } else { curl_easy_setopt(curl_->handle, CURLOPT_INTERFACE, iface.c_str()); } } void Session::SetLocalPort(const LocalPort& local_port) { curl_easy_setopt(curl_->handle, CURLOPT_LOCALPORT, static_cast(static_cast(local_port))); } void Session::SetLocalPortRange(const LocalPortRange& local_port_range) { curl_easy_setopt(curl_->handle, CURLOPT_LOCALPORTRANGE, static_cast(static_cast(local_port_range))); } void Session::SetHttpVersion(const HttpVersion& version) { switch (version.code) { case HttpVersionCode::VERSION_NONE: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE); break; case HttpVersionCode::VERSION_1_0: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); break; case HttpVersionCode::VERSION_1_1: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); break; #if LIBCURL_VERSION_NUM >= 0x072100 // 7.33.0 case HttpVersionCode::VERSION_2_0: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); break; #endif #if LIBCURL_VERSION_NUM >= 0x072F00 // 7.47.0 case HttpVersionCode::VERSION_2_0_TLS: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); break; #endif #if LIBCURL_VERSION_NUM >= 0x073100 // 7.49.0 case HttpVersionCode::VERSION_2_0_PRIOR_KNOWLEDGE: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE); break; #endif #if LIBCURL_VERSION_NUM >= 0x074200 // 7.66.0 case HttpVersionCode::VERSION_3_0: curl_easy_setopt(curl_->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3); break; #endif default: // Should not happen throw std::invalid_argument("Invalid/Unknown HTTP version type."); } } void Session::SetRange(const Range& range) { const std::string range_str = range.str(); curl_easy_setopt(curl_->handle, CURLOPT_RANGE, range_str.c_str()); } void Session::SetMultiRange(const MultiRange& multi_range) { const std::string multi_range_str = multi_range.str(); curl_easy_setopt(curl_->handle, CURLOPT_RANGE, multi_range_str.c_str()); } void Session::SetReserveSize(const ReserveSize& reserve_size) { ResponseStringReserve(reserve_size.size); } void Session::SetAcceptEncoding(const AcceptEncoding& accept_encoding) { acceptEncoding_ = accept_encoding; } void Session::SetAcceptEncoding(AcceptEncoding&& accept_encoding) { acceptEncoding_ = std::move(accept_encoding); } cpr_off_t Session::GetDownloadFileLength() { cpr_off_t downloadFileLenth = -1; curl_easy_setopt(curl_->handle, CURLOPT_URL, url_.c_str()); const std::string protocol = url_.str().substr(0, url_.str().find(':')); if (proxies_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXY, proxies_[protocol].c_str()); if (proxyAuth_.has(protocol)) { curl_easy_setopt(curl_->handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(curl_->handle, CURLOPT_PROXYUSERPWD, proxyAuth_[protocol]); } } curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 1); if (curl_easy_perform(curl_->handle) == CURLE_OK) { curl_easy_getinfo(curl_->handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &downloadFileLenth); } return downloadFileLenth; } void Session::ResponseStringReserve(size_t size) { response_string_reserve_size_ = size; } Response Session::Delete() { PrepareDelete(); return makeRequest(); } Response Session::Download(const WriteCallback& write) { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); SetWriteCallback(write); return makeDownloadRequest(); } Response Session::Download(std::ofstream& file) { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeFileFunction); curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &file); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); return makeDownloadRequest(); } Response Session::Get() { PrepareGet(); return makeRequest(); } Response Session::Head() { PrepareHead(); return makeRequest(); } Response Session::Options() { PrepareOptions(); return makeRequest(); } Response Session::Patch() { PreparePatch(); return makeRequest(); } Response Session::Post() { PreparePost(); return makeRequest(); } Response Session::Put() { PreparePut(); return makeRequest(); } std::shared_ptr Session::GetSharedPtrFromThis() { try { return shared_from_this(); } catch (std::bad_weak_ptr&) { throw std::runtime_error("Failed to get a shared pointer from this. The reason is probably that the session object is not managed by a shared pointer, which is required to use this functionality."); } } AsyncResponse Session::GetAsync() { auto shared_this = shared_from_this(); return async([shared_this]() { return shared_this->Get(); }); } AsyncResponse Session::DeleteAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Delete(); }); } AsyncResponse Session::DownloadAsync(const WriteCallback& write) { auto shared_this = GetSharedPtrFromThis(); return async([shared_this, write]() { return shared_this->Download(write); }); } AsyncResponse Session::DownloadAsync(std::ofstream& file) { auto shared_this = GetSharedPtrFromThis(); return async([shared_this, &file]() { return shared_this->Download(file); }); } AsyncResponse Session::HeadAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Head(); }); } AsyncResponse Session::OptionsAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Options(); }); } AsyncResponse Session::PatchAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Patch(); }); } AsyncResponse Session::PostAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Post(); }); } AsyncResponse Session::PutAsync() { auto shared_this = GetSharedPtrFromThis(); return async([shared_this]() { return shared_this->Put(); }); } std::shared_ptr Session::GetCurlHolder() { return curl_; } std::string Session::GetFullRequestUrl() { const std::string parametersContent = parameters_.GetContent(*curl_); return url_.str() + (parametersContent.empty() ? "" : "?") + parametersContent; } void Session::PrepareDelete() { curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 0L); curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "DELETE"); prepareCommon(); } void Session::PrepareGet() { // In case there is a body or payload for this request, we create a custom GET-Request since a // GET-Request with body is based on the HTTP RFC **not** a leagal request. if (hasBodyOrPayload_) { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "GET"); } else { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 1L); } prepareCommon(); } void Session::PrepareHead() { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 1L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); prepareCommon(); } void Session::PrepareOptions() { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "OPTIONS"); prepareCommon(); } void Session::PreparePatch() { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "PATCH"); prepareCommon(); } void Session::PreparePost() { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); // In case there is no body or payload set it to an empty post: if (hasBodyOrPayload_) { curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); } else { curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, readcb_.callback ? nullptr : ""); curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "POST"); } prepareCommon(); } void Session::PreparePut() { curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); if (!hasBodyOrPayload_ && readcb_.callback) { /** * Yes, this one has to be CURLOPT_POSTFIELDS even if we are performing a PUT request. * In case we don't set this one, performing a POST-request with PUT won't work. * It in theory this only enforces the usage of the readcallback for POST requests, but works here as well. **/ curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, nullptr); } curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "PUT"); curl_easy_setopt(curl_->handle, CURLOPT_RANGE, nullptr); prepareCommon(); } Response Session::Complete(CURLcode curl_error) { curl_slist* raw_cookies{nullptr}; curl_easy_getinfo(curl_->handle, CURLINFO_COOKIELIST, &raw_cookies); Cookies cookies = util::parseCookies(raw_cookies); curl_slist_free_all(raw_cookies); // Reset the has no body property: hasBodyOrPayload_ = false; std::string errorMsg = curl_->error.data(); return Response(curl_, std::move(response_string_), std::move(header_string_), std::move(cookies), Error(curl_error, std::move(errorMsg))); } void Session::AddInterceptor(const std::shared_ptr& pinterceptor) { interceptors_.push(pinterceptor); } Response Session::proceed() { prepareCommon(); return makeRequest(); } // clang-format off void Session::SetOption(const ReadCallback& read) { SetReadCallback(read); } void Session::SetOption(const HeaderCallback& header) { SetHeaderCallback(header); } void Session::SetOption(const WriteCallback& write) { SetWriteCallback(write); } void Session::SetOption(const ProgressCallback& progress) { SetProgressCallback(progress); } void Session::SetOption(const DebugCallback& debug) { SetDebugCallback(debug); } void Session::SetOption(const Url& url) { SetUrl(url); } void Session::SetOption(const Parameters& parameters) { SetParameters(parameters); } void Session::SetOption(Parameters&& parameters) { SetParameters(std::move(parameters)); } void Session::SetOption(const Header& header) { SetHeader(header); } void Session::SetOption(const Timeout& timeout) { SetTimeout(timeout); } void Session::SetOption(const ConnectTimeout& timeout) { SetConnectTimeout(timeout); } void Session::SetOption(const Authentication& auth) { SetAuth(auth); } void Session::SetOption(const LimitRate& limit_rate) { SetLimitRate(limit_rate); } // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 void Session::SetOption(const Bearer& auth) { SetBearer(auth); } #endif void Session::SetOption(const UserAgent& ua) { SetUserAgent(ua); } void Session::SetOption(const Payload& payload) { SetPayload(payload); } void Session::SetOption(Payload&& payload) { SetPayload(std::move(payload)); } void Session::SetOption(const Proxies& proxies) { SetProxies(proxies); } void Session::SetOption(Proxies&& proxies) { SetProxies(std::move(proxies)); } void Session::SetOption(ProxyAuthentication&& proxy_auth) { SetProxyAuth(std::move(proxy_auth)); } void Session::SetOption(const ProxyAuthentication& proxy_auth) { SetProxyAuth(proxy_auth); } void Session::SetOption(const Multipart& multipart) { SetMultipart(multipart); } void Session::SetOption(Multipart&& multipart) { SetMultipart(std::move(multipart)); } void Session::SetOption(const Redirect& redirect) { SetRedirect(redirect); } void Session::SetOption(const Cookies& cookies) { SetCookies(cookies); } void Session::SetOption(const Body& body) { SetBody(body); } void Session::SetOption(Body&& body) { SetBody(std::move(body)); } void Session::SetOption(const LowSpeed& low_speed) { SetLowSpeed(low_speed); } void Session::SetOption(const VerifySsl& verify) { SetVerifySsl(verify); } void Session::SetOption(const Verbose& verbose) { SetVerbose(verbose); } void Session::SetOption(const UnixSocket& unix_socket) { SetUnixSocket(unix_socket); } void Session::SetOption(const SslOptions& options) { SetSslOptions(options); } void Session::SetOption(const Interface& iface) { SetInterface(iface); } void Session::SetOption(const LocalPort& local_port) { SetLocalPort(local_port); } void Session::SetOption(const LocalPortRange& local_port_range) { SetLocalPortRange(local_port_range); } void Session::SetOption(const HttpVersion& version) { SetHttpVersion(version); } void Session::SetOption(const Range& range) { SetRange(range); } void Session::SetOption(const MultiRange& multi_range) { SetMultiRange(multi_range); } void Session::SetOption(const ReserveSize& reserve_size) { SetReserveSize(reserve_size.size); } void Session::SetOption(const AcceptEncoding& accept_encoding) { SetAcceptEncoding(accept_encoding); } void Session::SetOption(AcceptEncoding&& accept_encoding) { SetAcceptEncoding(accept_encoding); } // clang-format on } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/ssl_ctx.cpp000066400000000000000000000042411520575453600252470ustar00rootroot00000000000000 #include "cpr/ssl_ctx.h" #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION #ifdef OPENSSL_BACKEND_USED #include #include #include namespace cpr { /** * The ssl_ctx parameter is actually a pointer to the SSL library's SSL_CTX for OpenSSL. * If an error is returned from the callback no attempt to establish a connection is made and * the perform operation will return the callback's error code. * * Sources: https://curl.se/libcurl/c/CURLOPT_SSL_CTX_FUNCTION.html * https://curl.se/libcurl/c/CURLOPT_SSL_CTX_DATA.html */ CURLcode sslctx_function_load_ca_cert_from_buffer(CURL* /*curl*/, void* sslctx, void* raw_cert_buf) { // Check arguments if (raw_cert_buf == nullptr || sslctx == nullptr) { printf("Invalid callback arguments\n"); return CURLE_ABORTED_BY_CALLBACK; } // Setup pointer X509_STORE* store = nullptr; X509* cert = nullptr; BIO* bio = nullptr; char* cert_buf = static_cast(raw_cert_buf); // Create a memory BIO using the data of cert_buf. // Note: It is assumed, that cert_buf is nul terminated and its length is determined by strlen. bio = BIO_new_mem_buf(cert_buf, -1); // Load the PEM formatted certicifate into an X509 structure which OpenSSL can use. PEM_read_bio_X509(bio, &cert, nullptr, nullptr); if (cert == nullptr) { printf("PEM_read_bio_X509 failed\n"); return CURLE_ABORTED_BY_CALLBACK; } // Get a pointer to the current certificate verification storage store = SSL_CTX_get_cert_store(static_cast(sslctx)); // Add the loaded certificate to the verification storage const int status = X509_STORE_add_cert(store, cert); if (status == 0) { printf("Error adding certificate\n"); return CURLE_ABORTED_BY_CALLBACK; } // Decrement the reference count of the X509 structure cert and frees it up X509_free(cert); // Free the entire bio chain BIO_free(bio); // The CA certificate was loaded successfully into the verification storage return CURLE_OK; } } // namespace cpr #endif // OPENSSL_BACKEND_USED #endif // SUPPORT_CURLOPT_SSL_CTX_FUNCTION kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/threadpool.cpp000066400000000000000000000073471520575453600257430ustar00rootroot00000000000000#include "cpr/threadpool.h" namespace cpr { ThreadPool::ThreadPool(size_t min_threads, size_t max_threads, std::chrono::milliseconds max_idle_ms) : min_thread_num(min_threads), max_thread_num(max_threads), max_idle_time(max_idle_ms), status(STOP), cur_thread_num(0), idle_thread_num(0) {} ThreadPool::~ThreadPool() { Stop(); } int ThreadPool::Start(size_t start_threads) { if (status != STOP) { return -1; } status = RUNNING; if (start_threads < min_thread_num) { start_threads = min_thread_num; } if (start_threads > max_thread_num) { start_threads = max_thread_num; } for (size_t i = 0; i < start_threads; ++i) { CreateThread(); } return 0; } int ThreadPool::Stop() { if (status == STOP) { return -1; } status = STOP; task_cond.notify_all(); for (auto& i : threads) { if (i.thread->joinable()) { i.thread->join(); } } threads.clear(); cur_thread_num = 0; idle_thread_num = 0; return 0; } int ThreadPool::Pause() { if (status == RUNNING) { status = PAUSE; } return 0; } int ThreadPool::Resume() { if (status == PAUSE) { status = RUNNING; } return 0; } int ThreadPool::Wait() { while (true) { if (status == STOP || (tasks.empty() && idle_thread_num == cur_thread_num)) { break; } std::this_thread::yield(); } return 0; } bool ThreadPool::CreateThread() { if (cur_thread_num >= max_thread_num) { return false; } std::thread* thread = new std::thread([this] { bool initialRun = true; while (status != STOP) { while (status == PAUSE) { std::this_thread::yield(); } Task task; { std::unique_lock locker(task_mutex); task_cond.wait_for(locker, std::chrono::milliseconds(max_idle_time), [this]() { return status == STOP || !tasks.empty(); }); if (status == STOP) { return; } if (tasks.empty()) { if (cur_thread_num > min_thread_num) { DelThread(std::this_thread::get_id()); return; } continue; } if (!initialRun) { --idle_thread_num; } task = std::move(tasks.front()); tasks.pop(); } if (task) { task(); ++idle_thread_num; if (initialRun) { initialRun = false; } } } }); AddThread(thread); return true; } void ThreadPool::AddThread(std::thread* thread) { thread_mutex.lock(); ++cur_thread_num; ThreadData data; data.thread = std::shared_ptr(thread); data.id = thread->get_id(); data.status = RUNNING; data.start_time = time(nullptr); data.stop_time = 0; threads.emplace_back(data); thread_mutex.unlock(); } void ThreadPool::DelThread(std::thread::id id) { const time_t now = time(nullptr); thread_mutex.lock(); --cur_thread_num; --idle_thread_num; auto iter = threads.begin(); while (iter != threads.end()) { if (iter->status == STOP && now > iter->stop_time) { if (iter->thread->joinable()) { iter->thread->join(); iter = threads.erase(iter); continue; } } else if (iter->id == id) { iter->status = STOP; iter->stop_time = time(nullptr); } ++iter; } thread_mutex.unlock(); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/timeout.cpp000066400000000000000000000022071520575453600252560ustar00rootroot00000000000000#include "cpr/timeout.h" #include #include #include #include namespace cpr { // No way around since curl uses a long here. // NOLINTNEXTLINE(google-runtime-int) long Timeout::Milliseconds() const { static_assert(std::is_same::value, "Following casting expects milliseconds."); // No way around since curl uses a long here. // NOLINTNEXTLINE(google-runtime-int) if (ms.count() > static_cast(std::numeric_limits::max())) { throw std::overflow_error("cpr::Timeout: timeout value overflow: " + std::to_string(ms.count()) + " ms."); } // No way around since curl uses a long here. // NOLINTNEXTLINE(google-runtime-int) if (ms.count() < static_cast(std::numeric_limits::min())) { throw std::underflow_error("cpr::Timeout: timeout value underflow: " + std::to_string(ms.count()) + " ms."); } // No way around since curl uses a long here. // NOLINTNEXTLINE(google-runtime-int) return static_cast(ms.count()); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/unix_socket.cpp000066400000000000000000000002431520575453600261210ustar00rootroot00000000000000 #include "cpr/unix_socket.h" namespace cpr { const char* UnixSocket::GetUnixSocketString() const noexcept { return unix_socket_.data(); } } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/cpr/util.cpp000066400000000000000000000174761520575453600245630ustar00rootroot00000000000000#include "cpr/util.h" #include #include #include #include #include #include #include #include #include #include #include #if defined(_Win32) #include #else #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wreserved-macro-identifier") // Not all versions of clang support this flag like the one used on Ubuntu 18.04 #pragma clang diagnostic ignored "-Wreserved-macro-identifier" #endif #pragma clang diagnostic ignored "-Wunused-macros" #endif // https://en.cppreference.com/w/c/string/byte/memset // NOLINTNEXTLINE(bugprone-reserved-identifier, cert-dcl37-c, cert-dcl51-cpp, cppcoreguidelines-macro-usage) #define __STDC_WANT_LIB_EXT1__ 1 #ifdef __clang__ #pragma clang diagnostic pop #endif #include #endif namespace cpr { namespace util { enum class CurlHTTPCookieField : size_t { Domain = 0, IncludeSubdomains, Path, HttpsOnly, Expires, Name, Value, }; Cookies parseCookies(curl_slist* raw_cookies) { const int CURL_HTTP_COOKIE_SIZE = static_cast(CurlHTTPCookieField::Value) + 1; Cookies cookies; for (curl_slist* nc = raw_cookies; nc; nc = nc->next) { std::vector tokens = cpr::util::split(nc->data, '\t'); while (tokens.size() < CURL_HTTP_COOKIE_SIZE) { tokens.emplace_back(""); } const std::time_t expires = static_cast(std::stoul(tokens.at(static_cast(CurlHTTPCookieField::Expires)))); cookies.emplace_back(Cookie{ tokens.at(static_cast(CurlHTTPCookieField::Name)), tokens.at(static_cast(CurlHTTPCookieField::Value)), tokens.at(static_cast(CurlHTTPCookieField::Domain)), isTrue(tokens.at(static_cast(CurlHTTPCookieField::IncludeSubdomains))), tokens.at(static_cast(CurlHTTPCookieField::Path)), isTrue(tokens.at(static_cast(CurlHTTPCookieField::HttpsOnly))), std::chrono::system_clock::from_time_t(expires), }); } return cookies; } Header parseHeader(const std::string& headers, std::string* status_line, std::string* reason) { Header header; std::vector lines; std::istringstream stream(headers); { std::string line; while (std::getline(stream, line, '\n')) { lines.push_back(line); } } for (std::string& line : lines) { if (line.substr(0, 5) == "HTTP/") { // set the status_line if it was given if ((status_line != nullptr) || (reason != nullptr)) { line.resize(std::min(line.size(), line.find_last_not_of("\t\n\r ") + 1)); if (status_line != nullptr) { *status_line = line; } // set the reason if it was given if (reason != nullptr) { const size_t pos1 = line.find_first_of("\t "); size_t pos2 = std::string::npos; if (pos1 != std::string::npos) { pos2 = line.find_first_of("\t ", pos1 + 1); } if (pos2 != std::string::npos) { line.erase(0, pos2 + 1); *reason = line; } } } header.clear(); } if (line.length() > 0) { const size_t found = line.find(':'); if (found != std::string::npos) { std::string value = line.substr(found + 1); value.erase(0, value.find_first_not_of("\t ")); value.resize(std::min(value.size(), value.find_last_not_of("\t\n\r ") + 1)); header[line.substr(0, found)] = value; } } } return header; } std::vector split(const std::string& to_split, char delimiter) { std::vector tokens; std::stringstream stream(to_split); std::string item; while (std::getline(stream, item, delimiter)) { tokens.push_back(item); } return tokens; } size_t readUserFunction(char* ptr, size_t size, size_t nitems, const ReadCallback* read) { size *= nitems; return (*read)(ptr, size) ? size : CURL_READFUNC_ABORT; } size_t headerUserFunction(char* ptr, size_t size, size_t nmemb, const HeaderCallback* header) { size *= nmemb; return (*header)({ptr, size}) ? size : 0; } size_t writeFunction(char* ptr, size_t size, size_t nmemb, std::string* data) { size *= nmemb; data->append(ptr, size); return size; } size_t writeFileFunction(char* ptr, size_t size, size_t nmemb, std::ofstream* file) { size *= nmemb; file->write(ptr, static_cast(size)); return size; } size_t writeUserFunction(char* ptr, size_t size, size_t nmemb, const WriteCallback* write) { size *= nmemb; return (*write)({ptr, size}) ? size : 0; } #if LIBCURL_VERSION_NUM < 0x072000 int progressUserFunction(const ProgressCallback* progress, double dltotal, double dlnow, double ultotal, double ulnow) { #else int progressUserFunction(const ProgressCallback* progress, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { #endif return (*progress)(dltotal, dlnow, ultotal, ulnow) ? 0 : 1; } int debugUserFunction(CURL* /*handle*/, curl_infotype type, char* data, size_t size, const DebugCallback* debug) { (*debug)(static_cast(type), std::string(data, size)); return 0; } /** * Creates a temporary CurlHolder object and uses it to escape the given string. * If you plan to use this methode on a regular basis think about creating a CurlHolder * object and calling urlEncode(std::string) on it. * * Example: * CurlHolder holder; * std::string input = "Hello World!"; * std::string result = holder.urlEncode(input); **/ std::string urlEncode(const std::string& s) { const CurlHolder holder; // Create a temporary new holder for URL encoding return holder.urlEncode(s); } /** * Creates a temporary CurlHolder object and uses it to unescape the given string. * If you plan to use this methode on a regular basis think about creating a CurlHolder * object and calling urlDecode(std::string) on it. * * Example: * CurlHolder holder; * std::string input = "Hello%20World%21"; * std::string result = holder.urlDecode(input); **/ std::string urlDecode(const std::string& s) { const CurlHolder holder; // Create a temporary new holder for URL decoding return holder.urlDecode(s); } #if defined(__STDC_LIB_EXT1__) void secureStringClear(std::string& s) { if (s.empty()) { return; } memset_s(&s.front(), s.length(), 0, s.length()); s.clear(); } #elif defined(_WIN32) void secureStringClear(std::string& s) { if (s.empty()) { return; } SecureZeroMemory(&s.front(), s.length()); s.clear(); } #else #if defined(__clang__) #pragma clang optimize off // clang #elif defined(__GNUC__) || defined(__MINGW32__) || defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC push_options // g++ #pragma GCC optimize("O0") // g++ #endif void secureStringClear(std::string& s) { if (s.empty()) { return; } // NOLINTNEXTLINE (readability-container-data-pointer) char* ptr = &(s[0]); memset(ptr, '\0', s.length()); s.clear(); } #if defined(__clang__) #pragma clang optimize on // clang #elif defined(__GNUC__) || defined(__MINGW32__) || defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC pop_options // g++ #endif #endif bool isTrue(const std::string& s) { std::string temp_string{s}; std::transform(temp_string.begin(), temp_string.end(), temp_string.begin(), [](unsigned char c) { return std::tolower(c); }); return temp_string == "true"; } } // namespace util } // namespace cpr kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/000077500000000000000000000000001520575453600237225ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/CMakeLists.txt000066400000000000000000000023551520575453600264670ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.15) include_directories(cpr) target_include_directories(cpr PUBLIC $ $ $) target_sources(cpr PRIVATE # Header files (useful in IDEs) cpr/accept_encoding.h cpr/api.h cpr/async.h cpr/auth.h cpr/bearer.h cpr/body.h cpr/buffer.h cpr/cert_info.h cpr/cookies.h cpr/cpr.h cpr/cprtypes.h cpr/curlholder.h cpr/curlholder.h cpr/error.h cpr/file.h cpr/limit_rate.h cpr/local_port.h cpr/local_port_range.h cpr/multipart.h cpr/parameters.h cpr/payload.h cpr/proxies.h cpr/proxyauth.h cpr/response.h cpr/session.h cpr/singleton.h cpr/ssl_ctx.h cpr/ssl_options.h cpr/threadpool.h cpr/timeout.h cpr/unix_socket.h cpr/util.h cpr/verbose.h cpr/interface.h cpr/redirect.h cpr/http_version.h cpr/interceptor.h ${PROJECT_BINARY_DIR}/cpr_generated_includes/cpr/cprver.h ) install(DIRECTORY cpr DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(DIRECTORY ${PROJECT_BINARY_DIR}/cpr_generated_includes/cpr DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/000077500000000000000000000000001520575453600245065ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/accept_encoding.h000066400000000000000000000016111520575453600277630ustar00rootroot00000000000000#ifndef CPR_ACCEPT_ENCODING_H #define CPR_ACCEPT_ENCODING_H #include #include #include #include #include namespace cpr { enum class AcceptEncodingMethods { identity, deflate, zlib, gzip, }; static const std::map AcceptEncodingMethodsStringMap{{AcceptEncodingMethods::identity, "identity"}, {AcceptEncodingMethods::deflate, "deflate"}, {AcceptEncodingMethods::zlib, "zlib"}, {AcceptEncodingMethods::gzip, "gzip"}}; class AcceptEncoding { public: AcceptEncoding() = default; AcceptEncoding(const std::initializer_list& methods); AcceptEncoding(const std::initializer_list& methods); bool empty() const noexcept; const std::string getString() const; private: std::vector methods_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/api.h000066400000000000000000000170101520575453600254270ustar00rootroot00000000000000#ifndef CPR_API_H #define CPR_API_H #include #include #include #include #include #include "cpr/async.h" #include "cpr/auth.h" #include "cpr/bearer.h" #include "cpr/cprtypes.h" #include "cpr/multipart.h" #include "cpr/payload.h" #include "cpr/response.h" #include "cpr/session.h" #include namespace cpr { using AsyncResponse = std::future; namespace priv { template void set_option_internal(Session& session, CurrentType&& current_option) { session.SetOption(std::forward(current_option)); } template <> inline void set_option_internal(Session& session, Header&& current_option) { // Header option was already provided -> Update previous header session.UpdateHeader(std::forward
(current_option)); } template void set_option_internal(Session& session, CurrentType&& current_option, Ts&&... ts) { set_option_internal(session, std::forward(current_option)); if (std::is_same::value) { set_option_internal(session, std::forward(ts)...); } else { set_option_internal(session, std::forward(ts)...); } } template void set_option(Session& session, Ts&&... ts) { set_option_internal(session, std::forward(ts)...); } } // namespace priv // Get methods template Response Get(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Get(); } // Get async methods template AsyncResponse GetAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Get(std::move(ts_inner)...); }, std::move(ts)...); } // Get callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto GetCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Get(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Post methods template Response Post(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Post(); } // Post async methods template AsyncResponse PostAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Post(std::move(ts_inner)...); }, std::move(ts)...); } // Post callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto PostCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Post(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Put methods template Response Put(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Put(); } // Put async methods template AsyncResponse PutAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Put(std::move(ts_inner)...); }, std::move(ts)...); } // Put callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto PutCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Put(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Head methods template Response Head(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Head(); } // Head async methods template AsyncResponse HeadAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Head(std::move(ts_inner)...); }, std::move(ts)...); } // Head callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto HeadCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Head(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Delete methods template Response Delete(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Delete(); } // Delete async methods template AsyncResponse DeleteAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Delete(std::move(ts_inner)...); }, std::move(ts)...); } // Delete callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto DeleteCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Delete(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Options methods template Response Options(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Options(); } // Options async methods template AsyncResponse OptionsAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Options(std::move(ts_inner)...); }, std::move(ts)...); } // Options callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto OptionsCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Options(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Patch methods template Response Patch(Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Patch(); } // Patch async methods template AsyncResponse PatchAsync(Ts... ts) { return cpr::async( [](Ts... ts_inner) { return Patch(std::move(ts_inner)...); }, std::move(ts)...); } // Patch callback methods template // NOLINTNEXTLINE(fuchsia-trailing-return) auto PatchCallback(Then then, Ts... ts) -> std::future { return cpr::async( [](Then then_inner, Ts... ts_inner) { return then_inner(Patch(std::move(ts_inner)...)); }, std::move(then), std::move(ts)...); } // Download methods template Response Download(std::ofstream& file, Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Download(file); } // Download async method template AsyncResponse DownloadAsync(std::string local_path, Ts... ts) { return std::async( std::launch::async, [](std::string local_path, Ts... ts) { std::ofstream f(local_path); return Download(f, std::move(ts)...); }, std::move(local_path), std::move(ts)...); } // Download with user callback template Response Download(const WriteCallback& write, Ts&&... ts) { Session session; priv::set_option(session, std::forward(ts)...); return session.Download(write); } } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/async.h000066400000000000000000000025131520575453600257750ustar00rootroot00000000000000#ifndef CPR_ASYNC_H #define CPR_ASYNC_H #include "singleton.h" #include "threadpool.h" namespace cpr { class GlobalThreadPool : public ThreadPool { CPR_SINGLETON_DECL(GlobalThreadPool) protected: GlobalThreadPool() = default; public: ~GlobalThreadPool() override = default; }; /** * Return a future, calling future.get() will wait task done and return RetType. * async(fn, args...) * async(std::bind(&Class::mem_fn, &obj)) * async(std::mem_fn(&Class::mem_fn, &obj)) **/ template auto async(Fn&& fn, Args&&... args) -> std::future { return GlobalThreadPool::GetInstance()->Submit(std::forward(fn), std::forward(args)...); } class async { public: static void startup(size_t min_threads = CPR_DEFAULT_THREAD_POOL_MIN_THREAD_NUM, size_t max_threads = CPR_DEFAULT_THREAD_POOL_MAX_THREAD_NUM, std::chrono::milliseconds max_idle_ms = CPR_DEFAULT_THREAD_POOL_MAX_IDLE_TIME) { GlobalThreadPool* gtp = GlobalThreadPool::GetInstance(); if (gtp->IsStarted()) { return; } gtp->SetMinThreadNum(min_threads); gtp->SetMaxThreadNum(max_threads); gtp->SetMaxIdleTime(max_idle_ms); gtp->Start(); } static void cleanup() { GlobalThreadPool::ExitInstance(); } }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/auth.h000066400000000000000000000020031520575453600256130ustar00rootroot00000000000000#ifndef CPR_AUTH_H #define CPR_AUTH_H #include #include namespace cpr { enum class AuthMode { BASIC, DIGEST, NTLM }; class Authentication { public: Authentication(const std::string& username, const std::string& password, const AuthMode& auth_mode) : auth_string_{username + ":" + password}, auth_mode_{auth_mode} {} Authentication(std::string&& username, std::string&& password, const AuthMode&& auth_mode) : auth_string_{std::move(username) + ":" + std::move(password)}, auth_mode_{std::move(auth_mode)} {} Authentication(const Authentication& other) = default; Authentication(Authentication&& old) noexcept = default; ~Authentication() noexcept; Authentication& operator=(Authentication&& old) noexcept = default; Authentication& operator=(const Authentication& other) = default; const char* GetAuthString() const noexcept; AuthMode GetAuthMode() const noexcept; private: std::string auth_string_; AuthMode auth_mode_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/bearer.h000066400000000000000000000016631520575453600261250ustar00rootroot00000000000000#ifndef CPR_BEARER_H #define CPR_BEARER_H #include #include #include namespace cpr { // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 class Bearer { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Bearer(const std::string& token) : token_string_{token} {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Bearer(std::string&& token) : token_string_{std::move(token)} {} Bearer(const Bearer& other) = default; Bearer(Bearer&& old) noexcept = default; virtual ~Bearer() noexcept; Bearer& operator=(Bearer&& old) noexcept = default; Bearer& operator=(const Bearer& other) = default; virtual const char* GetToken() const noexcept; protected: std::string token_string_; }; #endif } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/body.h000066400000000000000000000034401520575453600256150ustar00rootroot00000000000000#ifndef CPR_BODY_H #define CPR_BODY_H #include #include #include #include #include #include "cpr/buffer.h" #include "cpr/cprtypes.h" #include "cpr/file.h" namespace cpr { class Body : public StringHolder { public: Body() : StringHolder() {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Body(const std::string& body) : StringHolder(body) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Body(std::string&& body) : StringHolder(std::move(body)) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Body(const char* body) : StringHolder(body) {} Body(const char* str, size_t len) : StringHolder(str, len) {} Body(const std::initializer_list args) : StringHolder(args) {} Body(const Buffer& buffer) : StringHolder(reinterpret_cast(buffer.data), static_cast(buffer.datalen)) {} Body(const File& file) { std::ifstream is(file.filepath, std::ifstream::binary); if (is) { is.seekg(0, is.end); int length = is.tellg(); is.seekg(0, is.beg); std::vector buffer; buffer.resize(length); is.read(&buffer[0], length); is.close(); str_ = std::string(buffer.begin(), buffer.end()); } else { throw std::invalid_argument("Can't open the file for HTTP request body!"); } } Body(const Body& other) = default; Body(Body&& old) noexcept = default; ~Body() override = default; Body& operator=(Body&& old) noexcept = default; Body& operator=(const Body& other) = default; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/buffer.h000066400000000000000000000022221520575453600261260ustar00rootroot00000000000000#ifndef CPR_BUFFER_H #define CPR_BUFFER_H #include namespace cpr { struct Buffer { using data_t = const char*; template Buffer(Iterator begin, Iterator end, std::string&& p_filename) // Ignored here since libcurl reqires a long. // There is also no way around the reinterpret_cast. // NOLINTNEXTLINE(google-runtime-int, cppcoreguidelines-pro-type-reinterpret-cast) : data{reinterpret_cast(&(*begin))}, datalen{static_cast(std::distance(begin, end))}, filename(std::move(p_filename)) { is_random_access_iterator(begin, end); static_assert(sizeof(*begin) == 1, "Only byte buffers can be used"); } template typename std::enable_if::iterator_category, std::random_access_iterator_tag>::value>::type is_random_access_iterator(Iterator /* begin */, Iterator /* end */) {} data_t data; // Ignored here since libcurl reqires a long: // NOLINTNEXTLINE(google-runtime-int) size_t datalen; const std::string filename; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/callback.h000066400000000000000000000067361520575453600264270ustar00rootroot00000000000000#ifndef CPR_CALLBACK_H #define CPR_CALLBACK_H #include "cprtypes.h" #include #include #include namespace cpr { class ReadCallback { public: ReadCallback() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) ReadCallback(std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), size{-1}, callback{std::move(p_callback)} {} ReadCallback(cpr_off_t p_size, std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), size{p_size}, callback{std::move(p_callback)} {} bool operator()(char* buffer, size_t& buffer_size) const { return callback(buffer, buffer_size, userdata); } intptr_t userdata; cpr_off_t size{}; std::function callback; }; class HeaderCallback { public: HeaderCallback() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) HeaderCallback(std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), callback(std::move(p_callback)) {} bool operator()(std::string header) const { return callback(std::move(header), userdata); } intptr_t userdata; std::function callback; }; class WriteCallback { public: WriteCallback() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) WriteCallback(std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), callback(std::move(p_callback)) {} bool operator()(std::string data) const { return callback(std::move(data), userdata); } intptr_t userdata; std::function callback; }; class ProgressCallback { public: ProgressCallback() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) ProgressCallback(std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), callback(std::move(p_callback)) {} bool operator()(cpr_off_t downloadTotal, cpr_off_t downloadNow, cpr_off_t uploadTotal, cpr_off_t uploadNow) const { return callback(downloadTotal, downloadNow, uploadTotal, uploadNow, userdata); } intptr_t userdata; std::function callback; }; class DebugCallback { public: enum class InfoType { TEXT = 0, HEADER_IN = 1, HEADER_OUT = 2, DATA_IN = 3, DATA_OUT = 4, SSL_DATA_IN = 5, SSL_DATA_OUT = 6, }; DebugCallback() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) DebugCallback(std::function p_callback, intptr_t p_userdata = 0) : userdata(p_userdata), callback(std::move(p_callback)) {} void operator()(InfoType type, std::string data) const { callback(type, std::move(data), userdata); } intptr_t userdata; std::function callback; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/cert_info.h000066400000000000000000000016531520575453600266340ustar00rootroot00000000000000#ifndef CPR_CERT_INFO_H #define CPR_CERT_INFO_H #include #include #include namespace cpr { class CertInfo { private: std::vector cert_info_; public: CertInfo() = default; CertInfo(const CertInfo& other) = default; CertInfo(CertInfo&& old) = default; CertInfo(const std::initializer_list& entry) : cert_info_{entry} {} ~CertInfo() noexcept = default; using iterator = std::vector::iterator; using const_iterator = std::vector::const_iterator; std::string& operator[](const size_t& pos); iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; void emplace_back(const std::string& str); void push_back(const std::string& str); void pop_back(); }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/connect_timeout.h000066400000000000000000000007741520575453600300660ustar00rootroot00000000000000#ifndef CPR_CONNECT_TIMEOUT_H #define CPR_CONNECT_TIMEOUT_H #include "cpr/timeout.h" namespace cpr { class ConnectTimeout : public Timeout { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) ConnectTimeout(const std::chrono::milliseconds& duration) : Timeout{duration} {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) ConnectTimeout(const std::int32_t& milliseconds) : Timeout{milliseconds} {} }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/cookies.h000066400000000000000000000066061520575453600263230ustar00rootroot00000000000000#ifndef CPR_COOKIES_H #define CPR_COOKIES_H #include "cpr/curlholder.h" #include #include #include #include #include namespace cpr { /** * EXPIRES_STRING_SIZE is an explicitly static and const variable that could be only accessed within the same namespace and is immutable. * To be used for "std::array", the expression must have a constant value, so EXPIRES_STRING_SIZE must be a const value. **/ static const std::size_t EXPIRES_STRING_SIZE = 100; class Cookie { public: Cookie() = default; /** * Some notes for the default value used by expires: * std::chrono::system_clock::time_point::min() won't work on Windows due to the min, max clash there. * So we fall back to std::chrono::system_clock::from_time_t(0) for the minimum value here. **/ Cookie(const std::string& name, const std::string& value, const std::string& domain = "", bool p_isIncludingSubdomains = false, const std::string& path = "/", bool p_isHttpsOnly = false, std::chrono::system_clock::time_point expires = std::chrono::system_clock::from_time_t(0)) : name_{name}, value_{value}, domain_{domain}, includeSubdomains_{p_isIncludingSubdomains}, path_{path}, httpsOnly_{p_isHttpsOnly}, expires_{expires} {} const std::string GetDomain() const; bool IsIncludingSubdomains() const; const std::string GetPath() const; bool IsHttpsOnly() const; const std::chrono::system_clock::time_point GetExpires() const; const std::string GetExpiresString() const; const std::string GetName() const; const std::string GetValue() const; private: std::string name_; std::string value_; std::string domain_; bool includeSubdomains_{}; std::string path_; bool httpsOnly_{}; /** * TODO: Update the implementation using `std::chrono::utc_clock` of C++20 **/ std::chrono::system_clock::time_point expires_{}; }; class Cookies { public: /** * Should we URL-encode cookies when making a request. * Based on RFC6265, it is recommended but not mandatory to encode cookies. * * ------- * To maximize compatibility with user agents, servers that wish to * store arbitrary data in a cookie-value SHOULD encode that data, for * example, using Base64 [RFC4648]. * ------- * Source: RFC6265 (https://www.ietf.org/rfc/rfc6265.txt) **/ bool encode{true}; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Cookies(bool p_encode = true) : encode{p_encode} {} Cookies(const std::initializer_list& cookies, bool p_encode = true) : encode{p_encode}, cookies_{cookies} {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Cookies(const cpr::Cookie& cookie, bool p_encode = true) : encode{p_encode}, cookies_{cookie} {} cpr::Cookie& operator[](size_t pos); const std::string GetEncoded(const CurlHolder& holder) const; using iterator = std::vector::iterator; using const_iterator = std::vector::const_iterator; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; void emplace_back(const Cookie& str); void push_back(const Cookie& str); void pop_back(); private: std::vector cookies_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/cpr.h000066400000000000000000000021021520575453600254360ustar00rootroot00000000000000#ifndef CPR_CPR_H #define CPR_CPR_H #include "cpr/api.h" #include "cpr/auth.h" #include "cpr/bearer.h" #include "cpr/callback.h" #include "cpr/cert_info.h" #include "cpr/connect_timeout.h" #include "cpr/cookies.h" #include "cpr/cprtypes.h" // #include "cpr/cprver.h" #include "cpr/curl_container.h" #include "cpr/curlholder.h" #include "cpr/error.h" #include "cpr/http_version.h" #include "cpr/interceptor.h" #include "cpr/interface.h" #include "cpr/limit_rate.h" #include "cpr/local_port.h" #include "cpr/local_port_range.h" #include "cpr/low_speed.h" #include "cpr/multipart.h" #include "cpr/parameters.h" #include "cpr/payload.h" #include "cpr/proxies.h" #include "cpr/proxyauth.h" #include "cpr/range.h" #include "cpr/redirect.h" #include "cpr/reserve_size.h" #include "cpr/response.h" #include "cpr/session.h" #include "cpr/ssl_ctx.h" #include "cpr/ssl_options.h" #include "cpr/status_codes.h" #include "cpr/timeout.h" #include "cpr/unix_socket.h" #include "cpr/user_agent.h" #include "cpr/util.h" #include "cpr/verbose.h" #define CPR_LIBCURL_VERSION_NUM LIBCURL_VERSION_NUM #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/cprtypes.h000066400000000000000000000071231520575453600265330ustar00rootroot00000000000000#ifndef CPR_CPR_TYPES_H #define CPR_CPR_TYPES_H #include #include #include #include #include #include namespace cpr { /** * Wrapper around "curl_off_t" to prevent applications from having to link against libcurl. **/ using cpr_off_t = curl_off_t; template class StringHolder { public: StringHolder() = default; explicit StringHolder(const std::string& str) : str_(str) {} explicit StringHolder(std::string&& str) : str_(std::move(str)) {} explicit StringHolder(const char* str) : str_(str) {} StringHolder(const char* str, size_t len) : str_(str, len) {} StringHolder(const std::initializer_list args) { str_ = std::accumulate(args.begin(), args.end(), str_); } StringHolder(const StringHolder& other) = default; StringHolder(StringHolder&& old) noexcept = default; virtual ~StringHolder() = default; StringHolder& operator=(StringHolder&& old) noexcept = default; StringHolder& operator=(const StringHolder& other) = default; explicit operator std::string() const { return str_; } T operator+(const char* rhs) const { return T(str_ + rhs); } T operator+(const std::string& rhs) const { return T(str_ + rhs); } T operator+(const StringHolder& rhs) const { return T(str_ + rhs.str_); } void operator+=(const char* rhs) { str_ += rhs; } void operator+=(const std::string& rhs) { str_ += rhs; } void operator+=(const StringHolder& rhs) { str_ += rhs; } bool operator==(const char* rhs) const { return str_ == rhs; } bool operator==(const std::string& rhs) const { return str_ == rhs; } bool operator==(const StringHolder& rhs) const { return str_ == rhs.str_; } bool operator!=(const char* rhs) const { return str_.c_str() != rhs; } bool operator!=(const std::string& rhs) const { return str_ != rhs; } bool operator!=(const StringHolder& rhs) const { return str_ != rhs.str_; } const std::string& str() { return str_; } const std::string& str() const { return str_; } const char* c_str() const { return str_.c_str(); } const char* data() const { return str_.data(); } protected: std::string str_{}; }; template std::ostream& operator<<(std::ostream& os, const StringHolder& s) { os << s.str(); return os; } class Url : public StringHolder { public: Url() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Url(const std::string& url) : StringHolder(url) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Url(std::string&& url) : StringHolder(std::move(url)) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Url(const char* url) : StringHolder(url) {} Url(const char* str, size_t len) : StringHolder(std::string(str, len)) {} Url(const std::initializer_list args) : StringHolder(args) {} Url(const Url& other) = default; Url(Url&& old) noexcept = default; ~Url() override = default; Url& operator=(Url&& old) noexcept = default; Url& operator=(const Url& other) = default; }; struct CaseInsensitiveCompare { bool operator()(const std::string& a, const std::string& b) const noexcept; }; using Header = std::map; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/curl_container.h000066400000000000000000000022701520575453600276670ustar00rootroot00000000000000#ifndef CURL_CONTAINER_H #define CURL_CONTAINER_H #include #include #include #include #include "cpr/curlholder.h" namespace cpr { struct Parameter { Parameter(const std::string& p_key, const std::string& p_value) : key{p_key}, value{p_value} {} Parameter(std::string&& p_key, std::string&& p_value) : key{std::move(p_key)}, value{std::move(p_value)} {} std::string key; std::string value; }; struct Pair { Pair(const std::string& p_key, const std::string& p_value) : key(p_key), value(p_value) {} Pair(std::string&& p_key, std::string&& p_value) : key(std::move(p_key)), value(std::move(p_value)) {} std::string key; std::string value; }; template class CurlContainer { public: /** * Enables or disables URL encoding for keys and values when calling GetContent(...). **/ bool encode = true; CurlContainer() = default; CurlContainer(const std::initializer_list&); void Add(const std::initializer_list&); void Add(const T&); const std::string GetContent(const CurlHolder&) const; protected: std::vector containerList_; }; } // namespace cpr #endif // kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/curlholder.h000066400000000000000000000025631520575453600270300ustar00rootroot00000000000000#ifndef CPR_CURL_HOLDER_H #define CPR_CURL_HOLDER_H #include #include #include #include namespace cpr { struct CurlHolder { private: /** * Mutex for curl_easy_init(). * curl_easy_init() is not thread save. * References: * https://curl.haxx.se/libcurl/c/curl_easy_init.html * https://curl.haxx.se/libcurl/c/threadsafe.html **/ // Avoids initalization order problems in a static build static std::mutex& curl_easy_init_mutex_() { static std::mutex curl_easy_init_mutex_; return curl_easy_init_mutex_; } public: CURL* handle{nullptr}; struct curl_slist* chunk{nullptr}; struct curl_slist* resolveCurlList{nullptr}; curl_mime* multipart{nullptr}; std::array error{}; CurlHolder(); CurlHolder(const CurlHolder& other) = default; CurlHolder(CurlHolder&& old) noexcept = default; ~CurlHolder(); CurlHolder& operator=(CurlHolder&& old) noexcept = default; CurlHolder& operator=(const CurlHolder& other) = default; /** * Uses curl_easy_escape(...) for escaping the given string. **/ std::string urlEncode(const std::string& s) const; /** * Uses curl_easy_unescape(...) for unescaping the given string. **/ std::string urlDecode(const std::string& s) const; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/error.h000066400000000000000000000021171520575453600260110ustar00rootroot00000000000000#ifndef CPR_ERROR_H #define CPR_ERROR_H #include #include #include "cpr/cprtypes.h" #include namespace cpr { enum class ErrorCode { OK = 0, CONNECTION_FAILURE, EMPTY_RESPONSE, HOST_RESOLUTION_FAILURE, INTERNAL_ERROR, INVALID_URL_FORMAT, NETWORK_RECEIVE_ERROR, NETWORK_SEND_FAILURE, OPERATION_TIMEDOUT, PROXY_RESOLUTION_FAILURE, SSL_CONNECT_ERROR, SSL_LOCAL_CERTIFICATE_ERROR, SSL_REMOTE_CERTIFICATE_ERROR, SSL_CACERT_ERROR, GENERIC_SSL_ERROR, UNSUPPORTED_PROTOCOL, REQUEST_CANCELLED, TOO_MANY_REDIRECTS, UNKNOWN_ERROR = 1000, }; class Error { public: ErrorCode code = ErrorCode::OK; std::string message{}; Error() = default; Error(const std::int32_t& curl_code, std::string&& p_error_message) : code{getErrorCodeForCurlError(curl_code)}, message(std::move(p_error_message)) {} explicit operator bool() const { return code != ErrorCode::OK; } private: static ErrorCode getErrorCodeForCurlError(std::int32_t curl_code); }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/file.h000066400000000000000000000004641520575453600256020ustar00rootroot00000000000000#ifndef CPR_FILE_H #define CPR_FILE_H #include namespace cpr { struct File { explicit File(std::string&& p_filepath) : filepath(std::move(p_filepath)) {} explicit File(const std::string& p_filepath) : filepath(p_filepath) {} const std::string filepath; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/http_version.h000066400000000000000000000032571520575453600274120ustar00rootroot00000000000000#ifndef CPR_HTTP_VERSION_H #define CPR_HTTP_VERSION_H #include namespace cpr { enum class HttpVersionCode { /** * Let libcurl decide which version is the best. **/ VERSION_NONE, /** * Enforce HTTP 1.0 requests. **/ VERSION_1_0, /** * Enforce HTTP 1.1 requests. **/ VERSION_1_1, #if LIBCURL_VERSION_NUM >= 0x072100 // 7.33.0 /** * Attempt HTTP 2.0 requests. * Fallback to HTTP 1.1 if negotiation fails. **/ VERSION_2_0, #endif #if LIBCURL_VERSION_NUM >= 0x072F00 // 7.47.0 /** * Attempt HTTP 2.0 for HTTPS requests only. * Fallback to HTTP 1.1 if negotiation fails. * HTTP 1.1 will be used for HTTP connections. **/ VERSION_2_0_TLS, #endif #if LIBCURL_VERSION_NUM >= 0x073100 // 7.49.0 /** * Start HTTP 2.0 for HTTP requests. * Requires prior knowledge that the server supports HTTP 2.0. * For HTTPS requests we will negotiate the protocol version in the TLS handshake. **/ VERSION_2_0_PRIOR_KNOWLEDGE, #endif #if LIBCURL_VERSION_NUM >= 0x074200 // 7.66.0 /** * Attempt HTTP 3.0 requests. * Requires prior knowledge that the server supports HTTP 3.0 since there is no gracefully downgrade. * Fallback to HTTP 1.1 if negotiation fails. **/ VERSION_3_0 #endif }; class HttpVersion { public: /** * The HTTP version that should be used by libcurl when initiating a HTTP(S) connection. * Default: HttpVersionCode::VERSION_NONE **/ HttpVersionCode code = HttpVersionCode::VERSION_NONE; HttpVersion() = default; explicit HttpVersion(HttpVersionCode _code) : code(_code) {} }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/interceptor.h000066400000000000000000000015701520575453600272200ustar00rootroot00000000000000#ifndef CPR_INTERCEPTOR_H #define CPR_INTERCEPTOR_H #include "cpr/response.h" #include "cpr/session.h" namespace cpr { class Interceptor { public: enum class ProceedHttpMethod { GET_REQUEST = 0, POST_REQUEST, PUT_REQUEST, DELETE_REQUEST, PATCH_REQUEST, HEAD_REQUEST, OPTIONS_REQUEST, DOWNLOAD_CALLBACK_REQUEST, DOWNLOAD_FILE_REQUEST, }; virtual ~Interceptor() = default; virtual Response intercept(Session& session) = 0; protected: static Response proceed(Session& session); static Response proceed(Session& session, ProceedHttpMethod httpMethod); static Response proceed(Session& session, ProceedHttpMethod httpMethod, std::ofstream& file); static Response proceed(Session& session, ProceedHttpMethod httpMethod, const WriteCallback& write); }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/interface.h000066400000000000000000000022341520575453600266200ustar00rootroot00000000000000#ifndef CPR_INTERFACE_H #define CPR_INTERFACE_H #include #include #include "cpr/cprtypes.h" namespace cpr { class Interface : public StringHolder { public: Interface() : StringHolder() {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Interface(const std::string& iface) : StringHolder(iface) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Interface(std::string&& iface) : StringHolder(std::move(iface)) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Interface(const char* iface) : StringHolder(iface) {} Interface(const char* str, size_t len) : StringHolder(str, len) {} Interface(const std::initializer_list args) : StringHolder(args) {} Interface(const Interface& other) = default; Interface(Interface&& old) noexcept = default; ~Interface() override = default; Interface& operator=(Interface&& old) noexcept = default; Interface& operator=(const Interface& other) = default; }; } // namespace cpr #endifkylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/limit_rate.h000066400000000000000000000005101520575453600270040ustar00rootroot00000000000000#ifndef CPR_SPEED_LIMIT_H #define CPR_SPEED_LIMIT_H #include namespace cpr { class LimitRate { public: LimitRate(const std::int64_t p_downrate, const std::int64_t p_uprate) : downrate(p_downrate), uprate(p_uprate) {} std::int64_t downrate = 0; std::int64_t uprate = 0; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/local_port.h000066400000000000000000000006071520575453600270200ustar00rootroot00000000000000#ifndef CPR_LOCAL_PORT_H #define CPR_LOCAL_PORT_H #include namespace cpr { class LocalPort { public: // NOLINTNEXTLINE(google-explicit-constructor) LocalPort(const std::uint16_t p_localport) : localport_(p_localport) {} operator std::uint16_t() const { return localport_; } private: std::uint16_t localport_ = 0; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/local_port_range.h000066400000000000000000000006661520575453600302010ustar00rootroot00000000000000#ifndef CPR_LOCAL_PORT_RANGE_H #define CPR_LOCAL_PORT_RANGE_H #include namespace cpr { class LocalPortRange { public: // NOLINTNEXTLINE(google-explicit-constructor) LocalPortRange(const std::uint16_t p_localportrange) : localportrange_(p_localportrange) {} operator std::uint16_t() const { return localportrange_; } private: std::uint16_t localportrange_ = 0; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/low_speed.h000066400000000000000000000004461520575453600266440ustar00rootroot00000000000000#ifndef CPR_LOW_SPEED_H #define CPR_LOW_SPEED_H #include namespace cpr { class LowSpeed { public: LowSpeed(const std::int32_t p_limit, const std::int32_t p_time) : limit(p_limit), time(p_time) {} std::int32_t limit; std::int32_t time; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/multipart.h000066400000000000000000000034271520575453600267060ustar00rootroot00000000000000#ifndef CPR_MULTIPART_H #define CPR_MULTIPART_H #include #include #include #include #include #include "buffer.h" #include "file.h" namespace cpr { struct Part { Part(const std::string& p_name, const std::string& p_value, const std::string& p_content_type = {}) : name{p_name}, value{p_value}, content_type{p_content_type}, is_file{false}, is_buffer{false}, has_filename{false} {} Part(const std::string& p_name, const std::int32_t& p_value, const std::string& p_content_type = {}) : name{p_name}, value{std::to_string(p_value)}, content_type{p_content_type}, is_file{false}, is_buffer{false}, has_filename{false} {} Part(const std::string& p_name, const File& file, const std::string& p_content_type = {}) : name{p_name}, value{file.filepath}, content_type{p_content_type}, is_file{true}, is_buffer{false}, has_filename{false} {} Part(const std::string& p_name, const std::string& p_filename, const File& file, const std::string& p_content_type = {}) : name{p_name}, filename{p_filename}, value{file.filepath}, content_type{p_content_type}, is_file{true}, is_buffer{false}, has_filename{true} {} Part(const std::string& p_name, const Buffer& buffer, const std::string& p_content_type = {}) : name{p_name}, value{buffer.filename}, content_type{p_content_type}, data{buffer.data}, datalen{buffer.datalen}, is_file{false}, is_buffer{true}, has_filename{false} {} std::string name; std::string filename; std::string value; std::string content_type; Buffer::data_t data{nullptr}; size_t datalen{0}; bool is_file; bool is_buffer; bool has_filename; }; class Multipart { public: Multipart(const std::initializer_list& parts); std::vector parts; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/parameters.h000066400000000000000000000005511520575453600270230ustar00rootroot00000000000000#ifndef CPR_PARAMETERS_H #define CPR_PARAMETERS_H #include #include "cpr/curl_container.h" namespace cpr { class Parameters : public CurlContainer { public: Parameters() = default; Parameters(const std::initializer_list& parameters) : CurlContainer(parameters) {} }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/payload.h000066400000000000000000000007111520575453600263070ustar00rootroot00000000000000#ifndef CPR_PAYLOAD_H #define CPR_PAYLOAD_H #include #include "cpr/curl_container.h" namespace cpr { class Payload : public CurlContainer { public: template Payload(const It begin, const It end) { for (It pair = begin; pair != end; ++pair) { Add(*pair); } } Payload(const std::initializer_list& pairs) : CurlContainer(pairs) {} }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/proxies.h000066400000000000000000000010231520575453600263440ustar00rootroot00000000000000#ifndef CPR_PROXIES_H #define CPR_PROXIES_H #include #include #include namespace cpr { class Proxies { public: Proxies() = default; Proxies(const std::initializer_list>& hosts); Proxies(const std::map& hosts); bool has(const std::string& protocol) const; const std::string& operator[](const std::string& protocol); private: std::map hosts_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/proxyauth.h000066400000000000000000000030711520575453600267230ustar00rootroot00000000000000#ifndef CPR_PROXYAUTH_H #define CPR_PROXYAUTH_H #include #include #include "cpr/auth.h" #include "cpr/util.h" namespace cpr { class EncodedAuthentication { public: EncodedAuthentication() : auth_string_{""} {} EncodedAuthentication(const std::string& username, const std::string& password) : auth_string_{cpr::util::urlEncode(username) + ":" + cpr::util::urlEncode(password)} {} EncodedAuthentication(std::string&& username, std::string&& password) : auth_string_{cpr::util::urlEncode(std::move(username)) + ":" + cpr::util::urlEncode(std::move(password))} {} EncodedAuthentication(const EncodedAuthentication& other) = default; EncodedAuthentication(EncodedAuthentication&& old) noexcept = default; virtual ~EncodedAuthentication() noexcept; EncodedAuthentication& operator=(EncodedAuthentication&& old) noexcept = default; EncodedAuthentication& operator=(const EncodedAuthentication& other) = default; const char* GetAuthString() const noexcept; protected: std::string auth_string_; }; class ProxyAuthentication { public: ProxyAuthentication() = default; ProxyAuthentication(const std::initializer_list>& auths) : proxyAuth_{auths} {} ProxyAuthentication(const std::map& auths) : proxyAuth_{auths} {} bool has(const std::string& protocol) const; const char* operator[](const std::string& protocol); private: std::map proxyAuth_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/range.h000066400000000000000000000020011520575453600257440ustar00rootroot00000000000000#ifndef CPR_RANGE_H #define CPR_RANGE_H #include namespace cpr { class Range { public: Range(const std::int64_t p_resume_from, const std::int64_t p_finish_at) : resume_from(p_resume_from), finish_at(p_finish_at) {} std::int64_t resume_from = 0; std::int64_t finish_at = 0; const std::string str() const { std::string from_str = (resume_from < (std::int64_t) 0) ? "" : std::to_string(resume_from); std::string to_str = (finish_at < (std::int64_t) 0) ? "" : std::to_string(finish_at); return from_str + "-" + to_str; } }; class MultiRange { public: MultiRange(std::initializer_list rs) : ranges{rs} {} const std::string str() const { std::string multi_range_string{}; for (Range range : ranges) { multi_range_string += ((multi_range_string.empty()) ? "" : ", ") + range.str(); } return multi_range_string; } private: std::vector ranges; }; // namespace cpr } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/redirect.h000066400000000000000000000057771520575453600265000ustar00rootroot00000000000000#ifndef CPR_REDIRECT_H #define CPR_REDIRECT_H #include namespace cpr { enum class PostRedirectFlags : uint8_t { /** * Respect RFC 7231 (section 6.4.2 to 6.4.4). * Same as CURL_REDIR_POST_301 (https://curl.se/libcurl/c/CURLOPT_POSTREDIR.html). **/ POST_301 = 0x1 << 0, /** * Maintain the request method after a 302 redirect. * Same as CURL_REDIR_POST_302 (https://curl.se/libcurl/c/CURLOPT_POSTREDIR.html). **/ POST_302 = 0x1 << 1, /** * Maintain the request method after a 303 redirect. * Same as CURL_REDIR_POST_303 (https://curl.se/libcurl/c/CURLOPT_POSTREDIR.html). **/ POST_303 = 0x1 << 2, /** * Default value. * Convenience option to enable all flags. * Same as CURL_REDIR_POST_ALL (https://curl.se/libcurl/c/CURLOPT_POSTREDIR.html). **/ POST_ALL = POST_301 | POST_302 | POST_303, /** * * Convenience option to disable all flags. **/ NONE = 0x0 }; PostRedirectFlags operator|(PostRedirectFlags lhs, PostRedirectFlags rhs); PostRedirectFlags operator&(PostRedirectFlags lhs, PostRedirectFlags rhs); PostRedirectFlags operator^(PostRedirectFlags lhs, PostRedirectFlags rhs); PostRedirectFlags operator~(PostRedirectFlags flag); PostRedirectFlags& operator|=(PostRedirectFlags& lhs, PostRedirectFlags rhs); PostRedirectFlags& operator&=(PostRedirectFlags& lhs, PostRedirectFlags rhs); PostRedirectFlags& operator^=(PostRedirectFlags& lhs, PostRedirectFlags rhs); bool any(PostRedirectFlags flag); class Redirect { public: /** * The maximum number of redirects to follow. * 0: Refuse any redirects. * -1: Infinite number of redirects. * Default: 50 * https://curl.se/libcurl/c/CURLOPT_MAXREDIRS.html **/ // NOLINTNEXTLINE (google-runtime-int) long maximum{50L}; /** * Follow 3xx redirects. * Default: true * https://curl.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html **/ bool follow{true}; /** * Continue to send authentication (user+password) credentials when following locations, even when hostname changed. * Default: false * https://curl.se/libcurl/c/CURLOPT_UNRESTRICTED_AUTH.html **/ bool cont_send_cred{false}; /** * Flags to control how to act after a redirect for a post request. * Default: POST_ALL **/ PostRedirectFlags post_flags{PostRedirectFlags::POST_ALL}; Redirect() = default; // NOLINTNEXTLINE (google-runtime-int) Redirect(long p_maximum, bool p_follow, bool p_cont_send_cred, PostRedirectFlags p_post_flags) : maximum(p_maximum), follow(p_follow), cont_send_cred(p_cont_send_cred), post_flags(p_post_flags){} // NOLINTNEXTLINE (google-runtime-int) explicit Redirect(long p_maximum) : maximum(p_maximum){} explicit Redirect(bool p_follow) : follow(p_follow){} Redirect(bool p_follow, bool p_cont_send_cred) : follow(p_follow), cont_send_cred(p_cont_send_cred){} explicit Redirect(PostRedirectFlags p_post_flags) : post_flags(p_post_flags){} }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/reserve_size.h000066400000000000000000000003441520575453600273650ustar00rootroot00000000000000#ifndef CPR_RESERVE_SIZE_H #define CPR_RESERVE_SIZE_H #include namespace cpr { class ReserveSize { public: ReserveSize(const size_t _size) : size(_size) {} size_t size = 0; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/response.h000066400000000000000000000026251520575453600265220ustar00rootroot00000000000000#ifndef CPR_RESPONSE_H #define CPR_RESPONSE_H #include #include #include #include #include #include #include "cpr/cert_info.h" #include "cpr/cookies.h" #include "cpr/cprtypes.h" #include "cpr/error.h" #include "cpr/ssl_options.h" #include "cpr/util.h" namespace cpr { class Response { private: std::shared_ptr curl_{nullptr}; public: // Ignored here since libcurl uses a long for this. // NOLINTNEXTLINE(google-runtime-int) long status_code{}; std::string text{}; Header header{}; Url url{}; double elapsed{}; Cookies cookies{}; Error error{}; std::string raw_header{}; std::string status_line{}; std::string reason{}; cpr_off_t uploaded_bytes{}; cpr_off_t downloaded_bytes{}; // Ignored here since libcurl uses a long for this. // NOLINTNEXTLINE(google-runtime-int) long redirect_count{}; Response() = default; Response(std::shared_ptr curl, std::string&& p_text, std::string&& p_header_string, Cookies&& p_cookies, Error&& p_error); std::vector GetCertInfos(); Response(const Response& other) = default; Response(Response&& old) noexcept = default; ~Response() noexcept = default; Response& operator=(Response&& old) noexcept = default; Response& operator=(const Response& other) = default; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/session.h000066400000000000000000000250661520575453600263530ustar00rootroot00000000000000#ifndef CPR_SESSION_H #define CPR_SESSION_H #include #include #include #include #include #include "cpr/accept_encoding.h" #include "cpr/auth.h" #include "cpr/bearer.h" #include "cpr/body.h" #include "cpr/callback.h" #include "cpr/connect_timeout.h" #include "cpr/cookies.h" #include "cpr/cprtypes.h" #include "cpr/curlholder.h" #include "cpr/http_version.h" #include "cpr/interface.h" #include "cpr/limit_rate.h" #include "cpr/local_port.h" #include "cpr/local_port_range.h" #include "cpr/low_speed.h" #include "cpr/multipart.h" #include "cpr/parameters.h" #include "cpr/payload.h" #include "cpr/proxies.h" #include "cpr/proxyauth.h" #include "cpr/range.h" #include "cpr/redirect.h" #include "cpr/reserve_size.h" #include "cpr/response.h" #include "cpr/ssl_options.h" #include "cpr/timeout.h" #include "cpr/unix_socket.h" #include "cpr/user_agent.h" #include "cpr/verbose.h" namespace cpr { using AsyncResponse = std::future; class Interceptor; class Session : public std::enable_shared_from_this { public: Session(); Session(const Session& other) = delete; ~Session() = default; Session& operator=(Session&& old) noexcept = default; Session& operator=(const Session& other) = delete; void SetUrl(const Url& url); void SetParameters(const Parameters& parameters); void SetParameters(Parameters&& parameters); void SetHeader(const Header& header); void UpdateHeader(const Header& header); void SetTimeout(const Timeout& timeout); void SetConnectTimeout(const ConnectTimeout& timeout); void SetAuth(const Authentication& auth); // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 void SetBearer(const Bearer& token); #endif void SetUserAgent(const UserAgent& ua); void SetPayload(Payload&& payload); void SetPayload(const Payload& payload); void SetProxies(Proxies&& proxies); void SetProxies(const Proxies& proxies); void SetProxyAuth(ProxyAuthentication&& proxy_auth); void SetProxyAuth(const ProxyAuthentication& proxy_auth); void SetMultipart(Multipart&& multipart); void SetMultipart(const Multipart& multipart); void SetRedirect(const Redirect& redirect); void SetCookies(const Cookies& cookies); void SetBody(Body&& body); void SetBody(const Body& body); void SetLowSpeed(const LowSpeed& low_speed); void SetVerifySsl(const VerifySsl& verify); void SetUnixSocket(const UnixSocket& unix_socket); void SetSslOptions(const SslOptions& options); void SetReadCallback(const ReadCallback& read); void SetHeaderCallback(const HeaderCallback& header); void SetWriteCallback(const WriteCallback& write); void SetProgressCallback(const ProgressCallback& progress); void SetDebugCallback(const DebugCallback& debug); void SetVerbose(const Verbose& verbose); void SetInterface(const Interface& iface); void SetLocalPort(const LocalPort& local_port); void SetLocalPortRange(const LocalPortRange& local_port_range); void SetHttpVersion(const HttpVersion& version); void SetRange(const Range& range); void SetMultiRange(const MultiRange& multi_range); void SetReserveSize(const ReserveSize& reserve_size); void SetAcceptEncoding(const AcceptEncoding& accept_encoding); void SetAcceptEncoding(AcceptEncoding&& accept_encoding); void SetLimitRate(const LimitRate& limit_rate); // Used in templated functions void SetOption(const Url& url); void SetOption(const Parameters& parameters); void SetOption(Parameters&& parameters); void SetOption(const Header& header); void SetOption(const Timeout& timeout); void SetOption(const ConnectTimeout& timeout); void SetOption(const Authentication& auth); // Only supported with libcurl >= 7.61.0. // As an alternative use SetHeader and add the token manually. #if LIBCURL_VERSION_NUM >= 0x073D00 void SetOption(const Bearer& auth); #endif void SetOption(const UserAgent& ua); void SetOption(Payload&& payload); void SetOption(const Payload& payload); void SetOption(const LimitRate& limit_rate); void SetOption(Proxies&& proxies); void SetOption(const Proxies& proxies); void SetOption(ProxyAuthentication&& proxy_auth); void SetOption(const ProxyAuthentication& proxy_auth); void SetOption(Multipart&& multipart); void SetOption(const Multipart& multipart); void SetOption(const Redirect& redirect); void SetOption(const Cookies& cookies); void SetOption(Body&& body); void SetOption(const Body& body); void SetOption(const ReadCallback& read); void SetOption(const HeaderCallback& header); void SetOption(const WriteCallback& write); void SetOption(const ProgressCallback& progress); void SetOption(const DebugCallback& debug); void SetOption(const LowSpeed& low_speed); void SetOption(const VerifySsl& verify); void SetOption(const Verbose& verbose); void SetOption(const UnixSocket& unix_socket); void SetOption(const SslOptions& options); void SetOption(const Interface& iface); void SetOption(const LocalPort& local_port); void SetOption(const LocalPortRange& local_port_range); void SetOption(const HttpVersion& version); void SetOption(const Range& range); void SetOption(const MultiRange& multi_range); void SetOption(const ReserveSize& reserve_size); void SetOption(const AcceptEncoding& accept_encoding); void SetOption(AcceptEncoding&& accept_encoding); cpr_off_t GetDownloadFileLength(); /** * Attempt to preallocate enough memory for specified number of characters in the response string. * Pass 0 to disable this behavior and let the response string be allocated dynamically on demand. * * Example: * cpr::Session session; * session.SetUrl(cpr::Url{"http://xxx/file"}); * session.ResponseStringReserve(1024 * 512); // Reserve space for at least 1024 * 512 characters * cpr::Response r = session.Get(); **/ void ResponseStringReserve(size_t size); Response Delete(); Response Download(const WriteCallback& write); Response Download(std::ofstream& file); Response Get(); Response Head(); Response Options(); Response Patch(); Response Post(); Response Put(); AsyncResponse GetAsync(); AsyncResponse DeleteAsync(); AsyncResponse DownloadAsync(const WriteCallback& write); AsyncResponse DownloadAsync(std::ofstream& file); AsyncResponse HeadAsync(); AsyncResponse OptionsAsync(); AsyncResponse PatchAsync(); AsyncResponse PostAsync(); AsyncResponse PutAsync(); template auto GetCallback(Then then) -> std::future; template auto PostCallback(Then then) -> std::future; template auto PutCallback(Then then) -> std::future; template auto HeadCallback(Then then) -> std::future; template auto DeleteCallback(Then then) -> std::future; template auto OptionsCallback(Then then) -> std::future; template auto PatchCallback(Then then) -> std::future; std::shared_ptr GetCurlHolder(); std::string GetFullRequestUrl(); void PrepareDelete(); void PrepareGet(); void PrepareHead(); void PrepareOptions(); void PreparePatch(); void PreparePost(); void PreparePut(); Response Complete(CURLcode curl_error); void AddInterceptor(const std::shared_ptr& pinterceptor); private: // Interceptors should be able to call the private procceed() function friend Interceptor; bool hasBodyOrPayload_{false}; bool chunkedTransferEncoding_{false}; std::shared_ptr curl_; Url url_; Parameters parameters_; Proxies proxies_; ProxyAuthentication proxyAuth_; Header header_; AcceptEncoding acceptEncoding_; /** * Will be set by the read callback. * Ensures that the "Transfer-Encoding" is set to "chunked", if not overriden in header_. **/ ReadCallback readcb_; HeaderCallback headercb_; WriteCallback writecb_; ProgressCallback progresscb_; DebugCallback debugcb_; size_t response_string_reserve_size_{0}; std::string response_string_; std::string header_string_; std::queue> interceptors_; Response makeDownloadRequest(); Response makeRequest(); Response proceed(); void prepareCommon(); void SetHeaderInternal(); std::shared_ptr GetSharedPtrFromThis(); }; template auto Session::GetCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Get()); }, std::move(then)); } template auto Session::PostCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Post()); }, std::move(then)); } template auto Session::PutCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Put()); }, std::move(then)); } template auto Session::HeadCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Head()); }, std::move(then)); } template auto Session::DeleteCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Delete()); }, std::move(then)); } template auto Session::OptionsCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Options()); }, std::move(then)); } template auto Session::PatchCallback(Then then) -> std::future { auto shared_this = GetSharedPtrFromThis(); return async([shared_this](Then then_inner) { return then_inner(shared_this->Patch()); }, std::move(then)); } } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/singleton.h000066400000000000000000000022011520575453600266540ustar00rootroot00000000000000#ifndef CPR_SINGLETON_H #define CPR_SINGLETON_H #include #ifndef CPR_DISABLE_COPY #define CPR_DISABLE_COPY(Class) \ Class(const Class&) = delete; \ Class& operator=(const Class&) = delete; #endif #ifndef CPR_SINGLETON_DECL #define CPR_SINGLETON_DECL(Class) \ public: \ static Class* GetInstance(); \ static void ExitInstance(); \ private: \ CPR_DISABLE_COPY(Class) \ static Class* s_pInstance; \ static std::mutex s_mutex; #endif #ifndef CPR_SINGLETON_IMPL #define CPR_SINGLETON_IMPL(Class) \ Class* Class::s_pInstance = nullptr; \ std::mutex Class::s_mutex; \ Class* Class::GetInstance() { \ if (s_pInstance == nullptr) { \ s_mutex.lock(); \ if (s_pInstance == nullptr) { \ s_pInstance = new Class; \ } \ s_mutex.unlock(); \ } \ return s_pInstance; \ } \ void Class::ExitInstance() { \ s_mutex.lock(); \ if (s_pInstance) { \ delete s_pInstance; \ s_pInstance = nullptr; \ } \ s_mutex.unlock(); \ } #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/ssl_ctx.h000066400000000000000000000012651520575453600263420ustar00rootroot00000000000000#ifndef CPR_SSL_CTX_H #define CPR_SSL_CTX_H #include "cpr/ssl_options.h" #include #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION namespace cpr { /** * This callback function loads a CA certificate from raw_cert_buf and gets called by libcurl * just before the initialization of an SSL connection. * The raw_cert_buf argument is set with the CURLOPT_SSL_CTX_DATA option and has to be a nul * terminated buffer. * * Sources: https://curl.se/libcurl/c/CURLOPT_SSL_CTX_FUNCTION.html * https://curl.se/libcurl/c/CURLOPT_SSL_CTX_DATA.html */ CURLcode sslctx_function_load_ca_cert_from_buffer(CURL* curl, void* sslctx, void* raw_cert_buf); } // Namespace cpr #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/ssl_options.h000066400000000000000000000375501520575453600272450ustar00rootroot00000000000000#ifndef CPR_SSLOPTIONS_H #define CPR_SSLOPTIONS_H #include #include #include #include #include "cpr/util.h" #include #ifndef SUPPORT_ALPN #define SUPPORT_ALPN LIBCURL_VERSION_NUM >= 0x072400 // 7.36.0 #endif #ifndef SUPPORT_NPN #define SUPPORT_NPN LIBCURL_VERSION_NUM >= 0x072400 && LIBCURL_VERSION_NUM <= 0x078600 // 7.36.0 - 7.86.0 #endif #ifndef SUPPORT_SSLv2 #define SUPPORT_SSLv2 LIBCURL_VERSION_NUM <= 0x071300 // 7.19.0 #endif #ifndef SUPPORT_SSLv3 #define SUPPORT_SSLv3 LIBCURL_VERSION_NUM <= 0x072700 // 7.39.0 #endif #ifndef SUPPORT_TLSv1_0 #define SUPPORT_TLSv1_0 LIBCURL_VERSION_NUM >= 0x072200 // 7.34.0 #endif #ifndef SUPPORT_TLSv1_1 #define SUPPORT_TLSv1_1 LIBCURL_VERSION_NUM >= 0x072200 // 7.34.0 #endif #ifndef SUPPORT_TLSv1_2 #define SUPPORT_TLSv1_2 LIBCURL_VERSION_NUM >= 0x072200 // 7.34.0 #endif #ifndef SUPPORT_TLSv1_3 #define SUPPORT_TLSv1_3 LIBCURL_VERSION_NUM >= 0x073400 // 7.52.0 #endif #ifndef SUPPORT_MAX_TLS_VERSION #define SUPPORT_MAX_TLS_VERSION LIBCURL_VERSION_NUM >= 0x073600 // 7.54.0 #endif #ifndef SUPPORT_MAX_TLSv1_1 #define SUPPORT_MAX_TLSv1_1 LIBCURL_VERSION_NUM >= 0x073600 // 7.54.0 #endif #ifndef SUPPORT_MAX_TLSv1_2 #define SUPPORT_MAX_TLSv1_2 LIBCURL_VERSION_NUM >= 0x073600 // 7.54.0 #endif #ifndef SUPPORT_MAX_TLSv1_3 #define SUPPORT_MAX_TLSv1_3 LIBCURL_VERSION_NUM >= 0x073600 // 7.54.0 #endif #ifndef SUPPORT_TLSv13_CIPHERS #define SUPPORT_TLSv13_CIPHERS LIBCURL_VERSION_NUM >= 0x073D00 // 7.61.0 #endif #ifndef SUPPORT_SESSIONID_CACHE #define SUPPORT_SESSIONID_CACHE LIBCURL_VERSION_NUM >= 0x071000 // 7.16.0 #endif #ifndef SUPPORT_SSL_FALSESTART #define SUPPORT_SSL_FALSESTART LIBCURL_VERSION_NUM >= 0x072A00 // 7.42.0 #endif #ifndef SUPPORT_SSL_NO_REVOKE #define SUPPORT_SSL_NO_REVOKE LIBCURL_VERSION_NUM >= 0x072C00 // 7.44.0 #endif #ifndef SUPPORT_CURLOPT_SSLKEY_BLOB #define SUPPORT_CURLOPT_SSLKEY_BLOB LIBCURL_VERSION_NUM >= 0x074700 // 7.71.0 #endif #ifndef SUPPORT_CURLOPT_SSL_CTX_FUNCTION #define SUPPORT_CURLOPT_SSL_CTX_FUNCTION LIBCURL_VERSION_NUM >= 0x070B00 // 7.11.0 #endif namespace cpr { class VerifySsl { public: VerifySsl() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) VerifySsl(bool p_verify) : verify(p_verify) {} explicit operator bool() const { return verify; } bool verify = true; }; namespace ssl { // set SSL client certificate class CertFile { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) CertFile(std::string&& p_filename) : filename(std::move(p_filename)) {} virtual ~CertFile() = default; const std::string filename; virtual const char* GetCertType() const { return "PEM"; } }; using PemCert = CertFile; class DerCert : public CertFile { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) DerCert(std::string&& p_filename) : CertFile(std::move(p_filename)) {} ~DerCert() override = default; const char* GetCertType() const override { return "DER"; } }; // specify private keyfile for TLS and SSL client cert class KeyFile { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) KeyFile(std::string&& p_filename) : filename(std::move(p_filename)) {} template KeyFile(FileType&& p_filename, PassType p_password) : filename(std::forward(p_filename)), password(std::move(p_password)) {} virtual ~KeyFile() { util::secureStringClear(password); } std::string filename; std::string password; virtual const char* GetKeyType() const { return "PEM"; } }; #if SUPPORT_CURLOPT_SSLKEY_BLOB class KeyBlob { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) KeyBlob(std::string&& p_blob) : blob(std::move(p_blob)) {} template KeyBlob(BlobType&& p_blob, PassType p_password) : blob(std::forward(p_blob)), password(std::move(p_password)) {} virtual ~KeyBlob() { util::secureStringClear(password); } std::string blob; std::string password; virtual const char* GetKeyType() const { return "PEM"; } }; #endif using PemKey = KeyFile; class DerKey : public KeyFile { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) DerKey(std::string&& p_filename) : KeyFile(std::move(p_filename)) {} template DerKey(FileType&& p_filename, PassType p_password) : KeyFile(std::forward(p_filename), std::move(p_password)) {} ~DerKey() override = default; const char* GetKeyType() const override { return "DER"; } }; class PinnedPublicKey { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) PinnedPublicKey(std::string&& p_pinned_public_key) : pinned_public_key(std::move(p_pinned_public_key)) {} const std::string pinned_public_key; }; #if SUPPORT_ALPN // This option enables/disables ALPN in the SSL handshake (if the SSL backend libcurl is built to // use supports it), which can be used to negotiate http2. class ALPN { public: ALPN() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) ALPN(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = true; }; #endif // SUPPORT_ALPN #if SUPPORT_NPN // This option enables/disables NPN in the SSL handshake (if the SSL backend libcurl is built to // use supports it), which can be used to negotiate http2. class NPN { public: NPN() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) NPN(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = true; }; #endif // SUPPORT_NPN // This option determines whether libcurl verifies that the server cert is for the server it is // known as. class VerifyHost { public: VerifyHost() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) VerifyHost(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = true; }; // This option determines whether libcurl verifies the authenticity of the peer's certificate. class VerifyPeer { public: VerifyPeer() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) VerifyPeer(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = true; }; // This option determines whether libcurl verifies the status of the server cert using the // "Certificate Status Request" TLS extension (aka. OCSP stapling). class VerifyStatus { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) VerifyStatus(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = false; }; // TLS v1.0 or later struct TLSv1 {}; #if SUPPORT_SSLv2 // SSL v2 (but not SSLv3) struct SSLv2 {}; #endif #if SUPPORT_SSLv3 // SSL v3 (but not SSLv2) struct SSLv3 {}; #endif #if SUPPORT_TLSv1_0 // TLS v1.0 or later (Added in 7.34.0) struct TLSv1_0 {}; #endif #if SUPPORT_TLSv1_1 // TLS v1.1 or later (Added in 7.34.0) struct TLSv1_1 {}; #endif #if SUPPORT_TLSv1_2 // TLS v1.2 or later (Added in 7.34.0) struct TLSv1_2 {}; #endif #if SUPPORT_TLSv1_3 // TLS v1.3 or later (Added in 7.52.0) struct TLSv1_3 {}; #endif #if SUPPORT_MAX_TLS_VERSION // The flag defines the maximum supported TLS version by libcurl, or the default value from the SSL // library is used. struct MaxTLSVersion {}; #endif #if SUPPORT_MAX_TLSv1_0 // The flag defines maximum supported TLS version as TLSv1.0. (Added in 7.54.0) struct MaxTLSv1_0 {}; #endif #if SUPPORT_MAX_TLSv1_1 // The flag defines maximum supported TLS version as TLSv1.1. (Added in 7.54.0) struct MaxTLSv1_1 {}; #endif #if SUPPORT_MAX_TLSv1_2 // The flag defines maximum supported TLS version as TLSv1.2. (Added in 7.54.0) struct MaxTLSv1_2 {}; #endif #if SUPPORT_MAX_TLSv1_3 // The flag defines maximum supported TLS version as TLSv1.3. (Added in 7.54.0) struct MaxTLSv1_3 {}; #endif // path to Certificate Authority (CA) bundle class CaInfo { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) CaInfo(std::string&& p_filename) : filename(std::move(p_filename)) {} std::string filename; }; // specify directory holding CA certificates class CaPath { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) CaPath(std::string&& p_filename) : filename(std::move(p_filename)) {} std::string filename; }; #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION class CaBuffer { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) CaBuffer(std::string&& p_buffer) : buffer(std::move(p_buffer)) {} const std::string buffer; }; #endif // specify a Certificate Revocation List file class Crl { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Crl(std::string&& p_filename) : filename(std::move(p_filename)) {} std::string filename; }; // specify ciphers to use for TLS class Ciphers { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Ciphers(std::string&& p_ciphers) : ciphers(std::move(p_ciphers)) {} std::string ciphers; }; #if SUPPORT_TLSv13_CIPHERS // specify ciphers suites to use for TLS 1.3 class TLS13_Ciphers { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) TLS13_Ciphers(std::string&& p_ciphers) : ciphers(std::move(p_ciphers)) {} std::string ciphers; }; #endif #if SUPPORT_SESSIONID_CACHE // enable/disable use of the SSL session-ID cache class SessionIdCache { public: SessionIdCache() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) SessionIdCache(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = true; }; #endif #if SUPPORT_SSL_FALSESTART class SslFastStart { public: SslFastStart() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) SslFastStart(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = false; }; #endif class NoRevoke { public: NoRevoke() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) NoRevoke(bool p_enabled) : enabled(p_enabled) {} explicit operator bool() const { return enabled; } bool enabled = false; }; } // namespace ssl struct SslOptions { std::string cert_file; std::string cert_type; std::string key_file; #if SUPPORT_CURLOPT_SSLKEY_BLOB std::string key_blob; #endif std::string key_type; std::string key_pass; std::string pinned_public_key; #if SUPPORT_ALPN bool enable_alpn = true; #endif // SUPPORT_ALPN #if SUPPORT_NPN bool enable_npn = true; #endif // SUPPORT_ALPN bool verify_host = true; bool verify_peer = true; bool verify_status = false; int ssl_version = CURL_SSLVERSION_DEFAULT; #if SUPPORT_SSL_NO_REVOKE bool ssl_no_revoke = false; #endif #if SUPPORT_MAX_TLS_VERSION int max_version = CURL_SSLVERSION_MAX_DEFAULT; #endif std::string ca_info; std::string ca_path; #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION std::string ca_buffer; #endif std::string crl_file; std::string ciphers; #if SUPPORT_TLSv13_CIPHERS std::string tls13_ciphers; #endif #if SUPPORT_SESSIONID_CACHE bool session_id_cache = true; #endif ~SslOptions() noexcept { #if SUPPORT_CURLOPT_SSLKEY_BLOB util::secureStringClear(key_blob); #endif util::secureStringClear(key_pass); } void SetOption(const ssl::CertFile& opt) { cert_file = opt.filename; cert_type = opt.GetCertType(); } void SetOption(const ssl::KeyFile& opt) { key_file = opt.filename; key_type = opt.GetKeyType(); key_pass = opt.password; } #if SUPPORT_CURLOPT_SSLKEY_BLOB void SetOption(const ssl::KeyBlob& opt) { key_blob = opt.blob; key_type = opt.GetKeyType(); key_pass = opt.password; } #endif void SetOption(const ssl::PinnedPublicKey& opt) { pinned_public_key = opt.pinned_public_key; } #if SUPPORT_ALPN void SetOption(const ssl::ALPN& opt) { enable_alpn = opt.enabled; } #endif // SUPPORT_ALPN #if SUPPORT_NPN void SetOption(const ssl::NPN& opt) { enable_npn = opt.enabled; } #endif // SUPPORT_NPN void SetOption(const ssl::VerifyHost& opt) { verify_host = opt.enabled; } void SetOption(const ssl::VerifyPeer& opt) { verify_peer = opt.enabled; } void SetOption(const ssl::VerifyStatus& opt) { verify_status = opt.enabled; } void SetOption(const ssl::TLSv1& /*opt*/) { ssl_version = CURL_SSLVERSION_TLSv1; } #if SUPPORT_SSL_NO_REVOKE void SetOption(const ssl::NoRevoke& opt) { ssl_no_revoke = opt.enabled; } #endif #if SUPPORT_SSLv2 void SetOption(const ssl::SSLv2& /*opt*/) { ssl_version = CURL_SSLVERSION_SSLv2; } #endif #if SUPPORT_SSLv3 void SetOption(const ssl::SSLv3& /*opt*/) { ssl_version = CURL_SSLVERSION_SSLv3; } #endif #if SUPPORT_TLSv1_0 void SetOption(const ssl::TLSv1_0& /*opt*/) { ssl_version = CURL_SSLVERSION_TLSv1_0; } #endif #if SUPPORT_TLSv1_1 void SetOption(const ssl::TLSv1_1& /*opt*/) { ssl_version = CURL_SSLVERSION_TLSv1_1; } #endif #if SUPPORT_TLSv1_2 void SetOption(const ssl::TLSv1_2& /*opt*/) { ssl_version = CURL_SSLVERSION_TLSv1_2; } #endif #if SUPPORT_TLSv1_3 void SetOption(const ssl::TLSv1_3& /*opt*/) { ssl_version = CURL_SSLVERSION_TLSv1_3; } #endif #if SUPPORT_MAX_TLS_VERSION void SetOption(const ssl::MaxTLSVersion& /*opt*/) { max_version = CURL_SSLVERSION_DEFAULT; } #endif #if SUPPORT_MAX_TLSv1_0 void SetOption(const ssl::MaxTLSv1_0& opt) { max_version = CURL_SSLVERSION_MAX_TLSv1_0; } #endif #if SUPPORT_MAX_TLSv1_1 void SetOption(const ssl::MaxTLSv1_1& /*opt*/) { max_version = CURL_SSLVERSION_MAX_TLSv1_1; } #endif #if SUPPORT_MAX_TLSv1_2 void SetOption(const ssl::MaxTLSv1_2& /*opt*/) { max_version = CURL_SSLVERSION_MAX_TLSv1_2; } #endif #if SUPPORT_MAX_TLSv1_3 void SetOption(const ssl::MaxTLSv1_3& /*opt*/) { max_version = CURL_SSLVERSION_MAX_TLSv1_3; } #endif void SetOption(const ssl::CaInfo& opt) { ca_info = opt.filename; } void SetOption(const ssl::CaPath& opt) { ca_path = opt.filename; } #if SUPPORT_CURLOPT_SSL_CTX_FUNCTION void SetOption(const ssl::CaBuffer& opt) { ca_buffer = opt.buffer; } #endif void SetOption(const ssl::Crl& opt) { crl_file = opt.filename; } void SetOption(const ssl::Ciphers& opt) { ciphers = opt.ciphers; } #if SUPPORT_TLSv13_CIPHERS void SetOption(const ssl::TLS13_Ciphers& opt) { tls13_ciphers = opt.ciphers; } #endif #if SUPPORT_SESSIONID_CACHE void SetOption(const ssl::SessionIdCache& opt) { session_id_cache = opt.enabled; } #endif }; namespace priv { template void set_ssl_option(SslOptions& opts, T&& t) { opts.SetOption(std::forward(t)); } template void set_ssl_option(SslOptions& opts, T&& t, Ts&&... ts) { set_ssl_option(opts, std::forward(t)); set_ssl_option(opts, std::move(ts)...); } } // namespace priv template SslOptions Ssl(Ts&&... ts) { SslOptions opts; priv::set_ssl_option(opts, std::move(ts)...); return opts; } } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/status_codes.h000066400000000000000000000105741520575453600273660ustar00rootroot00000000000000#ifndef CPR_STATUS_CODES #define CPR_STATUS_CODES #include namespace cpr { namespace status { // Information responses constexpr std::int32_t HTTP_CONTINUE = 100; constexpr std::int32_t HTTP_SWITCHING_PROTOCOL = 101; constexpr std::int32_t HTTP_PROCESSING = 102; constexpr std::int32_t HTTP_EARLY_HINTS = 103; // Successful responses constexpr std::int32_t HTTP_OK = 200; constexpr std::int32_t HTTP_CREATED = 201; constexpr std::int32_t HTTP_ACCEPTED = 202; constexpr std::int32_t HTTP_NON_AUTHORITATIVE_INFORMATION = 203; constexpr std::int32_t HTTP_NO_CONTENT = 204; constexpr std::int32_t HTTP_RESET_CONTENT = 205; constexpr std::int32_t HTTP_PARTIAL_CONTENT = 206; constexpr std::int32_t HTTP_MULTI_STATUS = 207; constexpr std::int32_t HTTP_ALREADY_REPORTED = 208; constexpr std::int32_t HTTP_IM_USED = 226; // Redirection messages constexpr std::int32_t HTTP_MULTIPLE_CHOICE = 300; constexpr std::int32_t HTTP_MOVED_PERMANENTLY = 301; constexpr std::int32_t HTTP_FOUND = 302; constexpr std::int32_t HTTP_SEE_OTHER = 303; constexpr std::int32_t HTTP_NOT_MODIFIED = 304; constexpr std::int32_t HTTP_USE_PROXY = 305; constexpr std::int32_t HTTP_UNUSED = 306; constexpr std::int32_t HTTP_TEMPORARY_REDIRECT = 307; constexpr std::int32_t HTTP_PERMANENT_REDIRECT = 308; // Client error responses constexpr std::int32_t HTTP_BAD_REQUEST = 400; constexpr std::int32_t HTTP_UNAUTHORIZED = 401; constexpr std::int32_t HTTP_PAYMENT_REQUIRED = 402; constexpr std::int32_t HTTP_FORBIDDEN = 403; constexpr std::int32_t HTTP_NOT_FOUND = 404; constexpr std::int32_t HTTP_METHOD_NOT_ALLOWED = 405; constexpr std::int32_t HTTP_NOT_ACCEPTABLE = 406; constexpr std::int32_t HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; constexpr std::int32_t HTTP_REQUEST_TIMEOUT = 408; constexpr std::int32_t HTTP_CONFLICT = 409; constexpr std::int32_t HTTP_GONE = 410; constexpr std::int32_t HTTP_LENGTH_REQUIRED = 411; constexpr std::int32_t HTTP_PRECONDITION_FAILED = 412; constexpr std::int32_t HTTP_PAYLOAD_TOO_LARGE = 413; constexpr std::int32_t HTTP_URI_TOO_LONG = 414; constexpr std::int32_t HTTP_UNSUPPORTED_MEDIA_TYPE = 415; constexpr std::int32_t HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; constexpr std::int32_t HTTP_EXPECTATION_FAILED = 417; constexpr std::int32_t HTTP_IM_A_TEAPOT = 418; constexpr std::int32_t HTTP_MISDIRECTED_REQUEST = 421; constexpr std::int32_t HTTP_UNPROCESSABLE_ENTITY = 422; constexpr std::int32_t HTTP_LOCKED = 423; constexpr std::int32_t HTTP_FAILED_DEPENDENCY = 424; constexpr std::int32_t HTTP_TOO_EARLY = 425; constexpr std::int32_t HTTP_UPGRADE_REQUIRED = 426; constexpr std::int32_t HTTP_PRECONDITION_REQUIRED = 428; constexpr std::int32_t HTTP_TOO_MANY_REQUESTS = 429; constexpr std::int32_t HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; constexpr std::int32_t HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; // Server response errors constexpr std::int32_t HTTP_INTERNAL_SERVER_ERROR = 500; constexpr std::int32_t HTTP_NOT_IMPLEMENTED = 501; constexpr std::int32_t HTTP_BAD_GATEWAY = 502; constexpr std::int32_t HTTP_SERVICE_UNAVAILABLE = 503; constexpr std::int32_t HTTP_GATEWAY_TIMEOUT = 504; constexpr std::int32_t HTTP_HTTP_VERSION_NOT_SUPPORTED = 505; constexpr std::int32_t HTTP_VARIANT_ALSO_NEGOTIATES = 506; constexpr std::int32_t HTTP_INSUFFICIENT_STORAGE = 507; constexpr std::int32_t HTTP_LOOP_DETECTED = 508; constexpr std::int32_t HTTP_NOT_EXTENDED = 510; constexpr std::int32_t HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; constexpr std::int32_t INFO_CODE_OFFSET = 100; constexpr std::int32_t SUCCESS_CODE_OFFSET = 200; constexpr std::int32_t REDIRECT_CODE_OFFSET = 300; constexpr std::int32_t CLIENT_ERROR_CODE_OFFSET = 400; constexpr std::int32_t SERVER_ERROR_CODE_OFFSET = 500; constexpr std::int32_t MISC_CODE_OFFSET = 600; constexpr bool is_informational(const std::int32_t code) { return (code >= INFO_CODE_OFFSET && code < SUCCESS_CODE_OFFSET); } constexpr bool is_success(const std::int32_t code) { return (code >= SUCCESS_CODE_OFFSET && code < REDIRECT_CODE_OFFSET); } constexpr bool is_redirect(const std::int32_t code) { return (code >= REDIRECT_CODE_OFFSET && code < CLIENT_ERROR_CODE_OFFSET); } constexpr bool is_client_error(const std::int32_t code) { return (code >= CLIENT_ERROR_CODE_OFFSET && code < SERVER_ERROR_CODE_OFFSET); } constexpr bool is_server_error(const std::int32_t code) { return (code >= SERVER_ERROR_CODE_OFFSET && code < MISC_CODE_OFFSET); } } // namespace status } // namespace cpr #endifkylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/threadpool.h000066400000000000000000000062221520575453600270220ustar00rootroot00000000000000#ifndef CPR_THREAD_POOL_H #define CPR_THREAD_POOL_H #include #include #include #include #include #include #include #include #include #include #include #define CPR_DEFAULT_THREAD_POOL_MAX_THREAD_NUM std::thread::hardware_concurrency() constexpr size_t CPR_DEFAULT_THREAD_POOL_MIN_THREAD_NUM = 1; constexpr std::chrono::milliseconds CPR_DEFAULT_THREAD_POOL_MAX_IDLE_TIME{60000}; namespace cpr { class ThreadPool { public: using Task = std::function; explicit ThreadPool(size_t min_threads = CPR_DEFAULT_THREAD_POOL_MIN_THREAD_NUM, size_t max_threads = CPR_DEFAULT_THREAD_POOL_MAX_THREAD_NUM, std::chrono::milliseconds max_idle_ms = CPR_DEFAULT_THREAD_POOL_MAX_IDLE_TIME); virtual ~ThreadPool(); void SetMinThreadNum(size_t min_threads) { min_thread_num = min_threads; } void SetMaxThreadNum(size_t max_threads) { max_thread_num = max_threads; } void SetMaxIdleTime(std::chrono::milliseconds ms) { max_idle_time = ms; } size_t GetCurrentThreadNum() { return cur_thread_num; } size_t GetIdleThreadNum() { return idle_thread_num; } bool IsStarted() { return status != STOP; } bool IsStopped() { return status == STOP; } int Start(size_t start_threads = 0); int Stop(); int Pause(); int Resume(); int Wait(); /** * Return a future, calling future.get() will wait task done and return RetType. * Submit(fn, args...) * Submit(std::bind(&Class::mem_fn, &obj)) * Submit(std::mem_fn(&Class::mem_fn, &obj)) **/ template auto Submit(Fn&& fn, Args&&... args) -> std::future { if (status == STOP) { Start(); } if (idle_thread_num <= 0 && cur_thread_num < max_thread_num) { CreateThread(); } using RetType = decltype(fn(args...)); auto task = std::make_shared >(std::bind(std::forward(fn), std::forward(args)...)); std::future future = task->get_future(); { std::lock_guard locker(task_mutex); tasks.emplace([task] { (*task)(); }); } task_cond.notify_one(); return future; } private: bool CreateThread(); void AddThread(std::thread* thread); void DelThread(std::thread::id id); public: size_t min_thread_num; size_t max_thread_num; std::chrono::milliseconds max_idle_time; private: enum Status { STOP, RUNNING, PAUSE, }; struct ThreadData { std::shared_ptr thread; std::thread::id id; Status status; time_t start_time; time_t stop_time; }; std::atomic status; std::atomic cur_thread_num; std::atomic idle_thread_num; std::list threads; std::mutex thread_mutex; std::queue tasks; std::mutex task_mutex; std::condition_variable task_cond; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/timeout.h000066400000000000000000000012071520575453600263450ustar00rootroot00000000000000#ifndef CPR_TIMEOUT_H #define CPR_TIMEOUT_H #include #include namespace cpr { class Timeout { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Timeout(const std::chrono::milliseconds& duration) : ms{duration} {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Timeout(const std::int32_t& milliseconds) : Timeout{std::chrono::milliseconds(milliseconds)} {} // No way around since curl uses a long here. // NOLINTNEXTLINE(google-runtime-int) long Milliseconds() const; std::chrono::milliseconds ms; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/unix_socket.h000066400000000000000000000006371520575453600272200ustar00rootroot00000000000000#ifndef CPR_UNIX_SOCKET_H #define CPR_UNIX_SOCKET_H #include namespace cpr { class UnixSocket { public: // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) UnixSocket(std::string&& unix_socket) : unix_socket_(std::move(unix_socket)) {} const char* GetUnixSocketString() const noexcept; private: const std::string unix_socket_; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/user_agent.h000066400000000000000000000022641520575453600270170ustar00rootroot00000000000000#ifndef CPR_USERAGENT_H #define CPR_USERAGENT_H #include #include #include "cpr/cprtypes.h" namespace cpr { class UserAgent : public StringHolder { public: UserAgent() : StringHolder() {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) UserAgent(const std::string& useragent) : StringHolder(useragent) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) UserAgent(std::string&& useragent) : StringHolder(std::move(useragent)) {} // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) UserAgent(const char* useragent) : StringHolder(useragent) {} UserAgent(const char* str, size_t len) : StringHolder(str, len) {} UserAgent(const std::initializer_list args) : StringHolder(args) {} UserAgent(const UserAgent& other) = default; UserAgent(UserAgent&& old) noexcept = default; ~UserAgent() override = default; UserAgent& operator=(UserAgent&& old) noexcept = default; UserAgent& operator=(const UserAgent& other) = default; }; } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/util.h000066400000000000000000000034341520575453600256400ustar00rootroot00000000000000#ifndef CPR_UTIL_H #define CPR_UTIL_H #include #include #include #include "cpr/callback.h" #include "cpr/cookies.h" #include "cpr/cprtypes.h" #include "cpr/curlholder.h" namespace cpr { namespace util { Header parseHeader(const std::string& headers, std::string* status_line = nullptr, std::string* reason = nullptr); Cookies parseCookies(curl_slist* raw_cookies); size_t readUserFunction(char* ptr, size_t size, size_t nitems, const ReadCallback* read); size_t headerUserFunction(char* ptr, size_t size, size_t nmemb, const HeaderCallback* header); size_t writeFunction(char* ptr, size_t size, size_t nmemb, std::string* data); size_t writeFileFunction(char* ptr, size_t size, size_t nmemb, std::ofstream* file); size_t writeUserFunction(char* ptr, size_t size, size_t nmemb, const WriteCallback* write); #if LIBCURL_VERSION_NUM < 0x072000 int progressUserFunction(const ProgressCallback* progress, double dltotal, double dlnow, double ultotal, double ulnow); #else int progressUserFunction(const ProgressCallback* progress, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); #endif int debugUserFunction(CURL* handle, curl_infotype type, char* data, size_t size, const DebugCallback* debug); std::vector split(const std::string& to_split, char delimiter); std::string urlEncode(const std::string& s); std::string urlDecode(const std::string& s); /** * Override the content of the provided string to hide sensitive data. The * string content after invocation is undefined. The string size is reset to zero. * impl. based on: * https://github.com/ojeda/secure_clear/blob/master/example-implementation/secure_clear.h **/ void secureStringClear(std::string& s); bool isTrue(const std::string& s); } // namespace util } // namespace cpr #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/cpr/include/cpr/verbose.h000066400000000000000000000005131520575453600263230ustar00rootroot00000000000000#ifndef CPR_VERBOSE_H_ #define CPR_VERBOSE_H_ namespace cpr { class Verbose { public: Verbose() = default; // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) Verbose(const bool p_verbose) : verbose{p_verbose} {} bool verbose = true; }; } // namespace cpr #endif /* CPR_VERBOSE_H_ */ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/000077500000000000000000000000001520575453600234455ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.bazelrc000066400000000000000000000013041520575453600250660ustar00rootroot00000000000000build --copt=-std=c99 build --cxxopt=-std=c++11 build --define BUILD_SHARED=ON build --define BUILD_STATIC=ON build --define BUILD_EXAMPLES=ON build --define BUILD_UNITTEST=OFF build --define WITH_PROTOCOL=OFF build --define WITH_EVPP=ON build --define WITH_HTTP=ON build --define WITH_HTTP_SERVER=ON build --define WITH_HTTP_CLIENT=ON build --define WITH_MQTT=OFF build --define ENABLE_UDS=OFF build --define USE_MULTIMAP=OFF build --define WITH_CURL=OFF build --define WITH_NGHTTP2=OFF build --define WITH_OPENSSL=OFF build --define WITH_GNUTLS=OFF build --define WITH_MBEDTLS=OFF build --define WITH_KCP=OFF build --define WITH_WEPOLL=ON build --define ENABLE_WINDUMP=OFF build --define BUILD_FOR_MT=OFF kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.clang-format000066400000000000000000000052521520575453600260240ustar00rootroot00000000000000--- Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlinesLeft: true AlignOperands: true AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: Inline AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false BeforeCatch: true BeforeElse: true IndentBraces: false BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 160 CommentPragmas: '^ IWYU pragma:' ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: true DisableFormat: false ExperimentalAutoDetectBinPacking: false ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] IncludeCategories: - Regex: '.*' Priority: 1 - Regex: '^".*/' Priority: 2 - Regex: '^<)' Priority: 3 IncludeIsMainRegex: '$' IndentCaseLabels: false IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBlockIndentWidth: 4 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: true SortIncludes: false SpaceAfterCStyleCast: false SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 TabWidth: 4 UseTab: Never ... kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.gitattributes000066400000000000000000000000431520575453600263350ustar00rootroot00000000000000cpputil/json.hpp linguist-vendored kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.github/000077500000000000000000000000001520575453600250055ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.github/workflows/000077500000000000000000000000001520575453600270425ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.github/workflows/CI.yml000066400000000000000000000045141520575453600300640ustar00rootroot00000000000000name: CI on: push: paths-ignore: - '**.md' pull_request: paths-ignore: - '**.md' jobs: build-linux: name: build-linux runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: build run: | sudo apt update sudo apt install libssl-dev libnghttp2-dev ./configure --with-openssl --with-nghttp2 --with-kcp --with-mqtt make libhv evpp - name: test run: | make check make run-unittest build-windows: name: build-windows runs-on: windows-latest steps: - uses: actions/checkout@v3 - name: build run: | mkdir cmake-build-win64 cd cmake-build-win64 cmake .. -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release cmake --build . --config Release cd .. - name: test run: | cd cmake-build-win64 start bin/Release/http_server_test bin/Release/http_client_test bin/Release/curl -v -X HEAD http://example.com/ bin/Release/curl -v -X HEAD https://example.com/ bin/Release/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/ping build-mac: name: build-mac runs-on: macos-latest steps: - uses: actions/checkout@v3 - name: build run: | ./configure make libhv evpp examples unittest - name: test run: | bin/curl -v -X HEAD http://example.com/ bin/curl -v -X HEAD https://example.com/ build-android: name: build-android runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: build run: | mkdir cmake-build-arm64 cd cmake-build-arm64 cmake .. -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK_ROOT/build/cmake/android.toolchain.cmake" -DANDROID_ABI="arm64-v8a" -DANDROID_PLATFORM=android-21 cmake --build . --target hv --config Release build-ios: name: build-ios runs-on: macos-latest steps: - uses: actions/checkout@v3 - name: build run: | mkdir cmake-build-ios cd cmake-build-ios cmake .. -G Xcode -DCMAKE_TOOLCHAIN_FILE=../cmake/ios.toolchain.cmake -DPLATFORM=OS64 -DARCHS="arm64" -DDEPLOYMENT_TARGET=9.0 cmake --build . --target hv_static --config Release kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.github/workflows/benchmark.yml000066400000000000000000000044631520575453600315260ustar00rootroot00000000000000name: benchmark on: push: paths-ignore: - '**.md' pull_request: paths-ignore: - '**.md' jobs: benchmark: name: benchmark runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: prepare run: | sudo apt update sudo apt install libssl-dev sudo apt install iperf sudo apt install nginx - name: make examples run: | ./configure make examples - name: build echo-servers run: | bash echo-servers/build.sh - name: benchmark echo-servers run: | bash echo-servers/benchmark.sh - name: benchmark tcp_proxy_server run: | iperf -s -p 5001 > /dev/null & bin/tcp_proxy_server 1212 127.0.0.1:5001 & iperf -c 127.0.0.1 -p 5001 -l 8K iperf -c 127.0.0.1 -p 1212 -l 8K - name: webbench run: | sudo nginx -c /etc/nginx/nginx.conf sudo cp html/index.html index.html sudo cp html/index.html /var/www/html/index.html bin/httpd -c etc/httpd.conf -d ps aux | grep nginx ps aux | grep httpd bin/tinyhttpd 9090 & echo -e "\n======Test nginx send file===============================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:80/ echo -e "\n======Test libhv/httpd send file (with FileCache)========" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/ echo -e "\n======Test libhv/tinyhttpd send file (no FileCache)======" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:9090/ echo -e "\n======Test nginx 404 Not Found===========================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:80/404 echo -e "\n======Test libhv/httpd 404 Not Found=====================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/404 echo -e "\n======Test libhv/tinyhttpd 404 Not found=================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:9090/404 echo -e "\n======Test libhv/httpd /ping=============================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/ping echo -e "\n======Test libhv/tinyhttpd /ping=========================" bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:9090/ping kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.gitignore000066400000000000000000000011111520575453600254270ustar00rootroot00000000000000# Bazel bazel-* MODULE.bazel MODULE.bazel.lock # Compiled Object files *.o *.lo *.slo *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Compiled Static libraries *.a *.la *.lai *.lib # Executables *.exe *.out *.app # cache *~ *.bk *.bak *.old *.new # IDE .vs .vscode .DS_Store tags cscope* .ycm* # generated examples/protorpc/generated # output *.pid *.log *.db include lib bin tmp dist test *_test build config.mk hconfig.h html/uploads # msvc *.VC.* *.vcxproj.* Debug Release # cmake CMakeFiles CMakeCache.txt cmake_install.cmake kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/.travis.yml000066400000000000000000000015401520575453600255560ustar00rootroot00000000000000language: cpp jobs: include: - os: linux dist: xenial compiler: gcc env: COVERALLS=no script: - ./configure - make libhv examples unittest evpp - os: osx compiler: clang env: COVERALLS=no script: - ./configure - make libhv examples unittest evpp - os: windows compiler: msvc env: COVERALLS=no script: - mkdir win64 - cd win64 - cmake .. -G "Visual Studio 15 2017 Win64" - cmake --build . before_script: - if [ "$COVERALLS" = "yes" ]; then pip install --user cpp-coveralls; export CC="$CC --coverage" CXX="$CXX --coverage"; fi after_success: - if [ "$COVERALLS" = "yes" ]; then scripts/test-coverage.sh; coveralls --gcov-options '\-lp' --include base --include event --include http; fi kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/BUILD.bazel000066400000000000000000000247371520575453600253400ustar00rootroot00000000000000load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") config_setting( name = "ios", constraint_values = ["@platforms//apple:ios"], ) config_setting( name = "msvc", values = { "compiler": "msvc-cl", }, ) config_setting( name = "debug", values = {"compilation_mode": "dbg"}, ) config_setting( name = "release", values = {"compilation_mode": "opt"}, ) config_setting( name = "build_shared", define_values = {"BUILD_SHARED": "ON"}, ) config_setting( name = "build_static", define_values = {"BUILD_STATIC": "ON"} ) config_setting( name = "build_examples", define_values = {"BUILD_EXAMPLES": "ON"}, ) config_setting( name = "build_unittest", define_values = {"BUILD_UNITTEST": "ON"} ) config_setting( name = "with_protocol", define_values = {"WITH_PROTOCOL": "ON"} ) config_setting( name = "with_evpp", define_values = { "WITH_EVPP": "ON", }, visibility = [":__subpackages__"] ) config_setting( name = "with_http", define_values = { "WITH_EVPP": "ON", "WITH_HTTP": "ON", }, visibility = [":__subpackages__"] ) config_setting( name = "with_http_server", define_values = { "WITH_EVPP": "ON", "WITH_HTTP": "ON", "WITH_HTTP_SERVER": "ON", }, visibility = [":__subpackages__"] ) config_setting( name = "with_http_client", define_values = { "WITH_EVPP": "ON", "WITH_HTTP": "ON", "WITH_HTTP_CLIENT": "ON", }, visibility = [":__subpackages__"] ) config_setting( name = "with_evpp_nghttp2", define_values = { "WITH_EVPP": "ON", "WITH_HTTP": "ON", "WITH_NGHTTP2": "ON", } ) config_setting( name = "with_mqtt", define_values = {"WITH_MQTT": "ON"}, visibility = [":__subpackages__"], ) config_setting( name = "enable_uds", define_values = {"ENABLE_UDS": "ON"} ) config_setting( name = "use_multimap", define_values = {"USE_MULTIMAP": "ON"} ) config_setting( name = "with_curl", define_values = {"WITH_CURL": "ON"} ) config_setting( name = "with_nghttp2", define_values = {"WITH_NGHTTP2": "ON"} ) config_setting( name = "with_openssl", define_values = {"WITH_OPENSSL": "ON"} ) config_setting( name = "with_gnutls", define_values = {"WITH_GNUTLS": "ON"} ) config_setting( name = "with_mbedtls", define_values = {"WITH_MBEDTLS": "ON"} ) config_setting( name = "with_kcp", define_values = {"WITH_KCP": "ON"} ) config_setting( name = "with_wepoll", constraint_values = ["@platforms//os:windows"], define_values = {"WITH_WEPOLL": "ON"} ) config_setting( name = "enable_windump", constraint_values = ["@platforms//os:windows"], define_values = {"ENABLE_WINDUMP": "ON"} ) config_setting( name = "build_for_mt_dbg", constraint_values = ["@platforms//os:windows"], define_values = { "BUILD_FOR_MT": "ON", "compilation_mode": "dbg" } ) config_setting( name = "build_for_mt_opt", constraint_values = ["@platforms//os:windows"], define_values = { "BUILD_FOR_MT": "ON", "compilation_mode": "opt" } ) genrule( name = "config", outs = ["hconfig.h"], cmd = "($(execpath configure) && cp hconfig.h $@) || exit 1", tools = ["configure"], ) HEADERS_DIRS = ["base", "ssl", "event"] + select({ "with_wepoll": ["event/wepoll"], "//conditions:default": [], }) + select({ "with_kcp": ["event/kcp"], "//conditions:default": [], }) + ["util"] + select({ "with_protocol": ["protocol"], "//conditions:default": [], }) + select({ "with_evpp": ["cpputil", "evpp"], "//conditions:default": [], }) + select({ "with_http": ["http"], "//conditions:default": [], }) + select({ "with_http_server": ["http/server"], "//conditions:default": [], }) + select({ "with_http_client": ["http/client"], "//conditions:default": [], }) + select({ "with_mqtt": ["mqtt"], "//conditions:default": [], }) COPTS = select({ "debug": ["-DDEBUG"], "release": ["-DNDEBUG"], "//conditions:default": [], }) + select({ "enable_uds": ["-DENABLE_UDS"], "//conditions:default": [], }) + select({ "use_multimap": ["-DUSE_MULTIMAP"], "//conditions:default": [], }) + select({ "with_curl": ["-DWITH_CURL"], "//conditions:default": [], }) + select({ "with_nghttp2": ["-DWITH_NGHTTP2"], "//conditions:default": [], }) + select({ "with_openssl": ["-DWITH_OPENSSL"], "//conditions:default": [], }) + select({ "with_gnutls": ["-DWITH_GNUTLS"], "//conditions:default": [], }) + select({ "with_mbedtls": ["-DWITH_MBEDTLS"], "//conditions:default": [], }) + select({ "@platforms//os:windows": ["-DWIN32_LEAN_AND_MEAN", "-D_CRT_SECURE_NO_WARNINGS", "-D_WIN32_WINNT=0x0600"], "//conditions:default": [], }) + select({ "enable_windump": ["-DENABLE_WINDUMP"], "//conditions:default": [], }) + select({ "build_for_mt_dbg": ["/MTd"], "build_for_mt_opt": ["/MT"], "//conditions:default": [], }) LINKOPTS = select({ "msvc": [], "//conditions:default": ["-pthread"], }) + select({ "@platforms//os:linux": [ "-lpthread", "-lm", "-ldl", ], "//conditions:default": [], }) + select({ "@bazel_tools//tools/cpp:gcc": ["-lrt"], "//conditions:default": [], }) BASE_HEADERS = [ "base/hplatform.h", "base/hdef.h", "base/hatomic.h", "base/herr.h", "base/htime.h", "base/hmath.h", "base/hbase.h", "base/hversion.h", "base/hsysinfo.h", "base/hproc.h", "base/hthread.h", "base/hmutex.h", "base/hsocket.h", "base/hlog.h", "base/hbuf.h", "base/hmain.h", "base/hendian.h", ] SSL_HEADERS = [ "ssl/hssl.h", ] EVENT_HEADERS = [ "event/hloop.h", "event/nlog.h", ] UTIL_HEADERS = [ "util/base64.h", "util/md5.h", "util/sha1.h", ] CPPUTIL_HEADERS = [ "cpputil/hmap.h", "cpputil/hstring.h", "cpputil/hfile.h", "cpputil/hpath.h", "cpputil/hdir.h", "cpputil/hurl.h", "cpputil/hscope.h", "cpputil/hthreadpool.h", "cpputil/hasync.h", "cpputil/hobjectpool.h", "cpputil/ifconfig.h", "cpputil/iniparser.h", "cpputil/json.hpp", "cpputil/singleton.h", "cpputil/ThreadLocalStorage.h", ] EVPP_HEADERS = [ "evpp/Buffer.h", "evpp/Channel.h", "evpp/Event.h", "evpp/EventLoop.h", "evpp/EventLoopThread.h", "evpp/EventLoopThreadPool.h", "evpp/Status.h", "evpp/TcpClient.h", "evpp/TcpServer.h", "evpp/UdpClient.h", "evpp/UdpServer.h", ] PROTOCOL_HEADERS = [ "protocol/icmp.h", "protocol/dns.h", "protocol/ftp.h", "protocol/smtp.h", ] HTTP_HEADERS = [ "http/httpdef.h", "http/wsdef.h", "http/http_content.h", "http/HttpMessage.h", "http/HttpParser.h", "http/WebSocketParser.h", "http/WebSocketChannel.h", ] HTTP2_HEADERS = [ "http/http2def.h", "http/grpcdef.h", ] HTTP_CLIENT_HEADERS = [ "http/client/HttpClient.h", "http/client/requests.h", "http/client/axios.h", "http/client/AsyncHttpClient.h", "http/client/WebSocketClient.h", ] HTTP_SERVER_HEADERS = [ "http/server/HttpServer.h", "http/server/HttpService.h", "http/server/HttpContext.h", "http/server/HttpResponseWriter.h", "http/server/WebSocketServer.h", ] MQTT_HEADERS = [ "mqtt/mqtt_protocol.h", "mqtt/mqtt_client.h", ] HEADERS = ["hv.h", ":config", "hexport.h"] + BASE_HEADERS + SSL_HEADERS + EVENT_HEADERS + UTIL_HEADERS + select({ "with_protocol": PROTOCOL_HEADERS, "//conditions:default": [], }) + select({ "with_evpp": CPPUTIL_HEADERS + EVPP_HEADERS, "//conditions:default": [], }) + select({ "with_http": HTTP_HEADERS, "//conditions:default": [], }) + select({ "with_evpp_nghttp2": HTTP2_HEADERS, "//conditions:default": [], }) + select({ "with_http_server": HTTP_SERVER_HEADERS, "//conditions:default": [], }) + select({ "with_http_client": HTTP_CLIENT_HEADERS, "//conditions:default": [], }) + select({ "with_mqtt": MQTT_HEADERS, "//conditions:default": [], }) CORE_SRCS = glob( ["*.h"], exclude = ["*_test.c"] ) + glob( ["base/*.h", "base/*.c", "base/*.cpp"], exclude = ["base/*_test.c"] ) + glob( ["ssl/*.h", "ssl/*.c", "ssl/*.cpp"], exclude = ["ssl/*_test.c"] ) + glob( ["event/*.h", "event/*.c", "event/*.cpp"], exclude = ["event/*_test.c"] ) + select({ "with_wepoll": glob(["event/wepoll/*.h", "event/wepoll/*.c", "event/wepoll/*.cpp"], exclude = ["event/wepoll/*_test.c"]), "//conditions:default": [], }) + select({ "with_kcp": glob(["event/kcp/*.h", "event/kcp/*.c", "event/kcp/*.cpp"], exclude = ["event/kcp/*_test.c"]), "//conditions:default": [], }) SRCS = CORE_SRCS + glob(["util/*.h", "util/*.c", "util/*.cpp"], exclude = ["util/*_test.c"]) + select({ "with_protocol": glob(["protocol/*.h", "protocol/*.c", "protocol/*.cpp"], exclude = ["protocol/*_test.c"]), "//conditions:default": [], }) + select({ "with_evpp": glob(["cpputil/*.h", "cpputil/*.c", "cpputil/*.cpp", "evpp/*.h", "evpp/*.c", "evpp/*.cpp"], exclude = ["cpputil/*_test.c", "evpp/*_test.c", "evpp/*_test.cpp"]), "//conditions:default": [], }) + select({ "with_http": glob(["http/*.h", "http/*.c", "http/*.cpp"], exclude = ["http/*_test.c"]), "//conditions:default": [], }) + select({ "with_http_server": glob(["http/server/*.h", "http/server/*.c", "http/server/*.cpp"], exclude = ["http/server/*_test.c"]), "//conditions:default": [], }) + select({ "with_http_client": glob(["http/client/*.h", "http/client/*.c", "http/client/*.cpp"], exclude = ["http/client/*_test.c"]), "//conditions:default": [], }) + select({ "with_mqtt": glob(["mqtt/*.h", "mqtt/*.c", "mqtt/*.cpp"], exclude = ["mqtt/*_test.c"]), "//conditions:default": [], }) cc_library( name = "hv_static", srcs = SRCS, hdrs = HEADERS, includes = HEADERS_DIRS, defines = ["HV_STATICLIB"], copts = COPTS, linkstatic = True, linkopts = LINKOPTS, ) cc_library( name = "hv", srcs = SRCS, hdrs = HEADERS, includes = HEADERS_DIRS, defines = ["HV_DYNAMICLIB"], copts = COPTS, linkopts = LINKOPTS, visibility = ["//visibility:public"] ) filegroup( name = "libhv", srcs = select({ "build_shared": [":hv"], "//conditions:default": [], }) + select({ "build_static": [":hv_static"], "//conditions:default": [], }) + select({ "build_examples": ["//examples:examples"], "//conditions:default": [], }) ) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/BUILD.md000066400000000000000000000054011520575453600246260ustar00rootroot00000000000000## Prequired - c99 - c++11 gcc4.8+, msvc2015 or later ## Makefile options see [config.ini](config.ini) ``` ./configure --with-openssl make sudo make install ``` ## cmake options see [CMakeLists.txt](CMakeLists.txt) ``` mkdir build cd build cmake .. -DWITH_OPENSSL=ON cmake --build . ``` ## bazel options see [.bazelrc](.bazelrc) ``` bazel build libhv ``` ## Unix use Makefile or cmake or bazel ## Windows use cmake ``` mkdir win64 cd win64 cmake .. -G "Visual Studio 15 2017 Win64" #cmake .. -G "Visual Studio 16 2019" -A x64 #cmake .. -G "Visual Studio 17 2022" -A x64 cmake --build . ``` ## CROSS_COMPILE use Makefile ``` sudo apt install gcc-arm-linux-gnueabi g++-arm-linux-gnueabi # ubuntu export CROSS_COMPILE=arm-linux-gnueabi- ./configure make clean make libhv ``` or use cmake ``` mkdir build cd build cmake .. -DCMAKE_C_COMPILER=arm-linux-gnueabi-gcc -DCMAKE_CXX_COMPILER=arm-linux-gnueabi-g++ cmake --build . --target libhv libhv_static ``` ### mingw see CROSS_COMPILE ``` sudo apt install mingw-w64 # ubuntu #export CROSS_COMPILE=i686-w64-mingw32- export CROSS_COMPILE=x86_64-w64-mingw32- ./configure make clean make libhv ``` ### Android ``` #https://developer.android.com/ndk/downloads #export ANDROID_NDK_ROOT=~/Downloads/android-ndk-r21b mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK_ROOT/build/cmake/android.toolchain.cmake" -DANDROID_ABI="arm64-v8a" -DANDROID_PLATFORM=android-21 cmake --build . --target hv --config Release ``` ### iOS ``` mkdir build cd build cmake .. -G Xcode -DCMAKE_TOOLCHAIN_FILE=../cmake/ios.toolchain.cmake -DPLATFORM=OS64 -DARCHS="arm64" -DDEPLOYMENT_TARGET=9.0 cmake --build . --target hv_static --config Release ``` ## targets ### lib - make libhv ### examples - make examples ### unittest - make unittest ## options ### compile without c++ ``` ./configure --without-evpp make clean && make libhv ``` ### compile WITH_OPENSSL Enable SSL/TLS in libhv is so easy :) ``` // see ssl/hssl.h hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt); // see event/hloop.h int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); ``` https is the best example. ``` sudo apt install openssl libssl-dev # ubuntu ./configure --with-openssl make clean && make bin/httpd -s restart -d bin/curl -v http://localhost:8080 bin/curl -v https://localhost:8443 ``` ### compile WITH_CURL ``` ./configure --with-curl make clean && make bin/httpd -s restart -d bin/curl -v http://localhost:8080 ``` ### compile WITH_NGHTTP2 ``` sudo apt install libnghttp2-dev # ubuntu ./configure --with-nghttp2 make clean && make bin/httpd -s restart -d bin/curl -v http://localhost:8080 --http2 ``` ### compile WITH_KCP ``` ./configure --with-kcp make clean && make ``` ### compile WITH_MQTT ``` ./configure --with-mqtt make clean && make ``` ### More ``` ./configure --help ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/CMakeLists.txt000066400000000000000000000221141520575453600262050ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.6) project(hv VERSION 1.3.3) option(BUILD_SHARED "build shared library" ON) option(BUILD_STATIC "build static library" ON) option(BUILD_EXAMPLES "build examples" ON) option(BUILD_UNITTEST "build unittest" OFF) # see config.ini option(WITH_PROTOCOL "compile protocol" OFF) option(WITH_EVPP "compile evpp" ON) option(WITH_HTTP "compile http" ON) option(WITH_HTTP_SERVER "compile http/server" ON) option(WITH_HTTP_CLIENT "compile http/client" ON) option(WITH_MQTT "compile mqtt" OFF) option(ENABLE_UDS "Unix Domain Socket" OFF) option(USE_MULTIMAP "MultiMap" OFF) option(WITH_CURL "with curl library (deprecated)" OFF) option(WITH_NGHTTP2 "with nghttp2 library" OFF) option(WITH_OPENSSL "with openssl library" OFF) option(WITH_GNUTLS "with gnutls library" OFF) option(WITH_MBEDTLS "with mbedtls library" OFF) option(WITH_KCP "compile event/kcp" OFF) if(WIN32 OR MINGW) option(WITH_WEPOLL "compile event/wepoll -> use iocp" ON) option(ENABLE_WINDUMP "Windows MiniDumpWriteDump" OFF) option(BUILD_FOR_MT "build for /MT" OFF) if(BUILD_FOR_MT) set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT") endif() endif() message(STATUS "CMAKE_SOURCE_DIR=${CMAKE_SOURCE_DIR}") message(STATUS "CMAKE_CURRENT_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}") if(NOT "${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}") set(BUILD_EXAMPLES OFF) endif() if(IOS) set(BUILD_SHARED OFF) set(BUILD_EXAMPLES OFF) endif() set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") include(utils) include(vars) # see configure # Checks for header files check_header("stdbool.h") check_header("stdint.h") check_header("stdatomic.h") check_header("sys/types.h") check_header("sys/stat.h") check_header("sys/time.h") check_header("fcntl.h") check_header("pthread.h") check_header("endian.h") check_header("sys/endian.h") # Checks for functions if(NOT MSVC) set(CMAKE_REQUIRED_LIBRARIES "-pthread") endif() check_function("gettid" "unistd.h") check_function("strlcpy" "string.h") check_function("strlcat" "string.h") check_function("clock_gettime" "time.h") check_function("gettimeofday" "sys/time.h") check_function("pthread_spin_lock" "pthread.h") check_function("pthread_mutex_timedlock" "pthread.h") check_function("sem_timedwait" "semaphore.h") check_function("pipe" "unistd.h") check_function("socketpair" "sys/socket.h") check_function("eventfd" "sys/eventfd.h") check_function("setproctitle" "unistd.h") configure_file(${CMAKE_CURRENT_SOURCE_DIR}/hconfig.h.in ${CMAKE_CURRENT_SOURCE_DIR}/hconfig.h) # see Makefile.in set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED True) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) set(INCDIR include) set(SRCDIR src) set(LIBDIR lib) set(BINDIR bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${LIBDIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${LIBDIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINDIR}) message(STATUS "CMAKE_LIBRARY_OUTPUT_DIRECTORY=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}") set(INCDIRS . include 3rd/include) set(LIBDIRS . lib 3rd/lib) include_directories(${INCDIRS} ${SRCDIR}) link_directories(${LIBDIRS}) message(STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") add_definitions(-DDEBUG) else() add_definitions(-DNDEBUG) endif() if(ENABLE_UDS) add_definitions(-DENABLE_UDS) endif() if(USE_MULTIMAP) add_definitions(-DUSE_MULTIMAP) endif() if(WITH_CURL) add_definitions(-DWITH_CURL) set(LIBS ${LIBS} curl) if(WIN32 OR MINGW) set(LIBS ${LIBS} wldap32 advapi32 crypt32) endif() endif() if(WITH_NGHTTP2) add_definitions(-DWITH_NGHTTP2) set(LIBS ${LIBS} nghttp2) endif() if(WITH_OPENSSL) add_definitions(-DWITH_OPENSSL) find_package(OpenSSL) if(OpenSSL_FOUND) set(LIBS ${LIBS} OpenSSL::SSL OpenSSL::Crypto) else() set(LIBS ${LIBS} ssl crypto) endif() endif() if(WITH_GNUTLS) add_definitions(-DWITH_GNUTLS) set(LIBS ${LIBS} gnutls) endif() if(WITH_MBEDTLS) add_definitions(-DWITH_MBEDTLS) set(LIBS ${LIBS} mbedtls mbedx509 mbedcrypto) endif() if(WIN32 OR MINGW) add_definitions(-DWIN32_LEAN_AND_MEAN -D_CRT_SECURE_NO_WARNINGS -D_WIN32_WINNT=0x0600) set(LIBS ${LIBS} secur32 crypt32 winmm iphlpapi ws2_32) if(ENABLE_WINDUMP) add_definitions(-DENABLE_WINDUMP) set(LIBS ${LIBS} dbghelp) endif() endif() if(ANDROID) set(LIBS ${LIBS} log) elseif(UNIX AND NOT MINGW) set(LIBS ${LIBS} pthread m dl) if(CMAKE_COMPILER_IS_GNUCC) set(LIBS ${LIBS} rt) endif() endif() if(APPLE) set(LIBS ${LIBS} "-framework CoreFoundation" "-framework Security") endif() # see Makefile set(ALL_SRCDIRS . base ssl event event/kcp util cpputil evpp protocol http http/client http/server mqtt) set(CORE_SRCDIRS . base ssl event) if(WIN32 OR MINGW) if(WITH_WEPOLL) set(CORE_SRCDIRS ${CORE_SRCDIRS} event/wepoll) endif() endif() if(WITH_KCP) set(CORE_SRCDIRS ${CORE_SRCDIRS} event/kcp) endif() set(LIBHV_SRCDIRS ${CORE_SRCDIRS} util) set(LIBHV_HEADERS hv.h hconfig.h hexport.h) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${BASE_HEADERS} ${SSL_HEADERS} ${EVENT_HEADERS} ${UTIL_HEADERS}) if(WITH_PROTOCOL) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${PROTOCOL_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} protocol) endif() if(WITH_EVPP) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${CPPUTIL_HEADERS} ${EVPP_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} cpputil evpp) if(WITH_HTTP) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http) if(WITH_NGHTTP2) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP2_HEADERS}) endif() if(WITH_HTTP_SERVER) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_SERVER_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http/server) endif() if(WITH_HTTP_CLIENT) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_CLIENT_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http/client) endif() endif() if(CMAKE_SYSTEM_NAME MATCHES "Linux" AND CMAKE_COMPILER_IS_GNUCC) set(LIBS ${LIBS} stdc++) endif() endif() if(WITH_MQTT) set(LIBHV_HEADERS ${LIBHV_HEADERS} ${MQTT_HEADERS}) set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} mqtt) endif() list_source_directories(LIBHV_SRCS ${LIBHV_SRCDIRS}) file(INSTALL ${LIBHV_HEADERS} DESTINATION include/hv) file(INSTALL ${LIBHV_HEADERS} DESTINATION ${PROJECT_SOURCE_DIR}/include/hv) if(BUILD_SHARED) add_library(hv SHARED ${LIBHV_SRCS}) target_compile_definitions(hv PRIVATE HV_DYNAMICLIB) target_include_directories(hv PRIVATE ${LIBHV_SRCDIRS} INTERFACE $ $) target_link_libraries(hv ${LIBS}) install(TARGETS hv EXPORT libhvConfig ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin) add_custom_target(libhv DEPENDS hv) endif() if(BUILD_STATIC) add_library(hv_static STATIC ${LIBHV_SRCS}) target_compile_definitions(hv_static PUBLIC HV_STATICLIB) target_include_directories(hv_static PRIVATE ${LIBHV_SRCDIRS} INTERFACE $ $) target_link_libraries(hv_static ${LIBS}) install(TARGETS hv_static EXPORT libhvConfig ARCHIVE DESTINATION lib) add_custom_target(libhv_static DEPENDS hv_static) endif() install(FILES ${LIBHV_HEADERS} DESTINATION include/hv) install(EXPORT libhvConfig DESTINATION lib/cmake/libhv) if(BUILD_SHARED) set(HV_LIBRARIES hv CACHE INTERNAL "link hv libraries") else() add_definitions(-DHV_STATICLIB) set(HV_LIBRARIES hv_static ${LIBS} CACHE INTERNAL "link hv libraries") endif() if(BUILD_EXAMPLES) add_subdirectory(examples) # for httpd -c etc/httpd.conf file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}) file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}/bin) file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}/examples) endif() if(BUILD_UNITTEST) add_subdirectory(unittest) endif() # CPack settings set(CPACK_PACKAGE_NAME "libhv") set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") set(CPACK_PACKAGE_RELEASE 1) set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "A high-performance C/C++ network library") set(CPACK_PACKAGE_VENDOR "libhv") set(CPACK_PACKAGE_CONTACT "ithewei ") set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CMAKE_HOST_SYSTEM_PROCESSOR}") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") # Specify the package generators set(CPACK_GENERATOR "TGZ;DEB;RPM") # Enable CPack debug output set(CPACK_PACKAGE_DEBUG True) # https://cmake.org/cmake/help/latest/variable/CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION.html set(CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION "ON") include(CPack) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/LICENSE000066400000000000000000000027441520575453600244610ustar00rootroot00000000000000BSD 3-Clause License Copyright (c) 2020, ithewei All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/README-CN.md000066400000000000000000000512531520575453600252300ustar00rootroot00000000000000[English](README.md) | 中文 # libhv [![Linux](https://badgen.net/badge/Linux/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![Windows](https://badgen.net/badge/Windows/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![macOS](https://badgen.net/badge/macOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![Android](https://badgen.net/badge/Android/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![iOS](https://badgen.net/badge/iOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![benchmark](https://github.com/ithewei/libhv/workflows/benchmark/badge.svg?branch=master)](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml?query=branch%3Amaster)
[![release](https://badgen.net/github/release/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/releases) [![stars](https://badgen.net/github/stars/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/stargazers) [![forks](https://badgen.net/github/forks/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/forks) [![issues](https://badgen.net/github/issues/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/issues) [![PRs](https://badgen.net/github/prs/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/pulls) [![contributors](https://badgen.net/github/contributors/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/contributors) [![license](https://badgen.net/github/license/ithewei/libhv?icon=github)](LICENSE)
[![gitee](https://badgen.net/badge/mirror/gitee/red)](https://gitee.com/libhv/libhv) [![awesome-c](https://badgen.net/badge/icon/awesome-c/pink?icon=awesome&label&color)](https://github.com/oz123/awesome-c) [![awesome-cpp](https://badgen.net/badge/icon/awesome-cpp/pink?icon=awesome&label&color)](https://github.com/fffaraz/awesome-cpp) `libhv`是一个类似于`libevent、libev、libuv`的跨平台网络库,提供了更易用的接口和更丰富的协议。 ## 📚 中文资料 - **libhv QQ群**: `739352073`,欢迎加群交流 - **libhv 源码剖析**: - **libhv 接口手册**: - **libhv 教程目录**: - [libhv教程01--介绍与体验](https://hewei.blog.csdn.net/article/details/113702536) - [libhv教程02--编译与安装](https://hewei.blog.csdn.net/article/details/113704737) - [libhv教程03--链库与使用](https://hewei.blog.csdn.net/article/details/113706378) - [libhv教程04--编写一个完整的命令行程序](https://hewei.blog.csdn.net/article/details/113719503) - [libhv教程05--事件循环以及定时器的简单使用](https://hewei.blog.csdn.net/article/details/113724474) - [libhv教程06--创建一个简单的TCP服务端](https://hewei.blog.csdn.net/article/details/113737580) - [libhv教程07--创建一个简单的TCP客户端](https://hewei.blog.csdn.net/article/details/113738900) - [libhv教程08--创建一个简单的UDP服务端](https://hewei.blog.csdn.net/article/details/113871498) - [libhv教程09--创建一个简单的UDP客户端](https://hewei.blog.csdn.net/article/details/113871724) - [libhv教程10--创建一个简单的HTTP服务端](https://hewei.blog.csdn.net/article/details/113982999) - [libhv教程11--创建一个简单的HTTP客户端](https://hewei.blog.csdn.net/article/details/113984302) - [libhv教程12--创建一个简单的WebSocket服务端](https://hewei.blog.csdn.net/article/details/113985321) - [libhv教程13--创建一个简单的WebSocket客户端](https://hewei.blog.csdn.net/article/details/113985895) - [libhv教程14--200行实现一个纯C版jsonrpc框架](https://hewei.blog.csdn.net/article/details/119920540) - [libhv教程15--200行实现一个C++版protorpc框架](https://hewei.blog.csdn.net/article/details/119966701) - [libhv教程16--多线程/多进程服务端编程](https://hewei.blog.csdn.net/article/details/120366024) - [libhv教程17--Qt中使用libhv](https://hewei.blog.csdn.net/article/details/120699890) - [libhv教程18--动手写一个tinyhttpd](https://hewei.blog.csdn.net/article/details/121706604) - [libhv教程19--MQTT的实现与使用](https://hewei.blog.csdn.net/article/details/122753665) ## ✨ 特性 - 跨平台(Linux, Windows, macOS, Android, iOS, BSD, Solaris) - 高性能事件循环(网络IO事件、定时器事件、空闲事件、自定义事件、信号) - TCP/UDP服务端/客户端/代理 - TCP支持心跳、重连、转发、多线程安全write和close等特性 - 内置常见的拆包模式(固定包长、分界符、头部长度字段) - 可靠UDP支持: WITH_KCP - SSL/TLS加密通信(可选WITH_OPENSSL、WITH_GNUTLS、WITH_MBEDTLS) - HTTP服务端/客户端(支持https http1/x http2 grpc) - HTTP支持静态文件服务、目录服务、正向/反向代理服务、同步/异步API处理器 - HTTP支持RESTful风格、路由、中间件、keep-alive长连接、chunked分块、SSE等特性 - WebSocket服务端/客户端 - MQTT客户端 ## ⌛️ 构建 见[BUILD.md](BUILD.md) libhv提供了以下构建方式: 1、通过Makefile: ```shell ./configure make sudo make install ``` 2、通过cmake: ```shell mkdir build cd build cmake .. cmake --build . ``` 3、通过bazel: ```shell bazel build libhv ``` 4、通过vcpkg: ```shell vcpkg install libhv ``` 5、通过xmake: ```shell xrepo install libhv ``` ## ⚡️ 快速入门 ### 体验 运行脚本`./getting_started.sh`: ```shell # 下载编译 git clone https://github.com/ithewei/libhv.git cd libhv ./configure make # 运行httpd服务 bin/httpd -h bin/httpd -d #bin/httpd -c etc/httpd.conf -s restart -d ps aux | grep httpd # 文件服务 bin/curl -v localhost:8080 # 目录服务 bin/curl -v localhost:8080/downloads/ # API服务 bin/curl -v localhost:8080/ping bin/curl -v localhost:8080/echo -d "hello,world!" bin/curl -v localhost:8080/query?page_no=1\&page_size=10 bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' bin/curl -v localhost:8080/upload -d "@LICENSE" bin/curl -v localhost:8080/upload -F "file=@LICENSE" bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' # RESTful API: /group/:group_name/user/:user_id bin/curl -v -X DELETE localhost:8080/group/test/user/123 # 压力测试 bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ ``` ### TCP #### TCP服务端 **c版本**: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) **c++版本**: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) ```c++ #include "TcpServer.h" using namespace hv; int main() { int port = 1234; TcpServer srv; int listenfd = srv.createsocket(port); if (listenfd < 0) { return -1; } printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); srv.onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { // echo channel->write(buf); }; srv.setThreadNum(4); srv.start(); // press Enter to stop while (getchar() != '\n'); return 0; } ``` **注意**: 以上示例只是简单的`echo`服务,TCP是流式协议,实际应用中请务必添加边界进行拆包。
文本协议建议加上`\0`或者`\r\n`分隔符,可参考 [examples/jsonrpc](examples/jsonrpc);
二进制协议建议加上自定义协议头,通过头部长度字段表明负载长度,可参考 [examples/protorpc](examples/protorpc);
通过`setUnpack`(c接口即`hio_set_unpack`)设置拆包规则,支持固定包长、分隔符、头部长度字段三种常见的拆包方式,
内部根据拆包规则处理粘包与分包,保证`onMessage`回调上来的是完整的一包数据,大大节省了上层处理粘包与分包的成本。
不想自定义协议和拆包组包的可直接使用现成的`HTTP/WebSocket`协议。

`channel->write`(c接口即`hio_write`)是非阻塞的(事件循环异步编程里所有的一切都要求是非阻塞的),且多线程安全的。
发送大数据时应该做流控,通过`onWriteComplete`监听写完成事件,在可写时再发送下一帧数据。
具体示例代码可参考 [examples/tinyhttpd.c](examples/tinyhttpd.c) 中的 `http_serve_file`。

`channel->close`(c接口即`hio_close`) 也是多线程安全的,这可以让网络IO事件循环线程里接收数据、拆包组包、反序列化后放入队列,
消费者线程/线程池从队列里取出数据、处理后发送响应和关闭连接,变得更加简单。
#### TCP客户端 **c版本**: [examples/tcp_client_test.c](examples/tcp_client_test.c) **c++版本**: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) ```c++ #include #include "TcpClient.h" using namespace hv; int main() { int port = 1234; TcpClient cli; int connfd = cli.createsocket(port); if (connfd < 0) { return -1; } cli.onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); }; cli.start(); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { cli.closesocket(); } else if (str == "start") { cli.start(); } else if (str == "stop") { cli.stop(); break; } else { if (!cli.isConnected()) break; cli.send(str); } } return 0; } ``` ### HTTP #### HTTP服务端 见[examples/http_server_test.cpp](examples/http_server_test.cpp) **golang gin 风格** ```c++ #include "HttpServer.h" using namespace hv; int main() { HttpService router; router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { return resp->String("pong"); }); router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { static char data[] = "0123456789"; return resp->Data(data, 10); }); router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { return resp->Json(router.Paths()); }); router.GET("/get", [](HttpRequest* req, HttpResponse* resp) { resp->json["origin"] = req->client_addr.ip; resp->json["url"] = req->url; resp->json["args"] = req->query_params; resp->json["headers"] = req->headers; return 200; }); router.POST("/echo", [](const HttpContextPtr& ctx) { return ctx->send(ctx->body(), ctx->type()); }); HttpServer server(&router); server.setPort(8080); server.setThreadNum(4); server.run(); return 0; } ``` **注意**: 上面示例直接运行在`main`主线程,`server.run()`会阻塞当前线程运行,所以`router`和`server`对象不会被析构,
如使用`server.start()`内部会另起线程运行,不会阻塞当前线程,但需要注意`router`和`server`的生命周期,
不要定义为局部变量被析构了,可定义为类成员变量或者全局变量,下面的`WebSocket`服务同理。
#### HTTP客户端 见[examples/http_client_test.cpp](examples/http_client_test.cpp) **python requests 风格** ```c++ #include "requests.h" int main() { auto resp = requests::get("http://www.example.com"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } resp = requests::post("127.0.0.1:8080/echo", "hello,world!"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } return 0; } ``` 附HTTP相关接口文档: - [class HttpMessage](docs/cn/HttpMessage.md) - [class HttpClient](docs/cn/HttpClient.md) - [class HttpServer](docs/cn/HttpServer.md) - [class HttpContext](docs/cn/HttpContext.md) ### WebSocket #### WebSocket服务端 见[examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) ```c++ #include "WebSocketServer.h" using namespace hv; int main(int argc, char** argv) { WebSocketService ws; ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { printf("onopen: GET %s\n", req->Path().c_str()); }; ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); }; ws.onclose = [](const WebSocketChannelPtr& channel) { printf("onclose\n"); }; WebSocketServer server(&ws); server.setPort(9999); server.setThreadNum(4); server.run(); return 0; } ``` #### WebSocket客户端 见[examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) ```c++ #include "WebSocketClient.h" using namespace hv; int main(int argc, char** argv) { WebSocketClient ws; ws.onopen = []() { printf("onopen\n"); }; ws.onmessage = [](const std::string& msg) { printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); }; ws.onclose = []() { printf("onclose\n"); }; // reconnect: 1,2,4,8,10,10,10... reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; ws.setReconnect(&reconn); ws.open("ws://127.0.0.1:9999/test"); std::string str; while (std::getline(std::cin, str)) { if (!ws.isConnected()) break; if (str == "quit") { ws.close(); break; } ws.send(str); } return 0; } ``` ## 🍭 更多示例 ### c版本 - 事件循环: [examples/hloop_test.c](examples/hloop_test.c) - 定时器: [examples/htimer_test.c](examples/htimer_test.c) - pipe示例: [examples/pipe_test.c](examples/pipe_test.c) - TCP回显服务: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) - TCP聊天服务: [examples/tcp_chat_server.c](examples/tcp_chat_server.c) - TCP代理服务: [examples/tcp_proxy_server.c](examples/tcp_proxy_server.c) - UDP回显服务: [examples/udp_echo_server.c](examples/udp_echo_server.c) - UDP代理服务: [examples/udp_proxy_server.c](examples/udp_proxy_server.c) - SOCKS5代理服务: [examples/socks5_proxy_server.c](examples/socks5_proxy_server.c) - HTTP服务: [examples/tinyhttpd.c](examples/tinyhttpd.c) - HTTP代理服务: [examples/tinyproxyd.c](examples/tinyproxyd.c) - jsonRPC示例: [examples/jsonrpc](examples/jsonrpc) - MQTT示例: [examples/mqtt](examples/mqtt) - 多accept进程模式: [examples/multi-thread/multi-acceptor-processes.c](examples/multi-thread/multi-acceptor-processes.c) - 多accept线程模式: [examples/multi-thread/multi-acceptor-threads.c](examples/multi-thread/multi-acceptor-threads.c) - 一个accept线程+多worker线程: [examples/multi-thread/one-acceptor-multi-workers.c](examples/multi-thread/one-acceptor-multi-workers.c) ### c++版本 - 事件循环: [evpp/EventLoop_test.cpp](evpp/EventLoop_test.cpp) - 事件循环线程: [evpp/EventLoopThread_test.cpp](evpp/EventLoopThread_test.cpp) - 事件循环线程池: [evpp/EventLoopThreadPool_test.cpp](evpp/EventLoopThreadPool_test.cpp) - 定时器: [evpp/TimerThread_test.cpp](evpp/TimerThread_test.cpp) - TCP服务端: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) - TCP客户端: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) - UDP服务端: [evpp/UdpServer_test.cpp](evpp/UdpServer_test.cpp) - UDP客户端: [evpp/UdpClient_test.cpp](evpp/UdpClient_test.cpp) - HTTP服务端: [examples/http_server_test.cpp](examples/http_server_test.cpp) - HTTP客户端: [examples/http_client_test.cpp](examples/http_client_test.cpp) - WebSocket服务端: [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) - WebSocket客户端: [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) - protobufRPC示例: [examples/protorpc](examples/protorpc) - Qt中使用libhv示例: [hv-projects/QtDemo](https://github.com/hv-projects/QtDemo) ### 模拟实现著名的命令行工具 - 网络连接工具: [examples/nc](examples/nc.c) - 网络扫描工具: [examples/nmap](examples/nmap) - HTTP服务程序: [examples/httpd](examples/httpd) - HTTP压测工具: [examples/wrk](examples/wrk.cpp) - URL请求工具: [examples/curl](examples/curl.cpp) - 文件下载工具: [examples/wget](examples/wget.cpp) - 服务注册与发现: [examples/consul](examples/consul) - kcptun隧道: [examples/kcptun](examples/kcptun) ## 🥇 性能测试 ### TCP回显服务pingpong测试 ```shell cd echo-servers ./build.sh ./benchmark.sh ``` **吞吐量**: ```shell libevent running on port 2001 libev running on port 2002 libuv running on port 2003 libhv running on port 2004 asio running on port 2005 poco running on port 2006 ==============2001===================================== [127.0.0.1:2001] 4 threads 1000 connections run 10s total readcount=1616761 readbytes=1655563264 throughput = 157 MB/s ==============2002===================================== [127.0.0.1:2002] 4 threads 1000 connections run 10s total readcount=2153171 readbytes=2204847104 throughput = 210 MB/s ==============2003===================================== [127.0.0.1:2003] 4 threads 1000 connections run 10s total readcount=1599727 readbytes=1638120448 throughput = 156 MB/s ==============2004===================================== [127.0.0.1:2004] 4 threads 1000 connections run 10s total readcount=2202271 readbytes=2255125504 throughput = 215 MB/s ==============2005===================================== [127.0.0.1:2005] 4 threads 1000 connections run 10s total readcount=1354230 readbytes=1386731520 throughput = 132 MB/s ==============2006===================================== [127.0.0.1:2006] 4 threads 1000 connections run 10s total readcount=1699652 readbytes=1740443648 throughput = 165 MB/s ``` ### TCP代理服务压测 ```shell # sudo apt install iperf iperf -s -p 5001 > /dev/null & bin/tcp_proxy_server 1212 127.0.0.1:5001 & iperf -c 127.0.0.1 -p 5001 -l 8K iperf -c 127.0.0.1 -p 1212 -l 8K ``` **带宽**: ```shell ------------------------------------------------------------ [ 3] local 127.0.0.1 port 52560 connected with 127.0.0.1 port 5001 [ ID] Interval Transfer Bandwidth [ 3] 0.0-10.0 sec 20.8 GBytes 17.9 Gbits/sec ------------------------------------------------------------ [ 3] local 127.0.0.1 port 48142 connected with 127.0.0.1 port 1212 [ ID] Interval Transfer Bandwidth [ 3] 0.0-10.0 sec 11.9 GBytes 10.2 Gbits/sec ``` ### HTTP压测 ```shell # sudo apt install wrk wrk -c 100 -t 4 -d 10s http://127.0.0.1:8080/ # sudo apt install apache2-utils ab -c 100 -n 100000 http://127.0.0.1:8080/ ``` **libhv(port:8080) vs nginx(port:80)** ![libhv-vs-nginx.png](html/downloads/libhv-vs-nginx.png) 以上测试结果可以在 [Github Actions](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml) 中查看。 ## 💎 用户案例 如果您在使用`libhv`,欢迎通过PR将信息提交至此列表,让更多的用户了解`libhv`的实际使用场景,以建立更好的网络生态。 | 用户 (公司名/项目名/个人联系方式) | 案例 (项目简介/业务场景) | | :--- | :--- | | [阅面科技](https://www.readsense.cn) | [猎户AIoT平台](https://orionweb.readsense.cn)设备管理、人脸检测HTTP服务、人脸搜索HTTP服务 | | [socks5-libhv](https://gitee.com/billykang/socks5-libhv) | socks5代理 | | [hvloop](https://github.com/xiispace/hvloop) | 类似[uvloop](https://github.com/MagicStack/uvloop)的python异步IO事件循环 | | [tsproxyd-android](https://github.com/Haiwen-GitHub/tsproxyd-android) | 一个基于libhv实现的android端web代理服务 | | [玄舟智维](https://zjzwxw.com) | C100K设备连接网关服务 | kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/README.md000066400000000000000000000351651520575453600247360ustar00rootroot00000000000000English | [中文](README-CN.md) # libhv [![Linux](https://badgen.net/badge/Linux/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![Windows](https://badgen.net/badge/Windows/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![macOS](https://badgen.net/badge/macOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![Android](https://badgen.net/badge/Android/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![iOS](https://badgen.net/badge/iOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) [![benchmark](https://github.com/ithewei/libhv/workflows/benchmark/badge.svg?branch=master)](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml?query=branch%3Amaster)
[![release](https://badgen.net/github/release/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/releases) [![stars](https://badgen.net/github/stars/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/stargazers) [![forks](https://badgen.net/github/forks/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/forks) [![issues](https://badgen.net/github/issues/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/issues) [![PRs](https://badgen.net/github/prs/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/pulls) [![contributors](https://badgen.net/github/contributors/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/contributors) [![license](https://badgen.net/github/license/ithewei/libhv?icon=github)](LICENSE)
[![gitee](https://badgen.net/badge/mirror/gitee/red)](https://gitee.com/libhv/libhv) [![awesome-c](https://badgen.net/badge/icon/awesome-c/pink?icon=awesome&label&color)](https://github.com/oz123/awesome-c) [![awesome-cpp](https://badgen.net/badge/icon/awesome-cpp/pink?icon=awesome&label&color)](https://github.com/fffaraz/awesome-cpp) Like `libevent, libev, and libuv`, `libhv` provides event-loop with non-blocking IO and timer, but simpler api and richer protocols. ## ✨ Features - Cross-platform (Linux, Windows, macOS, Android, iOS, BSD, Solaris) - High-performance EventLoop (IO, timer, idle, custom, signal) - TCP/UDP client/server/proxy - TCP supports heartbeat, reconnect, upstream, MultiThread-safe write and close, etc. - Built-in common unpacking modes (FixedLength, Delimiter, LengthField) - RUDP support: WITH_KCP - SSL/TLS support: (via WITH_OPENSSL or WITH_GNUTLS or WITH_MBEDTLS) - HTTP client/server (support https http1/x http2 grpc) - HTTP supports static service, indexof service, forward/reverse proxy service, sync/async API handler - HTTP supports RESTful, router, middleware, keep-alive, chunked, SSE, etc. - WebSocket client/server - MQTT client ## ⌛️ Build see [BUILD.md](BUILD.md) Makefile: ```shell ./configure make sudo make install ``` or cmake: ```shell mkdir build cd build cmake .. cmake --build . ``` or bazel: ```shell bazel build libhv ``` or vcpkg: ```shell vcpkg install libhv ``` or xmake: ```shell xrepo install libhv ``` ## ⚡️ Getting Started run `./getting_started.sh`: ```shell git clone https://github.com/ithewei/libhv.git cd libhv ./configure make bin/httpd -h bin/httpd -d #bin/httpd -c etc/httpd.conf -s restart -d ps aux | grep httpd # http file service bin/curl -v localhost:8080 # http indexof service bin/curl -v localhost:8080/downloads/ # http api service bin/curl -v localhost:8080/ping bin/curl -v localhost:8080/echo -d "hello,world!" bin/curl -v localhost:8080/query?page_no=1\&page_size=10 bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' bin/curl -v localhost:8080/upload -d "@LICENSE" bin/curl -v localhost:8080/upload -F "file=@LICENSE" bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' # RESTful API: /group/:group_name/user/:user_id bin/curl -v -X DELETE localhost:8080/group/test/user/123 # benchmark bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ ``` ### TCP #### tcp server **c version**: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) **c++ version**: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) ```c++ #include "TcpServer.h" using namespace hv; int main() { int port = 1234; TcpServer srv; int listenfd = srv.createsocket(port); if (listenfd < 0) { return -1; } printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); srv.onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { // echo channel->write(buf); }; srv.setThreadNum(4); srv.start(); // press Enter to stop while (getchar() != '\n'); return 0; } ``` #### tcp client **c version**: [examples/tcp_client_test.c](examples/tcp_client_test.c) **c++ version**: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) ```c++ #include #include "TcpClient.h" using namespace hv; int main() { int port = 1234; TcpClient cli; int connfd = cli.createsocket(port); if (connfd < 0) { return -1; } cli.onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); }; cli.start(); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { cli.closesocket(); } else if (str == "start") { cli.start(); } else if (str == "stop") { cli.stop(); break; } else { if (!cli.isConnected()) break; cli.send(str); } } return 0; } ``` ### HTTP #### http server see [examples/http_server_test.cpp](examples/http_server_test.cpp) **golang gin style** ```c++ #include "HttpServer.h" using namespace hv; int main() { HttpService router; router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { return resp->String("pong"); }); router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { static char data[] = "0123456789"; return resp->Data(data, 10); }); router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { return resp->Json(router.Paths()); }); router.GET("/get", [](HttpRequest* req, HttpResponse* resp) { resp->json["origin"] = req->client_addr.ip; resp->json["url"] = req->url; resp->json["args"] = req->query_params; resp->json["headers"] = req->headers; return 200; }); router.POST("/echo", [](const HttpContextPtr& ctx) { return ctx->send(ctx->body(), ctx->type()); }); HttpServer server(&router); server.setPort(8080); server.setThreadNum(4); server.run(); return 0; } ``` #### http client see [examples/http_client_test.cpp](examples/http_client_test.cpp) **python requests style** ```c++ #include "requests.h" int main() { auto resp = requests::get("http://www.example.com"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } resp = requests::post("127.0.0.1:8080/echo", "hello,world!"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } return 0; } ``` ### WebSocket #### WebSocket server see [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) ```c++ #include "WebSocketServer.h" using namespace hv; int main(int argc, char** argv) { WebSocketService ws; ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { printf("onopen: GET %s\n", req->Path().c_str()); }; ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); }; ws.onclose = [](const WebSocketChannelPtr& channel) { printf("onclose\n"); }; WebSocketServer server(&ws); server.setPort(9999); server.setThreadNum(4); server.run(); return 0; } ``` #### WebSocket client see [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) ```c++ #include "WebSocketClient.h" using namespace hv; int main(int argc, char** argv) { WebSocketClient ws; ws.onopen = []() { printf("onopen\n"); }; ws.onmessage = [](const std::string& msg) { printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); }; ws.onclose = []() { printf("onclose\n"); }; // reconnect: 1,2,4,8,10,10,10... reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; ws.setReconnect(&reconn); ws.open("ws://127.0.0.1:9999/test"); std::string str; while (std::getline(std::cin, str)) { if (!ws.isConnected()) break; if (str == "quit") { ws.close(); break; } ws.send(str); } return 0; } ``` ## 🍭 More examples ### c version - [examples/hloop_test.c](examples/hloop_test.c) - [examples/htimer_test.c](examples/htimer_test.c) - [examples/pipe_test.c](examples/pipe_test.c) - [examples/tcp_echo_server.c](examples/tcp_echo_server.c) - [examples/tcp_chat_server.c](examples/tcp_chat_server.c) - [examples/tcp_proxy_server.c](examples/tcp_proxy_server.c) - [examples/udp_echo_server.c](examples/udp_echo_server.c) - [examples/udp_proxy_server.c](examples/udp_proxy_server.c) - [examples/socks5_proxy_server.c](examples/socks5_proxy_server.c) - [examples/tinyhttpd.c](examples/tinyhttpd.c) - [examples/tinyproxyd.c](examples/tinyproxyd.c) - [examples/jsonrpc](examples/jsonrpc) - [examples/mqtt](examples/mqtt) - [examples/multi-thread/multi-acceptor-processes.c](examples/multi-thread/multi-acceptor-processes.c) - [examples/multi-thread/multi-acceptor-threads.c](examples/multi-thread/multi-acceptor-threads.c) - [examples/multi-thread/one-acceptor-multi-workers.c](examples/multi-thread/one-acceptor-multi-workers.c) ### c++ version - [evpp/EventLoop_test.cpp](evpp/EventLoop_test.cpp) - [evpp/EventLoopThread_test.cpp](evpp/EventLoopThread_test.cpp) - [evpp/EventLoopThreadPool_test.cpp](evpp/EventLoopThreadPool_test.cpp) - [evpp/TimerThread_test.cpp](evpp/TimerThread_test.cpp) - [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) - [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) - [evpp/UdpServer_test.cpp](evpp/UdpServer_test.cpp) - [evpp/UdpClient_test.cpp](evpp/UdpClient_test.cpp) - [examples/http_server_test.cpp](examples/http_server_test.cpp) - [examples/http_client_test.cpp](examples/http_client_test.cpp) - [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) - [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) - [examples/protorpc](examples/protorpc) - [hv-projects/QtDemo](https://github.com/hv-projects/QtDemo) ### simulate well-known command line tools - [examples/nc](examples/nc.c) - [examples/nmap](examples/nmap) - [examples/httpd](examples/httpd) - [examples/wrk](examples/wrk.cpp) - [examples/curl](examples/curl.cpp) - [examples/wget](examples/wget.cpp) - [examples/consul](examples/consul) - [examples/kcptun](examples/kcptun) ## 🥇 Benchmark ### `pingpong echo-servers` ```shell cd echo-servers ./build.sh ./benchmark.sh ``` **throughput**: ```shell libevent running on port 2001 libev running on port 2002 libuv running on port 2003 libhv running on port 2004 asio running on port 2005 poco running on port 2006 ==============2001===================================== [127.0.0.1:2001] 4 threads 1000 connections run 10s total readcount=1616761 readbytes=1655563264 throughput = 157 MB/s ==============2002===================================== [127.0.0.1:2002] 4 threads 1000 connections run 10s total readcount=2153171 readbytes=2204847104 throughput = 210 MB/s ==============2003===================================== [127.0.0.1:2003] 4 threads 1000 connections run 10s total readcount=1599727 readbytes=1638120448 throughput = 156 MB/s ==============2004===================================== [127.0.0.1:2004] 4 threads 1000 connections run 10s total readcount=2202271 readbytes=2255125504 throughput = 215 MB/s ==============2005===================================== [127.0.0.1:2005] 4 threads 1000 connections run 10s total readcount=1354230 readbytes=1386731520 throughput = 132 MB/s ==============2006===================================== [127.0.0.1:2006] 4 threads 1000 connections run 10s total readcount=1699652 readbytes=1740443648 throughput = 165 MB/s ``` ### `iperf tcp_proxy_server` ```shell # sudo apt install iperf iperf -s -p 5001 > /dev/null & bin/tcp_proxy_server 1212 127.0.0.1:5001 & iperf -c 127.0.0.1 -p 5001 -l 8K iperf -c 127.0.0.1 -p 1212 -l 8K ``` **Bandwidth**: ```shell ------------------------------------------------------------ [ 3] local 127.0.0.1 port 52560 connected with 127.0.0.1 port 5001 [ ID] Interval Transfer Bandwidth [ 3] 0.0-10.0 sec 20.8 GBytes 17.9 Gbits/sec ------------------------------------------------------------ [ 3] local 127.0.0.1 port 48142 connected with 127.0.0.1 port 1212 [ ID] Interval Transfer Bandwidth [ 3] 0.0-10.0 sec 11.9 GBytes 10.2 Gbits/sec ``` ### `webbench` ```shell # sudo apt install wrk wrk -c 100 -t 4 -d 10s http://127.0.0.1:8080/ # sudo apt install apache2-utils ab -c 100 -n 100000 http://127.0.0.1:8080/ ``` **libhv(port:8080) vs nginx(port:80)** ![libhv-vs-nginx.png](html/downloads/libhv-vs-nginx.png) Above test results can be found on [Github Actions](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml). kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/TREE.md000066400000000000000000000030011520575453600245200ustar00rootroot00000000000000## 目录结构 ``` . ├── base libhv基础设施,如常用宏定义、数据结构、日期时间、线程、进程、日志、套接字 ├── bin 可执行文件安装目录 ├── build cmake默认构建目录 ├── cert SSL证书存放目录 ├── cmake cmake脚本存放目录 ├── cpputil libhv工具类,如字符串、文件、路径、线程池、json解析、ini解析 ├── docs 文档存放目录 ├── echo-servers 包含libevent、libev、libuv、libhv、asio、poco、muduo等多个网络库的tcp echo server写法,并做压力测试 ├── etc 应用程序配置目录 ├── event libhv事件循环模块 ├── evpp 事件循环c++封装类 ├── examples 示例代码 │   └── httpd ├── html 网页document_root目录 │   ├── downloads 下载目录 │   └── uploads 上传目录 ├── http libhv http模块 │   ├── client │   └── server ├── include 头文件安装目录 │   └── hv ├── lib 库文件安装目录 ├── logs 日志生成目录 ├── misc 杂项 ├── mqtt MQTT协议 ├── protocol 包含icmp、dns、ftp、smtp等协议的实现 ├── scripts shell脚本存放目录 ├── ssl SSL/TLS加密通信 ├── unittest 单元测试代码 └── util libhv工具函数,如base64、md5、sha1 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/WORKSPACE.bazel000066400000000000000000000000271520575453600260210ustar00rootroot00000000000000workspace(name = "hv") kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/000077500000000000000000000000001520575453600243575ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/README.md000066400000000000000000000015001520575453600256320ustar00rootroot00000000000000## 目录结构 ``` . ├── array.h 动态数组 ├── hatomic.h 原子操作 ├── hbase.h 基础函数 ├── hbuf.h 缓存 ├── hdef.h 常见宏定义 ├── heap.h 堆 ├── hendian.h 大小端 ├── herr.h 错误码表 ├── hlog.h 日志 ├── hmain.h 命令行解析 ├── hmath.h 数学函数 ├── hmutex.h 线程同步锁 ├── hplatform.h 平台相关宏 ├── hproc.h 进程 ├── hsocket.h 套接字 ├── hsysinfo.h 系统信息 ├── hthread.h 线程 ├── htime.h 时间 ├── hversion.h 版本 ├── list.h 链表 ├── queue.h 队列 └── rbtree.h 红黑树 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/array.h000066400000000000000000000066631520575453600256610ustar00rootroot00000000000000#ifndef HV_ARRAY_H_ #define HV_ARRAY_H_ /* * array * at: random access by pos * @effective * push_back,pop_back,del_nomove,swap * @ineffective * add,del */ #include // for assert #include // for NULL #include // for malloc,realloc,free #include // for memset,memmove #include "hbase.h" // for HV_ALLOC, HV_FREE #define ARRAY_INIT_SIZE 16 // #include // typedef std::vector atype; #define ARRAY_DECL(type, atype) \ struct atype { \ type* ptr; \ size_t size; \ size_t maxsize;\ }; \ typedef struct atype atype;\ \ static inline type* atype##_data(atype* p) {\ return p->ptr;\ }\ \ static inline int atype##_size(atype* p) {\ return p->size;\ }\ \ static inline int atype##_maxsize(atype* p) {\ return p->maxsize;\ }\ \ static inline int atype##_empty(atype* p) {\ return p->size == 0;\ }\ \ static inline type* atype##_at(atype* p, int pos) {\ if (pos < 0) {\ pos += p->size;\ }\ assert(pos >= 0 && pos < p->size);\ return p->ptr + pos;\ }\ \ static inline type* atype##_front(atype* p) {\ return p->size == 0 ? NULL : p->ptr;\ }\ \ static inline type* atype##_back(atype* p) {\ return p->size == 0 ? NULL : p->ptr + p->size - 1;\ }\ \ static inline void atype##_init(atype* p, int maxsize) {\ p->size = 0;\ p->maxsize = maxsize;\ HV_ALLOC(p->ptr, sizeof(type) * maxsize);\ }\ \ static inline void atype##_clear(atype* p) {\ p->size = 0;\ memset(p->ptr, 0, sizeof(type) * p->maxsize);\ }\ \ static inline void atype##_cleanup(atype* p) {\ HV_FREE(p->ptr);\ p->size = p->maxsize = 0;\ }\ \ static inline void atype##_resize(atype* p, int maxsize) {\ if (maxsize == 0) maxsize = ARRAY_INIT_SIZE;\ p->ptr = (type*)hv_realloc(p->ptr, sizeof(type) * maxsize, sizeof(type) * p->maxsize);\ p->maxsize = maxsize;\ }\ \ static inline void atype##_double_resize(atype* p) {\ atype##_resize(p, p->maxsize * 2);\ }\ \ static inline void atype##_push_back(atype* p, type* elem) {\ if (p->size == p->maxsize) {\ atype##_double_resize(p);\ }\ p->ptr[p->size] = *elem;\ p->size++;\ }\ \ static inline void atype##_pop_back(atype* p) {\ assert(p->size > 0);\ p->size--;\ }\ \ static inline void atype##_add(atype* p, type* elem, int pos) {\ if (pos < 0) {\ pos += p->size;\ }\ assert(pos >= 0 && pos <= p->size);\ if (p->size == p->maxsize) {\ atype##_double_resize(p);\ }\ if (pos < p->size) {\ memmove(p->ptr + pos+1, p->ptr + pos, sizeof(type) * (p->size - pos));\ }\ p->ptr[pos] = *elem;\ p->size++;\ }\ \ static inline void atype##_del(atype* p, int pos) {\ if (pos < 0) {\ pos += p->size;\ }\ assert(pos >= 0 && pos < p->size);\ p->size--;\ if (pos < p->size) {\ memmove(p->ptr + pos, p->ptr + pos+1, sizeof(type) * (p->size - pos));\ }\ }\ \ static inline void atype##_del_nomove(atype* p, int pos) {\ if (pos < 0) {\ pos += p->size;\ }\ assert(pos >= 0 && pos < p->size);\ p->size--;\ if (pos < p->size) {\ p->ptr[pos] = p->ptr[p->size];\ }\ }\ \ static inline void atype##_swap(atype* p, int pos1, int pos2) {\ if (pos1 < 0) {\ pos1 += p->size;\ }\ if (pos2 < 0) {\ pos2 += p->size;\ }\ type tmp = p->ptr[pos1];\ p->ptr[pos1] = p->ptr[pos2];\ p->ptr[pos2] = tmp;\ }\ #endif // HV_ARRAY_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hatomic.h000066400000000000000000000070361520575453600261620ustar00rootroot00000000000000#ifndef HV_ATOMIC_H_ #define HV_ATOMIC_H_ #ifdef __cplusplus // c++11 #include using std::atomic_flag; using std::atomic_long; #define ATOMIC_FLAG_TEST_AND_SET(p) ((p)->test_and_set()) #define ATOMIC_FLAG_CLEAR(p) ((p)->clear()) #else #include "hplatform.h" // for HAVE_STDATOMIC_H #if HAVE_STDATOMIC_H // c11 #include #define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set #define ATOMIC_FLAG_CLEAR atomic_flag_clear #define ATOMIC_ADD atomic_fetch_add #define ATOMIC_SUB atomic_fetch_sub #define ATOMIC_INC(p) ATOMIC_ADD(p, 1) #define ATOMIC_DEC(p) ATOMIC_SUB(p, 1) #else typedef volatile bool atomic_bool; typedef volatile char atomic_char; typedef volatile unsigned char atomic_uchar; typedef volatile short atomic_short; typedef volatile unsigned short atomic_ushort; typedef volatile int atomic_int; typedef volatile unsigned int atomic_uint; typedef volatile long atomic_long; typedef volatile unsigned long atomic_ulong; typedef volatile long long atomic_llong; typedef volatile unsigned long long atomic_ullong; typedef volatile size_t atomic_size_t; typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; #ifdef _WIN32 #define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set static inline bool atomic_flag_test_and_set(atomic_flag* p) { // return InterlockedIncrement((LONG*)&p->_Value, 1); return InterlockedCompareExchange((LONG*)&p->_Value, 1, 0); } #define ATOMIC_ADD InterlockedAdd #define ATOMIC_SUB(p, n) InterlockedAdd(p, -n) #define ATOMIC_INC InterlockedIncrement #define ATOMIC_DEC InterlockedDecrement #elif defined(__GNUC__) #define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set static inline bool atomic_flag_test_and_set(atomic_flag* p) { return !__sync_bool_compare_and_swap(&p->_Value, 0, 1); } #define ATOMIC_ADD __sync_fetch_and_add #define ATOMIC_SUB __sync_fetch_and_sub #define ATOMIC_INC(p) ATOMIC_ADD(p, 1) #define ATOMIC_DEC(p) ATOMIC_SUB(p, 1) #endif #endif // HAVE_STDATOMIC_H #endif // __cplusplus #ifndef ATOMIC_FLAG_INIT #define ATOMIC_FLAG_INIT { 0 } #endif #ifndef ATOMIC_VAR_INIT #define ATOMIC_VAR_INIT(value) (value) #endif #ifndef ATOMIC_FLAG_TEST_AND_SET #define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set static inline bool atomic_flag_test_and_set(atomic_flag* p) { bool ret = p->_Value; p->_Value = 1; return ret; } #endif #ifndef ATOMIC_FLAG_CLEAR #define ATOMIC_FLAG_CLEAR atomic_flag_clear static inline void atomic_flag_clear(atomic_flag* p) { p->_Value = 0; } #endif #ifndef ATOMIC_ADD #define ATOMIC_ADD(p, n) (*(p) += (n)) #endif #ifndef ATOMIC_SUB #define ATOMIC_SUB(p, n) (*(p) -= (n)) #endif #ifndef ATOMIC_INC #define ATOMIC_INC(p) ((*(p))++) #endif #ifndef ATOMIC_DEC #define ATOMIC_DEC(p) ((*(p))--) #endif typedef atomic_flag hatomic_flag_t; #define HATOMIC_FLAG_INIT ATOMIC_FLAG_INIT #define hatomic_flag_test_and_set ATOMIC_FLAG_TEST_AND_SET #define hatomic_flag_clear ATOMIC_FLAG_CLEAR typedef atomic_long hatomic_t; #define HATOMIC_VAR_INIT ATOMIC_VAR_INIT #define hatomic_add ATOMIC_ADD #define hatomic_sub ATOMIC_SUB #define hatomic_inc ATOMIC_INC #define hatomic_dec ATOMIC_DEC #endif // HV_ATOMIC_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hbase.c000066400000000000000000000317111520575453600256100ustar00rootroot00000000000000#include "hbase.h" #ifdef OS_DARWIN #include // for _NSGetExecutablePath #endif #include "hatomic.h" #ifndef RAND_MAX #define RAND_MAX 2147483647 #endif static hatomic_t s_alloc_cnt = HATOMIC_VAR_INIT(0); static hatomic_t s_free_cnt = HATOMIC_VAR_INIT(0); long hv_alloc_cnt() { return s_alloc_cnt; } long hv_free_cnt() { return s_free_cnt; } void* hv_malloc(size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = malloc(size); if (!ptr) { fprintf(stderr, "malloc failed!\n"); exit(-1); } return ptr; } void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize) { hatomic_inc(&s_alloc_cnt); if (oldptr) hatomic_inc(&s_free_cnt); void* ptr = realloc(oldptr, newsize); if (!ptr) { fprintf(stderr, "realloc failed!\n"); exit(-1); } if (newsize > oldsize) { memset((char*)ptr + oldsize, 0, newsize - oldsize); } return ptr; } void* hv_calloc(size_t nmemb, size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = calloc(nmemb, size); if (!ptr) { fprintf(stderr, "calloc failed!\n"); exit(-1); } return ptr; } void* hv_zalloc(size_t size) { hatomic_inc(&s_alloc_cnt); void* ptr = malloc(size); if (!ptr) { fprintf(stderr, "malloc failed!\n"); exit(-1); } memset(ptr, 0, size); return ptr; } void hv_free(void* ptr) { if (ptr) { free(ptr); ptr = NULL; hatomic_inc(&s_free_cnt); } } char* hv_strupper(char* str) { char* p = str; while (*p != '\0') { if (*p >= 'a' && *p <= 'z') { *p &= ~0x20; } ++p; } return str; } char* hv_strlower(char* str) { char* p = str; while (*p != '\0') { if (*p >= 'A' && *p <= 'Z') { *p |= 0x20; } ++p; } return str; } char* hv_strreverse(char* str) { if (str == NULL) return NULL; char* b = str; char* e = str; while(*e) {++e;} --e; char tmp; while (e > b) { tmp = *e; *e = *b; *b = tmp; --e; ++b; } return str; } // n = sizeof(dest_buf) char* hv_strncpy(char* dest, const char* src, size_t n) { assert(dest != NULL && src != NULL); char* ret = dest; while (*src != '\0' && --n > 0) { *dest++ = *src++; } *dest = '\0'; return ret; } // n = sizeof(dest_buf) char* hv_strncat(char* dest, const char* src, size_t n) { assert(dest != NULL && src != NULL); char* ret = dest; while (*dest) {++dest;--n;} while (*src != '\0' && --n > 0) { *dest++ = *src++; } *dest = '\0'; return ret; } bool hv_strstartswith(const char* str, const char* start) { assert(str != NULL && start != NULL); while (*str && *start && *str == *start) { ++str; ++start; } return *start == '\0'; } bool hv_strendswith(const char* str, const char* end) { assert(str != NULL && end != NULL); int len1 = 0; int len2 = 0; while (*str) {++str; ++len1;} while (*end) {++end; ++len2;} if (len1 < len2) return false; while (len2-- > 0) { --str; --end; if (*str != *end) { return false; } } return true; } bool hv_strcontains(const char* str, const char* sub) { assert(str != NULL && sub != NULL); return strstr(str, sub) != NULL; } bool hv_wildcard_match(const char* str, const char* pattern) { assert(str != NULL && pattern != NULL); bool match = false; while (*str && *pattern) { if (*pattern == '*') { match = hv_strendswith(str, pattern + 1); break; } else if (*str != *pattern) { match = false; break; } else { ++str; ++pattern; } } return match ? match : (*str == '\0' && *pattern == '\0'); } char* hv_strnchr(const char* s, char c, size_t n) { assert(s != NULL); const char* p = s; while (*p != '\0' && n-- > 0) { if (*p == c) return (char*)p; ++p; } return NULL; } char* hv_strnrchr(const char* s, char c, size_t n) { assert(s != NULL); const char* p = s; const char* last = NULL; while (*p != '\0' && n-- > 0) { if (*p == c) last = p; ++p; } return (char*)last; } char* hv_strrchr_dir(const char* filepath) { char* p = (char*)filepath; while (*p) ++p; while (--p >= filepath) { #ifdef OS_WIN if (*p == '/' || *p == '\\') #else if (*p == '/') #endif return p; } return NULL; } const char* hv_basename(const char* filepath) { const char* pos = hv_strrchr_dir(filepath); return pos ? pos+1 : filepath; } const char* hv_suffixname(const char* filename) { const char* pos = hv_strrchr_dot(filename); return pos ? pos+1 : ""; } int hv_mkdir_p(const char* dir) { if (access(dir, 0) == 0) { return EEXIST; } char tmp[MAX_PATH] = {0}; hv_strncpy(tmp, dir, sizeof(tmp)); char* p = tmp; char delim = '/'; while (*p) { #ifdef OS_WIN if (*p == '/' || *p == '\\') { delim = *p; #else if (*p == '/') { #endif *p = '\0'; hv_mkdir(tmp); *p = delim; } ++p; } if (hv_mkdir(tmp) != 0) { return EPERM; } return 0; } int hv_rmdir_p(const char* dir) { if (access(dir, 0) != 0) { return ENOENT; } if (rmdir(dir) != 0) { return EPERM; } char tmp[MAX_PATH] = {0}; hv_strncpy(tmp, dir, sizeof(tmp)); char* p = tmp; while (*p) ++p; while (--p >= tmp) { #ifdef OS_WIN if (*p == '/' || *p == '\\') { #else if (*p == '/') { #endif *p = '\0'; if (rmdir(tmp) != 0) { return 0; } } } return 0; } bool hv_exists(const char* path) { return access(path, 0) == 0; } bool hv_isdir(const char* path) { if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); stat(path, &st); return S_ISDIR(st.st_mode); } bool hv_isfile(const char* path) { if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); stat(path, &st); return S_ISREG(st.st_mode); } bool hv_islink(const char* path) { #ifdef OS_WIN return hv_isdir(path) && (GetFileAttributes(path) & FILE_ATTRIBUTE_REPARSE_POINT); #else if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); lstat(path, &st); return S_ISLNK(st.st_mode); #endif } size_t hv_filesize(const char* filepath) { struct stat st; memset(&st, 0, sizeof(st)); stat(filepath, &st); return st.st_size; } char* get_executable_path(char* buf, int size) { #ifdef OS_WIN GetModuleFileName(NULL, buf, size); #elif defined(OS_LINUX) if (readlink("/proc/self/exe", buf, size) == -1) { return NULL; } #elif defined(OS_DARWIN) _NSGetExecutablePath(buf, (uint32_t*)&size); #endif return buf; } char* get_executable_dir(char* buf, int size) { char filepath[MAX_PATH] = {0}; get_executable_path(filepath, sizeof(filepath)); char* pos = hv_strrchr_dir(filepath); if (pos) { *pos = '\0'; strncpy(buf, filepath, size); } return buf; } char* get_executable_file(char* buf, int size) { char filepath[MAX_PATH] = {0}; get_executable_path(filepath, sizeof(filepath)); char* pos = hv_strrchr_dir(filepath); if (pos) { strncpy(buf, pos+1, size); } return buf; } char* get_run_dir(char* buf, int size) { return getcwd(buf, size); } int hv_rand(int min, int max) { static int s_seed = 0; assert(max > min); if (s_seed == 0) { s_seed = time(NULL); srand(s_seed); } int _rand = rand(); _rand = min + (int) ((double) ((double) (max) - (min) + 1.0) * ((_rand) / ((RAND_MAX) + 1.0))); return _rand; } char* hv_random_string(char *buf, int len) { static char s_characters[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; int i = 0; for (; i < len; i++) { buf[i] = s_characters[hv_rand(0, sizeof(s_characters) - 1)]; } buf[i] = '\0'; return buf; } bool hv_getboolean(const char* str) { if (str == NULL) return false; int len = strlen(str); if (len == 0) return false; switch (len) { case 1: return *str == '1' || *str == 'y' || *str == 'Y'; case 2: return stricmp(str, "on") == 0; case 3: return stricmp(str, "yes") == 0; case 4: return stricmp(str, "true") == 0; case 6: return stricmp(str, "enable") == 0; default: return false; } } size_t hv_parse_size(const char* str) { size_t size = 0, n = 0; const char* p = str; char c; while ((c = *p) != '\0') { if (c >= '0' && c <= '9') { n = n * 10 + c - '0'; } else { switch (c) { case 'K': case 'k': n <<= 10; break; case 'M': case 'm': n <<= 20; break; case 'G': case 'g': n <<= 30; break; case 'T': case 't': n <<= 40; break; default: break; } size += n; n = 0; } ++p; } return size + n; } time_t hv_parse_time(const char* str) { time_t time = 0, n = 0; const char* p = str; char c; while ((c = *p) != '\0') { if (c >= '0' && c <= '9') { n = n * 10 + c - '0'; } else { switch (c) { case 's': break; case 'm': n *= 60; break; case 'h': n *= 60 * 60; break; case 'd': n *= 24 * 60 * 60; break; case 'w': n *= 7 * 24 * 60 * 60; break; default: break; } time += n; n = 0; } ++p; } return time + n; } int hv_parse_url(hurl_t* stURL, const char* strURL) { if (stURL == NULL || strURL == NULL) return -1; memset(stURL, 0, sizeof(hurl_t)); const char* begin = strURL; const char* end = strURL; while (*end != '\0') ++end; if (end - begin > 65535) return -2; // scheme:// const char* sp = strURL; const char* ep = strstr(sp, "://"); if (ep) { // stURL->fields[HV_URL_SCHEME].off = sp - begin; stURL->fields[HV_URL_SCHEME].len = ep - sp; sp = ep + 3; } // user:pswd@host:port ep = strchr(sp, '/'); if (ep == NULL) ep = end; const char* user = sp; const char* host = sp; const char* pos = hv_strnchr(sp, '@', ep - sp); if (pos) { // user:pswd const char* pswd = hv_strnchr(user, ':', pos - user); if (pswd) { stURL->fields[HV_URL_PASSWORD].off = pswd + 1 - begin; stURL->fields[HV_URL_PASSWORD].len = pos - pswd - 1; } else { pswd = pos; } stURL->fields[HV_URL_USERNAME].off = user - begin; stURL->fields[HV_URL_USERNAME].len = pswd - user; // @ host = pos + 1; } // host:port or ipv4:port or [ipv6]:port const char* hostend = host; if (*host == '[') { pos = hv_strnchr(host, ']', ep - host); if (pos) { // ipv6 host++; hostend = pos; stURL->fields[HV_URL_HOST].off = host - begin; stURL->fields[HV_URL_HOST].len = hostend - host; } } const char* port = hv_strnchr(hostend, ':', ep - hostend); if (port) { stURL->fields[HV_URL_PORT].off = port + 1 - begin; stURL->fields[HV_URL_PORT].len = ep - port - 1; // atoi for (unsigned short i = 1; i <= stURL->fields[HV_URL_PORT].len; ++i) { stURL->port = stURL->port * 10 + (port[i] - '0'); } } else { port = ep; // set default port stURL->port = 80; if (stURL->fields[HV_URL_SCHEME].len > 0) { if (strncmp(strURL, "https://", 8) == 0) { stURL->port = 443; } } } if (stURL->fields[HV_URL_HOST].len == 0) { stURL->fields[HV_URL_HOST].off = host - begin; stURL->fields[HV_URL_HOST].len = port - host; } if (ep == end) return 0; // /path sp = ep; ep = strchr(sp, '?'); if (ep == NULL) ep = end; stURL->fields[HV_URL_PATH].off = sp - begin; stURL->fields[HV_URL_PATH].len = ep - sp; if (ep == end) return 0; // ?query sp = ep + 1; ep = strchr(sp, '#'); if (ep == NULL) ep = end; stURL->fields[HV_URL_QUERY].off = sp - begin; stURL->fields[HV_URL_QUERY].len = ep - sp; if (ep == end) return 0; // #fragment sp = ep + 1; ep = end; stURL->fields[HV_URL_FRAGMENT].off = sp - begin; stURL->fields[HV_URL_FRAGMENT].len = ep - sp; return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hbase.h000066400000000000000000000104021520575453600256070ustar00rootroot00000000000000#ifndef HV_BASE_H_ #define HV_BASE_H_ #include "hexport.h" #include "hplatform.h" // for bool #include "hdef.h" // for printd BEGIN_EXTERN_C //--------------------alloc/free--------------------------- HV_EXPORT void* hv_malloc(size_t size); HV_EXPORT void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize); HV_EXPORT void* hv_calloc(size_t nmemb, size_t size); HV_EXPORT void* hv_zalloc(size_t size); HV_EXPORT void hv_free(void* ptr); #define HV_ALLOC(ptr, size)\ do {\ *(void**)&(ptr) = hv_zalloc(size);\ printd("alloc(%p, size=%llu)\tat [%s:%d:%s]\n", ptr, (unsigned long long)size, __FILE__, __LINE__, __FUNCTION__);\ } while(0) #define HV_ALLOC_SIZEOF(ptr) HV_ALLOC(ptr, sizeof(*(ptr))) #define HV_FREE(ptr)\ do {\ if (ptr) {\ hv_free(ptr);\ printd("free( %p )\tat [%s:%d:%s]\n", ptr, __FILE__, __LINE__, __FUNCTION__);\ ptr = NULL;\ }\ } while(0) #define STACK_OR_HEAP_ALLOC(ptr, size, stack_size)\ unsigned char _stackbuf_[stack_size] = { 0 };\ if ((size) > (stack_size)) {\ HV_ALLOC(ptr, size);\ } else {\ *(unsigned char**)&(ptr) = _stackbuf_;\ } #define STACK_OR_HEAP_FREE(ptr)\ if ((unsigned char*)(ptr) != _stackbuf_) {\ HV_FREE(ptr);\ } #define HV_DEFAULT_STACKBUF_SIZE 1024 #define HV_STACK_ALLOC(ptr, size) STACK_OR_HEAP_ALLOC(ptr, size, HV_DEFAULT_STACKBUF_SIZE) #define HV_STACK_FREE(ptr) STACK_OR_HEAP_FREE(ptr) HV_EXPORT long hv_alloc_cnt(); HV_EXPORT long hv_free_cnt(); HV_INLINE void hv_memcheck(void) { printf("Memcheck => alloc:%ld free:%ld\n", hv_alloc_cnt(), hv_free_cnt()); } #define HV_MEMCHECK atexit(hv_memcheck); //--------------------string------------------------------- HV_EXPORT char* hv_strupper(char* str); HV_EXPORT char* hv_strlower(char* str); HV_EXPORT char* hv_strreverse(char* str); HV_EXPORT bool hv_strstartswith(const char* str, const char* start); HV_EXPORT bool hv_strendswith(const char* str, const char* end); HV_EXPORT bool hv_strcontains(const char* str, const char* sub); HV_EXPORT bool hv_wildcard_match(const char* str, const char* pattern); // strncpy n = sizeof(dest_buf)-1 // hv_strncpy n = sizeof(dest_buf) HV_EXPORT char* hv_strncpy(char* dest, const char* src, size_t n); // strncat n = sizeof(dest_buf)-1-strlen(dest) // hv_strncpy n = sizeof(dest_buf) HV_EXPORT char* hv_strncat(char* dest, const char* src, size_t n); #if !HAVE_STRLCPY #define strlcpy hv_strncpy #endif #if !HAVE_STRLCAT #define strlcat hv_strncat #endif HV_EXPORT char* hv_strnchr(const char* s, char c, size_t n); HV_EXPORT char* hv_strnrchr(const char* s, char c, size_t n); #define hv_strrchr_dot(str) strrchr(str, '.') HV_EXPORT char* hv_strrchr_dir(const char* filepath); // basename HV_EXPORT const char* hv_basename(const char* filepath); HV_EXPORT const char* hv_suffixname(const char* filename); // mkdir -p HV_EXPORT int hv_mkdir_p(const char* dir); // rmdir -p HV_EXPORT int hv_rmdir_p(const char* dir); // path HV_EXPORT bool hv_exists(const char* path); HV_EXPORT bool hv_isdir(const char* path); HV_EXPORT bool hv_isfile(const char* path); HV_EXPORT bool hv_islink(const char* path); HV_EXPORT size_t hv_filesize(const char* filepath); HV_EXPORT char* get_executable_path(char* buf, int size); HV_EXPORT char* get_executable_dir(char* buf, int size); HV_EXPORT char* get_executable_file(char* buf, int size); HV_EXPORT char* get_run_dir(char* buf, int size); // random HV_EXPORT int hv_rand(int min, int max); HV_EXPORT char* hv_random_string(char *buf, int len); // 1 y on yes true enable => true HV_EXPORT bool hv_getboolean(const char* str); // 1T2G3M4K5B => ?B HV_EXPORT size_t hv_parse_size(const char* str); // 1w2d3h4m5s => ?s HV_EXPORT time_t hv_parse_time(const char* str); // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] typedef enum { HV_URL_SCHEME, HV_URL_USERNAME, HV_URL_PASSWORD, HV_URL_HOST, HV_URL_PORT, HV_URL_PATH, HV_URL_QUERY, HV_URL_FRAGMENT, HV_URL_FIELD_NUM, } hurl_field_e; typedef struct hurl_s { struct { unsigned short off; unsigned short len; } fields[HV_URL_FIELD_NUM]; unsigned short port; } hurl_t; HV_EXPORT int hv_parse_url(hurl_t* stURL, const char* strURL); END_EXTERN_C #endif // HV_BASE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hbuf.h000066400000000000000000000124621520575453600254610ustar00rootroot00000000000000#ifndef HV_BUF_H_ #define HV_BUF_H_ #include "hdef.h" // for MAX #include "hbase.h" // for HV_ALLOC, HV_FREE typedef struct hbuf_s { char* base; size_t len; #ifdef __cplusplus hbuf_s() { base = NULL; len = 0; } hbuf_s(void* data, size_t len) { this->base = (char*)data; this->len = len; } #endif } hbuf_t; typedef struct offset_buf_s { char* base; size_t len; size_t offset; #ifdef __cplusplus offset_buf_s() { base = NULL; len = 0; offset = 0; } offset_buf_s(void* data, size_t len) { this->base = (char*)data; this->len = len; offset = 0; } #endif } offset_buf_t; typedef struct fifo_buf_s { char* base; size_t len; size_t head; size_t tail; #ifdef __cplusplus fifo_buf_s() { base = NULL; len = 0; head = tail = 0; } fifo_buf_s(void* data, size_t len) { this->base = (char*)data; this->len = len; head = tail = 0; } #endif } fifo_buf_t; #ifdef __cplusplus class HBuf : public hbuf_t { public: HBuf() : hbuf_t() { cleanup_ = false; } HBuf(void* data, size_t len) : hbuf_t(data, len) { cleanup_ = false; } HBuf(size_t cap) { resize(cap); } virtual ~HBuf() { cleanup(); } void* data() { return base; } size_t size() { return len; } bool isNull() { return base == NULL || len == 0; } void cleanup() { if (cleanup_) { HV_FREE(base); len = 0; cleanup_ = false; } } void resize(size_t cap) { if (cap == len) return; if (base == NULL) { HV_ALLOC(base, cap); } else { base = (char*)hv_realloc(base, cap, len); } len = cap; cleanup_ = true; } void copy(void* data, size_t len) { resize(len); memcpy(base, data, len); } void copy(hbuf_t* buf) { copy(buf->base, buf->len); } private: bool cleanup_; }; // VL: Variable-Length class HVLBuf : public HBuf { public: HVLBuf() : HBuf() {_offset = _size = 0;} HVLBuf(void* data, size_t len) : HBuf(data, len) {_offset = 0; _size = len;} HVLBuf(size_t cap) : HBuf(cap) {_offset = _size = 0;} virtual ~HVLBuf() {} char* data() { return base + _offset; } size_t size() { return _size; } void push_front(void* ptr, size_t len) { if (len > this->len - _size) { size_t newsize = MAX(this->len, len)*2; resize(newsize); } if (_offset < len) { // move => end memmove(base+this->len-_size, data(), _size); _offset = this->len-_size; } memcpy(data()-len, ptr, len); _offset -= len; _size += len; } void push_back(void* ptr, size_t len) { if (len > this->len - _size) { size_t newsize = MAX(this->len, len)*2; resize(newsize); } else if (len > this->len - _offset - _size) { // move => start memmove(base, data(), _size); _offset = 0; } memcpy(data()+_size, ptr, len); _size += len; } void pop_front(void* ptr, size_t len) { if (len <= _size) { if (ptr) { memcpy(ptr, data(), len); } _offset += len; if (_offset >= this->len) _offset = 0; _size -= len; } } void pop_back(void* ptr, size_t len) { if (len <= _size) { if (ptr) { memcpy(ptr, data()+_size-len, len); } _size -= len; } } void clear() { _offset = _size = 0; } void prepend(void* ptr, size_t len) { push_front(ptr, len); } void append(void* ptr, size_t len) { push_back(ptr, len); } void insert(void* ptr, size_t len) { push_back(ptr, len); } void remove(size_t len) { pop_front(NULL, len); } private: size_t _offset; size_t _size; }; class HRingBuf : public HBuf { public: HRingBuf() : HBuf() {_head = _tail = _size = 0;} HRingBuf(size_t cap) : HBuf(cap) {_head = _tail = _size = 0;} virtual ~HRingBuf() {} char* alloc(size_t len) { char* ret = NULL; if (_head < _tail || _size == 0) { // [_tail, this->len) && [0, _head) if (this->len - _tail >= len) { ret = base + _tail; _tail += len; if (_tail == this->len) _tail = 0; } else if (_head >= len) { ret = base; _tail = len; } } else { // [_tail, _head) if (_head - _tail >= len) { ret = base + _tail; _tail += len; } } _size += ret ? len : 0; return ret; } void free(size_t len) { _size -= len; if (len <= this->len - _head) { _head += len; if (_head == this->len) _head = 0; } else { _head = len; } } void clear() {_head = _tail = _size = 0;} size_t size() {return _size;} private: size_t _head; size_t _tail; size_t _size; }; #endif #endif // HV_BUF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hdef.h000066400000000000000000000116041520575453600254400ustar00rootroot00000000000000#ifndef HV_DEF_H_ #define HV_DEF_H_ #include "hplatform.h" #ifndef ABS #define ABS(n) ((n) > 0 ? (n) : -(n)) #endif #ifndef NABS #define NABS(n) ((n) < 0 ? (n) : -(n)) #endif #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) #endif #ifndef BITSET #define BITSET(p, n) (*(p) |= (1u << (n))) #endif #ifndef BITCLR #define BITCLR(p, n) (*(p) &= ~(1u << (n))) #endif #ifndef BITGET #define BITGET(i, n) ((i) & (1u << (n))) #endif /* #ifndef CR #define CR '\r' #endif #ifndef LF #define LF '\n' #endif #ifndef CRLF #define CRLF "\r\n" #endif */ #define FLOAT_PRECISION 1e-6 #define FLOAT_EQUAL_ZERO(f) (ABS(f) < FLOAT_PRECISION) #ifndef INFINITE #define INFINITE (uint32_t)-1 #endif /* ASCII: [0, 0x20) control-charaters [0x20, 0x7F) printable-charaters 0x0A => LF 0x0D => CR 0x20 => SPACE 0x7F => DEL [0x09, 0x0D] => \t\n\v\f\r [0x30, 0x39] => 0~9 [0x41, 0x5A] => A~Z [0x61, 0x7A] => a~z */ #ifndef IS_ALPHA #define IS_ALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) #endif // NOTE: IS_NUM conflicts with mysql.h #ifndef IS_DIGIT #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9') #endif #ifndef IS_ALPHANUM #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_DIGIT(c)) #endif #ifndef IS_CNTRL #define IS_CNTRL(c) ((c) >= 0 && (c) < 0x20) #endif #ifndef IS_GRAPH #define IS_GRAPH(c) ((c) >= 0x20 && (c) < 0x7F) #endif #ifndef IS_HEX #define IS_HEX(c) (IS_DIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) #endif #ifndef IS_LOWER #define IS_LOWER(c) (((c) >= 'a' && (c) <= 'z')) #endif #ifndef IS_UPPER #define IS_UPPER(c) (((c) >= 'A' && (c) <= 'Z')) #endif #ifndef LOWER #define LOWER(c) ((c) | 0x20) #endif #ifndef UPPER #define UPPER(c) ((c) & ~0x20) #endif // LD, LU, LLD, LLU for explicit conversion of integer // #ifndef LD // #define LD(v) ((long)(v)) // #endif // #ifndef LU // #define LU(v) ((unsigned long)(v)) // #endif #ifndef LLD #define LLD(v) ((long long)(v)) #endif #ifndef LLU #define LLU(v) ((unsigned long long)(v)) #endif #ifndef _WIN32 // MAKEWORD, HIBYTE, LOBYTE #ifndef MAKEWORD #define MAKEWORD(h, l) ( (((WORD)h) << 8) | (l & 0xff) ) #endif #ifndef HIBYTE #define HIBYTE(w) ( (BYTE)(((WORD)w) >> 8) ) #endif #ifndef LOBYTE #define LOBYTE(w) ( (BYTE)(w & 0xff) ) #endif // MAKELONG, HIWORD, LOWORD #ifndef MAKELONG #define MAKELONG(h, l) ( ((int32_t)h) << 16 | (l & 0xffff) ) #endif #ifndef HIWORD #define HIWORD(n) ( (WORD)(((int32_t)n) >> 16) ) #endif #ifndef LOWORD #define LOWORD(n) ( (WORD)(n & 0xffff) ) #endif #endif // _WIN32 // MAKEINT64, HIINT, LOINT #ifndef MAKEINT64 #define MAKEINT64(h, l) ( ((int64_t)h) << 32 | (l & 0xffffffff) ) #endif #ifndef HIINT #define HIINT(n) ( (int32_t)(((int64_t)n) >> 32) ) #endif #ifndef LOINT #define LOINT(n) ( (int32_t)(n & 0xffffffff) ) #endif #ifndef MAKE_FOURCC #define MAKE_FOURCC(a, b, c, d) \ ( ((uint32)d) | ( ((uint32)c) << 8 ) | ( ((uint32)b) << 16 ) | ( ((uint32)a) << 24 ) ) #endif #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #ifndef LIMIT #define LIMIT(lower, v, upper) ((v) < (lower) ? (lower) : (v) > (upper) ? (upper) : (v)) #endif #ifndef MAX_PATH #define MAX_PATH 260 #endif #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void*)0) #endif #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef SAFE_ALLOC #define SAFE_ALLOC(p, size)\ do {\ void* ptr = malloc(size);\ if (!ptr) {\ fprintf(stderr, "malloc failed!\n");\ exit(-1);\ }\ memset(ptr, 0, size);\ *(void**)&(p) = ptr;\ } while(0) #endif #ifndef SAFE_FREE #define SAFE_FREE(p) do {if (p) {free(p); (p) = NULL;}} while(0) #endif #ifndef SAFE_DELETE #define SAFE_DELETE(p) do {if (p) {delete (p); (p) = NULL;}} while(0) #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) do {if (p) {delete[] (p); (p) = NULL;}} while(0) #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) do {if (p) {(p)->release(); (p) = NULL;}} while(0) #endif #ifndef SAFE_CLOSE #define SAFE_CLOSE(fd) do {if ((fd) >= 0) {close(fd); (fd) = -1;}} while(0) #endif #define STRINGIFY(x) STRINGIFY_HELPER(x) #define STRINGIFY_HELPER(x) #x #define STRINGCAT(x, y) STRINGCAT_HELPER(x, y) #define STRINGCAT_HELPER(x, y) x##y #ifndef offsetof #define offsetof(type, member) \ ((size_t)(&((type*)0)->member)) #endif #ifndef offsetofend #define offsetofend(type, member) \ (offsetof(type, member) + sizeof(((type*)0)->member)) #endif #ifndef container_of #define container_of(ptr, type, member) \ ((type*)((char*)(ptr) - offsetof(type, member))) #endif #ifdef PRINT_DEBUG #define printd(...) printf(__VA_ARGS__) #else #define printd(...) #endif #ifdef PRINT_ERROR #define printe(...) fprintf(stderr, __VA_ARGS__) #else #define printe(...) #endif #endif // HV_DEF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/heap.h000066400000000000000000000112501520575453600254440ustar00rootroot00000000000000#ifndef HV_HEAP_H_ #define HV_HEAP_H_ #include // for assert #include // for NULL struct heap_node { struct heap_node* parent; struct heap_node* left; struct heap_node* right; }; typedef int (*heap_compare_fn)(const struct heap_node* lhs, const struct heap_node* rhs); struct heap { struct heap_node* root; int nelts; // if compare is less_than, root is min of heap // if compare is larger_than, root is max of heap heap_compare_fn compare; }; static inline void heap_init(struct heap* heap, heap_compare_fn fn) { heap->root = NULL; heap->nelts = 0; heap->compare = fn; } // replace s with r static inline void heap_replace(struct heap* heap, struct heap_node* s, struct heap_node* r) { // s->parent->child, s->left->parent, s->right->parent if (s->parent == NULL) heap->root = r; else if (s->parent->left == s) s->parent->left = r; else if (s->parent->right == s) s->parent->right = r; if (s->left) s->left->parent = r; if (s->right) s->right->parent = r; if (r) { //*r = *s; r->parent = s->parent; r->left = s->left; r->right = s->right; } } static inline void heap_swap(struct heap* heap, struct heap_node* parent, struct heap_node* child) { assert(child->parent == parent && (parent->left == child || parent->right == child)); struct heap_node* pparent = parent->parent; struct heap_node* lchild = child->left; struct heap_node* rchild = child->right; struct heap_node* sibling = NULL; if (pparent == NULL) heap->root = child; else if (pparent->left == parent) pparent->left = child; else if (pparent->right == parent) pparent->right = child; if (lchild) lchild->parent = parent; if (rchild) rchild->parent = parent; child->parent = pparent; if (parent->left == child) { sibling = parent->right; child->left = parent; child->right = sibling; } else { sibling = parent->left; child->left = sibling; child->right = parent; } if (sibling) sibling->parent = child; parent->parent = child; parent->left = lchild; parent->right = rchild; } static inline void heap_insert(struct heap* heap, struct heap_node* node) { // get last => insert node => sift up // 0: left, 1: right int path = 0; int n,d; ++heap->nelts; // traverse from bottom to up, get path of last node for (d = 0, n = heap->nelts; n >= 2; ++d, n>>=1) { path = (path << 1) | (n & 1); } // get last->parent by path struct heap_node* parent = heap->root; while(d > 1) { parent = (path & 1) ? parent->right : parent->left; --d; path >>= 1; } // insert node node->parent = parent; if (parent == NULL) heap->root = node; else if (path & 1) parent->right = node; else parent->left = node; // sift up if (heap->compare) { while (node->parent && heap->compare(node, node->parent)) { heap_swap(heap, node->parent, node); } } } static inline void heap_remove(struct heap* heap, struct heap_node* node) { if (heap->nelts == 0) return; // get last => replace node with last => sift down and sift up // 0: left, 1: right int path = 0; int n,d; // traverse from bottom to up, get path of last node for (d = 0, n = heap->nelts; n >= 2; ++d, n>>=1) { path = (path << 1) | (n & 1); } --heap->nelts; // get last->parent by path struct heap_node* parent = heap->root; while(d > 1) { parent = (path & 1) ? parent->right : parent->left; --d; path >>= 1; } // replace node with last struct heap_node* last = NULL; if (parent == NULL) { return; } else if (path & 1) { last = parent->right; parent->right = NULL; } else { last = parent->left; parent->left = NULL; } if (last == NULL) { if (heap->root == node) { heap->root = NULL; } return; } heap_replace(heap, node, last); node->parent = node->left = node->right = NULL; if (!heap->compare) return; struct heap_node* v = last; struct heap_node* est = NULL; // sift down while (1) { est = v; if (v->left) est = heap->compare(est, v->left) ? est : v->left; if (v->right) est = heap->compare(est, v->right) ? est : v->right; if (est == v) break; heap_swap(heap, v, est); } // sift up while (v->parent && heap->compare(v, v->parent)) { heap_swap(heap, v->parent, v); } } static inline void heap_dequeue(struct heap* heap) { heap_remove(heap, heap->root); } #endif // HV_HEAP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hendian.h000066400000000000000000000162661520575453600261510ustar00rootroot00000000000000#ifndef HV_ENDIAN_H_ #define HV_ENDIAN_H_ #include "hplatform.h" #if defined(OS_MAC) #include #define htobe16(v) OSSwapHostToBigInt16(v) #define htobe32(v) OSSwapHostToBigInt32(v) #define htobe64(v) OSSwapHostToBigInt64(v) #define be16toh(v) OSSwapBigToHostInt16(v) #define be32toh(v) OSSwapBigToHostInt32(v) #define be64toh(v) OSSwapBigToHostInt64(v) #define htole16(v) OSSwapHostToLittleInt16(v) #define htole32(v) OSSwapHostToLittleInt32(v) #define htole64(v) OSSwapHostToLittleInt64(v) #define le16toh(v) OSSwapLittleToHostInt16(v) #define le32toh(v) OSSwapLittleToHostInt32(v) #define le64toh(v) OSSwapLittleToHostInt64(v) #elif defined(OS_WIN) #if _WIN32_WINNT < _WIN32_WINNT_WIN8 /* * Byte order conversion functions for 64-bit integers and 32 + 64 bit * floating-point numbers. IEEE big-endian format is used for the * network floating point format. */ #define _WS2_32_WINSOCK_SWAP_LONG(l) \ ( ( ((l) >> 24) & 0x000000FFL ) | \ ( ((l) >> 8) & 0x0000FF00L ) | \ ( ((l) << 8) & 0x00FF0000L ) | \ ( ((l) << 24) & 0xFF000000L ) ) #define _WS2_32_WINSOCK_SWAP_LONGLONG(l) \ ( ( ((l) >> 56) & 0x00000000000000FFLL ) | \ ( ((l) >> 40) & 0x000000000000FF00LL ) | \ ( ((l) >> 24) & 0x0000000000FF0000LL ) | \ ( ((l) >> 8) & 0x00000000FF000000LL ) | \ ( ((l) << 8) & 0x000000FF00000000LL ) | \ ( ((l) << 24) & 0x0000FF0000000000LL ) | \ ( ((l) << 40) & 0x00FF000000000000LL ) | \ ( ((l) << 56) & 0xFF00000000000000LL ) ) #ifndef htonll __inline unsigned __int64 htonll ( unsigned __int64 Value ) { const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); return Retval; } #endif /* htonll */ #ifndef ntohll __inline unsigned __int64 ntohll ( unsigned __int64 Value ) { const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); return Retval; } #endif /* ntohll */ #ifndef htonf __inline unsigned __int32 htonf ( float Value ) { unsigned __int32 Tempval; unsigned __int32 Retval; Tempval = *(unsigned __int32*)(&Value); Retval = _WS2_32_WINSOCK_SWAP_LONG (Tempval); return Retval; } #endif /* htonf */ #ifndef ntohf __inline float ntohf ( unsigned __int32 Value ) { const unsigned __int32 Tempval = _WS2_32_WINSOCK_SWAP_LONG (Value); float Retval; *((unsigned __int32*)&Retval) = Tempval; return Retval; } #endif /* ntohf */ #ifndef htond __inline unsigned __int64 htond ( double Value ) { unsigned __int64 Tempval; unsigned __int64 Retval; Tempval = *(unsigned __int64*)(&Value); Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Tempval); return Retval; } #endif /* htond */ #ifndef ntohd __inline double ntohd ( unsigned __int64 Value ) { const unsigned __int64 Tempval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); double Retval; *((unsigned __int64*)&Retval) = Tempval; return Retval; } #endif /* ntohd */ #endif #define htobe16(v) htons(v) #define htobe32(v) htonl(v) #define htobe64(v) htonll(v) #define be16toh(v) ntohs(v) #define be32toh(v) ntohl(v) #define be64toh(v) ntohll(v) #if (BYTE_ORDER == LITTLE_ENDIAN) #define htole16(v) (v) #define htole32(v) (v) #define htole64(v) (v) #define le16toh(v) (v) #define le32toh(v) (v) #define le64toh(v) (v) #elif (BYTE_ORDER == BIG_ENDIAN) #define htole16(v) __builtin_bswap16(v) #define htole32(v) __builtin_bswap32(v) #define htole64(v) __builtin_bswap64(v) #define le16toh(v) __builtin_bswap16(v) #define le32toh(v) __builtin_bswap32(v) #define le64toh(v) __builtin_bswap64(v) #endif #elif HAVE_ENDIAN_H #include #elif HAVE_SYS_ENDIAN_H #include #else #warning "Not found endian.h!" #endif #define PI8(p) *(int8_t*)(p) #define PI16(p) *(int16_t*)(p) #define PI32(p) *(int32_t*)(p) #define PI64(p) *(int64_t*)(p) #define PU8(p) *(uint8_t*)(p) #define PU16(p) *(uint16_t*)(p) #define PU32(p) *(uint32_t*)(p) #define PU64(p) *(uint64_t*)(p) #define PF32(p) *(float*)(p) #define PF64(p) *(double*)(p) #define GET_BE16(p) be16toh(PU16(p)) #define GET_BE32(p) be32toh(PU32(p)) #define GET_BE64(p) be64toh(PU64(p)) #define GET_LE16(p) le16toh(PU16(p)) #define GET_LE32(p) le32toh(PU32(p)) #define GET_LE64(p) le64toh(PU64(p)) #define PUT_BE16(p, v) PU16(p) = htobe16(v) #define PUT_BE32(p, v) PU32(p) = htobe32(v) #define PUT_BE64(p, v) PU64(p) = htobe64(v) #define PUT_LE16(p, v) PU16(p) = htole16(v) #define PUT_LE32(p, v) PU32(p) = htole32(v) #define PUT_LE64(p, v) PU64(p) = htole64(v) // NOTE: uint8_t* p = (uint8_t*)buf; #define POP_BE8(p, v) v = *p; ++p #define POP_BE16(p, v) v = be16toh(PU16(p)); p += 2 #define POP_BE32(p, v) v = be32toh(PU32(p)); p += 4 #define POP_BE64(p, v) v = be64toh(PU64(p)); p += 8 #define POP_LE8(p, v) v= *p; ++p #define POP_LE16(p, v) v = le16toh(PU16(p)); p += 2 #define POP_LE32(p, v) v = le32toh(PU32(p)); p += 4 #define POP_LE64(p, v) v = le64toh(PU64(p)); p += 8 #define PUSH_BE8(p, v) *p = v; ++p #define PUSH_BE16(p, v) PU16(p) = htobe16(v); p += 2 #define PUSH_BE32(p, v) PU32(p) = htobe32(v); p += 4 #define PUSH_BE64(p, v) PU64(p) = htobe64(v); p += 8 #define PUSH_LE8(p, v) *p = v; ++p #define PUSH_LE16(p, v) PU16(p) = htole16(v); p += 2 #define PUSH_LE32(p, v) PU32(p) = htole32(v); p += 4 #define PUSH_LE64(p, v) PU64(p) = htole64(v); p += 8 // NOTE: NET_ENDIAN = BIG_ENDIAN #define POP8(p, v) POP_BE8(p, v) #define POP16(p, v) POP_BE16(p, v) #define POP32(p, v) POP_BE32(p, v) #define POP64(p, v) POP_BE64(p, v) #define POP_N(p, v, n) memcpy(v, p, n); p += n #define PUSH8(p, v) PUSH_BE8(p, v) #define PUSH16(p, v) PUSH_BE16(p, v) #define PUSH32(p, v) PUSH_BE32(p, v) #define PUSH64(p, v) PUSH_BE64(p, v) #define PUSH_N(p, v, n) memcpy(p, v, n); p += n static inline int detect_endian() { union { char c; short s; } u; u.s = 0x1122; return u.c ==0x11 ? BIG_ENDIAN : LITTLE_ENDIAN; } #ifdef __cplusplus template uint8_t* serialize(uint8_t* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) { size_t size = sizeof(T); uint8_t* pDst = buf; uint8_t* pSrc = (uint8_t*)&value; if (host_endian == buf_endian) { memcpy(pDst, pSrc, size); } else { for (int i = 0; i < size; ++i) { pDst[i] = pSrc[size-i-1]; } } return buf+size; } template uint8_t* deserialize(uint8_t* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) { size_t size = sizeof(T); uint8_t* pSrc = buf; uint8_t* pDst = (uint8_t*)value; if (host_endian == buf_endian) { memcpy(pDst, pSrc, size); } else { for (int i = 0; i < size; ++i) { pDst[i] = pSrc[size-i-1]; } } return buf+size; } #endif // __cplusplus #endif // HV_ENDIAN_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/herr.c000066400000000000000000000005461520575453600254700ustar00rootroot00000000000000#include "herr.h" #include // for strerror // errcode => errmsg const char* hv_strerror(int err) { if (err > 0 && err <= SYS_NERR) { return strerror(err); } switch (err) { #define F(errcode, name, errmsg) \ case errcode: return errmsg; FOREACH_ERR(F) #undef F default: return "Undefined error"; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/herr.h000066400000000000000000000106641520575453600254770ustar00rootroot00000000000000#ifndef HV_ERR_H_ #define HV_ERR_H_ #include #include "hexport.h" #ifndef SYS_NERR #define SYS_NERR 133 #endif // F(errcode, name, errmsg) // [1, 133] #define FOREACH_ERR_SYS(F) // [1xx~5xx] #define FOREACH_ERR_STATUS(F) // [1xxx] #define FOREACH_ERR_COMMON(F) \ F(0, OK, "OK") \ F(1000, UNKNOWN, "Unknown error") \ \ F(1001, NULL_PARAM, "Null parameter") \ F(1002, NULL_POINTER, "Null pointer") \ F(1003, NULL_DATA, "Null data") \ F(1004, NULL_HANDLE, "Null handle") \ \ F(1011, INVALID_PARAM, "Invalid parameter")\ F(1012, INVALID_POINTER, "Invalid pointer") \ F(1013, INVALID_DATA, "Invalid data") \ F(1014, INVALID_HANDLE, "Invalid handle") \ F(1015, INVALID_JSON, "Invalid json") \ F(1016, INVALID_XML, "Invalid xml") \ F(1017, INVALID_FMT, "Invalid format") \ F(1018, INVALID_PROTOCOL, "Invalid protocol") \ F(1019, INVALID_PACKAGE, "Invalid package") \ \ F(1021, OUT_OF_RANGE, "Out of range") \ F(1022, OVER_LIMIT, "Over the limit") \ F(1023, MISMATCH, "Mismatch") \ F(1024, PARSE, "Parse failed") \ \ F(1030, OPEN_FILE, "Open file failed") \ F(1031, SAVE_FILE, "Save file failed") \ F(1032, READ_FILE, "Read file failed") \ F(1033, WRITE_FILE, "Write file failed")\ \ F(1040, SSL, "SSL/TLS error") \ F(1041, NEW_SSL_CTX, "New SSL_CTX failed") \ F(1042, NEW_SSL, "New SSL failed") \ F(1043, SSL_HANDSHAKE, "SSL handshake failed") \ \ F(1100, TASK_TIMEOUT, "Task timeout") \ F(1101, TASK_QUEUE_FULL, "Task queue full") \ F(1102, TASK_QUEUE_EMPTY, "Task queue empty") \ \ F(1400, REQUEST, "Bad request") \ F(1401, RESPONSE, "Bad response") \ // [-1xxx] #define FOREACH_ERR_FUNC(F) \ F(-1001, MALLOC, "malloc() error") \ F(-1002, REALLOC, "realloc() error") \ F(-1003, CALLOC, "calloc() error") \ F(-1004, FREE, "free() error") \ \ F(-1011, SOCKET, "socket() error") \ F(-1012, BIND, "bind() error") \ F(-1013, LISTEN, "listen() error") \ F(-1014, ACCEPT, "accept() error") \ F(-1015, CONNECT, "connect() error") \ F(-1016, RECV, "recv() error") \ F(-1017, SEND, "send() error") \ F(-1018, RECVFROM, "recvfrom() error") \ F(-1019, SENDTO, "sendto() error") \ F(-1020, SETSOCKOPT, "setsockopt() error") \ F(-1021, GETSOCKOPT, "getsockopt() error") \ // grpc [4xxx] #define FOREACH_ERR_GRPC(F) \ F(4000, GRPC_FIRST, "grpc no error") \ F(4001, GRPC_STATUS_CANCELLED, "grpc status: cancelled") \ F(4002, GRPC_STATUS_UNKNOWN, "grpc unknown error") \ F(4003, GRPC_STATUS_INVALID_ARGUMENT, "grpc status: invalid argument")\ F(4004, GRPC_STATUS_DEADLINE, "grpc status: deadline") \ F(4005, GRPC_STATUS_NOT_FOUND, "grpc status: not found") \ F(4006, GRPC_STATUS_ALREADY_EXISTS, "grpc status: already exists") \ F(4007, GRPC_STATUS_PERMISSION_DENIED, "grpc status: permission denied") \ F(4008, GRPC_STATUS_RESOURCE_EXHAUSTED, "grpc status: resource exhausted") \ F(4009, GRPC_STATUS_FAILED_PRECONDITION,"grpc status: failed precondition") \ F(4010, GRPC_STATUS_ABORTED, "grpc status: aborted") \ F(4011, GRPC_STATUS_OUT_OF_RANGE, "grpc status: out of range") \ F(4012, GRPC_STATUS_UNIMPLEMENTED, "grpc status: unimplemented") \ F(4013, GRPC_STATUS_INTERNAL, "grpc internal error") \ F(4014, GRPC_STATUS_UNAVAILABLE, "grpc service unavailable") \ F(4015, GRPC_STATUS_DATA_LOSS, "grpc status: data loss") \ #define FOREACH_ERR(F) \ FOREACH_ERR_COMMON(F) \ FOREACH_ERR_FUNC(F) \ FOREACH_ERR_GRPC(F) \ #undef ERR_OK // prevent conflict enum { #define F(errcode, name, errmsg) ERR_##name = errcode, FOREACH_ERR(F) #undef F }; #ifdef __cplusplus extern "C" { #endif // errcode => errmsg HV_EXPORT const char* hv_strerror(int err); #ifdef __cplusplus } // extern "C" #endif #endif // HV_ERR_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hlog.c000066400000000000000000000316731520575453600254660ustar00rootroot00000000000000#include "hlog.h" #include #include #include #include #include //#include "hmutex.h" #ifdef _WIN32 #pragma warning (disable: 4244) // conversion loss of data #include #define hmutex_t CRITICAL_SECTION #define hmutex_init InitializeCriticalSection #define hmutex_destroy DeleteCriticalSection #define hmutex_lock EnterCriticalSection #define hmutex_unlock LeaveCriticalSection #else #include // for gettimeofday #include #define hmutex_t pthread_mutex_t #define hmutex_init(mutex) pthread_mutex_init(mutex, NULL) #define hmutex_destroy pthread_mutex_destroy #define hmutex_lock pthread_mutex_lock #define hmutex_unlock pthread_mutex_unlock #endif //#include "htime.h" #define SECONDS_PER_HOUR 3600 #define SECONDS_PER_DAY 86400 // 24*3600 #define SECONDS_PER_WEEK 604800 // 7*24*3600; static int s_gmtoff = 28800; // 8*3600 struct logger_s { logger_handler handler; unsigned int bufsize; char* buf; int level; int enable_color; char format[64]; // for file logger char filepath[256]; unsigned long long max_filesize; int remain_days; int enable_fsync; FILE* fp_; char cur_logfile[256]; time_t last_logfile_ts; int can_write_cnt; hmutex_t mutex_; // thread-safe }; static void logger_init(logger_t* logger) { logger->handler = NULL; logger->bufsize = DEFAULT_LOG_MAX_BUFSIZE; logger->buf = (char*)malloc(logger->bufsize); logger->level = DEFAULT_LOG_LEVEL; logger->enable_color = 0; // NOTE: format is faster 6% than snprintf // logger->format[0] = '\0'; strncpy(logger->format, DEFAULT_LOG_FORMAT, sizeof(logger->format) - 1); logger->fp_ = NULL; logger->max_filesize = DEFAULT_LOG_MAX_FILESIZE; logger->remain_days = DEFAULT_LOG_REMAIN_DAYS; logger->enable_fsync = 1; logger_set_file(logger, DEFAULT_LOG_FILE); logger->last_logfile_ts = 0; logger->can_write_cnt = -1; hmutex_init(&logger->mutex_); } logger_t* logger_create() { // init gmtoff here time_t ts = time(NULL); struct tm* local_tm = localtime(&ts); int local_hour = local_tm->tm_hour; struct tm* gmt_tm = gmtime(&ts); int gmt_hour = gmt_tm->tm_hour; s_gmtoff = (local_hour - gmt_hour) * SECONDS_PER_HOUR; logger_t* logger = (logger_t*)malloc(sizeof(logger_t)); logger_init(logger); return logger; } void logger_destroy(logger_t* logger) { if (logger) { if (logger->buf) { free(logger->buf); logger->buf = NULL; } if (logger->fp_) { fclose(logger->fp_); logger->fp_ = NULL; } hmutex_destroy(&logger->mutex_); free(logger); } } void logger_set_handler(logger_t* logger, logger_handler fn) { logger->handler = fn; } void logger_set_level(logger_t* logger, int level) { logger->level = level; } void logger_set_level_by_str(logger_t* logger, const char* szLoglevel) { int loglevel = DEFAULT_LOG_LEVEL; if (strcmp(szLoglevel, "VERBOSE") == 0) { loglevel = LOG_LEVEL_VERBOSE; } else if (strcmp(szLoglevel, "DEBUG") == 0) { loglevel = LOG_LEVEL_DEBUG; } else if (strcmp(szLoglevel, "INFO") == 0) { loglevel = LOG_LEVEL_INFO; } else if (strcmp(szLoglevel, "WARN") == 0) { loglevel = LOG_LEVEL_WARN; } else if (strcmp(szLoglevel, "ERROR") == 0) { loglevel = LOG_LEVEL_ERROR; } else if (strcmp(szLoglevel, "FATAL") == 0) { loglevel = LOG_LEVEL_FATAL; } else if (strcmp(szLoglevel, "SILENT") == 0) { loglevel = LOG_LEVEL_SILENT; } else { loglevel = DEFAULT_LOG_LEVEL; } logger->level = loglevel; } void logger_set_format(logger_t* logger, const char* format) { if (format) { strncpy(logger->format, format, sizeof(logger->format) - 1); } else { logger->format[0] = '\0'; } } void logger_set_remain_days(logger_t* logger, int days) { logger->remain_days = days; } void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize) { logger->bufsize = bufsize; logger->buf = (char*)realloc(logger->buf, bufsize); } void logger_enable_color(logger_t* logger, int on) { logger->enable_color = on; } void logger_set_file(logger_t* logger, const char* filepath) { strncpy(logger->filepath, filepath, sizeof(logger->filepath) - 1); // remove suffix .log char* suffix = strrchr(logger->filepath, '.'); if (suffix && strcmp(suffix, ".log") == 0) { *suffix = '\0'; } } void logger_set_max_filesize(logger_t* logger, unsigned long long filesize) { logger->max_filesize = filesize; } void logger_set_max_filesize_by_str(logger_t* logger, const char* str) { int num = atoi(str); if (num <= 0) return; // 16 16M 16MB const char* e = str; while (*e != '\0') ++e; --e; char unit; if (*e >= '0' && *e <= '9') unit = 'M'; else if (*e == 'B') unit = *(e-1); else unit = *e; unsigned long long filesize = num; switch (unit) { case 'K': filesize <<= 10; break; case 'M': filesize <<= 20; break; case 'G': filesize <<= 30; break; default: filesize <<= 20; break; } logger->max_filesize = filesize; } void logger_enable_fsync(logger_t* logger, int on) { logger->enable_fsync = on; } void logger_fsync(logger_t* logger) { hmutex_lock(&logger->mutex_); if (logger->fp_) { fflush(logger->fp_); } hmutex_unlock(&logger->mutex_); } const char* logger_get_cur_file(logger_t* logger) { return logger->cur_logfile; } static void logfile_name(const char* filepath, time_t ts, char* buf, int len) { struct tm* tm = localtime(&ts); snprintf(buf, len, "%s.%04d%02d%02d.log", filepath, tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday); } static FILE* logfile_shift(logger_t* logger) { time_t ts_now = time(NULL); int interval_days = logger->last_logfile_ts == 0 ? 0 : (ts_now+s_gmtoff) / SECONDS_PER_DAY - (logger->last_logfile_ts+s_gmtoff) / SECONDS_PER_DAY; if (logger->fp_ == NULL || interval_days > 0) { // close old logfile if (logger->fp_) { fclose(logger->fp_); logger->fp_ = NULL; } else { interval_days = 30; } if (logger->remain_days >= 0) { char rm_logfile[256] = {0}; if (interval_days >= logger->remain_days) { // remove [today-interval_days, today-remain_days] logfile for (int i = interval_days; i >= logger->remain_days; --i) { time_t ts_rm = ts_now - i * SECONDS_PER_DAY; logfile_name(logger->filepath, ts_rm, rm_logfile, sizeof(rm_logfile)); remove(rm_logfile); } } else { // remove today-remain_days logfile time_t ts_rm = ts_now - logger->remain_days * SECONDS_PER_DAY; logfile_name(logger->filepath, ts_rm, rm_logfile, sizeof(rm_logfile)); remove(rm_logfile); } } } // open today logfile if (logger->fp_ == NULL) { logfile_name(logger->filepath, ts_now, logger->cur_logfile, sizeof(logger->cur_logfile)); logger->fp_ = fopen(logger->cur_logfile, "a"); logger->last_logfile_ts = ts_now; } // NOTE: estimate can_write_cnt to avoid frequent fseek/ftell if (logger->fp_ && --logger->can_write_cnt < 0) { fseek(logger->fp_, 0, SEEK_END); long filesize = ftell(logger->fp_); if (filesize > logger->max_filesize) { fclose(logger->fp_); logger->fp_ = NULL; // ftruncate logger->fp_ = fopen(logger->cur_logfile, "w"); // reopen with O_APPEND for multi-processes if (logger->fp_) { fclose(logger->fp_); logger->fp_ = fopen(logger->cur_logfile, "a"); } } else { logger->can_write_cnt = (logger->max_filesize - filesize) / logger->bufsize; } } return logger->fp_; } static void logfile_write(logger_t* logger, const char* buf, int len) { FILE* fp = logfile_shift(logger); if (fp) { fwrite(buf, 1, len, fp); if (logger->enable_fsync) { fflush(fp); } } } static int i2a(int i, char* buf, int len) { for (int l = len - 1; l >= 0; --l) { if (i == 0) { buf[l] = '0'; } else { buf[l] = i % 10 + '0'; i /= 10; } } return len; } int logger_print(logger_t* logger, int level, const char* fmt, ...) { if (level < logger->level) return -10; int year,month,day,hour,min,sec,us; #ifdef _WIN32 SYSTEMTIME tm; GetLocalTime(&tm); year = tm.wYear; month = tm.wMonth; day = tm.wDay; hour = tm.wHour; min = tm.wMinute; sec = tm.wSecond; us = tm.wMilliseconds * 1000; #else struct timeval tv; struct tm* tm = NULL; gettimeofday(&tv, NULL); time_t tt = tv.tv_sec; tm = localtime(&tt); year = tm->tm_year + 1900; month = tm->tm_mon + 1; day = tm->tm_mday; hour = tm->tm_hour; min = tm->tm_min; sec = tm->tm_sec; us = tv.tv_usec; #endif const char* pcolor = ""; const char* plevel = ""; #define XXX(id, str, clr) \ case id: plevel = str; pcolor = clr; break; switch (level) { LOG_LEVEL_MAP(XXX) } #undef XXX // lock logger->buf hmutex_lock(&logger->mutex_); char* buf = logger->buf; int bufsize = logger->bufsize; int len = 0; if (logger->enable_color) { len = snprintf(buf, bufsize, "%s", pcolor); } const char* p = logger->format; if (*p) { while (*p) { if (*p == '%') { switch(*++p) { case 'y': len += i2a(year, buf + len, 4); break; case 'm': len += i2a(month, buf + len, 2); break; case 'd': len += i2a(day, buf + len, 2); break; case 'H': len += i2a(hour, buf + len, 2); break; case 'M': len += i2a(min, buf + len, 2); break; case 'S': len += i2a(sec, buf + len, 2); break; case 'z': len += i2a(us/1000, buf + len, 3); break; case 'Z': len += i2a(us, buf + len, 6); break; case 'l': buf[len++] = *plevel; break; case 'L': for (int i = 0; i < 5; ++i) { buf[len++] = plevel[i]; } break; case 's': { va_list ap; va_start(ap, fmt); len += vsnprintf(buf + len, bufsize - len, fmt, ap); va_end(ap); } break; case '%': buf[len++] = '%'; break; default: break; } } else { buf[len++] = *p; } ++p; } } else { len += snprintf(buf + len, bufsize - len, "%04d-%02d-%02d %02d:%02d:%02d.%03d %s ", year, month, day, hour, min, sec, us/1000, plevel); va_list ap; va_start(ap, fmt); len += vsnprintf(buf + len, bufsize - len, fmt, ap); va_end(ap); } if (logger->enable_color) { len += snprintf(buf + len, bufsize - len, "%s", CLR_CLR); } if(lenhandler) { logger->handler(level, buf, len); } else { logfile_write(logger, buf, len); } hmutex_unlock(&logger->mutex_); return len; } static logger_t* s_logger = NULL; logger_t* hv_default_logger() { if (s_logger == NULL) { s_logger = logger_create(); atexit(hv_destroy_default_logger); } return s_logger; } void hv_destroy_default_logger(void) { if (s_logger) { logger_fsync(s_logger); logger_destroy(s_logger); s_logger = NULL; } } void stdout_logger(int loglevel, const char* buf, int len) { fprintf(stdout, "%.*s", len, buf); } void stderr_logger(int loglevel, const char* buf, int len) { fprintf(stderr, "%.*s", len, buf); } void file_logger(int loglevel, const char* buf, int len) { logfile_write(hv_default_logger(), buf, len); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hlog.h000066400000000000000000000155151520575453600254700ustar00rootroot00000000000000#ifndef HV_LOG_H_ #define HV_LOG_H_ /* * hlog is thread-safe */ #include #ifdef _WIN32 #define DIR_SEPARATOR '\\' #define DIR_SEPARATOR_STR "\\" #else #define DIR_SEPARATOR '/' #define DIR_SEPARATOR_STR "/" #endif #ifndef __FILENAME__ // #define __FILENAME__ (strrchr(__FILE__, DIR_SEPARATOR) ? strrchr(__FILE__, DIR_SEPARATOR) + 1 : __FILE__) #define __FILENAME__ (strrchr(DIR_SEPARATOR_STR __FILE__, DIR_SEPARATOR) + 1) #endif #include "hexport.h" #ifdef __cplusplus extern "C" { #endif #define CLR_CLR "\033[0m" /* 恢复颜色 */ #define CLR_BLACK "\033[30m" /* 黑色字 */ #define CLR_RED "\033[31m" /* 红色字 */ #define CLR_GREEN "\033[32m" /* 绿色字 */ #define CLR_YELLOW "\033[33m" /* 黄色字 */ #define CLR_BLUE "\033[34m" /* 蓝色字 */ #define CLR_PURPLE "\033[35m" /* 紫色字 */ #define CLR_SKYBLUE "\033[36m" /* 天蓝字 */ #define CLR_WHITE "\033[37m" /* 白色字 */ #define CLR_BLK_WHT "\033[40;37m" /* 黑底白字 */ #define CLR_RED_WHT "\033[41;37m" /* 红底白字 */ #define CLR_GREEN_WHT "\033[42;37m" /* 绿底白字 */ #define CLR_YELLOW_WHT "\033[43;37m" /* 黄底白字 */ #define CLR_BLUE_WHT "\033[44;37m" /* 蓝底白字 */ #define CLR_PURPLE_WHT "\033[45;37m" /* 紫底白字 */ #define CLR_SKYBLUE_WHT "\033[46;37m" /* 天蓝底白字 */ #define CLR_WHT_BLK "\033[47;30m" /* 白底黑字 */ // XXX(id, str, clr) #define LOG_LEVEL_MAP(XXX) \ XXX(LOG_LEVEL_DEBUG, "DEBUG", CLR_WHITE) \ XXX(LOG_LEVEL_INFO, "INFO ", CLR_GREEN) \ XXX(LOG_LEVEL_WARN, "WARN ", CLR_YELLOW) \ XXX(LOG_LEVEL_ERROR, "ERROR", CLR_RED) \ XXX(LOG_LEVEL_FATAL, "FATAL", CLR_RED_WHT) typedef enum { LOG_LEVEL_VERBOSE = 0, #define XXX(id, str, clr) id, LOG_LEVEL_MAP(XXX) #undef XXX LOG_LEVEL_SILENT } log_level_e; #define DEFAULT_LOG_FILE "libhv" #define DEFAULT_LOG_LEVEL LOG_LEVEL_INFO #define DEFAULT_LOG_FORMAT "%y-%m-%d %H:%M:%S.%z %L %s" #define DEFAULT_LOG_REMAIN_DAYS 1 #define DEFAULT_LOG_MAX_BUFSIZE (1<<14) // 16k #define DEFAULT_LOG_MAX_FILESIZE (1<<24) // 16M // logger: default file_logger // network_logger() see event/nlog.h typedef void (*logger_handler)(int loglevel, const char* buf, int len); HV_EXPORT void stdout_logger(int loglevel, const char* buf, int len); HV_EXPORT void stderr_logger(int loglevel, const char* buf, int len); HV_EXPORT void file_logger(int loglevel, const char* buf, int len); // network_logger implement see event/nlog.h // HV_EXPORT void network_logger(int loglevel, const char* buf, int len); typedef struct logger_s logger_t; HV_EXPORT logger_t* logger_create(); HV_EXPORT void logger_destroy(logger_t* logger); HV_EXPORT void logger_set_handler(logger_t* logger, logger_handler fn); HV_EXPORT void logger_set_level(logger_t* logger, int level); // level = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] HV_EXPORT void logger_set_level_by_str(logger_t* logger, const char* level); /* * format = "%y-%m-%d %H:%M:%S.%z %L %s" * message = "2020-01-02 03:04:05.067 DEBUG message" * %y year * %m month * %d day * %H hour * %M min * %S sec * %z ms * %Z us * %l First character of level * %L All characters of level * %s message * %% % */ HV_EXPORT void logger_set_format(logger_t* logger, const char* format); HV_EXPORT void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize); HV_EXPORT void logger_enable_color(logger_t* logger, int on); HV_EXPORT int logger_print(logger_t* logger, int level, const char* fmt, ...); // below for file logger HV_EXPORT void logger_set_file(logger_t* logger, const char* filepath); HV_EXPORT void logger_set_max_filesize(logger_t* logger, unsigned long long filesize); // 16, 16M, 16MB HV_EXPORT void logger_set_max_filesize_by_str(logger_t* logger, const char* filesize); HV_EXPORT void logger_set_remain_days(logger_t* logger, int days); HV_EXPORT void logger_enable_fsync(logger_t* logger, int on); HV_EXPORT void logger_fsync(logger_t* logger); HV_EXPORT const char* logger_get_cur_file(logger_t* logger); // hlog: default logger instance HV_EXPORT logger_t* hv_default_logger(); HV_EXPORT void hv_destroy_default_logger(void); // macro hlog* #define hlog hv_default_logger() #define hlog_destory() hv_destroy_default_logger() #define hlog_disable() logger_set_level(hlog, LOG_LEVEL_SILENT) #define hlog_set_file(filepath) logger_set_file(hlog, filepath) #define hlog_set_level(level) logger_set_level(hlog, level) #define hlog_set_level_by_str(level) logger_set_level_by_str(hlog, level) #define hlog_set_handler(fn) logger_set_handler(hlog, fn) #define hlog_set_format(format) logger_set_format(hlog, format) #define hlog_set_max_filesize(filesize) logger_set_max_filesize(hlog, filesize) #define hlog_set_max_filesize_by_str(filesize) logger_set_max_filesize_by_str(hlog, filesize) #define hlog_set_remain_days(days) logger_set_remain_days(hlog, days) #define hlog_enable_fsync() logger_enable_fsync(hlog, 1) #define hlog_disable_fsync() logger_enable_fsync(hlog, 0) #define hlog_fsync() logger_fsync(hlog) #define hlog_get_cur_file() logger_get_cur_file(hlog) #define hlogd(fmt, ...) logger_print(hlog, LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogi(fmt, ...) logger_print(hlog, LOG_LEVEL_INFO, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogw(fmt, ...) logger_print(hlog, LOG_LEVEL_WARN, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hloge(fmt, ...) logger_print(hlog, LOG_LEVEL_ERROR, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogf(fmt, ...) logger_print(hlog, LOG_LEVEL_FATAL, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) // below for android #if defined(ANDROID) || defined(__ANDROID__) #include #define LOG_TAG "JNI" #undef hlogd #undef hlogi #undef hlogw #undef hloge #undef hlogf #define hlogd(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define hlogi(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define hlogw(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define hloge(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define hlogf(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__) #endif //// macro alias //#if !defined(LOGD) && !defined(LOGI) && !defined(LOGW) && !defined(LOGE) && !defined(LOGF) //#define LOGD hlogd //#define LOGI hlogi //#define LOGW hlogw //#define LOGE hloge //#define LOGF hlogf //#endif #ifdef __cplusplus } // extern "C" #endif #endif // HV_LOG_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hmain.c000066400000000000000000000552471520575453600256340ustar00rootroot00000000000000#include "hmain.h" #include "hbase.h" #include "hlog.h" #include "herr.h" #include "htime.h" #include "hthread.h" #ifdef OS_DARWIN #include #define environ (*_NSGetEnviron()) #endif main_ctx_t g_main_ctx; static void init_arg_kv(int maxsize) { g_main_ctx.arg_kv_size = 0; SAFE_ALLOC(g_main_ctx.arg_kv, sizeof(char*) * maxsize); } static void save_arg_kv(const char* key, int key_len, const char* val, int val_len) { if (key_len <= 0) key_len = strlen(key); if (val_len <= 0) val_len = strlen(val); char* arg = NULL; SAFE_ALLOC(arg, key_len + val_len + 2); memcpy(arg, key, key_len); arg[key_len] = '='; memcpy(arg + key_len + 1, val, val_len); // printf("save_arg_kv: %s\n", arg); g_main_ctx.arg_kv[g_main_ctx.arg_kv_size++] = arg; } static void init_arg_list(int maxsize) { g_main_ctx.arg_list_size = 0; SAFE_ALLOC(g_main_ctx.arg_list, sizeof(char*) * maxsize); } static void save_arg_list(const char* arg) { // printf("save_arg_list: %s\n", arg); g_main_ctx.arg_list[g_main_ctx.arg_list_size++] = strdup(arg); } static const char* get_val(char** kvs, const char* key) { if (kvs == NULL) return NULL; int key_len = strlen(key); char* kv = NULL; int kv_len = 0; for (int i = 0; kvs[i]; ++i) { kv = kvs[i]; kv_len = strlen(kv); if (kv_len <= key_len) continue; // key=val if (memcmp(kv, key, key_len) == 0 && kv[key_len] == '=') { return kv + key_len + 1; } } return NULL; } const char* get_arg(const char* key) { return get_val(g_main_ctx.arg_kv, key); } const char* get_env(const char* key) { return get_val(g_main_ctx.save_envp, key); } int main_ctx_init(int argc, char** argv) { if (argc == 0 || argv == NULL) { argc = 1; SAFE_ALLOC(argv, 2 * sizeof(char*)); SAFE_ALLOC(argv[0], MAX_PATH); get_executable_path(argv[0], MAX_PATH); } get_run_dir(g_main_ctx.run_dir, sizeof(g_main_ctx.run_dir)); //printf("run_dir=%s\n", g_main_ctx.run_dir); strncpy(g_main_ctx.program_name, hv_basename(argv[0]), sizeof(g_main_ctx.program_name)); #ifdef OS_WIN if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) { *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0'; } #endif //printf("program_name=%s\n", g_main_ctx.program_name); char logdir[MAX_PATH] = {0}; snprintf(logdir, sizeof(logdir), "%s/logs", g_main_ctx.run_dir); hv_mkdir(logdir); snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_dir, g_main_ctx.program_name); snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_dir, g_main_ctx.program_name); snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.logfile), "%s/logs/%s.log", g_main_ctx.run_dir, g_main_ctx.program_name); hlog_set_file(g_main_ctx.logfile); g_main_ctx.pid = getpid(); g_main_ctx.oldpid = getpid_from_pidfile(); #ifdef OS_UNIX if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) { g_main_ctx.oldpid = -1; } #else HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, g_main_ctx.oldpid); if (hproc == NULL) { g_main_ctx.oldpid = -1; } else { CloseHandle(hproc); } #endif // save arg int i = 0; g_main_ctx.os_argv = argv; g_main_ctx.argc = 0; g_main_ctx.arg_len = 0; for (i = 0; argv[i]; ++i) { g_main_ctx.arg_len += strlen(argv[i]) + 1; } g_main_ctx.argc = i; char* argp = NULL; SAFE_ALLOC(argp, g_main_ctx.arg_len); SAFE_ALLOC(g_main_ctx.save_argv, (g_main_ctx.argc + 1) * sizeof(char*)); char* cmdline = NULL; SAFE_ALLOC(cmdline, g_main_ctx.arg_len); g_main_ctx.cmdline = cmdline; for (i = 0; argv[i]; ++i) { strcpy(argp, argv[i]); g_main_ctx.save_argv[i] = argp; argp += strlen(argv[i]) + 1; strcpy(cmdline, argv[i]); cmdline += strlen(argv[i]); *cmdline = ' '; ++cmdline; } g_main_ctx.save_argv[g_main_ctx.argc] = NULL; g_main_ctx.cmdline[g_main_ctx.arg_len-1] = '\0'; #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_DARWIN) // save env g_main_ctx.os_envp = environ; g_main_ctx.envc = 0; g_main_ctx.env_len = 0; for (i = 0; environ[i]; ++i) { g_main_ctx.env_len += strlen(environ[i]) + 1; } g_main_ctx.envc = i; char* envp = NULL; SAFE_ALLOC(envp, g_main_ctx.env_len); SAFE_ALLOC(g_main_ctx.save_envp, (g_main_ctx.envc + 1) * sizeof(char*)); for (i = 0; environ[i]; ++i) { g_main_ctx.save_envp[i] = envp; strcpy(g_main_ctx.save_envp[i], environ[i]); envp += strlen(environ[i]) + 1; } g_main_ctx.save_envp[g_main_ctx.envc] = NULL; #endif // signals g_main_ctx.reload_fn = NULL; g_main_ctx.reload_userdata = NULL; // master workers g_main_ctx.worker_processes = 0; g_main_ctx.worker_threads = 0; g_main_ctx.worker_fn = 0; g_main_ctx.worker_userdata = 0; g_main_ctx.proc_ctxs = NULL; atexit(main_ctx_free); return 0; } void main_ctx_free(void) { if (g_main_ctx.save_argv) { SAFE_FREE(g_main_ctx.save_argv[0]); SAFE_FREE(g_main_ctx.save_argv); } SAFE_FREE(g_main_ctx.cmdline); if (g_main_ctx.save_envp) { SAFE_FREE(g_main_ctx.save_envp[0]); SAFE_FREE(g_main_ctx.save_envp); } if (g_main_ctx.arg_kv) { for (int i = 0; i < g_main_ctx.arg_kv_size; ++i) { SAFE_FREE(g_main_ctx.arg_kv[i]); } SAFE_FREE(g_main_ctx.arg_kv); } if (g_main_ctx.arg_list) { for (int i = 0; i < g_main_ctx.arg_list_size; ++i) { SAFE_FREE(g_main_ctx.arg_list[i]); } SAFE_FREE(g_main_ctx.arg_list); } } #define UNDEFINED_OPTION -1 static int get_arg_type(int short_opt, const char* options) { if (options == NULL) return UNDEFINED_OPTION; const char* p = options; while (*p && *p != short_opt) ++p; if (*p == '\0') return UNDEFINED_OPTION; if (*(p+1) == ':') return REQUIRED_ARGUMENT; return NO_ARGUMENT; } int parse_opt(int argc, char** argv, const char* options) { if (argc < 1) return 0; init_arg_kv(strlen(options) + 1); init_arg_list(argc); for (int i = 1; argv[i]; ++i) { char* p = argv[i]; if (*p != '-') { save_arg_list(argv[i]); continue; } while (*++p) { int arg_type = get_arg_type(*p, options); if (arg_type == UNDEFINED_OPTION) { printf("Invalid option '%c'\n", *p); return -20; } else if (arg_type == NO_ARGUMENT) { save_arg_kv(p, 1, OPTION_ENABLE, 0); continue; } else if (arg_type == REQUIRED_ARGUMENT) { if (*(p+1) != '\0') { save_arg_kv(p, 1, p+1, 0); break; } else if (argv[i+1] != NULL) { save_arg_kv(p, 1, argv[++i], 0); break; } else { printf("Option '%c' requires param\n", *p); return -30; } } } } return 0; } static const option_t* get_option(const char* opt, const option_t* long_options, int size) { if (opt == NULL || long_options == NULL) return NULL; int len = strlen(opt); if (len == 0) return NULL; if (len == 1) { for (int i = 0; i < size; ++i) { if (long_options[i].short_opt == *opt) { return &long_options[i]; } } } else { for (int i = 0; i < size; ++i) { if (strcmp(long_options[i].long_opt, opt) == 0) { return &long_options[i]; } } } return NULL; } #define MAX_OPTION 32 // opt type #define NOPREFIX_OPTION 0 #define SHORT_OPTION -1 #define LONG_OPTION -2 int parse_opt_long(int argc, char** argv, const option_t* long_options, int size) { if (argc < 1) return 0; init_arg_kv(size + 1); init_arg_list(argc); char opt[MAX_OPTION+1] = {0}; for (int i = 1; argv[i]; ++i) { char* arg = argv[i]; int opt_type = NOPREFIX_OPTION; // prefix if (*arg == OPTION_PREFIX) { ++arg; opt_type = SHORT_OPTION; if (*arg == OPTION_PREFIX) { ++arg; opt_type = LONG_OPTION; } } int arg_len = strlen(arg); // delim char* delim = strchr(arg, OPTION_DELIM); if (delim) { if (delim == arg || delim == arg+arg_len-1 || delim-arg > MAX_OPTION) { printf("Invalid option '%s'\n", argv[i]); return -10; } memcpy(opt, arg, delim-arg); opt[delim-arg] = '\0'; } else { if (opt_type == SHORT_OPTION) { *opt = *arg; opt[1] = '\0'; } else { strncpy(opt, arg, MAX_OPTION); } } // get_option const option_t* pOption = get_option(opt, long_options, size); if (pOption == NULL) { if (delim == NULL && opt_type == NOPREFIX_OPTION) { save_arg_list(arg); continue; } else { printf("Invalid option: '%s'\n", argv[i]); return -10; } } const char* value = NULL; if (pOption->arg_type == NO_ARGUMENT) { // -h value = OPTION_ENABLE; } else { if (delim) { // --port=80 value = delim+1; } else { if (opt_type == SHORT_OPTION && *(arg+1) != '\0') { // p80 value = arg+1; } else if (argv[i+1] != NULL) { // --port 80 value = argv[++i]; } else if (pOption->arg_type == REQUIRED_ARGUMENT) { printf("Option '%s' requires parament\n", opt); return -20; } else { // arg_type == OPTIONAL_ARGUMENT value = OPTION_ENABLE; } } } // preferred to use short_opt as key if (pOption->short_opt > 0) { save_arg_kv(&pOption->short_opt, 1, value, 0); } else if (pOption->long_opt) { save_arg_kv(pOption->long_opt, 0, value, 0); } } return 0; } int dump_opt_long(const option_t* long_options, int opt_size, char* out_str, int out_size) { /* * Usage: program_name [short_options] * Options: * -%c|--%s description * -%c|--%s description * -%c|--%s [value] description */ int align = 0, max_align = 0; char short_options[256] = {0}; char* p = short_options; for (int i = 0; i < opt_size; ++i) { if (long_options[i].short_opt > 0) { *p++ = long_options[i].short_opt; } if (long_options[i].arg_type == NO_ARGUMENT) { // " -%c|--%s " align = 9 + strlen(long_options[i].long_opt); } else { // " -%c|--%s " align = 17 + strlen(long_options[i].long_opt); if (long_options[i].short_opt > 0) { *p++ = ':'; } } if (align > max_align) max_align = align; } int offset = 0; if (*g_main_ctx.program_name) { offset = snprintf(out_str, out_size, "Usage: %s [%s]\n", g_main_ctx.program_name, short_options); } offset += snprintf(out_str + offset, out_size - offset, "Options:\n"); char short_opt_chars[4] = {0}; for (int i = 0; i < opt_size; ++i) { if (long_options[i].short_opt > 0) { // -%c| short_opt_chars[0] = '-'; short_opt_chars[1] = long_options[i].short_opt; short_opt_chars[2] = '|'; } else { short_opt_chars[0] = ' '; short_opt_chars[1] = ' '; short_opt_chars[2] = ' '; } if (long_options[i].arg_type == NO_ARGUMENT) { // " -%c|--%s " align = 9 + strlen(long_options[i].long_opt); } else { // " -%c|--%s " align = 17 + strlen(long_options[i].long_opt); } offset += snprintf(out_str + offset, out_size - offset, " %s--%s%s %*s%s\n", short_opt_chars, long_options[i].long_opt, long_options[i].arg_type == REQUIRED_ARGUMENT ? " " : long_options[i].arg_type == OPTIONAL_ARGUMENT ? " [value]" : "", max_align - align, "", long_options[i].description ? long_options[i].description : ""); } return offset; } #if defined(OS_UNIX) && !HAVE_SETPROCTITLE /* * memory layout * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0 */ void setproctitle(const char* fmt, ...) { char buf[256] = {0}; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf) - 1, fmt, ap); va_end(ap); int len = g_main_ctx.arg_len + g_main_ctx.env_len; if (g_main_ctx.os_argv && len) { strncpy(g_main_ctx.os_argv[0], buf, len-1); } } #endif int create_pidfile() { FILE* fp = fopen(g_main_ctx.pidfile, "w"); if (fp == NULL) { hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno); return -1; } g_main_ctx.pid = hv_getpid(); fprintf(fp, "%d\n", (int)g_main_ctx.pid); fclose(fp); hlogi("create_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid); atexit(delete_pidfile); return 0; } void delete_pidfile(void) { hlogi("delete_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid); remove(g_main_ctx.pidfile); } pid_t getpid_from_pidfile() { FILE* fp = fopen(g_main_ctx.pidfile, "r"); if (fp == NULL) { // hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno); return -1; } int pid = -1; fscanf(fp, "%d", &pid); fclose(fp); return pid; } #ifdef OS_UNIX // unix use signal #include void signal_handler(int signo) { hlogi("pid=%d recv signo=%d", getpid(), signo); switch (signo) { case SIGINT: case SIGNAL_TERMINATE: hlogi("killall processes"); signal(SIGCHLD, SIG_IGN); // master send SIGKILL => workers for (int i = 0; i < g_main_ctx.worker_processes; ++i) { if (g_main_ctx.proc_ctxs[i].pid <= 0) break; kill(g_main_ctx.proc_ctxs[i].pid, SIGKILL); g_main_ctx.proc_ctxs[i].pid = -1; } exit(0); break; case SIGCHLD: { pid_t pid = 0; int status = 0; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { hlogw("proc stop/waiting, pid=%d status=%d", pid, status); for (int i = 0; i < g_main_ctx.worker_processes; ++i) { proc_ctx_t* ctx = g_main_ctx.proc_ctxs + i; if (ctx->pid == pid) { ctx->pid = -1; // NOTE: avoid frequent crash and restart time_t run_time = time(NULL) - ctx->start_time; if (ctx->spawn_cnt < 3 || run_time > 3600) { hproc_spawn(ctx); } else { hloge("proc crash, pid=%d spawn_cnt=%d run_time=%us", pid, ctx->spawn_cnt, (unsigned int)run_time); bool have_worker = false; for (int i = 0; i < g_main_ctx.worker_processes; ++i) { if (g_main_ctx.proc_ctxs[i].pid > 0) { have_worker = true; break; } } if (!have_worker) { hlogw("No alive worker process, exit master process!"); exit(0); } } break; } } } } break; case SIGNAL_RELOAD: if (g_main_ctx.reload_fn) { g_main_ctx.reload_fn(g_main_ctx.reload_userdata); if (getpid_from_pidfile() == getpid()) { // master send SIGNAL_RELOAD => workers for (int i = 0; i < g_main_ctx.worker_processes; ++i) { if (g_main_ctx.proc_ctxs[i].pid <= 0) break; kill(g_main_ctx.proc_ctxs[i].pid, SIGNAL_RELOAD); } } } break; default: break; } } int signal_init(procedure_t reload_fn, void* reload_userdata) { g_main_ctx.reload_fn = reload_fn; g_main_ctx.reload_userdata = reload_userdata; signal(SIGINT, signal_handler); signal(SIGCHLD, signal_handler); signal(SIGNAL_TERMINATE, signal_handler); signal(SIGNAL_RELOAD, signal_handler); return 0; } #elif defined(OS_WIN) #include // for timeSetEvent // win32 use Event //static HANDLE s_hEventTerm = NULL; static HANDLE s_hEventReload = NULL; static void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { DWORD ret; /* ret = WaitForSingleObject(s_hEventTerm, 0); if (ret == WAIT_OBJECT_0) { hlogi("pid=%d recv event [TERM]", getpid()); if (getpid_from_pidfile() == getpid()) { timeKillEvent(uTimerID); exit(0); } } */ ret = WaitForSingleObject(s_hEventReload, 0); if (ret == WAIT_OBJECT_0) { hlogi("pid=%d recv event [RELOAD]", getpid()); if (g_main_ctx.reload_fn) { g_main_ctx.reload_fn(g_main_ctx.reload_userdata); } } } static void signal_cleanup(void) { //CloseHandle(s_hEventTerm); //s_hEventTerm = NULL; CloseHandle(s_hEventReload); s_hEventReload = NULL; } int signal_init(procedure_t reload_fn, void* reload_userdata) { g_main_ctx.reload_fn = reload_fn; g_main_ctx.reload_userdata = reload_userdata; char eventname[MAX_PATH] = {0}; //snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name); //s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname); //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname); snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name); s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname); timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC); atexit(signal_cleanup); return 0; } #endif static void kill_proc(int pid) { #ifdef OS_UNIX kill(pid, SIGNAL_TERMINATE); #else //SetEvent(s_hEventTerm); //hv_sleep(1); HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); if (hproc) { TerminateProcess(hproc, 0); CloseHandle(hproc); } #endif } void signal_handle(const char* signal) { if (strcmp(signal, "start") == 0) { if (g_main_ctx.oldpid > 0) { printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid); exit(0); } } else if (strcmp(signal, "stop") == 0) { if (g_main_ctx.oldpid > 0) { kill_proc(g_main_ctx.oldpid); printf("%s stop/waiting\n", g_main_ctx.program_name); } else { printf("%s is already stopped\n", g_main_ctx.program_name); } exit(0); } else if (strcmp(signal, "restart") == 0) { if (g_main_ctx.oldpid > 0) { kill_proc(g_main_ctx.oldpid); printf("%s stop/waiting\n", g_main_ctx.program_name); hv_sleep(1); } } else if (strcmp(signal, "status") == 0) { if (g_main_ctx.oldpid > 0) { printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid); } else { printf("%s stop/waiting\n", g_main_ctx.program_name); } exit(0); } else if (strcmp(signal, "reload") == 0) { if (g_main_ctx.oldpid > 0) { printf("reload confile [%s]\n", g_main_ctx.confile); #ifdef OS_UNIX kill(g_main_ctx.oldpid, SIGNAL_RELOAD); #else SetEvent(s_hEventReload); #endif } hv_sleep(1); exit(0); } else { printf("Invalid signal: '%s'\n", signal); exit(0); } printf("%s start/running\n", g_main_ctx.program_name); } // master-workers processes static HTHREAD_ROUTINE(worker_thread) { hlogi("worker_thread pid=%ld tid=%ld", hv_getpid(), hv_gettid()); if (g_main_ctx.worker_fn) { g_main_ctx.worker_fn(g_main_ctx.worker_userdata); } return 0; } static void worker_init(void* userdata) { #ifdef OS_UNIX setproctitle("%s: worker process", g_main_ctx.program_name); signal(SIGNAL_RELOAD, signal_handler); #endif } static void worker_proc(void* userdata) { for (int i = 1; i < g_main_ctx.worker_threads; ++i) { hthread_create(worker_thread, NULL); } worker_thread(NULL); } int master_workers_run(procedure_t worker_fn, void* worker_userdata, int worker_processes, int worker_threads, bool wait) { #ifdef OS_WIN // NOTE: Windows not provide MultiProcesses if (worker_threads == 0) { // MultiProcesses => MultiThreads worker_threads = worker_processes; } worker_processes = 0; #endif if (worker_threads == 0) worker_threads = 1; g_main_ctx.worker_threads = worker_threads; g_main_ctx.worker_fn = worker_fn; g_main_ctx.worker_userdata = worker_userdata; if (worker_processes == 0) { // single process if (wait) { for (int i = 1; i < worker_threads; ++i) { hthread_create(worker_thread, NULL); } worker_thread(NULL); } else { for (int i = 0; i < worker_threads; ++i) { hthread_create(worker_thread, NULL); } } } else { if (g_main_ctx.worker_processes != 0) { return ERR_OVER_LIMIT; } // master-workers processes #ifdef OS_UNIX setproctitle("%s: master process", g_main_ctx.program_name); signal(SIGNAL_RELOAD, signal_handler); #endif g_main_ctx.worker_processes = worker_processes; int bytes = g_main_ctx.worker_processes * sizeof(proc_ctx_t); SAFE_ALLOC(g_main_ctx.proc_ctxs, bytes); proc_ctx_t* ctx = g_main_ctx.proc_ctxs; for (int i = 0; i < g_main_ctx.worker_processes; ++i, ++ctx) { ctx->init = worker_init; ctx->proc = worker_proc; hproc_spawn(ctx); hlogi("workers[%d] start/running, pid=%d", i, ctx->pid); } g_main_ctx.pid = getpid(); hlogi("master start/running, pid=%d", g_main_ctx.pid); if (wait) { while (1) hv_sleep (1); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hmain.h000066400000000000000000000061441520575453600256310ustar00rootroot00000000000000#ifndef HV_MAIN_H_ #define HV_MAIN_H_ #include "hexport.h" #include "hplatform.h" #include "hdef.h" #include "hproc.h" #ifdef _MSC_VER #pragma comment(lib, "winmm.lib") // for timeSetEvent #endif BEGIN_EXTERN_C typedef struct main_ctx_s { char run_dir[MAX_PATH]; char program_name[MAX_PATH]; char confile[MAX_PATH]; // default etc/${program}.conf char pidfile[MAX_PATH]; // default logs/${program}.pid char logfile[MAX_PATH]; // default logs/${program}.log pid_t pid; // getpid pid_t oldpid; // getpid_from_pidfile // arg int argc; int arg_len; char** os_argv; char** save_argv; char* cmdline; // parsed arg int arg_kv_size; char** arg_kv; int arg_list_size; char** arg_list; // env int envc; int env_len; char** os_envp; char** save_envp; // signals procedure_t reload_fn; void* reload_userdata; // master workers model int worker_processes; int worker_threads; procedure_t worker_fn; void* worker_userdata; proc_ctx_t* proc_ctxs; } main_ctx_t; // arg_type #define NO_ARGUMENT 0 #define REQUIRED_ARGUMENT 1 #define OPTIONAL_ARGUMENT 2 // option define #define OPTION_PREFIX '-' #define OPTION_DELIM '=' #define OPTION_ENABLE "1" #define OPTION_DISABLE "0" typedef struct option_s { char short_opt; const char* long_opt; int arg_type; const char* description; } option_t; HV_EXPORT int main_ctx_init(int argc, char** argv); HV_EXPORT void main_ctx_free(void); // ls -a -l // ls -al // watch -n 10 ls // watch -n10 ls HV_EXPORT int parse_opt(int argc, char** argv, const char* opt); // gcc -g -Wall -O3 -std=cpp main.c HV_EXPORT int parse_opt_long(int argc, char** argv, const option_t* long_options, int opt_size); HV_EXPORT int dump_opt_long(const option_t* long_options, int opt_size, char* out_str, int out_size); HV_EXPORT const char* get_arg(const char* key); HV_EXPORT const char* get_env(const char* key); #if defined(OS_UNIX) && !HAVE_SETPROCTITLE HV_EXPORT void setproctitle(const char* fmt, ...); #endif // pidfile HV_EXPORT int create_pidfile(); HV_EXPORT void delete_pidfile(void); HV_EXPORT pid_t getpid_from_pidfile(); // signal=[start,stop,restart,status,reload] HV_EXPORT int signal_init(procedure_t reload_fn DEFAULT(NULL), void* reload_userdata DEFAULT(NULL)); HV_EXPORT void signal_handle(const char* signal); #ifdef OS_UNIX // we use SIGTERM to quit process, SIGUSR1 to reload confile #define SIGNAL_TERMINATE SIGTERM #define SIGNAL_RELOAD SIGUSR1 void signal_handler(int signo); #endif // global var #define DEFAULT_WORKER_PROCESSES 4 #define MAXNUM_WORKER_PROCESSES 256 HV_EXPORT extern main_ctx_t g_main_ctx; // master-workers processes HV_EXPORT int master_workers_run( procedure_t worker_fn, void* worker_userdata DEFAULT(NULL), int worker_processes DEFAULT(DEFAULT_WORKER_PROCESSES), int worker_threads DEFAULT(0), bool wait DEFAULT(true)); END_EXTERN_C #endif // HV_MAIN_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hmath.h000066400000000000000000000027731520575453600256420ustar00rootroot00000000000000#ifndef HV_MATH_H_ #define HV_MATH_H_ #include static inline unsigned long floor2e(unsigned long num) { unsigned long n = num; int e = 0; while (n>>=1) ++e; unsigned long ret = 1; while (e--) ret<<=1; return ret; } static inline unsigned long ceil2e(unsigned long num) { // 2**0 = 1 if (num == 0 || num == 1) return 1; unsigned long n = num - 1; int e = 1; while (n>>=1) ++e; unsigned long ret = 1; while (e--) ret<<=1; return ret; } // varint little-endian // MSB static inline int varint_encode(long long value, unsigned char* buf) { unsigned char ch; unsigned char *p = buf; int bytes = 0; do { ch = value & 0x7F; value >>= 7; *p++ = value == 0 ? ch : (ch | 0x80); ++bytes; } while (value); return bytes; } // @param[IN|OUT] len: in=>buflen, out=>varint bytesize static inline long long varint_decode(const unsigned char* buf, int* len) { long long ret = 0; int bytes = 0, bits = 0; const unsigned char *p = buf; do { if (len && *len && bytes == *len) { // Not enough length *len = 0; return 0; } ret |= ((long long)(*p & 0x7F)) << bits; ++bytes; if ((*p & 0x80) == 0) { // Found end if (len) *len = bytes; return ret; } ++p; bits += 7; } while(bytes < 10); // Not found end if (len) *len = -1; return ret; } #endif // HV_MATH_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hmutex.h000066400000000000000000000216331520575453600260470ustar00rootroot00000000000000#ifndef HV_MUTEX_H_ #define HV_MUTEX_H_ #include "hexport.h" #include "hplatform.h" #include "htime.h" BEGIN_EXTERN_C #ifdef OS_WIN #define hmutex_t CRITICAL_SECTION #define hmutex_init InitializeCriticalSection #define hmutex_destroy DeleteCriticalSection #define hmutex_lock EnterCriticalSection #define hmutex_unlock LeaveCriticalSection #define hrecursive_mutex_t CRITICAL_SECTION #define hrecursive_mutex_init InitializeCriticalSection #define hrecursive_mutex_destroy DeleteCriticalSection #define hrecursive_mutex_lock EnterCriticalSection #define hrecursive_mutex_unlock LeaveCriticalSection #define HSPINLOCK_COUNT -1 #define hspinlock_t CRITICAL_SECTION #define hspinlock_init(pspin) InitializeCriticalSectionAndSpinCount(pspin, HSPINLOCK_COUNT) #define hspinlock_destroy DeleteCriticalSection #define hspinlock_lock EnterCriticalSection #define hspinlock_unlock LeaveCriticalSection #define hrwlock_t SRWLOCK #define hrwlock_init InitializeSRWLock #define hrwlock_destroy(plock) #define hrwlock_rdlock AcquireSRWLockShared #define hrwlock_rdunlock ReleaseSRWLockShared #define hrwlock_wrlock AcquireSRWLockExclusive #define hrwlock_wrunlock ReleaseSRWLockExclusive #define htimed_mutex_t HANDLE #define htimed_mutex_init(pmutex) *(pmutex) = CreateMutex(NULL, FALSE, NULL) #define htimed_mutex_destroy(pmutex) CloseHandle(*(pmutex)) #define htimed_mutex_lock(pmutex) WaitForSingleObject(*(pmutex), INFINITE) #define htimed_mutex_unlock(pmutex) ReleaseMutex(*(pmutex)) // true: WAIT_OBJECT_0 // false: WAIT_OBJECT_TIMEOUT #define htimed_mutex_lock_for(pmutex, ms) ( WaitForSingleObject(*(pmutex), ms) == WAIT_OBJECT_0 ) #define hcondvar_t CONDITION_VARIABLE #define hcondvar_init InitializeConditionVariable #define hcondvar_destroy(pcond) #define hcondvar_wait(pcond, pmutex) SleepConditionVariableCS(pcond, pmutex, INFINITE) #define hcondvar_wait_for(pcond, pmutex, ms) SleepConditionVariableCS(pcond, pmutex, ms) #define hcondvar_signal WakeConditionVariable #define hcondvar_broadcast WakeAllConditionVariable #define honce_t INIT_ONCE #define HONCE_INIT INIT_ONCE_STATIC_INIT typedef void (*honce_fn)(); static inline BOOL WINAPI s_once_func(INIT_ONCE* once, PVOID arg, PVOID* _) { honce_fn fn = (honce_fn)arg; fn(); return TRUE; } static inline void honce(honce_t* once, honce_fn fn) { PVOID dummy = NULL; InitOnceExecuteOnce(once, s_once_func, (PVOID)fn, &dummy); } #define hsem_t HANDLE #define hsem_init(psem, value) *(psem) = CreateSemaphore(NULL, value, value+100000, NULL) #define hsem_destroy(psem) CloseHandle(*(psem)) #define hsem_wait(psem) WaitForSingleObject(*(psem), INFINITE) #define hsem_post(psem) ReleaseSemaphore(*(psem), 1, NULL) // true: WAIT_OBJECT_0 // false: WAIT_OBJECT_TIMEOUT #define hsem_wait_for(psem, ms) ( WaitForSingleObject(*(psem), ms) == WAIT_OBJECT_0 ) #else #define hmutex_t pthread_mutex_t #define hmutex_init(pmutex) pthread_mutex_init(pmutex, NULL) #define hmutex_destroy pthread_mutex_destroy #define hmutex_lock pthread_mutex_lock #define hmutex_unlock pthread_mutex_unlock #define hrecursive_mutex_t pthread_mutex_t #define hrecursive_mutex_init(pmutex) \ do {\ pthread_mutexattr_t attr;\ pthread_mutexattr_init(&attr);\ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\ pthread_mutex_init(pmutex, &attr);\ } while(0) #define hrecursive_mutex_destroy pthread_mutex_destroy #define hrecursive_mutex_lock pthread_mutex_lock #define hrecursive_mutex_unlock pthread_mutex_unlock #if HAVE_PTHREAD_SPIN_LOCK #define hspinlock_t pthread_spinlock_t #define hspinlock_init(pspin) pthread_spin_init(pspin, PTHREAD_PROCESS_PRIVATE) #define hspinlock_destroy pthread_spin_destroy #define hspinlock_lock pthread_spin_lock #define hspinlock_unlock pthread_spin_unlock #else #define hspinlock_t pthread_mutex_t #define hspinlock_init(pmutex) pthread_mutex_init(pmutex, NULL) #define hspinlock_destroy pthread_mutex_destroy #define hspinlock_lock pthread_mutex_lock #define hspinlock_unlock pthread_mutex_unlock #endif #define hrwlock_t pthread_rwlock_t #define hrwlock_init(prwlock) pthread_rwlock_init(prwlock, NULL) #define hrwlock_destroy pthread_rwlock_destroy #define hrwlock_rdlock pthread_rwlock_rdlock #define hrwlock_rdunlock pthread_rwlock_unlock #define hrwlock_wrlock pthread_rwlock_wrlock #define hrwlock_wrunlock pthread_rwlock_unlock #define htimed_mutex_t pthread_mutex_t #define htimed_mutex_init(pmutex) pthread_mutex_init(pmutex, NULL) #define htimed_mutex_destroy pthread_mutex_destroy #define htimed_mutex_lock pthread_mutex_lock #define htimed_mutex_unlock pthread_mutex_unlock static inline void timespec_after(struct timespec* ts, unsigned int ms) { struct timeval tv; gettimeofday(&tv, NULL); ts->tv_sec = tv.tv_sec + ms / 1000; ts->tv_nsec = tv.tv_usec * 1000 + ms % 1000 * 1000000; if (ts->tv_nsec >= 1000000000) { ts->tv_nsec -= 1000000000; ts->tv_sec += 1; } } // true: OK // false: ETIMEDOUT static inline int htimed_mutex_lock_for(htimed_mutex_t* mutex, unsigned int ms) { #if HAVE_PTHREAD_MUTEX_TIMEDLOCK struct timespec ts; timespec_after(&ts, ms); return pthread_mutex_timedlock(mutex, &ts) != ETIMEDOUT; #else int ret = 0; unsigned int end = gettick_ms() + ms; while ((ret = pthread_mutex_trylock(mutex)) != 0) { if (gettick_ms() >= end) { break; } hv_msleep(1); } return ret == 0; #endif } #define hcondvar_t pthread_cond_t #define hcondvar_init(pcond) pthread_cond_init(pcond, NULL) #define hcondvar_destroy pthread_cond_destroy #define hcondvar_wait pthread_cond_wait #define hcondvar_signal pthread_cond_signal #define hcondvar_broadcast pthread_cond_broadcast // true: OK // false: ETIMEDOUT static inline int hcondvar_wait_for(hcondvar_t* cond, hmutex_t* mutex, unsigned int ms) { struct timespec ts; timespec_after(&ts, ms); return pthread_cond_timedwait(cond, mutex, &ts) != ETIMEDOUT; } #define honce_t pthread_once_t #define HONCE_INIT PTHREAD_ONCE_INIT #define honce pthread_once #include #define hsem_t sem_t #define hsem_init(psem, value) sem_init(psem, 0, value) #define hsem_destroy sem_destroy #define hsem_wait sem_wait #define hsem_post sem_post // true: OK // false: ETIMEDOUT static inline int hsem_wait_for(hsem_t* sem, unsigned int ms) { #if HAVE_SEM_TIMEDWAIT struct timespec ts; timespec_after(&ts, ms); return sem_timedwait(sem, &ts) != ETIMEDOUT; #else int ret = 0; unsigned int end = gettick_ms() + ms; while ((ret = sem_trywait(sem)) != 0) { if (gettick_ms() >= end) { break; } hv_msleep(1); } return ret == 0; #endif } #endif END_EXTERN_C #ifdef __cplusplus #include #include // using std::mutex; // NOTE: test std::timed_mutex incorrect in some platforms, use htimed_mutex_t // using std::timed_mutex; using std::condition_variable; using std::lock_guard; using std::unique_lock; BEGIN_NAMESPACE_HV class MutexLock { public: MutexLock() { hmutex_init(&_mutex); } ~MutexLock() { hmutex_destroy(&_mutex); } void lock() { hmutex_lock(&_mutex); } void unlock() { hmutex_unlock(&_mutex); } protected: hmutex_t _mutex; }; class SpinLock { public: SpinLock() { hspinlock_init(&_spin); } ~SpinLock() { hspinlock_destroy(&_spin); } void lock() { hspinlock_lock(&_spin); } void unlock() { hspinlock_unlock(&_spin); } protected: hspinlock_t _spin; }; class RWLock { public: RWLock() { hrwlock_init(&_rwlock); } ~RWLock() { hrwlock_destroy(&_rwlock); } void rdlock() { hrwlock_rdlock(&_rwlock); } void rdunlock() { hrwlock_rdunlock(&_rwlock); } void wrlock() { hrwlock_wrlock(&_rwlock); } void wrunlock() { hrwlock_wrunlock(&_rwlock); } void lock() { rdlock(); } void unlock() { rdunlock(); } protected: hrwlock_t _rwlock; }; template class LockGuard { public: LockGuard(T& t) : _lock(t) { _lock.lock(); } ~LockGuard() { _lock.unlock(); } protected: T& _lock; }; END_NAMESPACE_HV // same as java synchronized(lock) { ... } #define synchronized(lock) for (std::lock_guard _lock_(lock), *p = &_lock_; p != NULL; p = NULL) #endif // __cplusplus #endif // HV_MUTEX_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hplatform.h000066400000000000000000000213541520575453600265310ustar00rootroot00000000000000#ifndef HV_PLATFORM_H_ #define HV_PLATFORM_H_ #include "hconfig.h" // OS #if defined(WIN64) || defined(_WIN64) #define OS_WIN64 #define OS_WIN32 #elif defined(WIN32)|| defined(_WIN32) #define OS_WIN32 #elif defined(ANDROID) || defined(__ANDROID__) #define OS_ANDROID #define OS_LINUX #elif defined(linux) || defined(__linux) || defined(__linux__) #define OS_LINUX #elif defined(__APPLE__) && (defined(__GNUC__) || defined(__xlC__) || defined(__xlc__)) #include #if defined(TARGET_OS_MAC) && TARGET_OS_MAC #define OS_MAC #elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE #define OS_IOS #endif #define OS_DARWIN #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #define OS_FREEBSD #define OS_BSD #elif defined(__NetBSD__) #define OS_NETBSD #define OS_BSD #elif defined(__OpenBSD__) #define OS_OPENBSD #define OS_BSD #elif defined(sun) || defined(__sun) || defined(__sun__) #define OS_SOLARIS #else #warning "Untested operating system platform!" #endif #if defined(OS_WIN32) || defined(OS_WIN64) #undef OS_UNIX #define OS_WIN #else #undef OS_WIN #define OS_UNIX #endif // ARCH #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) #define ARCH_X64 #define ARCH_X86_64 #elif defined(__i386) || defined(__i386__) || defined(_M_IX86) #define ARCH_X86 #define ARCH_X86_32 #elif defined(__aarch64__) || defined(__ARM64__) || defined(_M_ARM64) #define ARCH_ARM64 #elif defined(__arm__) || defined(_M_ARM) #define ARCH_ARM #elif defined(__mips64__) #define ARCH_MIPS64 #elif defined(__mips__) #define ARCH_MIPS #else #warning "Untested hardware architecture!" #endif // COMPILER #if defined (_MSC_VER) #define COMPILER_MSVC #if (_MSC_VER < 1200) // Visual C++ 6.0 #define MSVS_VERSION 1998 #define MSVC_VERSION 60 #elif (_MSC_VER >= 1200) && (_MSC_VER < 1300) // Visual Studio 2002, MSVC++ 7.0 #define MSVS_VERSION 2002 #define MSVC_VERSION 70 #elif (_MSC_VER >= 1300) && (_MSC_VER < 1400) // Visual Studio 2003, MSVC++ 7.1 #define MSVS_VERSION 2003 #define MSVC_VERSION 71 #elif (_MSC_VER >= 1400) && (_MSC_VER < 1500) // Visual Studio 2005, MSVC++ 8.0 #define MSVS_VERSION 2005 #define MSVC_VERSION 80 #elif (_MSC_VER >= 1500) && (_MSC_VER < 1600) // Visual Studio 2008, MSVC++ 9.0 #define MSVS_VERSION 2008 #define MSVC_VERSION 90 #elif (_MSC_VER >= 1600) && (_MSC_VER < 1700) // Visual Studio 2010, MSVC++ 10.0 #define MSVS_VERSION 2010 #define MSVC_VERSION 100 #elif (_MSC_VER >= 1700) && (_MSC_VER < 1800) // Visual Studio 2012, MSVC++ 11.0 #define MSVS_VERSION 2012 #define MSVC_VERSION 110 #elif (_MSC_VER >= 1800) && (_MSC_VER < 1900) // Visual Studio 2013, MSVC++ 12.0 #define MSVS_VERSION 2013 #define MSVC_VERSION 120 #elif (_MSC_VER >= 1900) && (_MSC_VER < 1910) // Visual Studio 2015, MSVC++ 14.0 #define MSVS_VERSION 2015 #define MSVC_VERSION 140 #elif (_MSC_VER >= 1910) && (_MSC_VER < 1920) // Visual Studio 2017, MSVC++ 15.0 #define MSVS_VERSION 2017 #define MSVC_VERSION 150 #elif (_MSC_VER >= 1920) && (_MSC_VER < 2000) // Visual Studio 2019, MSVC++ 16.0 #define MSVS_VERSION 2019 #define MSVC_VERSION 160 #endif #undef HAVE_STDATOMIC_H #define HAVE_STDATOMIC_H 0 #undef HAVE_SYS_TIME_H #define HAVE_SYS_TIME_H 0 #undef HAVE_PTHREAD_H #define HAVE_PTHREAD_H 0 #pragma warning (disable: 4018) // signed/unsigned comparison #pragma warning (disable: 4100) // unused param #pragma warning (disable: 4102) // unreferenced label #pragma warning (disable: 4244) // conversion loss of data #pragma warning (disable: 4267) // size_t => int #pragma warning (disable: 4819) // Unicode #pragma warning (disable: 4996) // _CRT_SECURE_NO_WARNINGS #elif defined(__GNUC__) #define COMPILER_GCC #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #elif defined(__clang__) #define COMPILER_CLANG #elif defined(__MINGW32__) || defined(__MINGW64__) #define COMPILER_MINGW #elif defined(__MSYS__) #define COMPILER_MSYS #elif defined(__CYGWIN__) #define COMPILER_CYGWIN #else #warning "Untested compiler!" #endif // headers #ifdef OS_WIN #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #elif _WIN32_WINNT < 0x0600 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #endif #include #include // for inet_pton,inet_ntop #include #include // for getpid,exec #include // for mkdir,rmdir,chdir,getcwd #include // for open,close,read,write,lseek,tell #define hv_sleep(s) Sleep((s) * 1000) #define hv_msleep(ms) Sleep(ms) #define hv_usleep(us) Sleep((us) / 1000) #define hv_delay(ms) hv_msleep(ms) #define hv_mkdir(dir) mkdir(dir) // access #ifndef F_OK #define F_OK 0 /* test for existence of file */ #endif #ifndef X_OK #define X_OK (1<<0) /* test for execute or search permission */ #endif #ifndef W_OK #define W_OK (1<<1) /* test for write permission */ #endif #ifndef R_OK #define R_OK (1<<2) /* test for read permission */ #endif // stat #ifndef S_ISREG #define S_ISREG(st_mode) (((st_mode) & S_IFMT) == S_IFREG) #endif #ifndef S_ISDIR #define S_ISDIR(st_mode) (((st_mode) & S_IFMT) == S_IFDIR) #endif #else #include #include // for mkdir,rmdir,chdir,getcwd // socket #include #include #include #include #include #include #include // for gethostbyname #define hv_sleep(s) sleep(s) #define hv_msleep(ms) usleep((ms) * 1000) #define hv_usleep(us) usleep(us) #define hv_delay(ms) hv_msleep(ms) #define hv_mkdir(dir) mkdir(dir, 0777) #endif #ifdef _MSC_VER typedef int pid_t; typedef int gid_t; typedef int uid_t; #define strcasecmp stricmp #define strncasecmp strnicmp #else typedef int BOOL; typedef unsigned char BYTE; typedef unsigned short WORD; typedef void* HANDLE; #include #define stricmp strcasecmp #define strnicmp strncasecmp #endif // ENDIAN #ifndef BIG_ENDIAN #define BIG_ENDIAN 4321 #endif #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN 1234 #endif #ifndef NET_ENDIAN #define NET_ENDIAN BIG_ENDIAN #endif // BYTE_ORDER #ifndef BYTE_ORDER #if defined(__BYTE_ORDER) #define BYTE_ORDER __BYTE_ORDER #elif defined(__BYTE_ORDER__) #define BYTE_ORDER __BYTE_ORDER__ #elif defined(ARCH_X86) || defined(ARCH_X86_64) || \ defined(__ARMEL__) || defined(__AARCH64EL__) || \ defined(__MIPSEL) || defined(__MIPS64EL) #define BYTE_ORDER LITTLE_ENDIAN #elif defined(__ARMEB__) || defined(__AARCH64EB__) || \ defined(__MIPSEB) || defined(__MIPS64EB) #define BYTE_ORDER BIG_ENDIAN #elif defined(OS_WIN) #define BYTE_ORDER LITTLE_ENDIAN #else #warning "Unknown byte order!" #endif #endif // ANSI C #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef __cplusplus #if HAVE_STDBOOL_H #include #else #ifndef bool #define bool char #endif #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #endif #endif #if HAVE_STDINT_H #include #elif defined(_MSC_VER) && _MSC_VER < 1700 typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif typedef float float32_t; typedef double float64_t; typedef int (*method_t)(void* userdata); typedef void (*procedure_t)(void* userdata); #if HAVE_SYS_TYPES_H #include #endif #if HAVE_SYS_STAT_H #include #endif #if HAVE_SYS_TIME_H #include // for gettimeofday #endif #if HAVE_FCNTL_H #include #endif #if HAVE_PTHREAD_H #include #endif #endif // HV_PLATFORM_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hproc.h000066400000000000000000000031251520575453600256440ustar00rootroot00000000000000#ifndef HV_PROC_H_ #define HV_PROC_H_ #include "hplatform.h" typedef struct proc_ctx_s { pid_t pid; // tid in Windows time_t start_time; int spawn_cnt; procedure_t init; void* init_userdata; procedure_t proc; void* proc_userdata; procedure_t exit; void* exit_userdata; } proc_ctx_t; static inline void hproc_run(proc_ctx_t* ctx) { if (ctx->init) { ctx->init(ctx->init_userdata); } if (ctx->proc) { ctx->proc(ctx->proc_userdata); } if (ctx->exit) { ctx->exit(ctx->exit_userdata); } } #ifdef OS_UNIX // unix use multi-processes static inline int hproc_spawn(proc_ctx_t* ctx) { ++ctx->spawn_cnt; ctx->start_time = time(NULL); pid_t pid = fork(); if (pid < 0) { perror("fork"); return -1; } else if (pid == 0) { // child process ctx->pid = getpid(); hproc_run(ctx); exit(0); } else if (pid > 0) { // parent process ctx->pid = pid; } return pid; } #elif defined(OS_WIN) // win32 use multi-threads static void win_thread(void* userdata) { proc_ctx_t* ctx = (proc_ctx_t*)userdata; ctx->pid = GetCurrentThreadId(); // tid in Windows hproc_run(ctx); } static inline int hproc_spawn(proc_ctx_t* ctx) { ++ctx->spawn_cnt; ctx->start_time = time(NULL); HANDLE h = (HANDLE)_beginthread(win_thread, 0, ctx); if (h == NULL) { return -1; } ctx->pid = GetThreadId(h); // tid in Windows return ctx->pid; } #endif #endif // HV_PROC_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hsocket.c000066400000000000000000000242451520575453600261720ustar00rootroot00000000000000#include "hsocket.h" #include "hdef.h" #ifdef OS_WIN #include "hatomic.h" static hatomic_flag_t s_wsa_initialized = HATOMIC_FLAG_INIT; void WSAInit() { if (!hatomic_flag_test_and_set(&s_wsa_initialized)) { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); } } void WSADeinit() { if (hatomic_flag_test_and_set(&s_wsa_initialized)) { hatomic_flag_clear(&s_wsa_initialized); WSACleanup(); } } #endif static inline int socket_errno_negative(int sockfd) { int err = socket_errno(); if (sockfd >= 0) closesocket(sockfd); return err > 0 ? -err : -1; } const char* socket_strerror(int err) { #ifdef OS_WIN static char buffer[128]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, 0, ABS(err), 0, buffer, sizeof(buffer), NULL); return buffer; #else return strerror(ABS(err)); #endif } bool is_ipv4(const char* host) { struct sockaddr_in sin; return inet_pton(AF_INET, host, &sin) == 1; } bool is_ipv6(const char* host) { struct sockaddr_in6 sin6; return inet_pton(AF_INET6, host, &sin6) == 1; } int ResolveAddr(const char* host, sockaddr_u* addr) { #ifdef OS_WIN WSAInit(); #endif if (inet_pton(AF_INET, host, &addr->sin.sin_addr) == 1) { addr->sa.sa_family = AF_INET; // host is ipv4, so easy ;) return 0; } if (inet_pton(AF_INET6, host, &addr->sin6.sin6_addr) == 1) { addr->sa.sa_family = AF_INET6; // host is ipv6 } struct addrinfo* ais = NULL; int ret = getaddrinfo(host, NULL, NULL, &ais); if (ret != 0 || ais == NULL || ais->ai_addr == NULL || ais->ai_addrlen == 0) { printd("unknown host: %s err:%d:%s\n", host, ret, gai_strerror(ret)); return ret; } struct addrinfo* pai = ais; while (pai != NULL) { if (pai->ai_family == AF_INET) break; pai = pai->ai_next; } if (pai == NULL) pai = ais; memcpy(addr, pai->ai_addr, pai->ai_addrlen); freeaddrinfo(ais); return 0; } const char* sockaddr_ip(sockaddr_u* addr, char *ip, int len) { if (addr->sa.sa_family == AF_INET) { return inet_ntop(AF_INET, &addr->sin.sin_addr, ip, len); } else if (addr->sa.sa_family == AF_INET6) { return inet_ntop(AF_INET6, &addr->sin6.sin6_addr, ip, len); } return ip; } uint16_t sockaddr_port(sockaddr_u* addr) { uint16_t port = 0; if (addr->sa.sa_family == AF_INET) { port = ntohs(addr->sin.sin_port); } else if (addr->sa.sa_family == AF_INET6) { port = ntohs(addr->sin6.sin6_port); } return port; } int sockaddr_set_ip(sockaddr_u* addr, const char* host) { if (!host || *host == '\0') { addr->sin.sin_family = AF_INET; addr->sin.sin_addr.s_addr = htonl(INADDR_ANY); return 0; } return ResolveAddr(host, addr); } void sockaddr_set_port(sockaddr_u* addr, int port) { if (addr->sa.sa_family == AF_INET) { addr->sin.sin_port = htons(port); } else if (addr->sa.sa_family == AF_INET6) { addr->sin6.sin6_port = htons(port); } } int sockaddr_set_ipport(sockaddr_u* addr, const char* host, int port) { #ifdef ENABLE_UDS if (port < 0) { sockaddr_set_path(addr, host); return 0; } #endif int ret = sockaddr_set_ip(addr, host); if (ret != 0) return ret; sockaddr_set_port(addr, port); // SOCKADDR_PRINT(addr); return 0; } socklen_t sockaddr_len(sockaddr_u* addr) { if (addr->sa.sa_family == AF_INET) { return sizeof(struct sockaddr_in); } else if (addr->sa.sa_family == AF_INET6) { return sizeof(struct sockaddr_in6); } #ifdef ENABLE_UDS else if (addr->sa.sa_family == AF_UNIX) { return sizeof(struct sockaddr_un); } #endif return sizeof(sockaddr_u); } const char* sockaddr_str(sockaddr_u* addr, char* buf, int len) { char ip[SOCKADDR_STRLEN] = {0}; uint16_t port = 0; if (addr->sa.sa_family == AF_INET) { inet_ntop(AF_INET, &addr->sin.sin_addr, ip, len); port = ntohs(addr->sin.sin_port); snprintf(buf, len, "%s:%d", ip, port); } else if (addr->sa.sa_family == AF_INET6) { inet_ntop(AF_INET6, &addr->sin6.sin6_addr, ip, len); port = ntohs(addr->sin6.sin6_port); snprintf(buf, len, "[%s]:%d", ip, port); } #ifdef ENABLE_UDS else if (addr->sa.sa_family == AF_UNIX) { snprintf(buf, len, "%s", addr->sun.sun_path); } #endif return buf; } static int sockaddr_bind(sockaddr_u* localaddr, int type) { // socket -> setsockopt -> bind #ifdef SOCK_CLOEXEC type |= SOCK_CLOEXEC; #endif int sockfd = socket(localaddr->sa.sa_family, type, 0); if (sockfd < 0) { perror("socket"); goto error; } #ifdef OS_UNIX so_reuseaddr(sockfd, 1); // so_reuseport(sockfd, 1); #endif if (localaddr->sa.sa_family == AF_INET6) { ip_v6only(sockfd, 0); } if (bind(sockfd, &localaddr->sa, sockaddr_len(localaddr)) < 0) { perror("bind"); goto error; } return sockfd; error: return socket_errno_negative(sockfd); } static int sockaddr_connect(sockaddr_u* peeraddr, int nonblock) { // socket -> nonblocking -> connect int ret = 0; int connfd = socket(peeraddr->sa.sa_family, SOCK_STREAM, 0); if (connfd < 0) { perror("socket"); goto error; } if (nonblock) { nonblocking(connfd); } ret = connect(connfd, &peeraddr->sa, sockaddr_len(peeraddr)); #ifdef OS_WIN if (ret < 0 && socket_errno() != WSAEWOULDBLOCK) { #else if (ret < 0 && socket_errno() != EINPROGRESS) { #endif // perror("connect"); goto error; } return connfd; error: return socket_errno_negative(connfd); } static int ListenFD(int sockfd) { if (sockfd < 0) return sockfd; if (listen(sockfd, SOMAXCONN) < 0) { perror("listen"); return socket_errno_negative(sockfd); } return sockfd; } static int ConnectFDTimeout(int connfd, int ms) { int err = 0; socklen_t optlen = sizeof(err); struct timeval tv = { ms / 1000, (ms % 1000) * 1000 }; fd_set writefds; FD_ZERO(&writefds); FD_SET(connfd, &writefds); int ret = select(connfd+1, 0, &writefds, 0, &tv); if (ret < 0) { perror("select"); goto error; } if (ret == 0) { errno = ETIMEDOUT; goto error; } if (getsockopt(connfd, SOL_SOCKET, SO_ERROR, (char*)&err, &optlen) < 0 || err != 0) { if (err != 0) errno = err; goto error; } blocking(connfd); return connfd; error: return socket_errno_negative(connfd); } int Bind(int port, const char* host, int type) { #ifdef OS_WIN WSAInit(); #endif sockaddr_u localaddr; memset(&localaddr, 0, sizeof(localaddr)); int ret = sockaddr_set_ipport(&localaddr, host, port); if (ret != 0) { return NABS(ret); } return sockaddr_bind(&localaddr, type); } int Listen(int port, const char* host) { int sockfd = Bind(port, host, SOCK_STREAM); if (sockfd < 0) return sockfd; return ListenFD(sockfd); } int Connect(const char* host, int port, int nonblock) { #ifdef OS_WIN WSAInit(); #endif sockaddr_u peeraddr; memset(&peeraddr, 0, sizeof(peeraddr)); int ret = sockaddr_set_ipport(&peeraddr, host, port); if (ret != 0) { return NABS(ret); } return sockaddr_connect(&peeraddr, nonblock); } int ConnectNonblock(const char* host, int port) { return Connect(host, port, 1); } int ConnectTimeout(const char* host, int port, int ms) { int connfd = Connect(host, port, 1); if (connfd < 0) return connfd; return ConnectFDTimeout(connfd, ms); } #ifdef ENABLE_UDS int BindUnix(const char* path, int type) { sockaddr_u localaddr; memset(&localaddr, 0, sizeof(localaddr)); sockaddr_set_path(&localaddr, path); return sockaddr_bind(&localaddr, type); } int ListenUnix(const char* path) { int sockfd = BindUnix(path, SOCK_STREAM); if (sockfd < 0) return sockfd; return ListenFD(sockfd); } int ConnectUnix(const char* path, int nonblock) { sockaddr_u peeraddr; memset(&peeraddr, 0, sizeof(peeraddr)); sockaddr_set_path(&peeraddr, path); return sockaddr_connect(&peeraddr, nonblock); } int ConnectUnixNonblock(const char* path) { return ConnectUnix(path, 1); } int ConnectUnixTimeout(const char* path, int ms) { int connfd = ConnectUnix(path, 1); if (connfd < 0) return connfd; return ConnectFDTimeout(connfd, ms); } #endif int Socketpair(int family, int type, int protocol, int sv[2]) { #if defined(OS_UNIX) && HAVE_SOCKETPAIR return socketpair(AF_LOCAL, type, protocol, sv); #endif if (family != AF_INET || type != SOCK_STREAM) { return -1; } #ifdef OS_WIN WSAInit(); #endif int listenfd, connfd, acceptfd; listenfd = connfd = acceptfd = -1; struct sockaddr_in localaddr; socklen_t addrlen = sizeof(localaddr); memset(&localaddr, 0, addrlen); localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); localaddr.sin_port = 0; // listener listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { perror("socket"); goto error; } if (bind(listenfd, (struct sockaddr*)&localaddr, addrlen) < 0) { perror("bind"); goto error; } if (listen(listenfd, 1) < 0) { perror("listen"); goto error; } if (getsockname(listenfd, (struct sockaddr*)&localaddr, &addrlen) < 0) { perror("getsockname"); goto error; } // connector connfd = socket(AF_INET, SOCK_STREAM, 0); if (connfd < 0) { perror("socket"); goto error; } if (connect(connfd, (struct sockaddr*)&localaddr, addrlen) < 0) { perror("connect"); goto error; } // acceptor acceptfd = accept(listenfd, (struct sockaddr*)&localaddr, &addrlen); if (acceptfd < 0) { perror("accept"); goto error; } closesocket(listenfd); sv[0] = connfd; sv[1] = acceptfd; return 0; error: if (listenfd != -1) { closesocket(listenfd); } if (connfd != -1) { closesocket(connfd); } if (acceptfd != -1) { closesocket(acceptfd); } return -1; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hsocket.h000066400000000000000000000177731520575453600262070ustar00rootroot00000000000000#ifndef HV_SOCKET_H_ #define HV_SOCKET_H_ #include "hexport.h" #include "hplatform.h" #ifdef ENABLE_UDS #ifdef OS_WIN #include // import struct sockaddr_un #else #include // import struct sockaddr_un #endif #endif #ifdef _MSC_VER #pragma comment(lib, "ws2_32.lib") #endif #define LOCALHOST "127.0.0.1" #define ANYADDR "0.0.0.0" BEGIN_EXTERN_C HV_INLINE int socket_errno() { #ifdef OS_WIN return WSAGetLastError(); #else return errno; #endif } HV_EXPORT const char* socket_strerror(int err); #ifdef OS_WIN typedef SOCKET hsocket_t; typedef int socklen_t; void WSAInit(); void WSADeinit(); HV_INLINE int blocking(int sockfd) { unsigned long nb = 0; return ioctlsocket(sockfd, FIONBIO, &nb); } HV_INLINE int nonblocking(int sockfd) { unsigned long nb = 1; return ioctlsocket(sockfd, FIONBIO, &nb); } #undef EAGAIN #define EAGAIN WSAEWOULDBLOCK #undef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #undef EINTR #define EINTR WSAEINTR #undef ENOTSOCK #define ENOTSOCK WSAENOTSOCK #undef EMSGSIZE #define EMSGSIZE WSAEMSGSIZE #else typedef int hsocket_t; #ifndef SOCKET #define SOCKET int #endif #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif HV_INLINE int blocking(int s) { return fcntl(s, F_SETFL, fcntl(s, F_GETFL) & ~O_NONBLOCK); } HV_INLINE int nonblocking(int s) { return fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK); } #ifndef closesocket HV_INLINE int closesocket(int sockfd) { return close(sockfd); } #endif #endif #ifndef SAFE_CLOSESOCKET #define SAFE_CLOSESOCKET(fd) do {if ((fd) >= 0) {closesocket(fd); (fd) = -1;}} while(0) #endif //-----------------------------sockaddr_u---------------------------------------------- typedef union { struct sockaddr sa; struct sockaddr_in sin; struct sockaddr_in6 sin6; #ifdef ENABLE_UDS struct sockaddr_un sun; #endif } sockaddr_u; HV_EXPORT bool is_ipv4(const char* host); HV_EXPORT bool is_ipv6(const char* host); HV_INLINE bool is_ipaddr(const char* host) { return is_ipv4(host) || is_ipv6(host); } // @param host: domain or ip // @retval 0:succeed HV_EXPORT int ResolveAddr(const char* host, sockaddr_u* addr); HV_EXPORT const char* sockaddr_ip(sockaddr_u* addr, char *ip, int len); HV_EXPORT uint16_t sockaddr_port(sockaddr_u* addr); HV_EXPORT int sockaddr_set_ip(sockaddr_u* addr, const char* host); HV_EXPORT void sockaddr_set_port(sockaddr_u* addr, int port); HV_EXPORT int sockaddr_set_ipport(sockaddr_u* addr, const char* host, int port); HV_EXPORT socklen_t sockaddr_len(sockaddr_u* addr); HV_EXPORT const char* sockaddr_str(sockaddr_u* addr, char* buf, int len); //#define INET_ADDRSTRLEN 16 //#define INET6_ADDRSTRLEN 46 #ifdef ENABLE_UDS #define SOCKADDR_STRLEN sizeof(((struct sockaddr_un*)(NULL))->sun_path) HV_INLINE void sockaddr_set_path(sockaddr_u* addr, const char* path) { addr->sa.sa_family = AF_UNIX; strncpy(addr->sun.sun_path, path, sizeof(addr->sun.sun_path)); } #else #define SOCKADDR_STRLEN 64 // ipv4:port | [ipv6]:port #endif HV_INLINE void sockaddr_print(sockaddr_u* addr) { char buf[SOCKADDR_STRLEN] = {0}; sockaddr_str(addr, buf, sizeof(buf)); puts(buf); } #define SOCKADDR_LEN(addr) sockaddr_len((sockaddr_u*)addr) #define SOCKADDR_STR(addr, buf) sockaddr_str((sockaddr_u*)addr, buf, sizeof(buf)) #define SOCKADDR_PRINT(addr) sockaddr_print((sockaddr_u*)addr) //===================================================================================== // socket -> setsockopt -> bind // @param type: SOCK_STREAM(tcp) SOCK_DGRAM(udp) // @return sockfd HV_EXPORT int Bind(int port, const char* host DEFAULT(ANYADDR), int type DEFAULT(SOCK_STREAM)); // Bind -> listen // @return listenfd HV_EXPORT int Listen(int port, const char* host DEFAULT(ANYADDR)); // @return connfd // ResolveAddr -> socket -> nonblocking -> connect HV_EXPORT int Connect(const char* host, int port, int nonblock DEFAULT(0)); // Connect(host, port, 1) HV_EXPORT int ConnectNonblock(const char* host, int port); // Connect(host, port, 1) -> select -> blocking #define DEFAULT_CONNECT_TIMEOUT 10000 // ms HV_EXPORT int ConnectTimeout(const char* host, int port, int ms DEFAULT(DEFAULT_CONNECT_TIMEOUT)); #ifdef ENABLE_UDS HV_EXPORT int BindUnix(const char* path, int type DEFAULT(SOCK_STREAM)); HV_EXPORT int ListenUnix(const char* path); HV_EXPORT int ConnectUnix(const char* path, int nonblock DEFAULT(0)); HV_EXPORT int ConnectUnixNonblock(const char* path); HV_EXPORT int ConnectUnixTimeout(const char* path, int ms DEFAULT(DEFAULT_CONNECT_TIMEOUT)); #endif // Just implement Socketpair(AF_INET, SOCK_STREAM, 0, sv); HV_EXPORT int Socketpair(int family, int type, int protocol, int sv[2]); HV_INLINE int tcp_nodelay(int sockfd, int on DEFAULT(1)) { return setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(int)); } HV_INLINE int tcp_nopush(int sockfd, int on DEFAULT(1)) { #ifdef TCP_NOPUSH return setsockopt(sockfd, IPPROTO_TCP, TCP_NOPUSH, (const char*)&on, sizeof(int)); #elif defined(TCP_CORK) return setsockopt(sockfd, IPPROTO_TCP, TCP_CORK, (const char*)&on, sizeof(int)); #else return 0; #endif } HV_INLINE int tcp_keepalive(int sockfd, int on DEFAULT(1), int delay DEFAULT(60)) { if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(int)) != 0) { return socket_errno(); } #ifdef TCP_KEEPALIVE return setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE, (const char*)&delay, sizeof(int)); #elif defined(TCP_KEEPIDLE) // TCP_KEEPIDLE => tcp_keepalive_time // TCP_KEEPCNT => tcp_keepalive_probes // TCP_KEEPINTVL => tcp_keepalive_intvl return setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (const char*)&delay, sizeof(int)); #else return 0; #endif } HV_INLINE int udp_broadcast(int sockfd, int on DEFAULT(1)) { return setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (const char*)&on, sizeof(int)); } HV_INLINE int ip_v6only(int sockfd, int on DEFAULT(1)) { #ifdef IPV6_V6ONLY return setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(int)); #else return 0; #endif } // send timeout HV_INLINE int so_sndtimeo(int sockfd, int timeout) { #ifdef OS_WIN return setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(int)); #else struct timeval tv = {timeout/1000, (timeout%1000)*1000}; return setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); #endif } // recv timeout HV_INLINE int so_rcvtimeo(int sockfd, int timeout) { #ifdef OS_WIN return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(int)); #else struct timeval tv = {timeout/1000, (timeout%1000)*1000}; return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); #endif } // send buffer size HV_INLINE int so_sndbuf(int sockfd, int len) { return setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&len, sizeof(int)); } // recv buffer size HV_INLINE int so_rcvbuf(int sockfd, int len) { return setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&len, sizeof(int)); } HV_INLINE int so_reuseaddr(int sockfd, int on DEFAULT(1)) { #ifdef SO_REUSEADDR // NOTE: SO_REUSEADDR allow to reuse sockaddr of TIME_WAIT status return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(int)); #else return 0; #endif } HV_INLINE int so_reuseport(int sockfd, int on DEFAULT(1)) { #ifdef SO_REUSEPORT // NOTE: SO_REUSEPORT allow multiple sockets to bind same port return setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&on, sizeof(int)); #else return 0; #endif } HV_INLINE int so_linger(int sockfd, int timeout DEFAULT(1)) { #ifdef SO_LINGER struct linger linger; if (timeout >= 0) { linger.l_onoff = 1; linger.l_linger = timeout; } else { linger.l_onoff = 0; linger.l_linger = 0; } // NOTE: SO_LINGER change the default behavior of close, send RST, avoid TIME_WAIT return setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger, sizeof(linger)); #else return 0; #endif } END_EXTERN_C #endif // HV_SOCKET_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hsysinfo.h000066400000000000000000000033551520575453600264000ustar00rootroot00000000000000#ifndef HV_SYS_INFO_H_ #define HV_SYS_INFO_H_ #include "hplatform.h" #ifdef OS_LINUX #include #endif #ifdef OS_DARWIN #include #include #endif static inline int get_ncpu() { #ifdef OS_WIN SYSTEM_INFO si; GetSystemInfo(&si); return si.dwNumberOfProcessors; #else //return get_nprocs(); //return get_nprocs_conf(); //return sysconf(_SC_NPROCESSORS_ONLN); // processors available return sysconf(_SC_NPROCESSORS_CONF); // processors configured #endif } typedef struct meminfo_s { unsigned long total; // KB unsigned long free; // KB } meminfo_t; static inline int get_meminfo(meminfo_t* mem) { #ifdef OS_WIN MEMORYSTATUSEX memstat; memset(&memstat, 0, sizeof(memstat)); memstat.dwLength = sizeof(memstat); GlobalMemoryStatusEx(&memstat); mem->total = (unsigned long)(memstat.ullTotalPhys >> 10); mem->free = (unsigned long)(memstat.ullAvailPhys >> 10); return 0; #elif defined(OS_LINUX) struct sysinfo info; if (sysinfo(&info) < 0) { return errno; } mem->total = info.totalram * info.mem_unit >> 10; mem->free = info.freeram * info.mem_unit >> 10; return 0; #elif defined(OS_DARWIN) uint64_t memsize = 0; size_t size = sizeof(memsize); int which[2] = {CTL_HW, HW_MEMSIZE}; sysctl(which, 2, &memsize, &size, NULL, 0); mem->total = memsize >> 10; vm_statistics_data_t info; mach_msg_type_number_t count = sizeof(info) / sizeof(integer_t); host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&info, &count); mem->free = ((uint64_t)info.free_count * sysconf(_SC_PAGESIZE)) >> 10; return 0; #else (void)(mem); return -10; #endif } #endif // HV_SYS_INFO_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hthread.h000066400000000000000000000113461520575453600261540ustar00rootroot00000000000000#ifndef HV_THREAD_H_ #define HV_THREAD_H_ #include "hplatform.h" #ifdef OS_WIN #define hv_getpid (long)GetCurrentProcessId #else #define hv_getpid (long)getpid #endif #ifdef OS_WIN #define hv_gettid (long)GetCurrentThreadId #elif HAVE_GETTID || defined(OS_ANDROID) #define hv_gettid (long)gettid #elif defined(OS_LINUX) #include #define hv_gettid() (long)syscall(SYS_gettid) #elif defined(OS_DARWIN) static inline long hv_gettid() { uint64_t tid = 0; pthread_threadid_np(NULL, &tid); return tid; } #elif HAVE_PTHREAD_H #define hv_gettid (long)pthread_self #else #define hv_gettid hv_getpid #endif /* #include "hthread.h" HTHREAD_ROUTINE(thread_demo) { printf("thread[%ld] start\n", hv_gettid()); hv_delay(3000); printf("thread[%ld] end\n", hv_gettid()); return 0; } int main() { hthread_t th = hthread_create(thread_demo, NULL); hthread_join(th); return 0; } */ #ifdef OS_WIN typedef HANDLE hthread_t; typedef DWORD (WINAPI *hthread_routine)(void*); #define HTHREAD_RETTYPE DWORD #define HTHREAD_ROUTINE(fname) DWORD WINAPI fname(void* userdata) static inline hthread_t hthread_create(hthread_routine fn, void* userdata) { return CreateThread(NULL, 0, fn, userdata, 0, NULL); } static inline int hthread_join(hthread_t th) { WaitForSingleObject(th, INFINITE); CloseHandle(th); return 0; } #else typedef pthread_t hthread_t; typedef void* (*hthread_routine)(void*); #define HTHREAD_RETTYPE void* #define HTHREAD_ROUTINE(fname) void* fname(void* userdata) static inline hthread_t hthread_create(hthread_routine fn, void* userdata) { pthread_t th; pthread_create(&th, NULL, fn, userdata); return th; } static inline int hthread_join(hthread_t th) { return pthread_join(th, NULL); } #endif #ifdef __cplusplus /************************************************ * HThread * Status: STOP,RUNNING,PAUSE * Control: start,stop,pause,resume * first-level virtual: doTask * second-level virtual: run ************************************************/ #include #include #include class HThread { public: enum Status { STOP, RUNNING, PAUSE, }; enum SleepPolicy { YIELD, SLEEP_FOR, SLEEP_UNTIL, NO_SLEEP, }; HThread() { status = STOP; status_changed = false; dotask_cnt = 0; sleep_policy = YIELD; sleep_ms = 0; } virtual ~HThread() {} void setStatus(Status stat) { status_changed = true; status = stat; } void setSleepPolicy(SleepPolicy policy, uint32_t ms = 0) { sleep_policy = policy; sleep_ms = ms; setStatus(status); } virtual int start() { if (status == STOP) { thread = std::thread([this] { if (!doPrepare()) return; setStatus(RUNNING); run(); setStatus(STOP); if (!doFinish()) return; }); } return 0; } virtual int stop() { if (status != STOP) { setStatus(STOP); } if (thread.joinable()) { thread.join(); // wait thread exit } return 0; } virtual int pause() { if (status == RUNNING) { setStatus(PAUSE); } return 0; } virtual int resume() { if (status == PAUSE) { setStatus(RUNNING); } return 0; } virtual void run() { while (status != STOP) { while (status == PAUSE) { std::this_thread::yield(); } doTask(); ++dotask_cnt; HThread::sleep(); } } virtual bool doPrepare() {return true;} virtual void doTask() {} virtual bool doFinish() {return true;} std::thread thread; std::atomic status; uint32_t dotask_cnt; protected: void sleep() { switch (sleep_policy) { case YIELD: std::this_thread::yield(); break; case SLEEP_FOR: std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms)); break; case SLEEP_UNTIL: { if (status_changed) { status_changed = false; base_tp = std::chrono::steady_clock::now(); } base_tp += std::chrono::milliseconds(sleep_ms); std::this_thread::sleep_until(base_tp); } break; default: // donothing, go all out. break; } } SleepPolicy sleep_policy; uint32_t sleep_ms; // for SLEEP_UNTIL std::atomic status_changed; std::chrono::steady_clock::time_point base_tp; }; #endif #endif // HV_THREAD_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/htime.c000066400000000000000000000155311520575453600256360ustar00rootroot00000000000000#include "htime.h" static const char* s_weekdays[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; static const char* s_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static const uint8_t s_days[] = \ // 1 3 5 7 8 10 12 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; unsigned int gettick_ms() { #ifdef OS_WIN return GetTickCount(); #elif HAVE_CLOCK_GETTIME struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; #endif } unsigned long long gethrtime_us() { #ifdef OS_WIN static LONGLONG s_freq = 0; if (s_freq == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); s_freq = freq.QuadPart; } if (s_freq != 0) { LARGE_INTEGER count; QueryPerformanceCounter(&count); return (unsigned long long)(count.QuadPart / (double)s_freq * 1000000); } return 0; #elif defined(OS_SOLARIS) return gethrtime() / 1000; #elif HAVE_CLOCK_GETTIME struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec*(unsigned long long)1000000 + ts.tv_nsec / 1000; #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*(unsigned long long)1000000 + tv.tv_usec; #endif } datetime_t datetime_now() { #ifdef OS_WIN SYSTEMTIME tm; GetLocalTime(&tm); datetime_t dt; dt.year = tm.wYear; dt.month = tm.wMonth; dt.day = tm.wDay; dt.hour = tm.wHour; dt.min = tm.wMinute; dt.sec = tm.wSecond; dt.ms = tm.wMilliseconds; return dt; #else struct timeval tv; gettimeofday(&tv, NULL); datetime_t dt = datetime_localtime(tv.tv_sec); dt.ms = tv.tv_usec / 1000; return dt; #endif } datetime_t datetime_localtime(time_t seconds) { struct tm* tm = localtime(&seconds); datetime_t dt; dt.year = tm->tm_year + 1900; dt.month = tm->tm_mon + 1; dt.day = tm->tm_mday; dt.hour = tm->tm_hour; dt.min = tm->tm_min; dt.sec = tm->tm_sec; return dt; } time_t datetime_mktime(datetime_t* dt) { struct tm tm; time_t ts; time(&ts); struct tm* ptm = localtime(&ts); memcpy(&tm, ptm, sizeof(struct tm)); tm.tm_year = dt->year - 1900; tm.tm_mon = dt->month - 1; tm.tm_mday = dt->day; tm.tm_hour = dt->hour; tm.tm_min = dt->min; tm.tm_sec = dt->sec; return mktime(&tm); } int days_of_month(int month, int year) { if (month < 1 || month > 12) { return 0; } int days = s_days[month-1]; return (month == 2 && IS_LEAP_YEAR(year)) ? ++days : days; } datetime_t* datetime_past(datetime_t* dt, int days) { assert(days >= 0); int sub = days; while (sub) { if (dt->day > sub) { dt->day -= sub; break; } sub -= dt->day; if (--dt->month == 0) { dt->month = 12; --dt->year; } dt->day = days_of_month(dt->month, dt->year); } return dt; } datetime_t* datetime_future(datetime_t* dt, int days) { assert(days >= 0); int sub = days; int mdays; while (sub) { mdays = days_of_month(dt->month, dt->year); if (dt->day + sub <= mdays) { dt->day += sub; break; } sub -= (mdays - dt->day + 1); if (++dt->month > 12) { dt->month = 1; ++dt->year; } dt->day = 1; } return dt; } char* duration_fmt(int sec, char* buf) { int h, m, s; m = sec / 60; s = sec % 60; h = m / 60; m = m % 60; sprintf(buf, TIME_FMT, h, m, s); return buf; } char* datetime_fmt(datetime_t* dt, char* buf) { sprintf(buf, DATETIME_FMT, dt->year, dt->month, dt->day, dt->hour, dt->min, dt->sec); return buf; } char* datetime_fmt_iso(datetime_t* dt, char* buf) { sprintf(buf, DATETIME_FMT_ISO, dt->year, dt->month, dt->day, dt->hour, dt->min, dt->sec, dt->ms); return buf; } char* gmtime_fmt(time_t time, char* buf) { struct tm* tm = gmtime(&time); //strftime(buf, GMTIME_FMT_BUFLEN, "%a, %d %b %Y %H:%M:%S GMT", tm); sprintf(buf, GMTIME_FMT, s_weekdays[tm->tm_wday], tm->tm_mday, s_months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return buf; } int month_atoi(const char* month) { for (size_t i = 0; i < 12; ++i) { if (strnicmp(month, s_months[i], strlen(month)) == 0) return i+1; } return 0; } const char* month_itoa(int month) { assert(month >= 1 && month <= 12); return s_months[month-1]; } int weekday_atoi(const char* weekday) { for (size_t i = 0; i < 7; ++i) { if (strnicmp(weekday, s_weekdays[i], strlen(weekday)) == 0) return i; } return 0; } const char* weekday_itoa(int weekday) { assert(weekday >= 0 && weekday <= 7); if (weekday == 7) weekday = 0; return s_weekdays[weekday]; } datetime_t hv_compile_datetime() { datetime_t dt; char month[32]; sscanf(__DATE__, "%s %d %d", month, &dt.day, &dt.year); sscanf(__TIME__, "%d:%d:%d", &dt.hour, &dt.min, &dt.sec); dt.month = month_atoi(month); return dt; } time_t cron_next_timeout(int minute, int hour, int day, int week, int month) { enum { MINUTELY, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY, } period_type = MINUTELY; struct tm tm; time_t tt; time(&tt); tm = *localtime(&tt); time_t tt_round = 0; tm.tm_sec = 0; if (minute >= 0) { period_type = HOURLY; tm.tm_min = minute; } if (hour >= 0) { period_type = DAILY; tm.tm_hour = hour; } if (week >= 0) { period_type = WEEKLY; } else if (day > 0) { period_type = MONTHLY; tm.tm_mday = day; if (month > 0) { period_type = YEARLY; tm.tm_mon = month - 1; } } tt_round = mktime(&tm); if (week >= 0) { tt_round += (week-tm.tm_wday)*SECONDS_PER_DAY; } if (tt_round > tt) { return tt_round; } switch(period_type) { case MINUTELY: tt_round += SECONDS_PER_MINUTE; return tt_round; case HOURLY: tt_round += SECONDS_PER_HOUR; return tt_round; case DAILY: tt_round += SECONDS_PER_DAY; return tt_round; case WEEKLY: tt_round += SECONDS_PER_WEEK; return tt_round; case MONTHLY: if (++tm.tm_mon == 12) { tm.tm_mon = 0; ++tm.tm_year; } break; case YEARLY: ++tm.tm_year; break; default: return -1; } return mktime(&tm); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/htime.h000066400000000000000000000063261520575453600256450ustar00rootroot00000000000000#ifndef HV_TIME_H_ #define HV_TIME_H_ #include "hexport.h" #include "hplatform.h" BEGIN_EXTERN_C #define SECONDS_PER_MINUTE 60 #define SECONDS_PER_HOUR 3600 #define SECONDS_PER_DAY 86400 // 24*3600 #define SECONDS_PER_WEEK 604800 // 7*24*3600 #define IS_LEAP_YEAR(year) (((year)%4 == 0 && (year)%100 != 0) || (year)%400 == 0) typedef struct datetime_s { int year; int month; int day; int hour; int min; int sec; int ms; } datetime_t; #ifdef _MSC_VER /* @see winsock2.h // Structure used in select() call, taken from the BSD file sys/time.h struct timeval { long tv_sec; long tv_usec; }; */ struct timezone { int tz_minuteswest; /* of Greenwich */ int tz_dsttime; /* type of dst correction to apply */ }; #include HV_INLINE int gettimeofday(struct timeval *tv, struct timezone *tz) { struct _timeb tb; _ftime(&tb); if (tv) { tv->tv_sec = (long)tb.time; tv->tv_usec = tb.millitm * 1000; } if (tz) { tz->tz_minuteswest = tb.timezone; tz->tz_dsttime = tb.dstflag; } return 0; } #endif HV_EXPORT unsigned int gettick_ms(); HV_INLINE unsigned long long gettimeofday_ms() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * (unsigned long long)1000 + tv.tv_usec/1000; } HV_INLINE unsigned long long gettimeofday_us() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * (unsigned long long)1000000 + tv.tv_usec; } HV_EXPORT unsigned long long gethrtime_us(); HV_EXPORT datetime_t datetime_now(); HV_EXPORT datetime_t datetime_localtime(time_t seconds); HV_EXPORT time_t datetime_mktime(datetime_t* dt); HV_EXPORT datetime_t* datetime_past(datetime_t* dt, int days DEFAULT(1)); HV_EXPORT datetime_t* datetime_future(datetime_t* dt, int days DEFAULT(1)); #define TIME_FMT "%02d:%02d:%02d" #define TIME_FMT_BUFLEN 12 HV_EXPORT char* duration_fmt(int sec, char* buf); #define DATETIME_FMT "%04d-%02d-%02d %02d:%02d:%02d" #define DATETIME_FMT_ISO "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ" #define DATETIME_FMT_BUFLEN 30 HV_EXPORT char* datetime_fmt(datetime_t* dt, char* buf); HV_EXPORT char* datetime_fmt_iso(datetime_t* dt, char* buf); #define GMTIME_FMT "%.3s, %02d %.3s %04d %02d:%02d:%02d GMT" #define GMTIME_FMT_BUFLEN 30 HV_EXPORT char* gmtime_fmt(time_t time, char* buf); HV_EXPORT int days_of_month(int month, int year); HV_EXPORT int month_atoi(const char* month); HV_EXPORT const char* month_itoa(int month); HV_EXPORT int weekday_atoi(const char* weekday); HV_EXPORT const char* weekday_itoa(int weekday); HV_EXPORT datetime_t hv_compile_datetime(); /* * minute hour day week month action * 0~59 0~23 1~31 0~6 1~12 * -1 -1 -1 -1 -1 cron.minutely * 30 -1 -1 -1 -1 cron.hourly * 30 1 -1 -1 -1 cron.daily * 30 1 15 -1 -1 cron.monthly * 30 1 -1 0 -1 cron.weekly * 30 1 1 -1 10 cron.yearly */ HV_EXPORT time_t cron_next_timeout(int minute, int hour, int day, int week, int month); END_EXTERN_C #endif // HV_TIME_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hversion.c000066400000000000000000000017321520575453600263630ustar00rootroot00000000000000#include "hversion.h" #include "htime.h" const char* hv_compile_version() { static char s_version[16] = {0}; datetime_t dt = hv_compile_datetime(); snprintf(s_version, sizeof(s_version), "%d.%d.%d.%d", HV_VERSION_MAJOR, dt.year%100, dt.month, dt.day); return s_version; } int version_atoi(const char* str) { int hex = 0; // trim v1.2.3.4 const char* pv = strchr(str, 'v'); const char* pdot = pv ? pv+1 : str; while (1) { hex = (hex << 8) | atoi(pdot); pdot = strchr(pdot, '.'); if (pdot == NULL) break; ++pdot; } return hex; } void version_itoa(int num, char* str) { char* ch = (char*)# sprintf(str, "%d.%d.%d.%d", ch[3], ch[2], ch[1], ch[0]); // trim 0.1.2.3 const char* p = str; while (1) { if (p[0] == '0' && p[1] == '.') { p += 2; } else { break; } } if (p != str) { strcpy(str, p); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/hversion.h000066400000000000000000000014061520575453600263660ustar00rootroot00000000000000#ifndef HV_VERSION_H_ #define HV_VERSION_H_ #include "hexport.h" #include "hdef.h" BEGIN_EXTERN_C #define HV_VERSION_MAJOR 1 #define HV_VERSION_MINOR 3 #define HV_VERSION_PATCH 3 #define HV_VERSION_STRING STRINGIFY(HV_VERSION_MAJOR) "." \ STRINGIFY(HV_VERSION_MINOR) "." \ STRINGIFY(HV_VERSION_PATCH) #define HV_VERSION_NUMBER ((HV_VERSION_MAJOR << 16) | (HV_VERSION_MINOR << 8) | HV_VERSION_PATCH) HV_INLINE const char* hv_version() { return HV_VERSION_STRING; } HV_EXPORT const char* hv_compile_version(); // 1.2.3.4 => 0x01020304 HV_EXPORT int version_atoi(const char* str); // 0x01020304 => 1.2.3.4 HV_EXPORT void version_itoa(int hex, char* str); END_EXTERN_C #endif // HV_VERSION_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/list.h000066400000000000000000000522611520575453600255110ustar00rootroot00000000000000#ifndef _LINUX_LIST_H #define _LINUX_LIST_H /* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */ #include #ifndef prefetch #ifdef __GNUC__ #define prefetch(x) __builtin_prefetch(x) #else #define prefetch(x) (void)0 #endif #endif struct list_head { struct list_head *next, *prev; }; #define list_node list_head struct hlist_head { struct hlist_node *first; }; struct hlist_node { struct hlist_node *next, **pprev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } // TODO: defined LIST_HEAD #ifndef LIST_HEAD #define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) #endif #define INIT_LIST_HEAD list_init static inline void list_init(struct list_head *list) { list->next = list; list->prev = list; } /* * Insert a new entry between two known consecutive entries. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_add(struct list_head *n, struct list_head *prev, struct list_head *next) { next->prev = n; n->next = next; n->prev = prev; prev->next = n; } /** * list_add - add a new entry * @new: new entry to be added * @head: list head to add it after * * Insert a new entry after the specified head. * This is good for implementing stacks. */ static inline void list_add(struct list_head *n, struct list_head *head) { __list_add(n, head, head->next); } /** * list_add_tail - add a new entry * @new: new entry to be added * @head: list head to add it before * * Insert a new entry before the specified head. * This is useful for implementing queues. */ static inline void list_add_tail(struct list_head *n, struct list_head *head) { __list_add(n, head->prev, head); } /* * Delete a list entry by making the prev/next entries * point to each other. * * This is only for internal list manipulation where we know * the prev/next entries already! */ static inline void __list_del(struct list_head * prev, struct list_head * next) { next->prev = prev; prev->next = next; } /** * list_del - deletes entry from list. * @entry: the element to delete from the list. * Note: list_empty() on entry does not return true after this, the entry is * in an undefined state. */ static inline void __list_del_entry(struct list_head *entry) { __list_del(entry->prev, entry->next); } static inline void list_del(struct list_head *entry) { __list_del(entry->prev, entry->next); //entry->next = NULL; //entry->prev = NULL; } /** * list_replace - replace old entry by new one * @old : the element to be replaced * @new : the new element to insert * * If @old was empty, it will be overwritten. */ static inline void list_replace(struct list_head *old, struct list_head *n) { n->next = old->next; n->next->prev = n; n->prev = old->prev; n->prev->next = n; } static inline void list_replace_init(struct list_head *old, struct list_head *n) { list_replace(old, n); INIT_LIST_HEAD(old); } /** * list_del_init - deletes entry from list and reinitialize it. * @entry: the element to delete from the list. */ static inline void list_del_init(struct list_head *entry) { __list_del_entry(entry); INIT_LIST_HEAD(entry); } /** * list_move - delete from one list and add as another's head * @list: the entry to move * @head: the head that will precede our entry */ static inline void list_move(struct list_head *list, struct list_head *head) { __list_del_entry(list); list_add(list, head); } /** * list_move_tail - delete from one list and add as another's tail * @list: the entry to move * @head: the head that will follow our entry */ static inline void list_move_tail(struct list_head *list, struct list_head *head) { __list_del_entry(list); list_add_tail(list, head); } /** * list_is_last - tests whether @list is the last entry in list @head * @list: the entry to test * @head: the head of the list */ static inline int list_is_last(const struct list_head *list, const struct list_head *head) { return list->next == head; } /** * list_empty - tests whether a list is empty * @head: the list to test. */ static inline int list_empty(const struct list_head *head) { return head->next == head; } /** * list_empty_careful - tests whether a list is empty and not being modified * @head: the list to test * * Description: * tests whether a list is empty _and_ checks that no other CPU might be * in the process of modifying either member (next or prev) * * NOTE: using list_empty_careful() without synchronization * can only be safe if the only activity that can happen * to the list entry is list_del_init(). Eg. it cannot be used * if another CPU could re-list_add() it. */ static inline int list_empty_careful(const struct list_head *head) { struct list_head *next = head->next; return (next == head) && (next == head->prev); } /** * list_rotate_left - rotate the list to the left * @head: the head of the list */ static inline void list_rotate_left(struct list_head *head) { struct list_head *first; if (!list_empty(head)) { first = head->next; list_move_tail(first, head); } } /** * list_is_singular - tests whether a list has just one entry. * @head: the list to test. */ static inline int list_is_singular(const struct list_head *head) { return !list_empty(head) && (head->next == head->prev); } static inline void __list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry) { struct list_head *new_first = entry->next; list->next = head->next; list->next->prev = list; list->prev = entry; entry->next = list; head->next = new_first; new_first->prev = head; } /** * list_cut_position - cut a list into two * @list: a new list to add all removed entries * @head: a list with entries * @entry: an entry within head, could be the head itself * and if so we won't cut the list * * This helper moves the initial part of @head, up to and * including @entry, from @head to @list. You should * pass on @entry an element you know is on @head. @list * should be an empty list or a list you do not care about * losing its data. * */ static inline void list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry) { if (list_empty(head)) return; if (list_is_singular(head) && (head->next != entry && head != entry)) return; if (entry == head) INIT_LIST_HEAD(list); else __list_cut_position(list, head, entry); } static inline void __list_splice(const struct list_head *list, struct list_head *prev, struct list_head *next) { struct list_head *first = list->next; struct list_head *last = list->prev; first->prev = prev; prev->next = first; last->next = next; next->prev = last; } /** * list_splice - join two lists, this is designed for stacks * @list: the new list to add. * @head: the place to add it in the first list. */ static inline void list_splice(const struct list_head *list, struct list_head *head) { if (!list_empty(list)) __list_splice(list, head, head->next); } /** * list_splice_tail - join two lists, each list being a queue * @list: the new list to add. * @head: the place to add it in the first list. */ static inline void list_splice_tail(struct list_head *list, struct list_head *head) { if (!list_empty(list)) __list_splice(list, head->prev, head); } /** * list_splice_init - join two lists and reinitialise the emptied list. * @list: the new list to add. * @head: the place to add it in the first list. * * The list at @list is reinitialised */ static inline void list_splice_init(struct list_head *list, struct list_head *head) { if (!list_empty(list)) { __list_splice(list, head, head->next); INIT_LIST_HEAD(list); } } /** * list_splice_tail_init - join two lists and reinitialise the emptied list * @list: the new list to add. * @head: the place to add it in the first list. * * Each of the lists is a queue. * The list at @list is reinitialised */ static inline void list_splice_tail_init(struct list_head *list, struct list_head *head) { if (!list_empty(list)) { __list_splice(list, head->prev, head); INIT_LIST_HEAD(list); } } /** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) /** * list_first_entry - get the first element from a list * @ptr: the list head to take the element from. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. * * Note, that list is expected to be not empty. */ #define list_first_entry(ptr, type, member) \ list_entry((ptr)->next, type, member) /** * list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop cursor. * @head: the head for your list. */ #define list_for_each(pos, head) \ for (pos = (head)->next; prefetch(pos->next), pos != (head); \ pos = pos->next) /** * __list_for_each - iterate over a list * @pos: the &struct list_head to use as a loop cursor. * @head: the head for your list. * * This variant differs from list_for_each() in that it's the * simplest possible list iteration code, no prefetching is done. * Use this for code that knows the list to be very short (empty * or 1 entry) most of the time. */ #define __list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) /** * list_for_each_prev - iterate over a list backwards * @pos: the &struct list_head to use as a loop cursor. * @head: the head for your list. */ #define list_for_each_prev(pos, head) \ for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \ pos = pos->prev) /** * list_for_each_safe - iterate over a list safe against removal of list entry * @pos: the &struct list_head to use as a loop cursor. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) /** * list_for_each_prev_safe - iterate over a list backwards safe against removal of list entry * @pos: the &struct list_head to use as a loop cursor. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_prev_safe(pos, n, head) \ for (pos = (head)->prev, n = pos->prev; \ prefetch(pos->prev), pos != (head); \ pos = n, n = pos->prev) /** * list_for_each_entry - iterate over list of given type * @pos: the type * to use as a loop cursor. * @head: the head for your list. * @member: the name of the list_struct within the struct. */ #define list_for_each_entry(pos, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member); \ prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member)) /** * list_for_each_entry_reverse - iterate backwards over list of given type. * @pos: the type * to use as a loop cursor. * @head: the head for your list. * @member: the name of the list_struct within the struct. */ #define list_for_each_entry_reverse(pos, head, member) \ for (pos = list_entry((head)->prev, typeof(*pos), member); \ prefetch(pos->member.prev), &pos->member != (head); \ pos = list_entry(pos->member.prev, typeof(*pos), member)) /** * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue() * @pos: the type * to use as a start point * @head: the head of the list * @member: the name of the list_struct within the struct. * * Prepares a pos entry for use as a start point in list_for_each_entry_continue(). */ #define list_prepare_entry(pos, head, member) \ ((pos) ? : list_entry(head, typeof(*pos), member)) /** * list_for_each_entry_continue - continue iteration over list of given type * @pos: the type * to use as a loop cursor. * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Continue to iterate over list of given type, continuing after * the current position. */ #define list_for_each_entry_continue(pos, head, member) \ for (pos = list_entry(pos->member.next, typeof(*pos), member); \ prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member)) /** * list_for_each_entry_continue_reverse - iterate backwards from the given point * @pos: the type * to use as a loop cursor. * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Start to iterate over list of given type backwards, continuing after * the current position. */ #define list_for_each_entry_continue_reverse(pos, head, member) \ for (pos = list_entry(pos->member.prev, typeof(*pos), member); \ prefetch(pos->member.prev), &pos->member != (head); \ pos = list_entry(pos->member.prev, typeof(*pos), member)) /** * list_for_each_entry_from - iterate over list of given type from the current point * @pos: the type * to use as a loop cursor. * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Iterate over list of given type, continuing from current position. */ #define list_for_each_entry_from(pos, head, member) \ for (; prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, typeof(*pos), member)) /** * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry * @pos: the type * to use as a loop cursor. * @n: another type * to use as temporary storage * @head: the head for your list. * @member: the name of the list_struct within the struct. */ #define list_for_each_entry_safe(pos, n, head, member) \ for (pos = list_entry((head)->next, typeof(*pos), member), \ n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member)) /** * list_for_each_entry_safe_continue - continue list iteration safe against removal * @pos: the type * to use as a loop cursor. * @n: another type * to use as temporary storage * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Iterate over list of given type, continuing after current point, * safe against removal of list entry. */ #define list_for_each_entry_safe_continue(pos, n, head, member) \ for (pos = list_entry(pos->member.next, typeof(*pos), member), \ n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member)) /** * list_for_each_entry_safe_from - iterate over list from current point safe against removal * @pos: the type * to use as a loop cursor. * @n: another type * to use as temporary storage * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Iterate over list of given type from current point, safe against * removal of list entry. */ #define list_for_each_entry_safe_from(pos, n, head, member) \ for (n = list_entry(pos->member.next, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, typeof(*n), member)) /** * list_for_each_entry_safe_reverse - iterate backwards over list safe against removal * @pos: the type * to use as a loop cursor. * @n: another type * to use as temporary storage * @head: the head for your list. * @member: the name of the list_struct within the struct. * * Iterate backwards over list of given type, safe against removal * of list entry. */ #define list_for_each_entry_safe_reverse(pos, n, head, member) \ for (pos = list_entry((head)->prev, typeof(*pos), member), \ n = list_entry(pos->member.prev, typeof(*pos), member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.prev, typeof(*n), member)) /** * list_safe_reset_next - reset a stale list_for_each_entry_safe loop * @pos: the loop cursor used in the list_for_each_entry_safe loop * @n: temporary storage used in list_for_each_entry_safe * @member: the name of the list_struct within the struct. * * list_safe_reset_next is not safe to use in general if the list may be * modified concurrently (eg. the lock is dropped in the loop body). An * exception to this is if the cursor element (pos) is pinned in the list, * and list_safe_reset_next is called after re-taking the lock and before * completing the current iteration of the loop body. */ #define list_safe_reset_next(pos, n, member) \ n = list_entry(pos->member.next, typeof(*pos), member) /* * Double linked lists with a single pointer list head. * Mostly useful for hash tables where the two pointer list head is * too wasteful. * You lose the ability to access the tail in O(1). */ #define HLIST_HEAD_INIT { .first = NULL } #define HLIST_HEAD(name) struct hlist_head name = { .first = NULL } #define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL) #define INIT_HLIST_NODE hlist_init static inline void hlist_init(struct hlist_node *h) { h->next = NULL; h->pprev = NULL; } static inline int hlist_unhashed(const struct hlist_node *h) { return !h->pprev; } static inline int hlist_empty(const struct hlist_head *h) { return !h->first; } static inline void __hlist_del(struct hlist_node *n) { struct hlist_node *next = n->next; struct hlist_node **pprev = n->pprev; *pprev = next; if (next) next->pprev = pprev; } static inline void hlist_del(struct hlist_node *n) { __hlist_del(n); //n->next = NULL; //n->pprev = NULL; } static inline void hlist_del_init(struct hlist_node *n) { if (!hlist_unhashed(n)) { __hlist_del(n); INIT_HLIST_NODE(n); } } static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) { struct hlist_node *first = h->first; n->next = first; if (first) first->pprev = &n->next; h->first = n; n->pprev = &h->first; } /* next must be != NULL */ static inline void hlist_add_before(struct hlist_node *n, struct hlist_node *next) { n->pprev = next->pprev; n->next = next; next->pprev = &n->next; *(n->pprev) = n; } static inline void hlist_add_after(struct hlist_node *n, struct hlist_node *next) { next->next = n->next; n->next = next; next->pprev = &n->next; if(next->next) next->next->pprev = &next->next; } /* after that we'll appear to be on some hlist and hlist_del will work */ static inline void hlist_add_fake(struct hlist_node *n) { n->pprev = &n->next; } /* * Move a list from one list head to another. Fixup the pprev * reference of the first entry if it exists. */ static inline void hlist_move_list(struct hlist_head *old, struct hlist_head *n) { n->first = old->first; if (n->first) n->first->pprev = &n->first; old->first = NULL; } #define hlist_entry(ptr, type, member) container_of(ptr,type,member) #define hlist_for_each(pos, head) \ for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ pos = pos->next) #define hlist_for_each_safe(pos, n, head) \ for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ pos = n) /** * hlist_for_each_entry - iterate over list of given type * @tpos: the type * to use as a loop cursor. * @pos: the &struct hlist_node to use as a loop cursor. * @head: the head for your list. * @member: the name of the hlist_node within the struct. */ #define hlist_for_each_entry(tpos, pos, head, member) \ for (pos = (head)->first; \ pos && ({ prefetch(pos->next); 1;}) && \ ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ pos = pos->next) /** * hlist_for_each_entry_continue - iterate over a hlist continuing after current point * @tpos: the type * to use as a loop cursor. * @pos: the &struct hlist_node to use as a loop cursor. * @member: the name of the hlist_node within the struct. */ #define hlist_for_each_entry_continue(tpos, pos, member) \ for (pos = (pos)->next; \ pos && ({ prefetch(pos->next); 1;}) && \ ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ pos = pos->next) /** * hlist_for_each_entry_from - iterate over a hlist continuing from current point * @tpos: the type * to use as a loop cursor. * @pos: the &struct hlist_node to use as a loop cursor. * @member: the name of the hlist_node within the struct. */ #define hlist_for_each_entry_from(tpos, pos, member) \ for (; pos && ({ prefetch(pos->next); 1;}) && \ ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ pos = pos->next) /** * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry * @tpos: the type * to use as a loop cursor. * @pos: the &struct hlist_node to use as a loop cursor. * @n: another &struct hlist_node to use as temporary storage * @head: the head for your list. * @member: the name of the hlist_node within the struct. */ #define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ for (pos = (head)->first; \ pos && ({ n = pos->next; 1; }) && \ ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ pos = n) #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/netinet.h000066400000000000000000000122021520575453600261730ustar00rootroot00000000000000#ifndef HV_NETINET_H_ #define HV_NETINET_H_ #include "hplatform.h" /* #ifdef OS_UNIX #include #include #include #include #include typedef struct iphdr iphdr_t; typedef struct udphdr udphdr_t; typedef struct tcphdr tcphdr_t; typedef struct icmphdr icmphdr_t; typedef struct icmp icmp_t; #else */ // sizeof(iphdr_t) = 20 typedef struct iphdr_s { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t ihl:4; // ip header length uint8_t version:4; #elif BYTE_ORDER == BIG_ENDIAN uint8_t version:4; uint8_t ihl:4; #else #error "BYTE_ORDER undefined!" #endif uint8_t tos; // type of service uint16_t tot_len; // total length uint16_t id; uint16_t frag_off; // fragment offset uint8_t ttl; // Time To Live uint8_t protocol; uint16_t check; // checksum uint32_t saddr; // srcaddr uint32_t daddr; // dstaddr /*The options start here.*/ } iphdr_t; // sizeof(udphdr_t) = 8 typedef struct udphdr_s { uint16_t source; // source port uint16_t dest; // dest port uint16_t len; // udp length uint16_t check; // checksum } udphdr_t; // sizeof(tcphdr_t) = 20 typedef struct tcphdr_s { uint16_t source; // source port uint16_t dest; // dest port uint32_t seq; // sequence uint32_t ack_seq; #if BYTE_ORDER == LITTLE_ENDIAN uint16_t res1:4; uint16_t doff:4; uint16_t fin:1; uint16_t syn:1; uint16_t rst:1; uint16_t psh:1; uint16_t ack:1; uint16_t urg:1; uint16_t res2:2; #elif BYTE_ORDER == BIG_ENDIAN uint16_t doff:4; uint16_t res1:4; uint16_t res2:2; uint16_t urg:1; uint16_t ack:1; uint16_t psh:1; uint16_t rst:1; uint16_t syn:1; uint16_t fin:1; #else #error "BYTE_ORDER undefined!" #endif uint16_t window; uint16_t check; // checksum uint16_t urg_ptr; // urgent pointer } tcphdr_t; //----------------------icmp---------------------------------- #define ICMP_ECHOREPLY 0 /* Echo Reply */ #define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ #define ICMP_SOURCE_QUENCH 4 /* Source Quench */ #define ICMP_REDIRECT 5 /* Redirect (change route) */ #define ICMP_ECHO 8 /* Echo Request */ #define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ #define ICMP_PARAMETERPROB 12 /* Parameter Problem */ #define ICMP_TIMESTAMP 13 /* Timestamp Request */ #define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ #define ICMP_INFO_REQUEST 15 /* Information Request */ #define ICMP_INFO_REPLY 16 /* Information Reply */ #define ICMP_ADDRESS 17 /* Address Mask Request */ #define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ // sizeof(icmphdr_t) = 8 typedef struct icmphdr_s { uint8_t type; // message type uint8_t code; // type sub-code uint16_t checksum; union { struct { uint16_t id; uint16_t sequence; } echo; uint32_t gateway; struct { uint16_t reserved; uint16_t mtu; } frag; } un; } icmphdr_t; typedef struct icmp_s { uint8_t icmp_type; uint8_t icmp_code; uint16_t icmp_cksum; union { uint8_t ih_pptr; struct in_addr ih_gwaddr; struct ih_idseq { uint16_t icd_id; uint16_t icd_seq; } ih_idseq; uint32_t ih_void; struct ih_pmtu { uint16_t ipm_void; uint16_t ipm_nextmtu; } ih_pmtu; struct ih_rtradv { uint8_t irt_num_addrs; uint8_t irt_wpa; uint16_t irt_lifetime; } ih_rtradv; } icmp_hun; #define icmp_pptr icmp_hun.ih_pptr #define icmp_gwaddr icmp_hun.ih_gwaddr #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq #define icmp_void icmp_hun.ih_void #define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void #define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu #define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs #define icmp_wpa icmp_hun.ih_rtradv.irt_wpa #define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime union { struct { uint32_t its_otime; uint32_t its_rtime; uint32_t its_ttime; } id_ts; /* struct { struct ip idi_ip; } id_ip; struct icmp_ra_addr id_radv; */ uint32_t id_mask; uint8_t id_data[1]; } icmp_dun; #define icmp_otime icmp_dun.id_ts.its_otime #define icmp_rtime icmp_dun.id_ts.its_rtime #define icmp_ttime icmp_dun.id_ts.its_ttime #define icmp_ip icmp_dun.id_ip.idi_ip #define icmp_radv icmp_dun.id_radv #define icmp_mask icmp_dun.id_mask #define icmp_data icmp_dun.id_data } icmp_t; //#endif static inline uint16_t checksum(uint8_t* buf, int len) { unsigned int sum = 0; uint16_t* ptr = (uint16_t*)buf; while(len > 1) { sum += *ptr++; len -= 2; } if(len) { sum += *(uint8_t*)ptr; } sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); return (uint16_t)(~sum); }; #endif // HV_NETINET_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/queue.h000066400000000000000000000047461520575453600256670ustar00rootroot00000000000000#ifndef HV_QUEUE_H_ #define HV_QUEUE_H_ /* * queue * FIFO: push_back,pop_front * stack * LIFO: push_back,pop_back */ #include // for assert #include // for NULL #include // for malloc,realloc,free #include // for memset,memmove #include "hbase.h" // for HV_ALLOC, HV_FREE #define QUEUE_INIT_SIZE 16 // #include // typedef std::deque qtype; #define QUEUE_DECL(type, qtype) \ struct qtype { \ type* ptr; \ size_t size; \ size_t maxsize;\ size_t _offset;\ }; \ typedef struct qtype qtype;\ \ static inline type* qtype##_data(qtype* p) {\ return p->ptr + p->_offset;\ }\ \ static inline int qtype##_size(qtype* p) {\ return p->size;\ }\ \ static inline int qtype##_maxsize(qtype* p) {\ return p->maxsize;\ }\ \ static inline int qtype##_empty(qtype* p) {\ return p->size == 0;\ }\ \ static inline type* qtype##_front(qtype* p) {\ return p->size == 0 ? NULL : p->ptr + p->_offset;\ }\ \ static inline type* qtype##_back(qtype* p) {\ return p->size == 0 ? NULL : p->ptr + p->_offset + p->size - 1;\ }\ \ static inline void qtype##_init(qtype* p, int maxsize) {\ p->_offset = 0;\ p->size = 0;\ p->maxsize = maxsize;\ HV_ALLOC(p->ptr, sizeof(type) * maxsize);\ }\ \ static inline void qtype##_clear(qtype* p) {\ p->_offset = 0;\ p->size = 0;\ memset(p->ptr, 0, sizeof(type) * p->maxsize);\ }\ \ static inline void qtype##_cleanup(qtype* p) {\ HV_FREE(p->ptr);\ p->_offset = p->size = p->maxsize = 0;\ }\ \ static inline void qtype##_resize(qtype* p, int maxsize) {\ if (maxsize == 0) maxsize = QUEUE_INIT_SIZE;\ p->ptr = (type*)hv_realloc(p->ptr, sizeof(type) * maxsize, sizeof(type) * p->maxsize);\ p->maxsize = maxsize;\ }\ \ static inline void qtype##_double_resize(qtype* p) {\ qtype##_resize(p, p->maxsize * 2);\ }\ \ static inline void qtype##_push_back(qtype* p, type* elem) {\ if (p->size == p->maxsize) {\ qtype##_double_resize(p);\ }\ else if (p->_offset + p->size == p->maxsize) {\ memmove(p->ptr, p->ptr + p->_offset, sizeof(type) * p->size);\ p->_offset = 0;\ }\ p->ptr[p->_offset + p->size] = *elem;\ p->size++;\ }\ static inline void qtype##_pop_front(qtype* p) {\ assert(p->size > 0);\ p->size--;\ if (++p->_offset == p->maxsize) p->_offset = 0;\ }\ \ static inline void qtype##_pop_back(qtype* p) {\ assert(p->size > 0);\ p->size--;\ }\ #endif // HV_QUEUE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/rbtree.c000066400000000000000000000256531520575453600260210ustar00rootroot00000000000000/* Red Black Trees (C) 1999 Andrea Arcangeli (C) 2002 David Woodhouse This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA linux/lib/rbtree.c */ #include "rbtree.h" static void __rb_rotate_left(struct rb_node *node, struct rb_root *root) { struct rb_node *right = node->rb_right; if ((node->rb_right = right->rb_left)) right->rb_left->rb_parent = node; right->rb_left = node; if ((right->rb_parent = node->rb_parent)) { if (node == node->rb_parent->rb_left) node->rb_parent->rb_left = right; else node->rb_parent->rb_right = right; } else root->rb_node = right; node->rb_parent = right; } static void __rb_rotate_right(struct rb_node *node, struct rb_root *root) { struct rb_node *left = node->rb_left; if ((node->rb_left = left->rb_right)) left->rb_right->rb_parent = node; left->rb_right = node; if ((left->rb_parent = node->rb_parent)) { if (node == node->rb_parent->rb_right) node->rb_parent->rb_right = left; else node->rb_parent->rb_left = left; } else root->rb_node = left; node->rb_parent = left; } void rb_insert_color(struct rb_node *node, struct rb_root *root) { struct rb_node *parent, *gparent; while ((parent = node->rb_parent) && parent->rb_color == RB_RED) { gparent = parent->rb_parent; if (parent == gparent->rb_left) { { register struct rb_node *uncle = gparent->rb_right; if (uncle && uncle->rb_color == RB_RED) { uncle->rb_color = RB_BLACK; parent->rb_color = RB_BLACK; gparent->rb_color = RB_RED; node = gparent; continue; } } if (parent->rb_right == node) { register struct rb_node *tmp; __rb_rotate_left(parent, root); tmp = parent; parent = node; node = tmp; } parent->rb_color = RB_BLACK; gparent->rb_color = RB_RED; __rb_rotate_right(gparent, root); } else { { register struct rb_node *uncle = gparent->rb_left; if (uncle && uncle->rb_color == RB_RED) { uncle->rb_color = RB_BLACK; parent->rb_color = RB_BLACK; gparent->rb_color = RB_RED; node = gparent; continue; } } if (parent->rb_left == node) { register struct rb_node *tmp; __rb_rotate_right(parent, root); tmp = parent; parent = node; node = tmp; } parent->rb_color = RB_BLACK; gparent->rb_color = RB_RED; __rb_rotate_left(gparent, root); } } root->rb_node->rb_color = RB_BLACK; } static void __rb_erase_color(struct rb_node *node, struct rb_node *parent, struct rb_root *root) { struct rb_node *other; while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node) { if (parent->rb_left == node) { other = parent->rb_right; if (other->rb_color == RB_RED) { other->rb_color = RB_BLACK; parent->rb_color = RB_RED; __rb_rotate_left(parent, root); other = parent->rb_right; } if ((!other->rb_left || other->rb_left->rb_color == RB_BLACK) && (!other->rb_right || other->rb_right->rb_color == RB_BLACK)) { other->rb_color = RB_RED; node = parent; parent = node->rb_parent; } else { if (!other->rb_right || other->rb_right->rb_color == RB_BLACK) { register struct rb_node *o_left; if ((o_left = other->rb_left)) o_left->rb_color = RB_BLACK; other->rb_color = RB_RED; __rb_rotate_right(other, root); other = parent->rb_right; } other->rb_color = parent->rb_color; parent->rb_color = RB_BLACK; if (other->rb_right) other->rb_right->rb_color = RB_BLACK; __rb_rotate_left(parent, root); node = root->rb_node; break; } } else { other = parent->rb_left; if (other->rb_color == RB_RED) { other->rb_color = RB_BLACK; parent->rb_color = RB_RED; __rb_rotate_right(parent, root); other = parent->rb_left; } if ((!other->rb_left || other->rb_left->rb_color == RB_BLACK) && (!other->rb_right || other->rb_right->rb_color == RB_BLACK)) { other->rb_color = RB_RED; node = parent; parent = node->rb_parent; } else { if (!other->rb_left || other->rb_left->rb_color == RB_BLACK) { register struct rb_node *o_right; if ((o_right = other->rb_right)) o_right->rb_color = RB_BLACK; other->rb_color = RB_RED; __rb_rotate_left(other, root); other = parent->rb_left; } other->rb_color = parent->rb_color; parent->rb_color = RB_BLACK; if (other->rb_left) other->rb_left->rb_color = RB_BLACK; __rb_rotate_right(parent, root); node = root->rb_node; break; } } } if (node) node->rb_color = RB_BLACK; } void rb_erase(struct rb_node *node, struct rb_root *root) { struct rb_node *child, *parent; int color; if (!node->rb_left) child = node->rb_right; else if (!node->rb_right) child = node->rb_left; else { struct rb_node *old = node, *left; node = node->rb_right; while ((left = node->rb_left)) node = left; child = node->rb_right; parent = node->rb_parent; color = node->rb_color; if (child) child->rb_parent = parent; if (parent) { if (parent->rb_left == node) parent->rb_left = child; else parent->rb_right = child; } else root->rb_node = child; if (node->rb_parent == old) parent = node; node->rb_parent = old->rb_parent; node->rb_color = old->rb_color; node->rb_right = old->rb_right; node->rb_left = old->rb_left; if (old->rb_parent) { if (old->rb_parent->rb_left == old) old->rb_parent->rb_left = node; else old->rb_parent->rb_right = node; } else root->rb_node = node; old->rb_left->rb_parent = node; if (old->rb_right) old->rb_right->rb_parent = node; goto color; } parent = node->rb_parent; color = node->rb_color; if (child) child->rb_parent = parent; if (parent) { if (parent->rb_left == node) parent->rb_left = child; else parent->rb_right = child; } else root->rb_node = child; color: if (color == RB_BLACK) __rb_erase_color(child, parent, root); } /* * This function returns the first node (in sort order) of the tree. */ struct rb_node *rb_first(struct rb_root *root) { struct rb_node *n; n = root->rb_node; if (!n) return (struct rb_node *)0; while (n->rb_left) n = n->rb_left; return n; } struct rb_node *rb_last(struct rb_root *root) { struct rb_node *n; n = root->rb_node; if (!n) return (struct rb_node *)0; while (n->rb_right) n = n->rb_right; return n; } struct rb_node *rb_next(struct rb_node *node) { /* If we have a right-hand child, go down and then left as far as we can. */ if (node->rb_right) { node = node->rb_right; while (node->rb_left) node = node->rb_left; return node; } /* No right-hand children. Everything down and left is smaller than us, so any 'next' node must be in the general direction of our parent. Go up the tree; any time the ancestor is a right-hand child of its parent, keep going up. First time it's a left-hand child of its parent, said parent is our 'next' node. */ while (node->rb_parent && node == node->rb_parent->rb_right) node = node->rb_parent; return node->rb_parent; } struct rb_node *rb_prev(struct rb_node *node) { /* If we have a left-hand child, go down and then right as far as we can. */ if (node->rb_left) { node = node->rb_left; while (node->rb_right) node = node->rb_right; return node; } /* No left-hand children. Go up till we find an ancestor which is a right-hand child of its parent */ while (node->rb_parent && node == node->rb_parent->rb_left) node = node->rb_parent; return node->rb_parent; } void rb_replace_node(struct rb_node *victim, struct rb_node *newnode, struct rb_root *root) { struct rb_node *parent = victim->rb_parent; /* Set the surrounding nodes to point to the replacement */ if (parent) { if (victim == parent->rb_left) parent->rb_left = newnode; else parent->rb_right = newnode; } else { root->rb_node = newnode; } if (victim->rb_left) victim->rb_left->rb_parent = newnode; if (victim->rb_right) victim->rb_right->rb_parent = newnode; /* Copy the pointers/colour from the victim to the replacement */ *newnode = *victim; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/base/rbtree.h000066400000000000000000000104701520575453600260150ustar00rootroot00000000000000/* Red Black Trees (C) 1999 Andrea Arcangeli This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA linux/include/linux/rbtree.h To use rbtrees you'll have to implement your own insert and search cores. This will avoid us to use callbacks and to drop drammatically performances. I know it's not the cleaner way, but in C (not in C++) to get performances and genericity... Some example of insert and search follows here. The search is a plain normal search over an ordered tree. The insert instead must be implemented in two steps: First, the code must insert the element in order as a red leaf in the tree, and then the support library function rb_insert_color() must be called. Such function will do the not trivial work to rebalance the rbtree, if necessary. ----------------------------------------------------------------------- static inline struct page * rb_search_page_cache(struct inode * inode, unsigned long offset) { struct rb_node * n = inode->i_rb_page_cache.rb_node; struct page * page; while (n) { page = rb_entry(n, struct page, rb_page_cache); if (offset < page->offset) n = n->rb_left; else if (offset > page->offset) n = n->rb_right; else return page; } return NULL; } static inline struct page * __rb_insert_page_cache(struct inode * inode, unsigned long offset, struct rb_node * node) { struct rb_node ** p = &inode->i_rb_page_cache.rb_node; struct rb_node * parent = NULL; struct page * page; while (*p) { parent = *p; page = rb_entry(parent, struct page, rb_page_cache); if (offset < page->offset) p = &(*p)->rb_left; else if (offset > page->offset) p = &(*p)->rb_right; else return page; } rb_link_node(node, parent, p); return NULL; } static inline struct page * rb_insert_page_cache(struct inode * inode, unsigned long offset, struct rb_node * node) { struct page * ret; if ((ret = __rb_insert_page_cache(inode, offset, node))) goto out; rb_insert_color(node, &inode->i_rb_page_cache); out: return ret; } ----------------------------------------------------------------------- */ #ifndef _LINUX_RBTREE_H #define _LINUX_RBTREE_H struct rb_node { struct rb_node *rb_parent; struct rb_node *rb_right; struct rb_node *rb_left; char rb_color; #define RB_RED 0 #define RB_BLACK 1 }; struct rb_root { struct rb_node *rb_node; }; #define RB_ROOT (struct rb_root){ (struct rb_node *)0, } #define rb_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) #ifdef __cplusplus extern "C" { #endif void rb_insert_color(struct rb_node *node, struct rb_root *root); void rb_erase(struct rb_node *node, struct rb_root *root); /* Find logical next and previous nodes in a tree */ struct rb_node *rb_next(struct rb_node *); struct rb_node *rb_prev(struct rb_node *); struct rb_node *rb_first(struct rb_root *); struct rb_node *rb_last(struct rb_root *); /* Fast replacement of a single node without remove/rebalance/add/rebalance */ void rb_replace_node(struct rb_node *victim, struct rb_node *newnode, struct rb_root *root); #ifdef __cplusplus } #endif static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **link) { node->rb_parent = parent; node->rb_color = RB_RED; node->rb_left = node->rb_right = (struct rb_node *)0; *link = node; } #endif /* _LINUX_RBTREE_H */ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cert/000077500000000000000000000000001520575453600244025ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cert/cacert.pem000066400000000000000000006655251520575453600263710ustar00rootroot00000000000000## ## Bundle of CA Root Certificates ## ## Certificate data from Mozilla as of: Wed Aug 28 03:12:10 2019 GMT ## ## This is a bundle of X.509 certificates of public Certificate Authorities ## (CA). These were automatically extracted from Mozilla's root certificates ## file (certdata.txt). This file can be found in the mozilla source tree: ## https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt ## ## It contains the certificates in PEM format and therefore ## can be directly used with curl / libcurl / php_curl, or with ## an Apache+mod_ssl webserver for SSL client authentication. ## Just configure this file as the SSLCACertificateFile. ## ## Conversion done with mk-ca-bundle.pl version 1.27. ## SHA256: fffa309937c3be940649293f749b8207fabc6eb224e50e4bb3f2c5e44e0d6a6b ## GlobalSign Root CA ================== -----BEGIN CERTIFICATE----- MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== -----END CERTIFICATE----- GlobalSign Root CA - R2 ======================= -----BEGIN CERTIFICATE----- MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6 ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp 9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu 01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7 9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== -----END CERTIFICATE----- Verisign Class 3 Public Primary Certification Authority - G3 ============================================================ -----BEGIN CERTIFICATE----- MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaM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RGAvtiJuQijMfmhJAkWuXAwDQYJ KoZIhvcNAQEFBQADggEBADubj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPy T/4xmf3IDExoU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5bu/8j72gZyxKT J1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+bYQLCIt+jerXmCHG8+c8eS9e nNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/ErfF6adulZkMV8gzURZVE= -----END CERTIFICATE----- Baltimore CyberTrust Root ========================= -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9 XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5 hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp -----END CERTIFICATE----- AddTrust External Root ====================== -----BEGIN CERTIFICATE----- MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821 +iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy 2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7 7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355 e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= -----END CERTIFICATE----- Entrust Root Certification Authority ==================================== -----BEGIN CERTIFICATE----- MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAU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QWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4 d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2 mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm Mw== -----END CERTIFICATE----- GeoTrust Universal CA ===================== -----BEGIN CERTIFICATE----- MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1 MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjO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SN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2 DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI P/rmMuGNG2+k5o7Y+SlIis5z/iw= -----END CERTIFICATE----- GeoTrust Universal CA 2 ======================= -----BEGIN CERTIFICATE----- MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0 MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0 DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17 j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2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P9VhdBLtUp gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS -----END CERTIFICATE----- Comodo AAA Services root ======================== -----BEGIN CERTIFICATE----- MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMA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RpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6 tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi 5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi 5nrQNiOKSnQ2+Q== -----END CERTIFICATE----- QuoVadis Root CA 2 ================== -----BEGIN CERTIFICATE----- MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6 XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8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PRTUIZ3Ph1 WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II 4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8 VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u -----END CERTIFICATE----- QuoVadis Root CA 3 ================== -----BEGIN CERTIFICATE----- MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA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/yZlZ25w9Rl6VSDE1JUZU2 Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp 8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto= -----END CERTIFICATE----- Security Communication Root CA ============================== -----BEGIN CERTIFICATE----- MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw 8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX 5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2 JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g 0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ 6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi FL39vmwLAw== -----END CERTIFICATE----- Sonera Class 2 Root CA ====================== -----BEGIN CERTIFICATE----- MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3 /Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt 0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH llpwrN9M -----END CERTIFICATE----- XRamp Global CA Root ==================== -----BEGIN CERTIFICATE----- MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJp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Jbw= -----END CERTIFICATE----- Go Daddy Class 2 CA =================== -----BEGIN CERTIFICATE----- MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv 2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32 qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b vZ8= -----END CERTIFICATE----- Starfield Class 2 CA ==================== -----BEGIN CERTIFICATE----- MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3 QBFGmh95DmK/D5fs4C8fF5Q= -----END CERTIFICATE----- Taiwan GRCA =========== -----BEGIN CERTIFICATE----- MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7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prv4j9wabak2BegUqZIJxIZhm1AHlU D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk 7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy +fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS -----END CERTIFICATE----- DigiCert Assured ID Root CA =========================== -----BEGIN CERTIFICATE----- MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO 9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW /lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF 66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i 8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe +o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== -----END CERTIFICATE----- DigiCert Global Root CA ======================= -----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5 BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H 4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y 7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm 8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886 UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE----- DigiCert High Assurance EV Root CA ================================== -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs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wGXFK3xPkK mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K -----END CERTIFICATE----- Certplus Class 2 Primary CA =========================== -----BEGIN CERTIFICATE----- MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR 5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t L0NSTC9j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qtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ -----END CERTIFICATE----- SwissSign Gold CA - G2 ====================== -----BEGIN CERTIFICATE----- MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg vd21mWR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BIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ -----END CERTIFICATE----- SwissSign Silver CA - G2 ======================== -----BEGIN CERTIFICATE----- MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3 aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG 9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644 N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm +/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH 6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXP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+Ssuu WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u -----END CERTIFICATE----- GeoTrust Primary Certification Authority ======================================== -----BEGIN CERTIFICATE----- MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9 nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD AQH/MA4GA1UdDwEB/wQEAwIBBj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BDwAwggEKAoIBAQCs oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ 1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89 jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA== -----END CERTIFICATE----- VeriSign Class 3 Public Primary Certification Authority - G5 ============================================================ -----BEGIN CERTIFICATE----- MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNi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BAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g 8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi 0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+ OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5 3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW -----END CERTIFICATE----- COMODO Certification Authority ============================== -----BEGIN CERTIFICATE----- MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE BhMCR0Ix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8CP OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN +8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ== -----END CERTIFICATE----- Network Solutions Certificate Authority ======================================= -----BEGIN CERTIFICATE----- MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc /Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q 4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/ GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey -----END CERTIFICATE----- COMODO ECC Certification Authority ================================== -----BEGIN CERTIFICATE----- MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X 4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= -----END CERTIFICATE----- OISTE WISeKey Global Root GA CA =============================== -----BEGIN CERTIFICATE----- MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5 IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9 Nt350UlqaxBJH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oAPjPuCp1NJ70rOo4nI8 rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU Cm26OWMohpLzGITY+9HPBVZkVw== -----END CERTIFICATE----- Cybertrust Global Root ====================== -----BEGIN CERTIFICATE----- MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4 MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW 0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin 89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT 8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2 MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi 5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2 hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW WL1WMRJOEcgh4LMRkWXbtKaIOM5V -----END CERTIFICATE----- ePKI Root Certification Authority ================================= -----BEGIN CERTIFICATE----- MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYf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SbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8 SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0 x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD -----END CERTIFICATE----- GeoTrust Primary Certification Authority - G3 ============================================= -----BEGIN CERTIFICATE----- MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0 IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr 2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9 cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt -----END CERTIFICATE----- thawte Primary Root CA - G2 =========================== -----BEGIN CERTIFICATE----- MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5 8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== -----END CERTIFICATE----- thawte Primary Root CA - G3 =========================== -----BEGIN CERTIFICATE----- MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC +BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY 7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC 8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A= -----END CERTIFICATE----- GeoTrust Primary Certification Authority - G2 ============================================= -----BEGIN CERTIFICATE----- MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1 OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+ EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2 npaqBA+K -----END CERTIFICATE----- VeriSign Universal Root Certification Authority =============================================== -----BEGIN CERTIFICATE----- MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE BhMCVVMxF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GrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3 Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4 mJO37M2CYfE45k+XmCpajQ== -----END CERTIFICATE----- VeriSign Class 3 Public Primary Certification Authority - G4 ============================================================ -----BEGIN CERTIFICATE----- MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3 b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5 IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8 Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB /zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== -----END CERTIFICATE----- NetLock Arany (Class Gold) Főtanúsítvány ======================================== -----BEGIN CERTIFICATE----- MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610 dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwOD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jG4Kvte9nHfRCaexOYNkbQu dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= -----END CERTIFICATE----- Staat der Nederlanden Root CA - G2 ================================== -----BEGIN CERTIFICATE----- MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ 5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65 48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737 qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz +51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm 66+KAQ== -----END CERTIFICATE----- Hongkong Post Root CA 1 ======================= -----BEG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afU9hDDl3WY4JxHYB0yvbiAmvZWg== -----END CERTIFICATE----- SecureSign RootCA11 =================== -----BEGIN CERTIFICATE----- MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1 cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01 y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061 lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I= -----END CERTIFICATE----- Microsec e-Szigno Root CA 2009 ============================== -----BEGIN CERTIFICATE----- MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG 0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm 1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02 yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi LXpUq3DDfSJlgnCW -----END CERTIFICATE----- GlobalSign Root CA - R3 ======================= -----BEGIN CERTIFICATE----- MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ 0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3 rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2 xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7 lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8 EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18 YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r kpeDMdmztcpHWD9f -----END CERTIFICATE----- Autoridad de Certificacion Firmaprofesional CIF A62634068 ========================================================= -----BEGIN CERTIFICATE----- MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2 MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zl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AAx ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx 51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi 6Et8Vcad+qMUu2WFbm5PEn4KPJ2V -----END CERTIFICATE----- Izenpe.com ========== -----BEGIN CERTIFICATE----- MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ 03rKDx6sp4boFmVqscIbRTJx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vV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5 aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5 nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== -----END CERTIFICATE----- Chambers of Commerce Root - 2008 ================================ -----BEGIN CERTIFICATE----- MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaW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ERTIFICATE----- Global Chambersign Root - 2008 ============================== -----BEGIN CERTIFICATE----- MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0 ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB /gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3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pUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z 09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B -----END CERTIFICATE----- Go Daddy Root Certificate Authority - G2 ======================================== -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq 9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD +qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9 BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r 5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1 -----END CERTIFICATE----- Starfield Root Certificate Authority - G2 ========================================= -----BEGIN CERTIFICATE----- MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0 eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx 4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 -----END CERTIFICATE----- Starfield Services Root Certificate Authority - G2 ================================================== -----BEGIN CERTIFICATE----- MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMA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fdqlS5sdJ/PHLTy xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6 -----END CERTIFICATE----- AffirmTrust Commercial ====================== -----BEGIN CERTIFICATE----- MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6 BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv 0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= -----END CERTIFICATE----- AffirmTrust Networking ====================== -----BEGIN CERTIFICATE----- MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24 /PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV HQ4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ZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60 g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw== -----END CERTIFICATE----- AffirmTrust Premium ECC ======================= -----BEGIN CERTIFICATE----- MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X 57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM eQ== -----END CERTIFICATE----- Certum Trusted Network CA ========================= -----BEGIN CERTIFICATE----- MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTL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vi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI 03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= -----END CERTIFICATE----- TWCA Root Certification Authority ================================= -----BEGIN CERTIFICATE----- MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP 4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG 9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== -----END CERTIFICATE----- Security Communication RootCA2 ============================== -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++ +T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R 3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXd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t/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2 E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D 5EI= -----END CERTIFICATE----- Hellenic Academic and Research Institutions RootCA 2011 ======================================================= -----BEGIN CERTIFICATE----- MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNVBAoT O0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9y aXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z IFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYT AkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z IENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNo IEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB AKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPzdYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI 1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa 71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u 8yBRQlqD75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSPFEDH 3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNVHRMBAf8EBTADAQH/ MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp5dgTBCPuQSUwRwYDVR0eBEAwPqA8 MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQub3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQu b3JnMA0GCSqGSIb3DQEBBQUAA4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVt XdMiKahsog2p6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7dIsXRSZMFpGD /md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8AcysNnq/onN694/BtZqhFLKPM58N 7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXIl7WdmplNsDz4SgCbZN2fOUvRJ9e4 -----END CERTIFICATE----- Actalis Authentication Root CA ============================== -----BEGIN CERTIFICATE----- MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQxDjAM BgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UE AwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDky MjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlz IFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 IENBMIICIjANBgkqhkiG9w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2avl4VSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+ Xlff1ANATIGk0k9jpwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC 4yyXX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+OkfcvHlXHo 2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7RK4X9p2jIugErsWx0Hbhz lefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btUZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXem OR/qnuOf0GZvBeyqdn6/axag67XH/JJULysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9 vwGYT7JZVEc+NHt4bVaTLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== -----END CERTIFICATE----- Trustis FPS Root CA =================== -----BEGIN CERTIFICATE----- MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQG EwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQLExNUcnVzdGlzIEZQUyBSb290 IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTExMzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNV BAoTD1RydXN0aXMgTGltaXRlZDEcMBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQ RUN+AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihHiTHcDnlk H5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjjvSkCqPoc4Vu5g6hBSLw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M/crqJIByw5c/8nerQyIKx+u2DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWD LfJ6v9r9jv6ly0UsH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0 oyLQI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK75t98biGC wWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h3PFaTWwyI0PurKju7koS CTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPzY11aWOIv4x3kqdbQCtCev9eBCfHJxyYN rJgWVqA= -----END CERTIFICATE----- Buypass Class 3 Root CA ======================= -----BEGIN CERTIFICATE----- MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMyBSb290IENBMB4X DTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFowTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIw DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRH sJ8YZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3EN3coTRiR 5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9tznDDgFHmV0ST9tD+leh 7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX0DJq1l1sDPGzbjniazEuOQAnFN44wOwZ ZoYS6J1yFhNkUsepNxz9gjDthB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Vp9D0VzgalLA8+9oG6lLvDu79leNKGef9JOxqDDPDe eOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq4/g7u9xN12TyUb7mqqta6THuBrxzvxNi Cp/HuZc= -----END CERTIFICATE----- T-TeleSec GlobalRoot Class 3 ============================ -----BEGIN CERTIFICATE----- MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgx MDAxMTAyOTU2WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN8ELg63iIVl6bmlQdTQyK 9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/RLyTPWGrTs0NvvAgJ1gORH8EGoel15YU NpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZF iP0Zf3WHHx+xGwpzJFu5ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W 0eDrXltMEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGjQjBA MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1A/d2O2GCahKqGFPr AyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOyWL6ukK2YJ5f+AbGwUgC4TeQbIXQb fsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzT ucpH9sry9uetuUg/vBa3wW306gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7h P0HHRwA11fXT91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4pTpPDpFQUWw== -----END CERTIFICATE----- EE Certification Centre Root CA =============================== -----BEGIN CERTIFICATE----- MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEoMCYGA1UEAwwfRUUgQ2Vy dGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIw MTAxMDMwMTAxMDMwWhgPMjAzMDEyMTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlB UyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRy ZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUyeuuOF0+W2Ap7kaJjbMeM TC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvObntl8jixwKIy72KyaOBhU8E2lf/slLo2 rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw 93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtN P2MbRMNE1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0T AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZ MEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEF BQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+Rj xY6hUFaTlrg4wCQiZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqM lIpPnTX/dqQGE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU 3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM dcGWxZ0= -----END CERTIFICATE----- D-TRUST Root Class 3 CA 2 2009 ============================== -----BEGIN CERTIFICATE----- MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTAe Fw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NThaME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxE LVRydX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fGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8PIWmawomDeCTmGCufsYkl4ph X5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3YJohw1+qRzT65ysCQblrGXnRl11z+o+I= -----END CERTIFICATE----- D-TRUST Root Class 3 CA 2 EV 2009 ================================= -----BEGIN CERTIFICATE----- MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw OTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUwNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfS egpnljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM03TP1YtHh zRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6ZqQTMFexgaDbtCHu39b+T 7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lRp75mpoo6Kr3HGrHhFPC+Oh25z1uxav60 sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure35 11H3a6UCAwEAAaOCASQwggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyv cop9NteaHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFwOi8v ZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQ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6g cFGn90xHNcgL1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WFH6vPNOw/KP4M 8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNoRI2T9GRwoD2dKAXDOXC4Ynsg /eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlg lPx4mI88k1HtQJAH32RjJMtOcQWh15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryP A9gK8kxkRr05YuWW6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3m i4TWnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5jwa19hAM8 EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWzaGHQRiapIVJpLesux+t3 zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmyKwbQBM0= -----END CERTIFICATE----- TeliaSonera Root CA v1 ====================== -----BEGIN CERTIFICATE----- MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAwNzEUMBIGA1UE CgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJvb3QgQ0EgdjEwHhcNMDcxMDE4 MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYDVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwW VGVsaWFTb25lcmEgUm9vdCBDQSB2MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+ 6yfwIaPzaSZVfp3FVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnw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pYxmUKeFfyxiMPAdkgS94P+5KFdSpc c41teyWRyu5FrgZLAMzTsVlQ2jqIOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOT JsjrDNYmiLbAJM+7vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2 qReWt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcnHL/EVlP6 Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVxSK236thZiNSQvxaz2ems WWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= -----END CERTIFICATE----- E-Tugra Certification Authority =============================== -----BEGIN CERTIFICATE----- MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNVBAYTAlRSMQ8w DQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamls ZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMw NTEyMDk0OFoXDTIzMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmEx QDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxl cmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQD DB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A MIICCgKCAgEA4vU/kwVRHoViVF56C/UYB4Oufq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u8W1Ki/QY3OEBhj0qWuJA3+GbHeJAAFS6LrVE1Uweo a2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WKvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCc dlqMQ1DujjByTd//SffGqWfZbawCEeI6FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEV KV0jq9BgoRJP3vQXzTLlyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gT Dx4JnW2PAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpDy4Q0 8ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8dNL/+I5c30jn6PQ0G C7TbO6Orb1wdtn7os4I07QZcJA== -----END CERTIFICATE----- T-TeleSec GlobalRoot Class 2 ============================ -----BEGIN CERTIFICATE----- MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgx MDAxMTA0MDE0WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUdAqSzm1nzHoqvNK38DcLZ SBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiCFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/F vudocP05l03Sx5iRUKrERLMjfTlH6VJi1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx970 2cu+fjOlbpSD8DT6IavqjnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGV WOHAD3bZwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGjQjBA MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/WSA2AHmgoCJrjNXy YdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhyNsZt+U2e+iKo4YFWz827n+qrkRk4 r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPACuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNf vNoBYimipidx5joifsFvHZVwIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR 3p1m0IvVVGb6g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN 9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlPBSeOE6Fuwg== -----END CERTIFICATE----- Atos TrustedRoot 2011 ===================== -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UEAwwVQXRvcyBU cnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0xMTA3MDcxNDU4 MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsG A1UECgwEQXRvczELMAkGA1UEBhMCREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwA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yt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2cDMT/uFPpiN3 GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUNqXsCHKnQO18LwIE6PWThv6ct Tr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP +V04ikkwj+3x6xn0dxoxGE1nVGwvb2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh 3jRJjehZrJ3ydlo28hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fa wx/kNSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNjZgKAvQU6 O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhpq1467HxpvMc7hU6eFbm0 FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFtnh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOV hMJKzRwuJIczYOXD -----END CERTIFICATE----- QuoVadis Root CA 2 G3 ===================== -----BEGIN CERTIFICATE----- MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQELBQAwSDELMAkG A1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAcBgNVBAMTFVF1b1ZhZGlzIFJv b3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJN MRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIg RzMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQChriW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2vd+DhcI00iX 0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HNPlopNLk9hM6xZdRZkZFW dSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ywaZWWDYWGWVjUTR939+J399roD1B0y2 PpxxVJkES/1Y+Zj0 -----END CERTIFICATE----- DigiCert Assured ID Root G2 =========================== -----BEGIN CERTIFICATE----- MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgw MTE1MTIwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSAn61UQbVH 35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4HteccbiJVMWWXvdMX0h5i89vq bFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9HpEgjAALAcKxHad3A2m67OeYfcgnDmCXRw VWmvo2ifv922ebPynXApVfSr/5Vh88lAbx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OP YLfykqGxvYmJHzDNw6YuYjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+Rn lTGNAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBTO w0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPIQW5pJ6d1Ee88hjZv 0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I0jJmwYrA8y8678Dj1JGG0VDjA9tz d29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4GnilmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAW hsI6yLETcDbYz+70CjTVW0z9B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0M jomZmWzwPDCvON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo IhNzbM8m9Yop5w== -----END CERTIFICATE----- DigiCert Assured ID Root G3 =========================== -----BEGIN CERTIFICATE----- MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQswCQYDVQQGEwJV UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYD VQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1 MTIwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQ BgcqhkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJfZn4f5dwb RXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17QRSAPWXYQ1qAk8C3eNvJs KTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgF UaFNN6KDec6NHSrkhDAKBggqhkjOPQQDAwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5Fy YZ5eEJJZVrmDxxDnOOlYJjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy 1vUhZscv6pZjamVFkpUBtA== -----END CERTIFICATE----- DigiCert Global Root G2 ======================= -----BEGIN CERTIFICATE----- MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUx MjAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkq hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI2/Ou8jqJ kTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx1x7e/dfgy5SDN67sH0NO 3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQq2EGnI/yuum06ZIya7XzV+hdG82MHauV BJVJ8zUtluNJbd134/tJS7SsVQepj5WztCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyM UNGPHgm+F6HmIcr9g+UQvIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQAB o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV5uNu 5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY1Yl9PMWLSn/pvtsr F9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4NeF22d+mQrvHRAiGfzZ0JFrabA0U WTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NGFdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBH QRFXGU7Aj64GxJUTFy8bJZ918rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/ iyK5S9kJRaTepLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl MrY= -----END CERTIFICATE----- DigiCert Global Root G3 ======================= -----BEGIN CERTIFICATE----- MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQswCQYDVQQGEwJV UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAwHgYD VQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAw MDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5k aWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0C AQYFK4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FGfp4tn+6O YwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPOZ9wj/wMco+I+o0IwQDAP BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNp Yim8S8YwCgYIKoZIzj0EAwMDaAAwZQIxAK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y 3maTD/HMsQmP3Wyr+mt/oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34 VOKa5Vt8sycX -----END CERTIFICATE----- DigiCert Trusted Root G4 ======================== -----BEGIN CERTIFICATE----- MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBiMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSEw HwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1 MTIwMDAwWjBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0G CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3yithZwuEp pz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1Ifxp4VpX6+n6lXFllVcq9o k3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDVySAdYyktzuxeTsiT+CFhmzTrBcZe7Fsa vOvJz82sNEBfsXpm7nfISKhmV1efVFiODCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGY QJB5w3jHtrHEtWoYOAMQjdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6 MUSaM0C/CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCiEhtm mnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6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UGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+C GCe01a60y1Dma/RMhnEw6abfFobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5 WdYgGq/yapiqcrxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w DQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvlwFTPoCWOAvn9sKIN9SCYPBMt rFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+ nq6PK7o9mfjYcwlYRm6mnPTXJ9OV2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSg tZx8jb8uk2IntznaFxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwW sRqZCuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiKboHGhfKp pC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmckejkk9u+UJueBPSZI9FoJA zMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yLS0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHq ZJx64SIDqZxubw5lT2yHh17zbqD5daWbQOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk52 7RH89elWsn2/x20Kk4yl0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7I LaZRfyHBNVOFBkpdn627G190 -----END CERTIFICATE----- USERTrust RSA Certification Authority ===================================== -----BEGIN CERTIFICATE----- MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhki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tPAlR1n6BB6T1CZGSlCBst6+ eLf8ZxXhyVeEHg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF MAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPFUp/L+M+ZBn8b2kMVn54CVVeW FPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KOVWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ 7l8wXEskEVX/JJpuXior7gtNn3/3ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQ Eg9zKC7F4iRO/Fjs8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM 8WcRiQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYzeSf7dNXGi FSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZXHlKYC6SQK5MNyosycdi yA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9c J2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRBVXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGw sAvgnEzDHNb842m1R0aBL6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gx Q+6IHdfGjjxDah2nGN59PRbxYvnKkKj9 -----END CERTIFICATE----- USERTrust ECC Certification Authority ===================================== -----BEGIN CERTIFICATE----- MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDELMAkGA1UEBhMC VVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASB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AAwZQIxAOVpEslu28Yx uglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7 yFz9SO8NdCKoCOJuxUnOxwy8p2Fp8fc74SrL+SvzZpA3 -----END CERTIFICATE----- Staat der Nederlanden Root CA - G3 ================================== -----BEGIN CERTIFICATE----- MIIFdDCCA1ygAwIBAgIEAJiiOTANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g Um9vdCBDQSAtIEczMB4XDTEzMTExNDExMjg0MloXDTI4MTExMzIzMDAwMFowWjELMAkGA1UEBhMC TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAL4y olQPcPssXFnrbMSkUeiFKrPMSjTysF/zDsccPVMeiAho2G89rcKezIJnByeHaHE6n3WWIkYFsO2t x1ueKt6c/DrGlaf1F2cY5y9JCAxcz+bMNO14+1Cx3Gsy8KL+tjzk7FqXxz8ecAgwoNzFs21v0IJy EavSgWhZghe3eJJg+szeP4TrjTgzkApyI/o1zCZxMdFyKJLZWyNtZrVtB0LrpjPOktvA9mxjeM3K Tj215VKb8b475lRgsGYeCasH/lSJEULR9yS6YHgamPfJEf0WwTUaVHXvQ9Plrk7O53vDxk5hUUur mkVLoR9BvUhTFXFkC4az5S6+zqQbwSmEorXLCCN2QyIkHxcE1G6cxvx/K2Ya7Irl1s9N9WMJtxU5 1nus6+N86U78dULI7ViVDAZCopz35HCz33JvWjdAidiFpNfxC95DGdRKWCyMijmev4SH8RY7Ngzp 07TKbBlBUgmhHbBqv4LvcFEhMtwFdozL92TkA1CvjJFnq8Xy7ljY3r735zHPbMk7ccHViLVlvMDo FxcHErVc0qsgk7TmgoNwNsXNo42ti+yjwUOH5kPiNL6VizXtBznaqB16nzaeErAMZRKQFWDZJkBE 41ZgpRDUajz9QdwOWke275dhdU/Z/seyHdTtXUmzqWrLZoQT1Vyg3N9udwbRcXXIV2+vD3dbAgMB AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRUrfrHkleu yjWcLhL75LpdINyUVzANBgkqhkiG9w0BAQsFAAOCAgEAMJmdBTLIXg47mAE6iqTnB/d6+Oea31BD U5cqPco8R5gu4RV78ZLzYdqQJRZlwJ9UXQ4DO1t3ApyEtg2YXzTdO2PCwyiBwpwpLiniyMMB8jPq KqrMCQj3ZWfGzd/TtiunvczRDnBfuCPRy5FOCvTIeuXZYzbB1N/8Ipf3YF3qKS9Ysr1YvY2WTxB1 v0h7PVGHoTx0IsL8B3+A3MSs/mrBcDCw6Y5p4ixpgZQJut3+TcCDjJRYwEYgr5wfAvg1VUkvRtTA 8KCWAg8zxXHzniN9lLf9OtMJgwYh/WA9rjLA0u6NpvDntIJ8CsxwyXmA+P5M9zWEGYox+wrZ13+b 8KKaa8MFSu1BYBQw0aoRQm7TIwIEC8Zl3d1Sd9qBa7Ko+gE4uZbqKmxnl4mUnrzhVNXkanjvSr0r mj1AfsbAddJu+2gw7OyLnflJNZoaLNmzlTnVHpL3prllL+U9bTpITAjc5CgSKL59NVzq4BZ+Extq 1z7XnvwtdbLBFNUjA9tbbws+eC8N3jONFrdI54OagQ97wUNNVQQXOEpR1VmiiXTTn74eS9fGbbeI JG9gkaSChVtWQbzQRKtqE77RLFi3EjNYsjdj3BP1lB0/QFH1T/U67cjF68IeHRaVesd+QnGTbksV tzDfqu1XhUisHWrdOWnk4Xl4vs4Fv6EM94B7IWcnMFk= -----END CERTIFICATE----- Staat der Nederlanden EV Root CA ================================ -----BEGIN CERTIFICATE----- MIIFcDCCA1igAwIBAgIEA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BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFP6rAJCYniT8qcwa ivsnuL8wbqg7MA0GCSqGSIb3DQEBCwUAA4ICAQDPdyxuVr5Os7aEAJSrR8kN0nbHhp8dB9O2tLsI eK9p0gtJ3jPFrK3CiAJ9Brc1AsFgyb/E6JTe1NOpEyVa/m6irn0F3H3zbPB+po3u2dfOWBfoqSmu c0iH55vKbimhZF8ZE/euBhD/UcabTVUlT5OZEAFTdfETzsemQUHSv4ilf0X8rLiltTMMgsT7B/Zq 5SWEXwbKwYY5EdtYzXc7LMJMD16a4/CrPmEbUCTCwPTxGfARKbalGAKb12NMcIxHowNDXLldRqAN b/9Zjr7dn3LDWyvfjFvO5QxGbJKyCqNMVEIYFRIYvdr8unRu/8G2oGTYqV9Vrp9canaW2HNnh/tN f1zuacpzEPuKqf2evTY4SUmH9A4U8OmHuD+nT3pajnnUk+S7aFKErGzp85hwVXIy+TSrK0m1zSBi 5Dp6Z2Orltxtrpfs/J92VoguZs9btsmksNcFuuEnL5O7Jiqik7Ab846+HUCjuTaPPoIaGl6I6lD4 WeKDRikL40Rc4ZW2aZCaFG+XroHPaO+Zmr615+F/+PoTRxZMzG0IQOeLeG9QgkRQP2YGiqtDhFZK DyAthg710tvSeopLzaXoTvFeJiUBWSOgftL2fiFX1ye8FVdMpEbB4IMeDExNH08GGeL5qPQ6gqGy eUN51q1veieQA6TqJIc/2b3Z6fJfUEkc7uzXLg== -----END CERTIFICATE----- IdenTrust Commercial Root CA 1 ============================== -----BEGIN CERTIFICATE----- MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBKMQswCQYDVQQG EwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBS b290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQwMTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzES MBAG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eKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93nAbowacYXVKV7cndJZ5t+qnt ozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmV YjzlVYA211QC//G5Xc7UI2/YRYRKW2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUX feu+h1sXIFRRk0pTAwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/ro kTLql1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG4iZZRHUe 2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZmUlO+KWA2yUPHGNiiskz Z2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7R cGzM7vRX+Bi6hG6H -----END CERTIFICATE----- IdenTrust Public Sector Root CA 1 ================================= -----BEGIN CERTIFICATE----- MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBNMQswCQYDVQQG EwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3Rv ciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcNMzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJV UzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBS b290IENBIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTy P4o7ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGyRBb06tD6 Hi9e28tzQa68ALBKK0CyrO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rEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4 Mhn5+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJtshquDDI ajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhAGaQdp/lLQzfcaFpPz+vC ZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ 3Wl9af0AVqW3rLatt8o+Ae+c -----END CERTIFICATE----- Entrust Root Certification Authority - G2 ========================================= -----BEGIN CERTIFICATE----- MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMCVVMxFjAUBgNV BAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVy bXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ug b25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIw HhcNMDkwNzA3MTcyNTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoT DUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMx OTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25s eTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwggEi MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP /vaCeb9zYQYKpSfYs1/TRU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXz HHfV1IWNcCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hWwcKU s/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1U1+cPvQXLOZprE4y TGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0jaWvYkxN4FisZDQSA/i2jZRjJKRx AgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ6 0B7vfec7aVHUbI2fkBJmqzANBgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5Z iXMRrEPR9RP/jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v1fN2D807iDgi nWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4RnAuknZoh8/CbCzB428Hch0P+ vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmHVHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xO e4pIb4tF9g== -----END CERTIFICATE----- Entrust Root Certification Authority - EC1 ========================================== -----BEGIN CERTIFICATE----- MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkGA1UEBhMCVVMx FjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVn YWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXpl ZCB1c2Ugb25seTEzMDEGA1UEAxMqRW50cnVzdCBSb290IENlcnRpZmljYXRpb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UqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBSESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sG E5uPhnEFtC+NiWYzKXZUmhH4J/qyP5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfX BDrDMlI1Dlb4pd19xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjn aH9dCi77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN5mydLIhy PDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe/v5WOaHIz16eGWRGENoX kbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+ZAAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3C ekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su -----END CERTIFICATE----- OISTE WISeKey Global Root GB CA =============================== -----BEGIN CERTIFICATE----- MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBtMQswCQYDVQQG EwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNl ZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAw MzJaFw0zOTEyMDExNTEwMzFaMG0xCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYD VQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEds b2JhbCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3HEokKtaX scriHvt9OO+Y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MFExCzAJ BgNVBAYTAlBMMSgwJgYDVQQKDB9LcmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYD VQQDDA9TWkFGSVIgUk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5Q qEvNQLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT3PSQ1hNK DJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw3gAeqDRHu5rr/gsUvTaE 2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr63fE9biCloBK0TXC5ztdyO4mTp4CEHCdJ ckm1/zuVnsHMyAHs6A6KCpbns6aH5db5BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwi ieDhZNRnvDF5YTy7ykHNXGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0P AQH/BAQDAgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsFAAOC AQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw8PRBEew/R40/cof5 O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOGnXkZ7/e7DDWQw4rtTw/1zBLZpD67 oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCPoky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul 4+vJhaAlIDf7js4MNIThPIGyd05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6 +/NNIxuZMzSgLvWpCz/UXeHPhJ/iGcJfitYgHuNztw== -----END CERTIFICATE----- Certum Trusted Network CA 2 =========================== -----BEGIN CERTIFICATE----- MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgk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jW/jAux9JG9uWOdf3yzLnQh1vM BhBgu4M1t15n3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZI hvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQF/xlhMcQSZDe28cmk4gmb3DW Al45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTfCVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuA L55MYIR4PSFk1vtBHxgP58l1cb29XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMo clm2q8KMZiYcdywmdjWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tM pkT/WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jbAoJnwTnb w3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksqP/ujmv5zMnHCnsZy4Ypo J/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Kob7a6bINDd82Kkhehnlt4Fj1F4jNy3eFm ypnTycUm/Q1oBEauttmbjL4ZvrHG8hnjXALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLX is7VmFxWlgPF7ncGNf/P5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7 zAYspsbiDrW5viSP -----END CERTIFICATE----- Hellenic Academic and Research Institutions RootCA 2015 ======================================================= -----BEGIN CERTIFICATE----- MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1IxDzANBgNVBAcT BkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmN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ZSRm2Ekax+0VVFqmjZayc Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNVHRMBAf8EBTAD AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVdctA4GGqd83EkVAswDQYJKoZI hvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0IXtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+ D1hYc2Ryx+hFjtyp8iY/xnmMsVMIM4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrM d/K4kPFox/la/vot9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+y d+2VZ5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/eaj8GsGsVn 82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnhX9izjFk0WaSrT2y7Hxjb davYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQl033DlZdwJVqwjbDG2jJ9SrcR5q+ss7F Jej6A7na+RZukYT1HCjI/CbM1xyQVqdfbzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVt J94Cj8rDtSvK6evIIVM4pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGa JI7ZjnHKe7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0vm9q p/UsQu0yrbYhnr68 -----END CERTIFICATE----- Hellenic Academic and Research Institutions ECC RootCA 2015 =========================================================== -----BEGIN CERTIFICATE----- MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzANBgNVBAcTBkF0 aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k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cK2NJpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW +YJF1DngoABd15jmfZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7 Ixjp6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp1txyM/1d 8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B9kiABdcPUXmsEKvU7ANm 5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wokRqEIr9baRRmW1FMdW4R58MD3R++Lj8UG rp1MYp3/RgT408m2ECVAdf4WqslKYIYvuu8wd+RU4riEmViAqhOLUTpPSPaLtrM= -----END CERTIFICATE----- Amazon Root CA 1 ================ -----BEGIN CERTIFICATE----- MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsFADA5MQswCQYD VQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSAxMB4XDTE1 MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpv bjEZMBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBALJ4gHHKeNXjca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgH FzZM9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qwIFAGbHrQ gLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6VOujw5H5SNz/0egwLX0t dHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L93FcXmn/6pUCyziKrlA4b9v7LWIbxcce VOF34GfID5y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kr5v2c69BoV Yh63n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE76KlXIx3 KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H9jVlpNMKVv/1F2Rs76gi JUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT4PsJYGw= -----END CERTIFICATE----- Amazon Root CA 3 ================ -----BEGIN CERTIFICATE----- MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5MQswCQYDVQQG EwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSAzMB4XDTE1MDUy NjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZ MBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZB f8ANm+gBG1bG8lKlui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjr Zt6jQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSrttvXBp43 rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkrBqWTrBqYaGFy+uGh0Psc eGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteMYyRIHN8wfdVoOw== -----END CERTIFICATE----- Amazon Root CA 4 ================ -----BEGIN CERTIFICATE----- MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5MQswCQYDVQQG EwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSA0MB4XDTE1MDUy NjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZ MBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN /sGKe0uoe0ZLY7Bi9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri 83BkM6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV HQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WBMAoGCCqGSM49BAMDA2gA MGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlwCkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1 AE47xDqUEpHJWEadIRNyp4iciuRMStuW1KyLa2tJElMzrdfkviT8tQp21KW8EA== -----END CERTIFICATE----- LuxTrust Global Root 2 ====================== -----BEGIN CERTIFICATE----- MIIFwzCCA6ugAwIBAgIUCn6m30tEntpqJIWe5rgV0xZ/u7EwDQYJKoZIhvcNAQELBQAwRjELMAkG A1UEBhMCTFUxFjAUBgNVBAoMDUx1eFRydXN0IFMuQS4xHzAdBgNVBAMMFkx1eFRydXN0IEdsb2Jh bCBSb290IDIwHhcNMTUwMzA1MTMyMTU3WhcNMzUwMzA1MTMyMTU3WjBGMQswCQYDVQQGEwJMVTEW MBQGA1UECgwNTHV4VHJ1c3QgUy5BLjEfMB0GA1UEAwwWTHV4VHJ1c3QgR2xvYmFsIFJvb3QgMjCC AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANeFl78RmOnwYoNMPIf5U2o3C/IPPIfOb9wm Kb3FibrJgz337spbxm1Jc7TJRqMbNBM/wYlFV/TZsfs2ZUv7COJIcRHIbjuend+JZTemhfY7RBi2 xjcwYkSSl2l9QjAk5A0MiWtj3sXh306pFGxT4GHO9hcvHTy95iJMHZP1EMShdu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xDVbYQw8wkbIEa91WvpWA VWe+2M2D2RjuLg+GLZKecBPs3lHJQ3gCpU3I+V/EkVhGFndadKpAvAefMLmx9xIX3eP/JEAdemrR TxgKqpAd60Ae36EeRJIQmvKN4dFLRp7oRUKX6kWZ8+xm1QL68qZKJKrezrnK+T+Tb/mjuuqlPpmt /f97mfVl7vBZKGfXkJWkE4SphMHozs51k2MavDzq1WQfLSoSOcbDWjLtR5EWDrw4wVDej8oqkDQc 7kGUnF4ZLvhFSZl0kbAEb+MEWrGrKqv+x9CWttrhSmQGbmBNvUJO/3jaJMobtNeWOWyu8Q6qp31I iyBMz2TWuJdGsE7RKlY6oJO9r4Ak4Ap+58rVyuiFVdw2KuGUaJPHZnJED4AhMmwlxyOAgwrr -----END CERTIFICATE----- TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 ============================================= -----BEGIN CERTIFICATE----- MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIxGDAWBgNVBAcT D0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxpbXNlbCB2ZSBUZWtub2xvamlr IEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0wKwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24g TWVya2V6aSAtIEthbXUgU00xNjA0BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRp ZmlrYXNpIC0gU3VydW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYD VQQGEwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXllIEJpbGlt c2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklUQUsxLTArBgNVBAsTJEth bXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBTTTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11 IFNNIFNTTCBLb2sgU2VydGlmaWthc2kgLSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAr3UwM6q7a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y8 6Ij5iySrLqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INrN3wc wv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2XYacQuFWQfw4tJzh0 3+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/iSIzL+aFCr2lqBs23tPcLG07xxO9 WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4fAJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQU ZT/HiobGPN08VFw1+DrtUgxHV8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJ KoZIhvcNAQELBQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPfIPP54+M638yc lNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4lzwDGrpDxpa5RXI4s6ehlj2R e37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0j q5Rm+K37DwhuJi1/FwcJsoz7UMCflo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= -----END CERTIFICATE----- GDCA TrustAUTH R5 ROOT ====================== -----BEGIN CERTIFICATE----- MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UEBhMCQ04xMjAw BgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSU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zkX2woloPV+g7zPIlstR8L+xNxqE6FXrntl019fZISjZFZtS6mFjBAgMBAAGj YzBhMB0GA1UdDgQWBBREnkj1zG1I1KBLf/5ZJC+Dl5mahjAfBgNVHSMEGDAWgBREnkj1zG1I1KBL f/5ZJC+Dl5mahjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF AAOCAQEABT41XBVwm8nHc2FvcivUwo/yQ10CzsSUuZQRg2dd4mdsdXa/uwyqNsatR5Nj3B5+1t4u /ukZMjgDfxT2AHMsWbEhBuH7rBiVDKP/mZb3Kyeb1STMHd3BOuCYRLDE5D53sXOpZCz2HAF8P11F hcCF5yWPldwX8zyfGm6wyuMdKulMY/okYWLW2n62HGz1Ah3UKt1VkOsqEUc8Ll50soIipX1TH0Xs J5F95yIW6MBoNtjG8U+ARDL54dHRHareqKucBK+tIA5kmE2la8BIWJZpTdwHjFGTot+fDz2LYLSC jaoITmJF4PkL0uDgPFveXHEnJcLmA4GLEFPjx1WitJ/X5g== -----END CERTIFICATE----- SSL.com Root Certification Authority RSA ======================================== -----BEGIN CERTIFICATE----- MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UEBhMCVVMxDjAM BgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24x MTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYw MjEyMTczOTM5WhcNNDEwMjEyMTczOTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMx EDAOBgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NM LmNvbSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcNAQE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RfSda/wZY52jvATGGAsl u1OJD7OAUN5F7kR/q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjq erQ0cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jra6x+3uxj MxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90IH37hVZkLId6Tngr75qNJ vTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/YK9f1JmzJBjSWFupwWRoyeXkLtoh/D1JI Pb9s2KJELtFOt3JY04kTlf5Eq/jXixtunLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406y wKBjYZC6VWg3dGq2ktufoYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NI WuuA8ShYIc2wBlX7Jz9TkHCpBB5XJ7k= -----END CERTIFICATE----- SSL.com Root Certification Authority ECC ======================================== -----BEGIN CERTIFICATE----- MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMCVVMxDjAMBgNV BAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24xMTAv BgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEy MTgxNDAzWhcNNDEwMjEyMTgxNDAzWjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAO BgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuBBAAiA2IA BEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI7Z4INcgn64mMU1jrYor+ 8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPgCemB+vNH06NjMGEwHQYDVR0OBBYEFILR hXMw5zUE044CkvvlpNHEIejNMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTT jgKS++Wk0cQh6M0wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCW e+0F+S8Tkdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+gA0z 5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl -----END CERTIFICATE----- SSL.com EV Root Certification Authority RSA R2 ============================================== -----BEGIN CERTIFICATE----- MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNVBAYTAlVTMQ4w DAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9u MTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy MB4XDTE3MDUzMTE4MTQzN1oXDTQyMDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI DAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYD VQQDDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMIICIjAN BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvqM0fNTPl9fb69LT3w23jh hqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssufOePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7w cXHswxzpY6IXFJ3vG2fThVUCA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KsRspGPKAcTNZEtF4uXBVmCeEmKf7GUmG6sXP/wwyc5Wxq lD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKKQbNmC1r7fSOl8hqw/96bg5Qu0T/fkreR rwU7ZcegbLHNYhLDkBvjJc40vG93drEQw/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1 hlMYegouCRw2n5H9gooiS9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX 9hwJ1C07mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== -----END CERTIFICATE----- SSL.com EV Root Certification Authority ECC =========================================== -----BEGIN CERTIFICATE----- MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMCVVMxDjAMBgNV BAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24xNDAy BgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYw MjEyMTgxNTIzWhcNNDEwMjEyMTgxNTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMx EDAOBgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NM LmNvbSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB BAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMAVIbc/R/fALhBYlzccBYy 3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1KthkuWnBaBu2+8KGwytAJKaNjMGEwHQYDVR0O BBYEFFvKXuXe0oGqzagtZFG22XKbl+ZPMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe 5d7SgarNqC1kUbbZcpuX5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJ N+vp1RPZytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZgh5Mm m7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== -----END CERTIFICATE----- GlobalSign Root CA - R6 ======================= -----BEGIN CERTIFICATE----- MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEgMB4GA1UECxMX R2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkds b2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQxMjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9i YWxTaWduIFJvb3QgQ0EgLSBSNjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs U2lnbjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQss grRIxutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1kZguSgMpE 3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxDaNc9PIrFsmbVkJq3MQbF vuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJwLnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqM PKq0pPbzlUoSB239jLKJz9CgYXfIWHSw1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+ azayOeSsJDa38O+2HBNXk7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05O WgtH8wY2SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/hbgu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global Root GC CA =============================== -----BEGIN CERTIFICATE----- MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQswCQYDVQQGEwJD SDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEo MCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRa Fw00MjA1MDkwOTU4MzNaMG0xCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQL ExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh bCBSb290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4nieUqjFqdr VCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4Wp2OQ0jnUsYd4XxiWD1Ab NTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAd BgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7TrYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0E AwMDaAAwZQIwJsdpW9zV57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtk AjEA2zQgMgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 -----END CERTIFICATE----- GTS Root R1 =========== -----BEGIN CERTIFICATE----- MIIFWjCCA0KgAwIBAgIQbkepxUtHDA3sM9CJuRz04TANBgkqhkiG9w0BAQwFADBHMQswCQYDVQQG EwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJv b3QgUjE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KaOOpMQkpAWBz40d8U6iQSifvS9efk+eCNs6aaAyC58/UEBZvXw6ZXPYfcX3v73sv fuo21pdwCxXu11xWajOl40k4DLh9+42FpLFZXvRq4d2h9mREruZRgyFmxhE+885H7pwoHyXa/6xm ld01D1zvICxi/ZG6qcz8WpyTgYMpl0p8WnK0OdC3d8t5/Wk6kjftbjhlRn7pYL15iJdfOBL07q9b gsiG1eGZbYwE8na6SfZu6W0eX6DvJ4J2QPim01hcDyxC2kLGe4g0x8HYRZvBPsVhHdljUEn2NIVq 4BjFbkerQUIpm/ZgDdIx02OYI5NaAIFItO/Nis3Jz5nu2Z6qNuFoS3FJFDYoOj0dzpqPJeaAcWEr tXvM+SUWgeExX6GjfhaknBZqlxi9dnKlC54dNuYvoS++cJEPqOba+MSSQGwlfnuzCdyyF62ARPBo pY+Udf90WuioAnwMCeKpSwughQtiue+hMZL77/ZRBIls6Kl0obsXs7X9SQ98POyDGCBDTtWTurQ0 sR8WNh8M5mQ5Fkzc4P4dyKliPUDqysU0ArSuiYgzNdwsE3PYJ/HQcu51OyLemGhmW/HGY0dVHLql CFF1pkgl -----END CERTIFICATE----- GTS Root R2 =========== -----BEGIN CERTIFICATE----- MIIFWjCCA0KgAwIBAgIQbkepxlqz5yDFMJo/aFLybzANBgkqhkiG9w0BAQwFADBHMQswCQYDVQQG EwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJv b3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAG A1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIi MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTuk k3LvCvptnfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+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OOa KaqW04MjyaR7YbPMAuhd -----END CERTIFICATE----- GTS Root R4 =========== -----BEGIN CERTIFICATE----- MIICCjCCAZGgAwIBAgIQbkepyIuUtui7OyrYorLBmTAKBggqhkjOPQQDAzBHMQswCQYDVQQGEwJV UzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3Qg UjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UE ChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcq hkjOPQIBBgUrgQQAIgNiAATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa 6zzuhXyiQHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvRHYqj QjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSATNbrdP9JNqPV 2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNnADBkAjBqUFJ0CMRw3J5QdCHojXohw0+WbhXRIjVhLfoI N+4Zba3bssx9BzT1YBkstTTZbyACMANxsbqjYAuG7ZoIapVon+Kz4ZNkfF6Tpt95LY2F45TPI11x zPKwTdb+mciUqXWi4w== -----END CERTIFICATE----- UCA Global G2 Root ================== -----BEGIN CERTIFICATE----- MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9MQswCQYDVQQG EwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBHbG9iYWwgRzIgUm9vdDAeFw0x NjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0xCzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlU cnVzdDEbMBkGA1UEAwwSVUN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HzJsBPd+aBJ9J3O5oUb3n09tDh05S60FdRvScFDcH9 yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LVPtateJLbXDzz2K36uGt/xDYotgIVilQsnLAX c47QN6MUPJiVAAwpBVueSUmxX8fjy88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHo jhJi6IjMtX9Gl8CbEGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZk bxqgDMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI+Vg7RE+x ygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGyYiGqhkCyLmTTX8jjfhFn RR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bXUB+K+wb1whnw0A== -----END CERTIFICATE----- UCA Extended Validation Root ============================ -----BEGIN CERTIFICATE----- MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBHMQswCQYDVQQG EwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9u IFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMxMDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8G A1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIi MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrs iWogD4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvSsPGP2KxF Rv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aopO2z6+I9tTcg1367r3CTu eUW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BdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrH hQIDAQABo0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQDAgEG MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31xPaOfG1vR2vjTnGs2 vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjMwiI/aTvFthUvozXGaCocV685743Q NcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6dGNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q +Mri/Tm3R7nrft8EI6/6nAYH6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeih U80Bv2noWgbyRQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx iN66zB+Afko= -----END CERTIFICATE----- emSign ECC Root CA - G3 ======================= -----BEGIN CERTIFICATE----- MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQGEwJJTjETMBEG A1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEg MB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4 MTgzMDAwWjBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11 ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g RzMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0WXTsuwYc 58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xySfvalY8L1X44uT6EYGQIr MgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuBzhccLikenEhjQjAOBgNVHQ8BAf8EBAMC AQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+D CBeQyh+KTOgNG3qxrdWBCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7 jHvrZQnD+JbNR6iC8hZVdyR+EhCVBCyj -----END CERTIFICATE----- emSign Root CA - C1 =================== -----BEGIN CERTIFICATE----- MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMx EzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNp Z24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAwMFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UE BhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQD ExNlbVNpZ24gUm9vdCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+up ufGZBczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZHdPIWoU/ Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH3DspVpNqs8FqOp099cGX OFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvHGPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4V I5b2P/AgNBbeCsbEBEV5f6f9vtKppa+cxSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleooms lMuoaJuvimUnzYnu3Yy1aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+ XJGFehiqTbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQAD ggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87/kOXSTKZEhVb3xEp /6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4kqNPEjE2NuLe/gDEo2APJ62gsIq1 NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrGYQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9 wC68AivTxEDkigcxHpvOJpkT+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQ BmIMMMAVSKeoWXzhriKi4gp6D/piq1JM4fHfyr6DDUI= -----END CERTIFICATE----- emSign ECC Root CA - C3 ======================= -----BEGIN CERTIFICATE----- MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQGEwJVUzETMBEG A1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMxIDAeBgNVBAMTF2VtU2lnbiBF Q0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAwMFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UE BhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQD ExdlbVNpZ24gRUNDIFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd 6bciMK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4OjavtisIGJAnB9 SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0OBBYEFPtaSNCAIEDyqOkA B2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMDA2gA MGUCMQC02C8Cif22TGK6Q04ThHK1rt0c3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwU ZOR8loMRnLDRWmFLpg9J0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== -----END CERTIFICATE----- Hongkong Post Root CA 3 ======================= -----BEGIN CERTIFICATE----- MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQELBQAwbzELMAkG A1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJSG9uZyBLb25nMRYwFAYDVQQK Ew1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25na29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2 MDMwMjI5NDZaFw00MjA2MDMwMjI5NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtv bmcxEjAQBgNVBAcTCUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMX SG9uZ2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz iNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFOdem1p+/l6TWZ5Mwc50tf jTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mIVoBc+L0sPOFMV4i707mV78vH9toxdCim 5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOe sL4jpNrcyCse2m5FHomY2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj 0mRiikKYvLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+TtbNe/ JgERohYpSms0BpDsE9K2+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0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fq dBb9HxEGmpv0 -----END CERTIFICATE----- kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cert/gen.sh000066400000000000000000000001461520575453600255100ustar00rootroot00000000000000openssl genrsa -out server.key 2048 openssl req -new -x509 -key server.key -out server.crt -days 3650 kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cert/server.crt000066400000000000000000000023751520575453600264310ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIDgjCCAmqgAwIBAgIJAL/XKTs4cCwRMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV BAYTAkNOMREwDwYDVQQIDAhTaGFuZ2hhaTERMA8GA1UEBwwIU2hhbmdoYWkxITAf BgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xOTA4MjkwNDA1NDda Fw0yOTA4MjYwNDA1NDdaMFYxCzAJBgNVBAYTAkNOMREwDwYDVQQIDAhTaGFuZ2hh aTERMA8GA1UEBwwIU2hhbmdoYWkxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMg UHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANJJ5DaZroEg N34H6A3uq5qDRlJe/ELhWcmtkj57cYb5U/T39C7dEjqGfhURb/NEuYbYoEb+4/lD xJOvn0qqXiJGPt0avecGhQUpggykEj4NZe6W1/WIX81Z1tF6QJZrpUDq4MD1S3KA ETvnTDv0bc6lvT/YDDb8qYMKGNZUTIQKpucdrIet9kDVIrXON4icJL9PDi/zFu3S e6feGsG7SAWv1ZInzF6wkEr8pCQc2Aab9R2BsbDsnVc8qZahfLniif7yDxiRbcEf P4P4cJ7YCD6T1Vyv7bDCnxSEJ+b+j4Ih5XVwHUeK2wG9rrNQ6Z4sSMrv1oSoxVfG mGdHHEhBN0ECAwEAAaNTMFEwHQYDVR0OBBYEFGPOMSeA6p3Vkf4uHdt5eRbrkoXU MB8GA1UdIwQYMBaAFGPOMSeA6p3Vkf4uHdt5eRbrkoXUMA8GA1UdEwEB/wQFMAMB Af8wDQYJKoZIhvcNAQELBQADggEBAEa3x7MzIBQvr43l6zuoK9SBoW6DET42yCRb YA6as/8fFYc4A1GqJStjvOgS0nIhBeCdyLJCy40U5ERhhVKqjPLLHHB4i7sv98Ac aXgVr91eUZcKeuiEkDHWRPCitkPj3p2v9J2VDAHpxfKvIB+r/q+7O4W6tjJT5fPq iUgdpr/R6uBFndBtGc+k65byxSQgvAvdM4kpGA8nnypT9i8SGVp0gB7lMG8avUTU zH16msecIEKLBHED40w9aiuOf3CnMDqGSTilP7p4gvMY4u+qm3zAXN29OHqoldbn j/A8RE9Q1F1H3G+eSltBuug3DBGp0q0EskxiqtfJbzW9G5fwGxM= -----END CERTIFICATE----- kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cert/server.key000066400000000000000000000032171520575453600264250ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA0knkNpmugSA3fgfoDe6rmoNGUl78QuFZya2SPntxhvlT9Pf0 Lt0SOoZ+FRFv80S5htigRv7j+UPEk6+fSqpeIkY+3Rq95waFBSmCDKQSPg1l7pbX 9YhfzVnW0XpAlmulQOrgwPVLcoARO+dMO/RtzqW9P9gMNvypgwoY1lRMhAqm5x2s h632QNUitc43iJwkv08OL/MW7dJ7p94awbtIBa/VkifMXrCQSvykJBzYBpv1HYGx sOydVzyplqF8ueKJ/vIPGJFtwR8/g/hwntgIPpPVXK/tsMKfFIQn5v6PgiHldXAd R4rbAb2us1DpnixIyu/WhKjFV8aYZ0ccSEE3QQIDAQABAoIBAG/JthbMdbbRAI7v 9w1I/lKCTKTHN8T59PhAXAj5KG2/J0GHenhbLzCLhIUAowmoVBP6HqH/KAO/YcW8 y6oujSIdQ5fYenFQxu/qk+bSZZw1FSXTbHRrDbqlcowjOCh+ivfKpLYO8A+rQv4c RCtvEdyTwNoqqL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EY----- kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cmake/000077500000000000000000000000001520575453600245255ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cmake/ios.toolchain.cmake000066400000000000000000001337751520575453600303200ustar00rootroot00000000000000# This file is part of the ios-cmake project. It was retrieved from # https://github.com/leetal/ios-cmake.git, which is a fork of # https://github.com/gerstrong/ios-cmake.git, which is a fork of # https://github.com/cristeab/ios-cmake.git, which is a fork of # https://code.google.com/p/ios-cmake/. Which in turn is based off of # the Platform/Darwin.cmake and Platform/UnixPaths.cmake files which # are included with CMake 2.8.4 # # The ios-cmake project is licensed under the new BSD license. # # Copyright (c) 2014, Bogdan Cristea and LTE Engineering Software, # Kitware, Inc., Insight Software Consortium. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER 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. # # This file is based on the Platform/Darwin.cmake and # Platform/UnixPaths.cmake files which are included with CMake 2.8.4 # It has been altered for iOS development. # # Updated by Alex Stewart (alexs.mac@gmail.com) # # ***************************************************************************** # Now maintained by Alexander Widerberg (widerbergaren [at] gmail.com) # under the BSD-3-Clause license # https://github.com/leetal/ios-cmake # ***************************************************************************** # # INFORMATION / HELP # ############################################################################### # OPTIONS # ############################################################################### # # PLATFORM: (default "OS64") # OS = Build for iPhoneOS. # OS64 = Build for arm64 iphoneOS. # OS64COMBINED = Build for arm64 x86_64 iphoneOS + iphoneOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) # SIMULATOR = Build for x86 i386 iphoneOS Simulator. # SIMULATOR64 = Build for x86_64 iphoneOS Simulator. # SIMULATORARM64 = Build for arm64 iphoneOS Simulator. # TVOS = Build for arm64 tvOS. # TVOSCOMBINED = Build for arm64 x86_64 tvOS + tvOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) # SIMULATOR_TVOS = Build for x86_64 tvOS Simulator. # WATCHOS = Build for armv7k arm64_32 for watchOS. # WATCHOSCOMBINED = Build for armv7k arm64_32 x86_64 watchOS + watchOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) # SIMULATOR_WATCHOS = Build for x86_64 for watchOS Simulator. # MAC = Build for x86_64 macOS. # MAC_ARM64 = Build for Apple Silicon macOS. # MAC_UNIVERSAL = Combined build for x86_64 and Apple Silicon on macOS. # MAC_CATALYST = Build for x86_64 macOS with Catalyst support (iOS toolchain on macOS). # Note: The build argument "MACOSX_DEPLOYMENT_TARGET" can be used to control min-version of macOS # MAC_CATALYST_ARM64 = Build for Apple Silicon macOS with Catalyst support (iOS toolchain on macOS). # Note: The build argument "MACOSX_DEPLOYMENT_TARGET" can be used to control min-version of macOS # # CMAKE_OSX_SYSROOT: Path to the SDK to use. By default this is # automatically determined from PLATFORM and xcodebuild, but # can also be manually specified (although this should not be required). # # CMAKE_DEVELOPER_ROOT: Path to the Developer directory for the platform # being compiled for. By default, this is automatically determined from # CMAKE_OSX_SYSROOT, but can also be manually specified (although this should # not be required). # # DEPLOYMENT_TARGET: Minimum SDK version to target. Default 2.0 on watchOS and 9.0 on tvOS+iOS # # NAMED_LANGUAGE_SUPPORT: # ON (default) = Will require "enable_language(OBJC) and/or enable_language(OBJCXX)" for full OBJC|OBJCXX support # OFF = Will embed the OBJC and OBJCXX flags into the CMAKE_C_FLAGS and CMAKE_CXX_FLAGS (legacy behavior, CMake version < 3.16) # # ENABLE_BITCODE: (ON|OFF) Enables or disables bitcode support. Default ON # # ENABLE_ARC: (ON|OFF) Enables or disables ARC support. Default ON (ARC enabled by default) # # ENABLE_VISIBILITY: (ON|OFF) Enables or disables symbol visibility support. Default OFF (visibility hidden by default) # # ENABLE_STRICT_TRY_COMPILE: (ON|OFF) Enables or disables strict try_compile() on all Check* directives (will run linker # to actually check if linking is possible). Default OFF (will set CMAKE_TRY_COMPILE_TARGET_TYPE to STATIC_LIBRARY) # # ARCHS: (armv7 armv7s armv7k arm64 arm64_32 i386 x86_64) If specified, will override the default architectures for the given PLATFORM # OS = armv7 armv7s arm64 (if applicable) # OS64 = arm64 (if applicable) # SIMULATOR = i386 # SIMULATOR64 = x86_64 # SIMULATORARM64 = arm64 # TVOS = arm64 # SIMULATOR_TVOS = x86_64 (i386 has since long been deprecated) # WATCHOS = armv7k arm64_32 (if applicable) # SIMULATOR_WATCHOS = x86_64 (i386 has since long been deprecated) # MAC = x86_64 # MAC_ARM64 = arm64 # MAC_UNIVERSAL = x86_64 arm64 # MAC_CATALYST = x86_64 # MAC_CATALYST_ARM64 = arm64 # # NOTE: When manually specifying ARCHS, put a semi-colon between the entries. E.g., -DARCHS="armv7;arm64" # ############################################################################### # END OPTIONS # ############################################################################### # # This toolchain defines the following properties (available via get_property()) for use externally: # # PLATFORM: The currently targeted platform. # XCODE_VERSION: Version number (not including Build version) of Xcode detected. # SDK_VERSION: Version of SDK being used. # OSX_ARCHITECTURES: Architectures being compiled for (generated from PLATFORM). # APPLE_TARGET_TRIPLE: Used by autoconf build systems. NOTE: If "ARCHS" is overridden, this will *NOT* be set! # # This toolchain defines the following macros for use externally: # # set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE XCODE_VARIANT) # A convenience macro for setting xcode specific properties on targets. # Available variants are: All, Release, RelWithDebInfo, Debug, MinSizeRel # example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1" "all"). # # find_host_package (PROGRAM ARGS) # A macro used to find executable programs on the host system, not within the # environment. Thanks to the android-cmake project for providing the # command. # cmake_minimum_required(VERSION 3.8.0) # CMake invokes the toolchain file twice during the first build, but only once during subsequent rebuilds. if(DEFINED ENV{_IOS_TOOLCHAIN_HAS_RUN}) return() endif() set(ENV{_IOS_TOOLCHAIN_HAS_RUN} true) # List of supported platform values list(APPEND _supported_platforms "OS" "OS64" "OS64COMBINED" "SIMULATOR" "SIMULATOR64" "SIMULATORARM64" "TVOS" "TVOSCOMBINED" "SIMULATOR_TVOS" "WATCHOS" "WATCHOSCOMBINED" "SIMULATOR_WATCHOS" "MAC" "MAC_ARM64" "MAC_UNIVERSAL" "MAC_CATALYST" "MAC_CATALYST_ARM64") # Cache what generator is used set(USED_CMAKE_GENERATOR "${CMAKE_GENERATOR}") # Check if using a CMake version capable of building combined FAT builds (simulator and target slices combined in one static lib) if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14") set(MODERN_CMAKE YES) endif() # Get the Xcode version being used. # Problem: CMake runs toolchain files multiple times, but can't read cache variables on some runs. # Workaround: On the first run (in which cache variables are always accessible), set an intermediary environment variable. # # NOTE: This pattern is used in many places in this toolchain to speed up checks of all sorts if(DEFINED XCODE_VERSION_INT) # Environment variables are always preserved. set(ENV{_XCODE_VERSION_INT} "${XCODE_VERSION_INT}") elseif(DEFINED ENV{_XCODE_VERSION_INT}) set(XCODE_VERSION_INT "$ENV{_XCODE_VERSION_INT}") elseif(NOT DEFINED XCODE_VERSION_INT) find_program(XCODEBUILD_EXECUTABLE xcodebuild) if(NOT XCODEBUILD_EXECUTABLE) message(FATAL_ERROR "xcodebuild not found. Please install either the standalone commandline tools or Xcode.") endif() execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -version OUTPUT_VARIABLE XCODE_VERSION_INT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) string(REGEX MATCH "Xcode [0-9\\.]+" XCODE_VERSION_INT "${XCODE_VERSION_INT}") string(REGEX REPLACE "Xcode ([0-9\\.]+)" "\\1" XCODE_VERSION_INT "${XCODE_VERSION_INT}") set(XCODE_VERSION_INT "${XCODE_VERSION_INT}" CACHE INTERNAL "") endif() # Assuming that xcode 12.0 is installed you most probably have ios sdk 14.0 or later installed (tested on Big Sur) # if you don't set a deployment target it will be set the way you only get 64-bit builds if(NOT DEFINED DEPLOYMENT_TARGET AND XCODE_VERSION_INT VERSION_GREATER 12.0) # Temporarily fix the arm64 issues in CMake install-combined by excluding arm64 for simulator builds (needed for Apple Silicon...) set(CMAKE_XCODE_ATTRIBUTE_EXCLUDED_ARCHS[sdk=iphonesimulator*] "arm64") endif() # Check if the platform variable is set if(DEFINED PLATFORM) # Environment variables are always preserved. set(ENV{_PLATFORM} "${PLATFORM}") elseif(DEFINED ENV{_PLATFORM}) set(PLATFORM "$ENV{_PLATFORM}") elseif(NOT DEFINED PLATFORM) message(FATAL_ERROR "PLATFORM argument not set. Bailing configure since I don't know what target you want to build for!") endif () if(PLATFORM MATCHES ".*COMBINED" AND NOT CMAKE_GENERATOR MATCHES "Xcode") message(FATAL_ERROR "The combined builds support requires Xcode to be used as a generator via '-G Xcode' command-line argument in CMake") endif() # Safeguard that the platform value is set and is one of the supported values list(FIND _supported_platforms ${PLATFORM} contains_PLATFORM) if("${contains_PLATFORM}" EQUAL "-1") string(REPLACE ";" "\n * " _supported_platforms_formatted "${_supported_platforms}") message(FATAL_ERROR " Invalid PLATFORM specified! Current value: ${PLATFORM}.\n" " Supported PLATFORM values: \n * ${_supported_platforms_formatted}") endif() # Check if Apple Silicon is supported if(PLATFORM MATCHES "^(MAC_ARM64)$|^(MAC_CATALYST_ARM64)$|^(MAC_UNIVERSAL)$" AND ${CMAKE_VERSION} VERSION_LESS "3.19.5") message(FATAL_ERROR "Apple Silicon builds requires a minimum of CMake 3.19.5") endif() # Touch the toolchain variable to suppress the "unused variable" warning. # This happens if CMake is invoked with the same command line the second time. if(CMAKE_TOOLCHAIN_FILE) endif() # Fix for PThread library not in path set(CMAKE_THREAD_LIBS_INIT "-lpthread") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(CMAKE_USE_WIN32_THREADS_INIT 0) set(CMAKE_USE_PTHREADS_INIT 1) # Specify named language support defaults. if(NOT DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.16") set(NAMED_LANGUAGE_SUPPORT ON) message(STATUS "[DEFAULTS] Using explicit named language support! E.g., enable_language(CXX) is needed in the project files.") elseif(NOT DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_LESS "3.16") set(NAMED_LANGUAGE_SUPPORT OFF) message(STATUS "[DEFAULTS] Disabling explicit named language support. Falling back to legacy behavior.") elseif(DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_LESS "3.16") message(FATAL_ERROR "CMake named language support for OBJC and OBJCXX was added in CMake 3.16.") endif() set(NAMED_LANGUAGE_SUPPORT_INT ${NAMED_LANGUAGE_SUPPORT} CACHE BOOL "Whether or not to enable explicit named language support" FORCE) # Specify the minimum version of the deployment target. if(NOT DEFINED DEPLOYMENT_TARGET) if (PLATFORM MATCHES "WATCHOS") # Unless specified, SDK version 4.0 is used by default as minimum target version (watchOS). set(DEPLOYMENT_TARGET "4.0") elseif(PLATFORM STREQUAL "MAC") # Unless specified, SDK version 10.13 (High Sierra) is used by default as the minimum target version (macos). set(DEPLOYMENT_TARGET "10.13") elseif(PLATFORM STREQUAL "MAC_ARM64") # Unless specified, SDK version 11.0 (Big Sur) is used by default as the minimum target version (macOS on arm). set(DEPLOYMENT_TARGET "11.0") elseif(PLATFORM STREQUAL "MAC_UNIVERSAL") # Unless specified, SDK version 11.0 (Big Sur) is used by default as minimum target version for universal builds. set(DEPLOYMENT_TARGET "11.0") elseif(PLATFORM STREQUAL "MAC_CATALYST" OR PLATFORM STREQUAL "MAC_CATALYST_ARM64") # Unless specified, SDK version 13.0 is used by default as the minimum target version (mac catalyst minimum requirement). set(DEPLOYMENT_TARGET "13.1") else() # Unless specified, SDK version 11.0 is used by default as the minimum target version (iOS, tvOS). set(DEPLOYMENT_TARGET "11.0") endif() message(STATUS "[DEFAULTS] Using the default min-version since DEPLOYMENT_TARGET not provided!") elseif(DEFINED DEPLOYMENT_TARGET AND PLATFORM MATCHES "^MAC_CATALYST" AND ${DEPLOYMENT_TARGET} VERSION_LESS "13.1") message(FATAL_ERROR "Mac Catalyst builds requires a minimum deployment target of 13.1!") endif() # Store the DEPLOYMENT_TARGET in the cache set(DEPLOYMENT_TARGET "${DEPLOYMENT_TARGET}" CACHE INTERNAL "") # Handle the case where we are targeting iOS and a version above 10.3.4 (32-bit support dropped officially) if(PLATFORM STREQUAL "OS" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) set(PLATFORM "OS64") message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") elseif(PLATFORM STREQUAL "SIMULATOR" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) set(PLATFORM "SIMULATOR64") message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") endif() set(PLATFORM_INT "${PLATFORM}") if(DEFINED ARCHS) string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") endif() # Determine the platform name and architectures for use in xcodebuild commands # from the specified PLATFORM_INT name. if(PLATFORM_INT STREQUAL "OS") set(SDK_NAME iphoneos) if(NOT ARCHS) set(ARCHS armv7 armv7s arm64) set(APPLE_TARGET_TRIPLE_INT arm-apple-ios${DEPLOYMENT_TARGET}) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) endif() elseif(PLATFORM_INT STREQUAL "OS64") set(SDK_NAME iphoneos) if(NOT ARCHS) if (XCODE_VERSION_INT VERSION_GREATER 10.0) set(ARCHS arm64) # FIXME: Add arm64e when Apple has fixed the integration issues with it, libarclite_iphoneos.a is currently missing bitcode markers for example else() set(ARCHS arm64) endif() set(APPLE_TARGET_TRIPLE_INT aarch64-apple-ios${DEPLOYMENT_TARGET}) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) endif() elseif(PLATFORM_INT STREQUAL "OS64COMBINED") set(SDK_NAME iphoneos) if(MODERN_CMAKE) if(NOT ARCHS) if (XCODE_VERSION_INT VERSION_GREATER 10.0) set(ARCHS arm64 x86_64) # FIXME: Add arm64e when Apple has fixed the integration issues with it, libarclite_iphoneos.a is currently missing bitcode markers for example set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphonesimulator*] "x86_64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphonesimulator*] "x86_64") else() set(ARCHS arm64 x86_64) set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphonesimulator*] "x86_64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphoneos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphonesimulator*] "x86_64") endif() set(APPLE_TARGET_TRIPLE_INT aarch64-x86_64-apple-ios${DEPLOYMENT_TARGET}) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the OS64COMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR") set(SDK_NAME iphonesimulator) if(NOT ARCHS) set(ARCHS i386) set(APPLE_TARGET_TRIPLE_INT i386-apple-ios${DEPLOYMENT_TARGET}-simulator) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) endif() message(DEPRECATION "SIMULATOR IS DEPRECATED. Consider using SIMULATOR64 instead.") elseif(PLATFORM_INT STREQUAL "SIMULATOR64") set(SDK_NAME iphonesimulator) if(NOT ARCHS) set(ARCHS x86_64) set(APPLE_TARGET_TRIPLE_INT x86_64-apple-ios${DEPLOYMENT_TARGET}-simulator) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) endif() elseif(PLATFORM_INT STREQUAL "SIMULATORARM64") set(SDK_NAME iphonesimulator) if(NOT ARCHS) set(ARCHS arm64) set(APPLE_TARGET_TRIPLE_INT aarch64-apple-ios${DEPLOYMENT_TARGET}-simulator) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) endif() elseif(PLATFORM_INT STREQUAL "TVOS") set(SDK_NAME appletvos) if(NOT ARCHS) set(ARCHS arm64) set(APPLE_TARGET_TRIPLE_INT aarch64-apple-tvos${DEPLOYMENT_TARGET}) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}) endif() elseif (PLATFORM_INT STREQUAL "TVOSCOMBINED") set(SDK_NAME appletvos) if(MODERN_CMAKE) if(NOT ARCHS) set(ARCHS arm64 x86_64) set(APPLE_TARGET_TRIPLE_INT aarch64-x86_64-apple-tvos${DEPLOYMENT_TARGET}) set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=appletvos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=appletvsimulator*] "x86_64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=appletvos*] "arm64") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=appletvsimulator*] "x86_64") else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}) endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the TVOSCOMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") set(SDK_NAME appletvsimulator) if(NOT ARCHS) set(ARCHS x86_64) set(APPLE_TARGET_TRIPLE_INT x86_64-apple-tvos${DEPLOYMENT_TARGET}-simulator) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}-simulator) endif() elseif(PLATFORM_INT STREQUAL "WATCHOS") set(SDK_NAME watchos) if(NOT ARCHS) if (XCODE_VERSION_INT VERSION_GREATER 10.0) set(ARCHS armv7k arm64_32) set(APPLE_TARGET_TRIPLE_INT aarch64_32-apple-watchos${DEPLOYMENT_TARGET}) else() set(ARCHS armv7k) set(APPLE_TARGET_TRIPLE_INT arm-apple-watchos${DEPLOYMENT_TARGET}) endif() else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}) endif() elseif(PLATFORM_INT STREQUAL "WATCHOSCOMBINED") set(SDK_NAME watchos) if(MODERN_CMAKE) if(NOT ARCHS) if (XCODE_VERSION_INT VERSION_GREATER 10.0) set(ARCHS armv7k arm64_32 i386) set(APPLE_TARGET_TRIPLE_INT aarch64_32-i386-apple-watchos${DEPLOYMENT_TARGET}) set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchos*] "armv7k arm64_32") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchsimulator*] "i386") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchos*] "armv7k arm64_32") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchsimulator*] "i386") else() set(ARCHS armv7k i386) set(APPLE_TARGET_TRIPLE_INT arm-i386-apple-watchos${DEPLOYMENT_TARGET}) set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchos*] "armv7k") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchsimulator*] "i386") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchos*] "armv7k") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchsimulator*] "i386") endif() else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}) endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the WATCHOSCOMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") set(SDK_NAME watchsimulator) if(NOT ARCHS) set(ARCHS i386) set(APPLE_TARGET_TRIPLE_INT i386-apple-watchos${DEPLOYMENT_TARGET}-simulator) else() set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}-simulator) endif() elseif(PLATFORM_INT STREQUAL "MAC" OR PLATFORM_INT STREQUAL "MAC_CATALYST") set(SDK_NAME macosx) if(NOT ARCHS) set(ARCHS x86_64) endif() string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") if(PLATFORM_INT STREQUAL "MAC") set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) elseif(PLATFORM_INT STREQUAL "MAC_CATALYST") set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-macabi) endif() elseif(PLATFORM_INT MATCHES "^(MAC_ARM64)$|^(MAC_CATALYST_ARM64)$") set(SDK_NAME macosx) if(NOT ARCHS) set(ARCHS arm64) endif() string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") if(PLATFORM_INT STREQUAL "MAC_ARM64") set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) elseif(PLATFORM_INT STREQUAL "MAC_CATALYST_ARM64") set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-macabi) endif() elseif(PLATFORM_INT STREQUAL "MAC_UNIVERSAL") set(SDK_NAME macosx) if(NOT ARCHS) set(ARCHS "x86_64;arm64") endif() string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) else() message(FATAL_ERROR "Invalid PLATFORM: ${PLATFORM_INT}") endif() string(REPLACE ";" " " ARCHS_SPACED "${ARCHS}") if(MODERN_CMAKE AND PLATFORM_INT MATCHES ".*COMBINED" AND NOT CMAKE_GENERATOR MATCHES "Xcode") message(FATAL_ERROR "The COMBINED options only work with Xcode generator, -G Xcode") endif() if(CMAKE_GENERATOR MATCHES "Xcode" AND PLATFORM_INT MATCHES "^MAC_CATALYST") set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") set(CMAKE_XCODE_ATTRIBUTE_SUPPORTED_PLATFORMS "macosx") set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-maccatalyst") if(NOT DEFINED MACOSX_DEPLOYMENT_TARGET) set(CMAKE_XCODE_ATTRIBUTE_MACOSX_DEPLOYMENT_TARGET "10.15") else() set(CMAKE_XCODE_ATTRIBUTE_MACOSX_DEPLOYMENT_TARGET "${MACOSX_DEPLOYMENT_TARGET}") endif() elseif(CMAKE_GENERATOR MATCHES "Xcode") set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") set(CMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET "${DEPLOYMENT_TARGET}") if(NOT PLATFORM_INT MATCHES ".*COMBINED") set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=${SDK_NAME}*] "${ARCHS_SPACED}") set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=${SDK_NAME}*] "${ARCHS_SPACED}") endif() endif() # If the user did not specify the SDK root to use, then query xcodebuild for it. if(DEFINED CMAKE_OSX_SYSROOT_INT) # Environment variables are always preserved. set(ENV{_CMAKE_OSX_SYSROOT_INT} "${CMAKE_OSX_SYSROOT_INT}") elseif(DEFINED ENV{_CMAKE_OSX_SYSROOT_INT}) set(CMAKE_OSX_SYSROOT_INT "$ENV{_CMAKE_OSX_SYSROOT_INT}") elseif(NOT DEFINED CMAKE_OSX_SYSROOT_INT) execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -version -sdk ${SDK_NAME} Path OUTPUT_VARIABLE CMAKE_OSX_SYSROOT_INT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) endif() if (NOT DEFINED CMAKE_OSX_SYSROOT_INT AND NOT DEFINED CMAKE_OSX_SYSROOT) message(SEND_ERROR "Please make sure that Xcode is installed and that the toolchain" "is pointing to the correct path. Please run:" "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" "and see if that fixes the problem for you.") message(FATAL_ERROR "Invalid CMAKE_OSX_SYSROOT: ${CMAKE_OSX_SYSROOT} " "does not exist.") elseif(DEFINED CMAKE_OSX_SYSROOT_INT) set(CMAKE_OSX_SYSROOT_INT "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") # Specify the location or name of the platform SDK to be used in CMAKE_OSX_SYSROOT. set(CMAKE_OSX_SYSROOT "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") endif() # Use bitcode or not if(NOT DEFINED ENABLE_BITCODE AND NOT ARCHS MATCHES "((^|;|, )(i386|x86_64))+") # Unless specified, enable bitcode support by default message(STATUS "[DEFAULTS] Enabling bitcode support by default. ENABLE_BITCODE not provided!") set(ENABLE_BITCODE ON) elseif(NOT DEFINED ENABLE_BITCODE) message(STATUS "[DEFAULTS] Disabling bitcode support by default on simulators. ENABLE_BITCODE not provided for override!") set(ENABLE_BITCODE OFF) endif() set(ENABLE_BITCODE_INT ${ENABLE_BITCODE} CACHE BOOL "Whether or not to enable bitcode" FORCE) # Use ARC or not if(NOT DEFINED ENABLE_ARC) # Unless specified, enable ARC support by default set(ENABLE_ARC ON) message(STATUS "[DEFAULTS] Enabling ARC support by default. ENABLE_ARC not provided!") endif() set(ENABLE_ARC_INT ${ENABLE_ARC} CACHE BOOL "Whether or not to enable ARC" FORCE) # Use hidden visibility or not if(NOT DEFINED ENABLE_VISIBILITY) # Unless specified, disable symbols visibility by default set(ENABLE_VISIBILITY OFF) message(STATUS "[DEFAULTS] Hiding symbols visibility by default. ENABLE_VISIBILITY not provided!") endif() set(ENABLE_VISIBILITY_INT ${ENABLE_VISIBILITY} CACHE BOOL "Whether or not to hide symbols from the dynamic linker (-fvisibility=hidden)" FORCE) # Set strict compiler checks or not if(NOT DEFINED ENABLE_STRICT_TRY_COMPILE) # Unless specified, disable strict try_compile() set(ENABLE_STRICT_TRY_COMPILE OFF) message(STATUS "[DEFAULTS] Using NON-strict compiler checks by default. ENABLE_STRICT_TRY_COMPILE not provided!") endif() set(ENABLE_STRICT_TRY_COMPILE_INT ${ENABLE_STRICT_TRY_COMPILE} CACHE BOOL "Whether or not to use strict compiler checks" FORCE) # Get the SDK version information. if(DEFINED SDK_VERSION) # Environment variables are always preserved. set(ENV{_SDK_VERSION} "${SDK_VERSION}") elseif(DEFINED ENV{_SDK_VERSION}) set(SDK_VERSION "$ENV{_SDK_VERSION}") elseif(NOT DEFINED SDK_VERSION) execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -sdk ${CMAKE_OSX_SYSROOT_INT} -version SDKVersion OUTPUT_VARIABLE SDK_VERSION ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) endif() # Find the Developer root for the specific iOS platform being compiled for # from CMAKE_OSX_SYSROOT. Should be ../../ from SDK specified in # CMAKE_OSX_SYSROOT. There does not appear to be a direct way to obtain # this information from xcrun or xcodebuild. if (NOT DEFINED CMAKE_DEVELOPER_ROOT AND NOT CMAKE_GENERATOR MATCHES "Xcode") get_filename_component(PLATFORM_SDK_DIR ${CMAKE_OSX_SYSROOT_INT} PATH) get_filename_component(CMAKE_DEVELOPER_ROOT ${PLATFORM_SDK_DIR} PATH) if (NOT EXISTS "${CMAKE_DEVELOPER_ROOT}") message(FATAL_ERROR "Invalid CMAKE_DEVELOPER_ROOT: ${CMAKE_DEVELOPER_ROOT} does not exist.") endif() endif() # Find the C & C++ compilers for the specified SDK. if(DEFINED CMAKE_C_COMPILER) # Environment variables are always preserved. set(ENV{_CMAKE_C_COMPILER} "${CMAKE_C_COMPILER}") elseif(DEFINED ENV{_CMAKE_C_COMPILER}) set(CMAKE_C_COMPILER "$ENV{_CMAKE_C_COMPILER}") set(CMAKE_ASM_COMPILER ${CMAKE_C_COMPILER}) elseif(NOT DEFINED CMAKE_C_COMPILER) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find clang OUTPUT_VARIABLE CMAKE_C_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) set(CMAKE_ASM_COMPILER ${CMAKE_C_COMPILER}) endif() if(DEFINED CMAKE_CXX_COMPILER) # Environment variables are always preserved. set(ENV{_CMAKE_CXX_COMPILER} "${CMAKE_CXX_COMPILER}") elseif(DEFINED ENV{_CMAKE_CXX_COMPILER}) set(CMAKE_CXX_COMPILER "$ENV{_CMAKE_CXX_COMPILER}") elseif(NOT DEFINED CMAKE_CXX_COMPILER) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find clang++ OUTPUT_VARIABLE CMAKE_CXX_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) endif() # Find (Apple's) libtool. if(DEFINED BUILD_LIBTOOL) # Environment variables are always preserved. set(ENV{_BUILD_LIBTOOL} "${BUILD_LIBTOOL}") elseif(DEFINED ENV{_BUILD_LIBTOOL}) set(BUILD_LIBTOOL "$ENV{_BUILD_LIBTOOL}") elseif(NOT DEFINED BUILD_LIBTOOL) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find libtool OUTPUT_VARIABLE BUILD_LIBTOOL ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) endif() # Find the toolchain's provided install_name_tool if none is found on the host if(DEFINED CMAKE_INSTALL_NAME_TOOL) # Environment variables are always preserved. set(ENV{_CMAKE_INSTALL_NAME_TOOL} "${CMAKE_INSTALL_NAME_TOOL}") elseif(DEFINED ENV{_CMAKE_INSTALL_NAME_TOOL}) set(CMAKE_INSTALL_NAME_TOOL "$ENV{_CMAKE_INSTALL_NAME_TOOL}") elseif(NOT DEFINED CMAKE_INSTALL_NAME_TOOL) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find install_name_tool OUTPUT_VARIABLE CMAKE_INSTALL_NAME_TOOL_INT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) set(CMAKE_INSTALL_NAME_TOOL ${CMAKE_INSTALL_NAME_TOOL_INT} CACHE INTERNAL "") endif() # Configure libtool to be used instead of ar + ranlib to build static libraries. # This is required on Xcode 7+, but should also work on previous versions of # Xcode. get_property(languages GLOBAL PROPERTY ENABLED_LANGUAGES) foreach(lang ${languages}) set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "${BUILD_LIBTOOL} -static -o " CACHE INTERNAL "") endforeach() # CMake 3.14+ support building for iOS, watchOS, and tvOS out of the box. if(MODERN_CMAKE) if(SDK_NAME MATCHES "iphone") set(CMAKE_SYSTEM_NAME iOS) elseif(SDK_NAME MATCHES "macosx") set(CMAKE_SYSTEM_NAME Darwin) elseif(SDK_NAME MATCHES "appletv") set(CMAKE_SYSTEM_NAME tvOS) elseif(SDK_NAME MATCHES "watch") set(CMAKE_SYSTEM_NAME watchOS) endif() # Provide flags for a combined FAT library build on newer CMake versions if(PLATFORM_INT MATCHES ".*COMBINED") set(CMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") set(CMAKE_IOS_INSTALL_COMBINED YES) endif() elseif(NOT DEFINED CMAKE_SYSTEM_NAME AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.10") # Legacy code path prior to CMake 3.14 or fallback if no CMAKE_SYSTEM_NAME specified set(CMAKE_SYSTEM_NAME iOS) elseif(NOT DEFINED CMAKE_SYSTEM_NAME) # Legacy code path before CMake 3.14 or fallback if no CMAKE_SYSTEM_NAME specified set(CMAKE_SYSTEM_NAME Darwin) endif() # Standard settings. set(CMAKE_SYSTEM_VERSION ${SDK_VERSION} CACHE INTERNAL "") set(UNIX ON CACHE BOOL "") set(APPLE ON CACHE BOOL "") if(PLATFORM STREQUAL "MAC" OR PLATFORM STREQUAL "MAC_ARM64" OR PLATFORM STREQUAL "MAC_UNIVERSAL") set(IOS OFF CACHE BOOL "") set(MACOS ON CACHE BOOL "") elseif(PLATFORM STREQUAL "MAC_CATALYST" OR PLATFORM STREQUAL "MAC_CATALYST_ARM64") set(IOS ON CACHE BOOL "") set(MACOS ON CACHE BOOL "") else() set(IOS ON CACHE BOOL "") endif() set(CMAKE_AR ar CACHE FILEPATH "" FORCE) set(CMAKE_RANLIB ranlib CACHE FILEPATH "" FORCE) set(CMAKE_STRIP strip CACHE FILEPATH "" FORCE) # Set the architectures for which to build. set(CMAKE_OSX_ARCHITECTURES ${ARCHS} CACHE INTERNAL "") # Change the type of target generated for try_compile() so it'll work when cross-compiling, weak compiler checks if(NOT ENABLE_STRICT_TRY_COMPILE_INT) set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) endif() # All iOS/Darwin specific settings - some may be redundant. if (NOT DEFINED CMAKE_MACOSX_BUNDLE) set(CMAKE_MACOSX_BUNDLE YES) endif() set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO") set(CMAKE_SHARED_LIBRARY_PREFIX "lib") set(CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") set(CMAKE_SHARED_MODULE_PREFIX "lib") set(CMAKE_SHARED_MODULE_SUFFIX ".so") set(CMAKE_C_COMPILER_ABI ELF) set(CMAKE_CXX_COMPILER_ABI ELF) set(CMAKE_C_HAS_ISYSROOT 1) set(CMAKE_CXX_HAS_ISYSROOT 1) set(CMAKE_MODULE_EXISTS 1) set(CMAKE_DL_LIBS "") set(CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") set(CMAKE_C_OSX_CURRENT_VERSION_FLAG "-current_version ") set(CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG "${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}") set(CMAKE_CXX_OSX_CURRENT_VERSION_FLAG "${CMAKE_C_OSX_CURRENT_VERSION_FLAG}") if(ARCHS MATCHES "((^|;|, )(arm64|arm64e|x86_64))+") set(CMAKE_C_SIZEOF_DATA_PTR 8) set(CMAKE_CXX_SIZEOF_DATA_PTR 8) if(ARCHS MATCHES "((^|;|, )(arm64|arm64e))+") set(CMAKE_SYSTEM_PROCESSOR "aarch64") else() set(CMAKE_SYSTEM_PROCESSOR "x86_64") endif() else() set(CMAKE_C_SIZEOF_DATA_PTR 4) set(CMAKE_CXX_SIZEOF_DATA_PTR 4) set(CMAKE_SYSTEM_PROCESSOR "arm") endif() # Note that only Xcode 7+ supports the newer more specific: # -m${SDK_NAME}-version-min flags, older versions of Xcode use: # -m(ios/ios-simulator)-version-min instead. if(${CMAKE_VERSION} VERSION_LESS "3.11") if(PLATFORM_INT STREQUAL "OS" OR PLATFORM_INT STREQUAL "OS64") if(XCODE_VERSION_INT VERSION_LESS 7.0) set(SDK_NAME_VERSION_FLAGS "-mios-version-min=${DEPLOYMENT_TARGET}") else() # Xcode 7.0+ uses flags we can build directly from SDK_NAME. set(SDK_NAME_VERSION_FLAGS "-m${SDK_NAME}-version-min=${DEPLOYMENT_TARGET}") endif() elseif(PLATFORM_INT STREQUAL "TVOS") set(SDK_NAME_VERSION_FLAGS "-mtvos-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") set(SDK_NAME_VERSION_FLAGS "-mtvos-simulator-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "WATCHOS") set(SDK_NAME_VERSION_FLAGS "-mwatchos-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") set(SDK_NAME_VERSION_FLAGS "-mwatchos-simulator-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "MAC") set(SDK_NAME_VERSION_FLAGS "-mmacosx-version-min=${DEPLOYMENT_TARGET}") else() # SIMULATOR or SIMULATOR64 both use -mios-simulator-version-min. set(SDK_NAME_VERSION_FLAGS "-mios-simulator-version-min=${DEPLOYMENT_TARGET}") endif() elseif(NOT PLATFORM_INT MATCHES "^MAC_CATALYST") # Newer versions of CMake sets the version min flags correctly, skip this for Mac Catalyst targets set(CMAKE_OSX_DEPLOYMENT_TARGET ${DEPLOYMENT_TARGET}) endif() if(DEFINED APPLE_TARGET_TRIPLE_INT) set(APPLE_TARGET_TRIPLE ${APPLE_TARGET_TRIPLE_INT} CACHE INTERNAL "") set(CMAKE_C_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) set(CMAKE_CXX_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) set(CMAKE_ASM_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) endif() if(PLATFORM_INT MATCHES "^MAC_CATALYST") set(C_TARGET_FLAGS "-isystem ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/usr/include -iframework ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/System/Library/Frameworks") endif() if(ENABLE_BITCODE_INT) set(BITCODE "-fembed-bitcode") set(CMAKE_XCODE_ATTRIBUTE_BITCODE_GENERATION_MODE "bitcode") set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "YES") else() set(BITCODE "") set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "NO") endif() if(ENABLE_ARC_INT) set(FOBJC_ARC "-fobjc-arc") set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC "YES") else() set(FOBJC_ARC "-fno-objc-arc") set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC "NO") endif() if(NAMED_LANGUAGE_SUPPORT_INT) set(OBJC_VARS "-fobjc-abi-version=2 -DOBJC_OLD_DISPATCH_PROTOTYPES=0") set(OBJC_LEGACY_VARS "") else() set(OBJC_VARS "") set(OBJC_LEGACY_VARS "-fobjc-abi-version=2 -DOBJC_OLD_DISPATCH_PROTOTYPES=0") endif() if(NOT ENABLE_VISIBILITY_INT) foreach(lang ${languages}) set(CMAKE_${lang}_VISIBILITY_PRESET "hidden" CACHE INTERNAL "") endforeach() set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN "YES") set(VISIBILITY "-fvisibility=hidden -fvisibility-inlines-hidden") else() foreach(lang ${languages}) set(CMAKE_${lang}_VISIBILITY_PRESET "default" CACHE INTERNAL "") endforeach() set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN "NO") set(VISIBILITY "-fvisibility=default") endif() if(DEFINED APPLE_TARGET_TRIPLE) set(APPLE_TARGET_TRIPLE_FLAG "-target ${APPLE_TARGET_TRIPLE}") endif() #Check if Xcode generator is used since that will handle these flags automagically if(CMAKE_GENERATOR MATCHES "Xcode") message(STATUS "Not setting any manual command-line buildflags, since Xcode is selected as the generator. Modifying the Xcode build-settings directly instead.") else() set(CMAKE_C_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${OBJC_LEGACY_VARS} ${BITCODE} ${VISIBILITY} ${CMAKE_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "-O0 -g ${CMAKE_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_C_FLAGS_MINSIZEREL}") set(CMAKE_C_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_C_FLAGS_RELWITHDEBINFO}") set(CMAKE_C_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${OBJC_LEGACY_VARS} ${BITCODE} ${VISIBILITY} ${CMAKE_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g ${CMAKE_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_CXX_FLAGS_MINSIZEREL}") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_CXX_FLAGS_RELEASE}") if(NAMED_LANGUAGE_SUPPORT_INT) set(CMAKE_OBJC_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} ${FOBJC_ARC} ${OBJC_VARS} ${CMAKE_OBJC_FLAGS}") set(CMAKE_OBJC_FLAGS_DEBUG "-O0 -g ${CMAKE_OBJC_FLAGS_DEBUG}") set(CMAKE_OBJC_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_OBJC_FLAGS_MINSIZEREL}") set(CMAKE_OBJC_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_OBJC_FLAGS_RELWITHDEBINFO}") set(CMAKE_OBJC_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_OBJC_FLAGS_RELEASE}") set(CMAKE_OBJCXX_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} ${FOBJC_ARC} ${OBJC_VARS} ${CMAKE_OBJCXX_FLAGS}") set(CMAKE_OBJCXX_FLAGS_DEBUG "-O0 -g ${CMAKE_OBJCXX_FLAGS_DEBUG}") set(CMAKE_OBJCXX_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_OBJCXX_FLAGS_MINSIZEREL}") set(CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO}") set(CMAKE_OBJCXX_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_OBJCXX_FLAGS_RELEASE}") endif() set(CMAKE_C_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}") set(CMAKE_CXX_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}") if(NAMED_LANGUAGE_SUPPORT_INT) set(CMAKE_OBJC_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_OBJC_LINK_FLAGS}") set(CMAKE_OBJCXX_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_OBJCXX_LINK_FLAGS}") endif() set(CMAKE_ASM_FLAGS "${CMAKE_C_FLAGS} -x assembler-with-cpp -arch ${CMAKE_OSX_ARCHITECTURES} ${APPLE_TARGET_TRIPLE_FLAG}") endif() ## Print status messages to inform of the current state message(STATUS "Configuring ${SDK_NAME} build for platform: ${PLATFORM_INT}, architecture(s): ${ARCHS}") message(STATUS "Using SDK: ${CMAKE_OSX_SYSROOT_INT}") message(STATUS "Using C compiler: ${CMAKE_C_COMPILER}") message(STATUS "Using CXX compiler: ${CMAKE_CXX_COMPILER}") message(STATUS "Using libtool: ${BUILD_LIBTOOL}") message(STATUS "Using install name tool: ${CMAKE_INSTALL_NAME_TOOL}") if(DEFINED APPLE_TARGET_TRIPLE) message(STATUS "Autoconf target triple: ${APPLE_TARGET_TRIPLE}") endif() message(STATUS "Using minimum deployment version: ${DEPLOYMENT_TARGET}" " (SDK version: ${SDK_VERSION})") if(MODERN_CMAKE) message(STATUS "Merging integrated CMake 3.14+ iOS,tvOS,watchOS,macOS toolchain(s) with this toolchain!") if(PLATFORM_INT MATCHES ".*COMBINED") message(STATUS "Will combine built (static) artifacts into FAT lib...") endif() endif() if(CMAKE_GENERATOR MATCHES "Xcode") message(STATUS "Using Xcode version: ${XCODE_VERSION_INT}") endif() message(STATUS "CMake version: ${CMAKE_VERSION}") if(DEFINED SDK_NAME_VERSION_FLAGS) message(STATUS "Using version flags: ${SDK_NAME_VERSION_FLAGS}") endif() message(STATUS "Using a data_ptr size of: ${CMAKE_CXX_SIZEOF_DATA_PTR}") if(ENABLE_BITCODE_INT) message(STATUS "Bitcode: Enabled") else() message(STATUS "Bitcode: Disabled") endif() if(ENABLE_ARC_INT) message(STATUS "ARC: Enabled") else() message(STATUS "ARC: Disabled") endif() if(ENABLE_VISIBILITY_INT) message(STATUS "Hiding symbols: Disabled") else() message(STATUS "Hiding symbols: Enabled") endif() # Set global properties set_property(GLOBAL PROPERTY PLATFORM "${PLATFORM}") set_property(GLOBAL PROPERTY APPLE_TARGET_TRIPLE "${APPLE_TARGET_TRIPLE_INT}") set_property(GLOBAL PROPERTY SDK_VERSION "${SDK_VERSION}") set_property(GLOBAL PROPERTY XCODE_VERSION "${XCODE_VERSION_INT}") set_property(GLOBAL PROPERTY OSX_ARCHITECTURES "${CMAKE_OSX_ARCHITECTURES}") # Export configurable variables for the try_compile() command. set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES PLATFORM XCODE_VERSION_INT SDK_VERSION NAMED_LANGUAGE_SUPPORT DEPLOYMENT_TARGET CMAKE_DEVELOPER_ROOT CMAKE_OSX_SYSROOT_INT ENABLE_BITCODE ENABLE_ARC CMAKE_ASM_COMPILER CMAKE_C_COMPILER CMAKE_C_COMPILER_TARGET CMAKE_CXX_COMPILER CMAKE_CXX_COMPILER_TARGET BUILD_LIBTOOL CMAKE_INSTALL_NAME_TOOL CMAKE_C_FLAGS CMAKE_C_DEBUG CMAKE_C_MINSIZEREL CMAKE_C_RELWITHDEBINFO CMAKE_C_RELEASE CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_RELEASE CMAKE_C_LINK_FLAGS CMAKE_CXX_LINK_FLAGS CMAKE_ASM_FLAGS ) if(NAMED_LANGUAGE_SUPPORT_INT) list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_OBJC_FLAGS CMAKE_OBJC_DEBUG CMAKE_OBJC_MINSIZEREL CMAKE_OBJC_RELWITHDEBINFO CMAKE_OBJC_RELEASE CMAKE_OBJCXX_FLAGS CMAKE_OBJCXX_DEBUG CMAKE_OBJCXX_MINSIZEREL CMAKE_OBJCXX_RELWITHDEBINFO CMAKE_OBJCXX_RELEASE CMAKE_OBJC_LINK_FLAGS CMAKE_OBJCXX_LINK_FLAGS ) endif() set(CMAKE_PLATFORM_HAS_INSTALLNAME 1) set(CMAKE_SHARED_LINKER_FLAGS "-rpath @executable_path/Frameworks -rpath @loader_path/Frameworks") set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_LOADER_C_FLAG "-Wl,-bundle_loader,") set(CMAKE_SHARED_MODULE_LOADER_CXX_FLAG "-Wl,-bundle_loader,") set(CMAKE_FIND_LIBRARY_SUFFIXES ".tbd" ".dylib" ".so" ".a") set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-install_name") # Set the find root to the SDK developer roots. # Note: CMAKE_FIND_ROOT_PATH is only useful when cross-compiling. Thus, do not set on macOS builds. if(NOT PLATFORM_INT MATCHES "^MAC.*$") list(APPEND CMAKE_FIND_ROOT_PATH "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") set(CMAKE_IGNORE_PATH "/System/Library/Frameworks;/usr/local/lib" CACHE INTERNAL "") endif() # Default to searching for frameworks first. set(CMAKE_FIND_FRAMEWORK FIRST) # Set up the default search directories for frameworks. if(PLATFORM_INT MATCHES "^MAC_CATALYST") set(CMAKE_FRAMEWORK_PATH ${CMAKE_DEVELOPER_ROOT}/Library/PrivateFrameworks ${CMAKE_OSX_SYSROOT_INT}/System/Library/Frameworks ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/System/Library/Frameworks ${CMAKE_FRAMEWORK_PATH} CACHE INTERNAL "") else() set(CMAKE_FRAMEWORK_PATH ${CMAKE_DEVELOPER_ROOT}/Library/PrivateFrameworks ${CMAKE_OSX_SYSROOT_INT}/System/Library/Frameworks ${CMAKE_FRAMEWORK_PATH} CACHE INTERNAL "") endif() # By default, search both the specified iOS SDK and the remainder of the host filesystem. if(NOT CMAKE_FIND_ROOT_PATH_MODE_PROGRAM) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH CACHE INTERNAL "") endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_LIBRARY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH CACHE INTERNAL "") endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_INCLUDE) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH CACHE INTERNAL "") endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_PACKAGE) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE BOTH CACHE INTERNAL "") endif() # # Some helper-macros below to simplify and beautify the CMakeFile # # This little macro lets you set any Xcode specific property. macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE XCODE_RELVERSION) set(XCODE_RELVERSION_I "${XCODE_RELVERSION}") if(XCODE_RELVERSION_I STREQUAL "All") set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} "${XCODE_VALUE}") else() set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY}[variant=${XCODE_RELVERSION_I}] "${XCODE_VALUE}") endif() endmacro(set_xcode_property) # This macro lets you find executable programs on the host system. macro(find_host_package) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) set(_TOOLCHAIN_IOS ${IOS}) set(IOS OFF) find_package(${ARGN}) set(IOS ${_TOOLCHAIN_IOS}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE BOTH) endmacro(find_host_package) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cmake/libhvConfig.cmake000066400000000000000000000060421520575453600277630ustar00rootroot00000000000000 include(SelectLibraryConfigurations) find_path(libhv_INCLUDE_DIRS hv/hv.h) message("libhv_INCLUDE_DIRS: " ${libhv_INCLUDE_DIRS}) find_library(libhv_LIBRARY_RELEASE NAMES hv PATHS "${CMAKE_CURRENT_LIST_DIR}/../../lib" NO_DEFAULT_PATH) find_library(libhv_LIBRARY_DEBUG NAMES hv PATHS "${CMAKE_CURRENT_LIST_DIR}/../../debug/lib" NO_DEFAULT_PATH) select_library_configurations(libhv) if(NOT libhv_LIBRARY) set(libhv_FOUND FALSE) set(LIBHV_FOUND FALSE) return() endif() if(WIN32) find_file(libhv_LIBRARY_RELEASE_DLL NAMES hv.dll PATHS "${CMAKE_CURRENT_LIST_DIR}/../../bin" NO_DEFAULT_PATH) find_file(libhv_LIBRARY_DEBUG_DLL NAMES hv.dll PATHS "${CMAKE_CURRENT_LIST_DIR}/../../debug/bin" NO_DEFAULT_PATH) endif() # Manage Release Windows shared if(EXISTS "${libhv_LIBRARY_RELEASE_DLL}") add_library(libhv SHARED IMPORTED) set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS Release IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE_DLL}" IMPORTED_IMPLIB_RELEASE "${libhv_LIBRARY_RELEASE}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) endif() # Manage Debug Windows shared if(EXISTS "${libhv_LIBRARY_DEBUG_DLL}") if(EXISTS "${libhv_LIBRARY_RELEASE_DLL}") #message("Debug mode") set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS "Release;Debug" IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE_DLL}" IMPORTED_IMPLIB_RELEASE "${libhv_LIBRARY_RELEASE}" IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG_DLL}" IMPORTED_IMPLIB_DEBUG "${libhv_LIBRARY_DEBUG}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) else() add_library(libhv SHARED IMPORTED) set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS Debug IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG_DLL}" IMPORTED_IMPLIB_DEBUG "${libhv_LIBRARY_DEBUG}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) endif() endif() # Manage Release Windows static and Linux shared/static if((NOT EXISTS "${libhv_LIBRARY_RELEASE_DLL}") AND (EXISTS "${libhv_LIBRARY_RELEASE}")) add_library(libhv UNKNOWN IMPORTED) set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS Release IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) endif() # Manage Debug Windows static and Linux shared/static if((NOT EXISTS "${libhv_LIBRARY_DEBUG_DLL}") AND (EXISTS "${libhv_LIBRARY_DEBUG}")) if(EXISTS "${libhv_LIBRARY_RELEASE}") set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS "Release;Debug" IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE}" IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) else() add_library(libhv UNKNOWN IMPORTED) set_target_properties(libhv PROPERTIES IMPORTED_CONFIGURATIONS Debug IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG}" INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" ) endif() endif() set(libhv_FOUND TRUE) set(LIBHV_FOUND TRUE) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cmake/utils.cmake000066400000000000000000000020701520575453600266660ustar00rootroot00000000000000include(CheckIncludeFiles) macro(check_header header) string(TOUPPER ${header} str1) string(REGEX REPLACE "[/.]" "_" str2 ${str1}) set(str3 HAVE_${str2}) check_include_files(${header} ${str3}) if (${str3}) set(${str3} 1) else() set(${str3} 0) endif() endmacro() include(CheckSymbolExists) macro(check_function function header) string(TOUPPER ${function} str1) set(str2 HAVE_${str1}) check_symbol_exists(${function} ${header} ${str2}) if (${str2}) set(${str2} 1) else() set(${str2} 0) endif() endmacro() macro(list_source_directories srcs) unset(tmp) foreach(dir ${ARGN}) aux_source_directory(${dir} tmp) endforeach() set(${srcs} ${tmp}) list(FILTER ${srcs} EXCLUDE REGEX ".*_test\\.c") endmacro() macro(glob_headers_and_sources files) unset(tmp) foreach(dir ${ARGN}) file(GLOB tmp ${dir}/*.h ${dir}/*.c ${dir}/*.hpp ${dir}/*.cpp) list(APPEND ${files} ${tmp}) endforeach() list(FILTER ${files} EXCLUDE REGEX ".*_test\\.c") endmacro() kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cmake/vars.cmake000066400000000000000000000035421520575453600265060ustar00rootroot00000000000000# see Makefile.vars set(BASE_HEADERS base/hplatform.h base/hdef.h base/hatomic.h base/herr.h base/htime.h base/hmath.h base/hbase.h base/hversion.h base/hsysinfo.h base/hproc.h base/hthread.h base/hmutex.h base/hsocket.h base/hlog.h base/hbuf.h base/hmain.h base/hendian.h ) set(SSL_HEADERS ssl/hssl.h ) set(EVENT_HEADERS event/hloop.h event/nlog.h ) set(UTIL_HEADERS util/base64.h util/md5.h util/sha1.h ) set(CPPUTIL_HEADERS cpputil/hmap.h cpputil/hstring.h cpputil/hfile.h cpputil/hpath.h cpputil/hdir.h cpputil/hurl.h cpputil/hscope.h cpputil/hthreadpool.h cpputil/hasync.h cpputil/hobjectpool.h cpputil/ifconfig.h cpputil/iniparser.h cpputil/json.hpp cpputil/singleton.h cpputil/ThreadLocalStorage.h ) set(EVPP_HEADERS evpp/Buffer.h evpp/Channel.h evpp/Event.h evpp/EventLoop.h evpp/EventLoopThread.h evpp/EventLoopThreadPool.h evpp/Status.h evpp/TcpClient.h evpp/TcpServer.h evpp/UdpClient.h evpp/UdpServer.h ) set(PROTOCOL_HEADERS protocol/icmp.h protocol/dns.h protocol/ftp.h protocol/smtp.h ) set(HTTP_HEADERS http/httpdef.h http/wsdef.h http/http_content.h http/HttpMessage.h http/HttpParser.h http/WebSocketParser.h http/WebSocketChannel.h ) set(HTTP2_HEADERS http/http2def.h http/grpcdef.h ) set(HTTP_CLIENT_HEADERS http/client/HttpClient.h http/client/requests.h http/client/axios.h http/client/AsyncHttpClient.h http/client/WebSocketClient.h) set(HTTP_SERVER_HEADERS http/server/HttpServer.h http/server/HttpService.h http/server/HttpContext.h http/server/HttpResponseWriter.h http/server/WebSocketServer.h ) set(MQTT_HEADERS mqtt/mqtt_protocol.h mqtt/mqtt_client.h ) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/config.ini000066400000000000000000000012501520575453600254110ustar00rootroot00000000000000# Don't modify this file, you should modify config.mk or # run ./configure --with-MODULE --enable-FEATURE PREFIX=/usr/local INSTALL_INCDIR=$(PREFIX)/include/hv INSTALL_LIBDIR=$(PREFIX)/lib # modules # include icmp dns ftp smtp WITH_PROTOCOL=no WITH_EVPP=yes WITH_HTTP=yes WITH_HTTP_SERVER=yes WITH_HTTP_CLIENT=yes WITH_MQTT=no # features # base/hsocket.h: Unix Domain Socket ENABLE_UDS=no # base/RAII.cpp: Windows MiniDumpWriteDump ENABLE_WINDUMP=no # http/http_content.h: KeyValue,QueryParams,MultiPart USE_MULTIMAP=no # dependencies # for http/client WITH_CURL=no # for http2 WITH_NGHTTP2=no # for SSL/TLS WITH_OPENSSL=no WITH_GNUTLS=no WITH_MBEDTLS=no # rudp WITH_KCP=no kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/configure000077500000000000000000000146471520575453600253700ustar00rootroot00000000000000#!/bin/bash . "$(dirname "$0")/scripts/shini.sh" print_help() { shini_parse "config.ini" cat << END Usage: ./configure [--option] ... options: --prefix=PREFIX (DEFAULT: $PREFIX) --incdir=INSTALL_INCDIR (DEFAULT: $PREFIX/include/hv) --libdir=INSTALL_LIBDIR (DEFAULT: $PREFIX/lib) --with-MODULE --without-MODULE --enable-FEATURE --disable-FEATURE modules: --with-protocol compile protocol module? (DEFAULT: $WITH_PROTOCOL) --with-evpp compile evpp module? (DEFAULT: $WITH_EVPP) --with-http compile http module? (DEFAULT: $WITH_HTTP) --with-http-client compile http client module? (DEFAULT: $WITH_HTTP_CLIENT) --with-http-server compile http server module? (DEFAULT: $WITH_HTTP_SERVER) --with-mqtt compile mqtt module? (DEFAULT: $WITH_MQTT) features: --enable-uds enable Unix Domain Socket? (DEFAULT: $ENABLE_UDS) --enable-windump enable Windows coredump? (DEFAULT: $ENABLE_WINDUMP) dependencies: --with-curl compile with curl? (DEFAULT: $WITH_CURL) --with-nghttp2 compile with nghttp2? (DEFAULT: $WITH_NGHTTP2) --with-openssl compile with openssl? (DEFAULT: $WITH_OPENSSL) --with-gnutls compile with gnutls? (DEFAULT: $WITH_GNUTLS) --with-mbedtls compile with mbedtls? (DEFAULT: $WITH_MBEDTLS) rudp: --with-kcp compile with kcp? (DEFAULT: $WITH_KCP) END } mkdir tmp 2>/dev/null while [ -n "$1" ] do opt="$1" KEY="" VAL=yes case $opt in --help) print_help exit 0 ;; --prefix=*) KEY="PREFIX" VAL=${opt:9} ;; --incdir=*) KEY="INSTALL_INCDIR" VAL=${opt:9} ;; --libdir=*) KEY="INSTALL_LIBDIR" VAL=${opt:9} ;; --with-*) KEY="WITH_${opt:7}" ;; --without-*) KEY="WITH_${opt:10}" VAL=no ;; --enable-*) KEY="ENABLE_${opt:9}" ;; --disable-*) KEY="ENABLE_${opt:10}" VAL=no ;; *) print_help exit 255 ;; esac if [ -n $KEY ]; then FEATURE=$(echo "$KEY" | tr "a-z-" "A-Z_") if [ ! -f tmp/config.mk ]; then cp config.ini tmp/config.mk fi shini_write "tmp/config.mk" "" "$FEATURE" "$VAL" fi shift 1 done # config.mk echo "[config.mk]" if [ -f tmp/config.mk ]; then mv tmp/config.mk config.mk shini_write "config.mk" "" "CONFIG_DATE" "$(date +%Y%m%d)" fi cat config.mk echo "" # Checks for compiler echo -e "\nchecking for compiler..." if [ $CROSS_COMPILE ]; then CC=${CROSS_COMPILE}gcc CXX=${CROSS_COMPILE}g++ fi if [ ! $CC ]; then CC=gcc CXX=g++ fi CC_VERSION=`$CC --version 2>&1 | head -n 1` echo "CC = $CC" echo "CXX = $CXX" echo "$CC_VERSION" # Checks for os echo -e "\nchecking for os..." HOST_OS=`uname -s` HOST_ARCH=`uname -m` TARGET_PLATFORM=`$CC -v 2>&1 | grep Target | sed 's/Target: //'` TARGET_ARCH=`echo $TARGET_PLATFORM | awk -F'-' '{print $1}'` case $TARGET_PLATFORM in *mingw*) TARGET_OS=Windows ;; *android*) TARGET_OS=Android ;; *darwin*) TARGET_OS=Darwin ;; *) TARGET_OS=Linux ;; esac echo "HOST_OS = $HOST_OS" echo "HOST_ARCH = $HOST_ARCH" echo "TARGET_PLATFORM = $TARGET_PLATFORM" echo "TARGET_OS = $TARGET_OS" echo "TARGET_ARCH = $TARGET_ARCH" # hconfig.h echo -e "\n>> hconfig.h" confile=hconfig.h cat << END > $confile #ifndef HV_CONFIG_H_ #define HV_CONFIG_H_ END write_define() { cat << END >> hconfig.h #ifndef $macro #define $macro $value #endif END } CheckHeaderExists() { rm tmp/check 2>/dev/null cat << END > tmp/check.c #include <$header> int main() { return 0; } END $CC -o tmp/check tmp/check.c 2>/dev/null if [ -x tmp/check ]; then value=1 else value=0 fi } CheckSymbolExists() { CheckHeaderExists if [ $value -eq 0 ]; then return; fi rm tmp/check 2>/dev/null cat << END > tmp/check.c #include <$header> int $function(void** pp) {return 0;} int main() { void* p; return $function(&p); } END $CC -o tmp/check tmp/check.c 2>/dev/null if [ -x tmp/check ]; then value=0 else value=1 fi } check_header() { echo -n "checking for $header... " CheckHeaderExists if [ $value -eq 0 ]; then echo "no" else echo "yes" fi macro=HAVE_$(echo $header | tr a-z./ A-Z__) write_define } check_function() { echo -n "checking for $function... " CheckSymbolExists if [ $value -eq 0 ]; then echo "no" else echo "yes" fi macro=HAVE_$(echo $function | tr a-z A-Z) write_define } check_option() { value=$(eval echo \$$option) echo "checking for $option=$value" if [ "$value" == "yes" ]; then cat << END >> $confile #define $option 1 END else cat << END >> $confile /* #undef $option */ END fi } # Checks for programs # Checks for libraries # Checks for header files header=stdbool.h && check_header header=stdint.h && check_header header=stdatomic.h && check_header header=sys/types.h && check_header header=sys/stat.h && check_header header=sys/time.h && check_header header=fcntl.h && check_header header=pthread.h && check_header header=endian.h && check_header header=sys/endian.h && check_header # Checks for functions function=gettid && header=unistd.h && check_function function=strlcpy && header=string.h && check_function function=strlcat && header=string.h && check_function function=clock_gettime && header=time.h && check_function function=gettimeofday && header=sys/time.h && check_function function=pthread_spin_lock && header=pthread.h && check_function function=pthread_mutex_timedlock && header=pthread.h && check_function function=sem_timedwait && header=semaphore.h && check_function function=pipe && header=unistd.h && check_function function=socketpair && header=sys/socket.h && check_function function=eventfd && header=sys/eventfd.h && check_function function=setproctitle && header=unistd.h && check_function # Checks for options source config.mk 2>/dev/null option=WITH_OPENSSL && check_option option=WITH_GNUTLS && check_option option=WITH_MBEDTLS && check_option option=ENABLE_UDS && check_option option=USE_MULTIMAP && check_option option=WITH_KCP && check_option # end confile cat << END >> $confile #endif // HV_CONFIG_H_ END echo "configure done." kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/000077500000000000000000000000001520575453600251255ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/RAII.cpp000066400000000000000000000034331520575453600263600ustar00rootroot00000000000000#include "hplatform.h" #ifdef OS_WIN #ifdef ENABLE_WINDUMP #include #ifdef _MSC_VER #pragma comment(lib,"dbghelp.lib") #endif static LONG UnhandledException(EXCEPTION_POINTERS *pException) { char modulefile[256]; GetModuleFileName(NULL, modulefile, sizeof(modulefile)); char* pos = strrchr(modulefile, '\\'); char* modulefilename = pos + 1; SYSTEMTIME st; GetLocalTime(&st); char filename[256]; snprintf(filename, sizeof(filename), "core_%s_%04d%02d%02d_%02d%02d%02d_%03d.dump", modulefilename, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); HANDLE hDumpFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); MINIDUMP_EXCEPTION_INFORMATION dumpInfo; dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); return EXCEPTION_EXECUTE_HANDLER; } #endif #include "hsocket.h" class WsaRAII { public: WsaRAII() { WSAInit(); #ifdef ENABLE_WINDUMP SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)UnhandledException); #endif } ~WsaRAII() { WSADeinit(); } }; static WsaRAII s_wsa; #endif #ifdef WITH_CURL #include "curl/curl.h" #ifdef _MSC_VER //#pragma comment(lib, "libcurl.a") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "wldap32.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "crypt32.lib") #endif class CurlRAII { public: CurlRAII() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlRAII() { curl_global_cleanup(); } }; static CurlRAII s_curl; #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/README.md000066400000000000000000000011361520575453600264050ustar00rootroot00000000000000## 目录结构 ``` . ├── hasync.h hv::async实现 ├── hdir.h 目录(ls实现) ├── hfile.h 文件类 ├── hobjectpool.h 对象池 ├── hpath.h 路径操作 ├── hscope.h 作用域模板类 ├── hstring.h 字符串操作 ├── hthreadpool.h 线程池 ├── hurl.h URL操作 ├── ifconfig.h 网络配置(ifconfig实现) ├── iniparser.h INI解析 ├── json.hpp JSON解析 ├── singleton.h 单例模式宏 └── ThreadLocalStorage.h 线程本地存储类 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/ThreadLocalStorage.cpp000066400000000000000000000012261520575453600313410ustar00rootroot00000000000000#include "ThreadLocalStorage.h" #include "hthread.h" namespace hv { ThreadLocalStorage ThreadLocalStorage::tls[ThreadLocalStorage::MAX_NUM]; void ThreadLocalStorage::set(int idx, void* val) { return tls[idx].set(val); } void* ThreadLocalStorage::get(int idx) { return tls[idx].get(); } void ThreadLocalStorage::setThreadName(const char* name) { set(THREAD_NAME, (void*)name); } const char* ThreadLocalStorage::threadName() { void* value = get(THREAD_NAME); if (value) { return (char*)value; } static char unnamed[32] = {0}; snprintf(unnamed, sizeof(unnamed)-1, "thread-%ld", hv_gettid()); return unnamed; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/ThreadLocalStorage.h000066400000000000000000000027301520575453600310070ustar00rootroot00000000000000#ifndef HV_THREAD_LOCAL_STORAGE_H_ #define HV_THREAD_LOCAL_STORAGE_H_ #include "hexport.h" #include "hplatform.h" #ifdef OS_WIN #define hthread_key_t DWORD #define INVALID_HTHREAD_KEY 0xFFFFFFFF #define hthread_key_create(pkey) *pkey = TlsAlloc() #define hthread_key_delete TlsFree #define hthread_get_value TlsGetValue #define hthread_set_value TlsSetValue #else #define hthread_key_t pthread_key_t #define INVALID_HTHREAD_KEY 0xFFFFFFFF #define hthread_key_create(pkey) pthread_key_create(pkey, NULL) #define hthread_key_delete pthread_key_delete #define hthread_get_value pthread_getspecific #define hthread_set_value pthread_setspecific #endif #ifdef __cplusplus namespace hv { class HV_EXPORT ThreadLocalStorage { public: enum { THREAD_NAME = 0, EVENT_LOOP = 1, MAX_NUM = 16, }; ThreadLocalStorage() { hthread_key_create(&key); } ~ThreadLocalStorage() { hthread_key_delete(key); } void set(void* val) { hthread_set_value(key, val); } void* get() { return hthread_get_value(key); } static void set(int idx, void* val); static void* get(int idx); static void setThreadName(const char* name); static const char* threadName(); private: hthread_key_t key; static ThreadLocalStorage tls[MAX_NUM]; }; } #endif #endif // HV_THREAD_LOCAL_STORAGE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hasync.cpp000066400000000000000000000001111520575453600271070ustar00rootroot00000000000000#include "hasync.h" namespace hv { SINGLETON_IMPL(GlobalThreadPool) } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hasync.h000066400000000000000000000024751520575453600265730ustar00rootroot00000000000000#ifndef HV_ASYNC_H_ #define HV_ASYNC_H_ #include "hexport.h" #include "hthreadpool.h" #include "singleton.h" namespace hv { class HV_EXPORT GlobalThreadPool : public HThreadPool { SINGLETON_DECL(GlobalThreadPool) protected: GlobalThreadPool() : HThreadPool() {} ~GlobalThreadPool() {} }; /* * return a future, calling future.get() will wait task done and return RetType. * async(fn, args...) * async(std::bind(&Class::mem_fn, &obj)) * async(std::mem_fn(&Class::mem_fn, &obj)) * */ template auto async(Fn&& fn, Args&&... args) -> std::future { return GlobalThreadPool::instance()->commit(std::forward(fn), std::forward(args)...); } class async { public: static void startup(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM, int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM, int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) { GlobalThreadPool* gtp = GlobalThreadPool::instance(); if (gtp->isStarted()) return; gtp->setMinThreadNum(min_threads); gtp->setMaxThreadNum(max_threads); gtp->setMaxIdleTime(max_idle_ms); gtp->start(); } static void cleanup() { GlobalThreadPool::exitInstance(); } }; } // end namespace hv #endif // HV_ASYNC_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hdir.cpp000066400000000000000000000053601520575453600265630ustar00rootroot00000000000000#include "hdir.h" #include "hplatform.h" #ifdef OS_WIN //FILETIME starts from 1601-01-01 UTC, epoch from 1970-01-01 UTC //FILETIME unit (100ns) #define FILETIME_EPOCH_DIFF 11644473600 // s time_t FileTime2Epoch(FILETIME filetime) { uint64_t ll = (((uint64_t)filetime.dwHighDateTime) << 32) | filetime.dwLowDateTime; ll /= 1e7; // s return ll - FILETIME_EPOCH_DIFF; } #endif static bool less(const hdir_t& lhs, const hdir_t& rhs) { return stricmp(lhs.name, rhs.name) < 0; } int listdir(const char* dir, std::list& dirs) { int dirlen = strlen(dir); if (dirlen > 256) { return -1; } char path[512]; strcpy(path, dir); if (dir[dirlen-1] != '/') { strcat(path, "/"); ++dirlen; } dirs.clear(); #ifdef OS_UNIX // opendir -> readdir -> closedir DIR* dp = opendir(dir); if (dp == NULL) return -1; struct dirent* result = NULL; struct stat st; hdir_t tmp; while ((result = readdir(dp))) { memset(&tmp, 0, sizeof(hdir_t)); strncpy(tmp.name, result->d_name, sizeof(tmp.name)); strncpy(path+dirlen, result->d_name, sizeof(path)-dirlen); if (lstat(path, &st) == 0) { if (S_ISREG(st.st_mode)) tmp.type = 'f'; else if (S_ISDIR(st.st_mode)) tmp.type = 'd'; else if (S_ISLNK(st.st_mode)) tmp.type = 'l'; else if (S_ISBLK(st.st_mode)) tmp.type = 'b'; else if (S_ISCHR(st.st_mode)) tmp.type = 'c'; else if (S_ISSOCK(st.st_mode)) tmp.type = 's'; else if (S_ISFIFO(st.st_mode)) tmp.type = 'p'; else tmp.type = '-'; tmp.mode = st.st_mode & 0777; tmp.size = st.st_size; tmp.atime = st.st_atime; tmp.mtime = st.st_mtime; tmp.ctime = st.st_ctime; } dirs.push_back(tmp); } closedir(dp); #elif defined(OS_WIN) // FindFirstFile -> FindNextFile -> FindClose strcat(path, "*"); WIN32_FIND_DATAA data; HANDLE h = FindFirstFileA(path, &data); if (h == NULL) { return -1; } hdir_t tmp; do { memset(&tmp, 0, sizeof(hdir_t)); strncpy(tmp.name, data.cFileName, sizeof(tmp.name)); tmp.type = 'f'; if (data.dwFileAttributes & _A_SUBDIR) { tmp.type = 'd'; } tmp.mode = 0777; tmp.size = (((uint64_t)data.nFileSizeHigh) << 32) | data.nFileSizeLow; tmp.atime = FileTime2Epoch(data.ftLastAccessTime); tmp.mtime = FileTime2Epoch(data.ftLastWriteTime); tmp.ctime = FileTime2Epoch(data.ftCreationTime); dirs.push_back(tmp); } while (FindNextFileA(h, &data)); FindClose(h); #endif dirs.sort(less); return dirs.size(); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hdir.h000066400000000000000000000034501520575453600262260ustar00rootroot00000000000000#ifndef HV_DIR_H_ #define HV_DIR_H_ /* *@code int main(int argc, char* argv[]) { const char* dir = "."; if (argc > 1) { dir = argv[1]; } std::list dirs; listdir(dir, dirs); for (auto& item : dirs) { printf("%c%c%c%c%c%c%c%c%c%c\t", item.type, item.mode & 0400 ? 'r' : '-', item.mode & 0200 ? 'w' : '-', item.mode & 0100 ? 'x' : '-', item.mode & 0040 ? 'r' : '-', item.mode & 0020 ? 'w' : '-', item.mode & 0010 ? 'x' : '-', item.mode & 0004 ? 'r' : '-', item.mode & 0002 ? 'w' : '-', item.mode & 0001 ? 'x' : '-'); float hsize; if (item.size < 1024) { printf("%lu\t", item.size); } else if ((hsize = item.size/1024.0f) < 1024.0f) { printf("%.1fK\t", hsize); } else if ((hsize /= 1024.0f) < 1024.0f) { printf("%.1fM\t", hsize); } else { hsize /= 1024.0f; printf("%.1fG\t", hsize); } struct tm* tm = localtime(&item.mtime); printf("%04d-%02d-%02d %02d:%02d:%02d\t", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); printf("%s%s\n", item.name, item.type == 'd' ? "/" : ""); } return 0; } */ #include #include #include #include "hexport.h" typedef struct hdir_s { char name[256]; char type; // f:file d:dir l:link b:block c:char s:socket p:pipe char reserverd; unsigned short mode; size_t size; time_t atime; time_t mtime; time_t ctime; } hdir_t; // listdir: same as ls on unix, dir on win HV_EXPORT int listdir(const char* dir, std::list& dirs); #endif // HV_DIR_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hfile.h000066400000000000000000000056051520575453600263730ustar00rootroot00000000000000#ifndef HV_FILE_H_ #define HV_FILE_H_ #include // for std::string #include "hplatform.h" // for stat #include "hbuf.h" // for HBuf class HFile { public: HFile() { filepath[0] = '\0'; fp = NULL; } ~HFile() { close(); } int open(const char* filepath, const char* mode) { close(); strncpy(this->filepath, filepath, MAX_PATH - 1); fp = fopen(filepath, mode); return fp ? 0 : errno; } void close() { if (fp) { fclose(fp); fp = NULL; } } bool isopen() { return fp != NULL; } int remove() { close(); return ::remove(filepath); } int rename(const char* newpath) { close(); return ::rename(filepath, newpath); } size_t read(void* ptr, size_t len) { return fread(ptr, 1, len, fp); } size_t write(const void* ptr, size_t len) { return fwrite(ptr, 1, len, fp); } size_t write(const std::string& str) { return write(str.c_str(), str.length()); } int seek(size_t offset, int whence = SEEK_SET) { return fseek(fp, offset, whence); } int tell() { return ftell(fp); } int flush() { return fflush(fp); } static size_t size(const char* filepath) { struct stat st; memset(&st, 0, sizeof(st)); stat(filepath, &st); return st.st_size; } size_t size() { return HFile::size(filepath); } size_t readall(HBuf& buf) { size_t filesize = size(); if (filesize == 0) return 0; buf.resize(filesize); return fread(buf.base, 1, filesize, fp); } size_t readall(std::string& str) { size_t filesize = size(); if (filesize == 0) return 0; str.resize(filesize); return fread((void*)str.data(), 1, filesize, fp); } bool readline(std::string& str) { str.clear(); char ch; while (fread(&ch, 1, 1, fp)) { if (ch == '\n') { // unix: LF return true; } if (ch == '\r') { // dos: CRLF // read LF if (fread(&ch, 1, 1, fp) && ch != '\n') { // mac: CR fseek(fp, -1, SEEK_CUR); } return true; } str += ch; } return str.length() != 0; } int readrange(std::string& str, size_t from = 0, size_t to = 0) { size_t filesize = size(); if (filesize == 0) return 0; if (to == 0 || to >= filesize) to = filesize - 1; size_t readbytes = to - from + 1; str.resize(readbytes); fseek(fp, from, SEEK_SET); return fread((void*)str.data(), 1, readbytes, fp); } public: char filepath[MAX_PATH]; FILE* fp; }; #endif // HV_FILE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hmap.h000066400000000000000000000025711520575453600262300ustar00rootroot00000000000000#ifndef HV_MAP_H_ #define HV_MAP_H_ #include "hconfig.h" #include #include // MultiMap namespace std { /* int main() { std::MultiMap kvs; kvs["name"] = "hw"; kvs["filename"] = "1.jpg"; kvs["filename"] = "2.jpg"; //kvs.insert(std::pair("name", "hw")); //kvs.insert(std::pair("filename", "1.jpg")); //kvs.insert(std::pair("filename", "2.jpg")); for (auto& pair : kvs) { printf("%s:%s\n", pair.first.c_str(), pair.second.c_str()); } auto iter = kvs.find("filename"); if (iter != kvs.end()) { for (int i = 0; i < kvs.count("filename"); ++i, ++iter) { printf("%s:%s\n", iter->first.c_str(), iter->second.c_str()); } } return 0; } */ template class MultiMap : public multimap { public: Value& operator[](Key key) { auto iter = this->insert(std::pair(key,Value())); return (*iter).second; } }; } #ifdef USE_MULTIMAP #define HV_MAP std::MultiMap #else #define HV_MAP std::map #endif // KeyValue namespace hv { typedef std::map keyval_t; typedef std::MultiMap multi_keyval_t; typedef HV_MAP KeyValue; } #endif // HV_MAP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hobjectpool.h000066400000000000000000000104271520575453600276120ustar00rootroot00000000000000#ifndef HV_OBJECT_POOL_H_ #define HV_OBJECT_POOL_H_ /* * @usage unittest/objectpool_test.cpp */ #include #include #include #include #define DEFAULT_OBJECT_POOL_INIT_NUM 0 #define DEFAULT_OBJECT_POOL_MAX_NUM 4 #define DEFAULT_OBJECT_POOL_TIMEOUT 3000 // ms template class HObjectFactory { public: static T* create() { return new T; } }; template> class HObjectPool { public: HObjectPool( int init_num = DEFAULT_OBJECT_POOL_INIT_NUM, int max_num = DEFAULT_OBJECT_POOL_MAX_NUM, int timeout = DEFAULT_OBJECT_POOL_TIMEOUT) : _max_num(max_num) , _timeout(timeout) { for (int i = 0; i < init_num; ++i) { T* p = TFactory::create(); if (p) { objects_.push_back(std::shared_ptr(p)); } } _object_num = objects_.size(); } ~HObjectPool() {} int ObjectNum() { return _object_num; } int IdleNum() { return objects_.size(); } int BorrowNum() { return ObjectNum() - IdleNum(); } std::shared_ptr TryBorrow() { std::shared_ptr pObj = NULL; std::lock_guard locker(mutex_); if (!objects_.empty()) { pObj = objects_.front(); objects_.pop_front(); } return pObj; } std::shared_ptr Borrow() { std::shared_ptr pObj = TryBorrow(); if (pObj) { return pObj; } std::unique_lock locker(mutex_); if (_object_num < _max_num) { ++_object_num; // NOTE: unlock to avoid TFactory::create block mutex_.unlock(); T* p = TFactory::create(); mutex_.lock(); if (!p) --_object_num; return std::shared_ptr(p); } if (_timeout > 0) { std::cv_status status = cond_.wait_for(locker, std::chrono::milliseconds(_timeout)); if (status == std::cv_status::timeout) { return NULL; } if (!objects_.empty()) { pObj = objects_.front(); objects_.pop_front(); return pObj; } else { // WARN: No idle object } } return pObj; } void Return(std::shared_ptr& pObj) { if (!pObj) return; std::lock_guard locker(mutex_); objects_.push_back(pObj); cond_.notify_one(); } bool Add(std::shared_ptr& pObj) { std::lock_guard locker(mutex_); if (_object_num >= _max_num) { return false; } objects_.push_back(pObj); ++_object_num; cond_.notify_one(); return true; } bool Remove(std::shared_ptr& pObj) { std::lock_guard locker(mutex_); auto iter = objects_.begin(); while (iter != objects_.end()) { if (*iter == pObj) { iter = objects_.erase(iter); --_object_num; return true; } else { ++iter; } } return false; } void Clear() { std::lock_guard locker(mutex_); objects_.clear(); _object_num = 0; } int _object_num; int _max_num; int _timeout; private: std::list> objects_; std::mutex mutex_; std::condition_variable cond_; }; template> class HPoolObject { public: typedef HObjectPool PoolType; HPoolObject(PoolType& pool) : pool_(pool) { sptr_ = pool_.Borrow(); } ~HPoolObject() { if (sptr_) { pool_.Return(sptr_); } } HPoolObject(const HPoolObject&) = delete; HPoolObject& operator=(const HPoolObject&) = delete; T* get() { return sptr_.get(); } operator bool() { return sptr_.get() != NULL; } T* operator->() { return sptr_.get(); } T operator*() { return *sptr_.get(); } private: PoolType& pool_; std::shared_ptr sptr_; }; #endif // HV_OBJECT_POOL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hpath.cpp000066400000000000000000000054171520575453600267440ustar00rootroot00000000000000#include "hpath.h" #include "hplatform.h" bool HPath::exists(const char* path) { return access(path, 0) == 0; } bool HPath::isdir(const char* path) { if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); stat(path, &st); return S_ISDIR(st.st_mode); } bool HPath::isfile(const char* path) { if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); stat(path, &st); return S_ISREG(st.st_mode); } bool HPath::islink(const char* path) { #ifdef OS_WIN return HPath::isdir(path) && (GetFileAttributesA(path) & FILE_ATTRIBUTE_REPARSE_POINT); #else if (access(path, 0) != 0) return false; struct stat st; memset(&st, 0, sizeof(st)); lstat(path, &st); return S_ISLNK(st.st_mode); #endif } std::string HPath::basename(const std::string& filepath) { std::string::size_type pos1 = filepath.find_last_not_of("/\\"); if (pos1 == std::string::npos) { return "/"; } std::string::size_type pos2 = filepath.find_last_of("/\\", pos1); if (pos2 == std::string::npos) { pos2 = 0; } else { pos2++; } return filepath.substr(pos2, pos1-pos2+1); } std::string HPath::dirname(const std::string& filepath) { std::string::size_type pos1 = filepath.find_last_not_of("/\\"); if (pos1 == std::string::npos) { return "/"; } std::string::size_type pos2 = filepath.find_last_of("/\\", pos1); if (pos2 == std::string::npos) { return "."; } else if (pos2 == 0) { pos2 = 1; } return filepath.substr(0, pos2); } std::string HPath::filename(const std::string& filepath) { std::string::size_type pos1 = filepath.find_last_of("/\\"); if (pos1 == std::string::npos) { pos1 = 0; } else { pos1++; } std::string file = filepath.substr(pos1); std::string::size_type pos2 = file.find_last_of("."); if (pos2 == std::string::npos) { return file; } return file.substr(0, pos2); } std::string HPath::suffixname(const std::string& filepath) { std::string::size_type pos1 = filepath.find_last_of("/\\"); if (pos1 == std::string::npos) { pos1 = 0; } else { pos1++; } std::string file = filepath.substr(pos1); std::string::size_type pos2 = file.find_last_of("."); if (pos2 == std::string::npos) { return ""; } return file.substr(pos2+1); } std::string HPath::join(const std::string& dir, const std::string& filename) { char separator = '/'; #ifdef OS_WIN if (dir.find_first_of("\\") != std::string::npos) { separator = '\\'; } #endif std::string filepath(dir); if (dir[dir.length()-1] != separator) { filepath += separator; } filepath += filename; return filepath; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hpath.h000066400000000000000000000014511520575453600264030ustar00rootroot00000000000000#ifndef HV_PATH_H_ #define HV_PATH_H_ #include // for std::string #include "hexport.h" class HV_EXPORT HPath { public: static bool exists(const char* path); static bool isdir(const char* path); static bool isfile(const char* path); static bool islink(const char* path); // filepath = /mnt/share/image/test.jpg // basename = test.jpg // dirname = /mnt/share/image // filename = test // suffixname = jpg static std::string basename(const std::string& filepath); static std::string dirname(const std::string& filepath); static std::string filename(const std::string& filepath); static std::string suffixname(const std::string& filepath); static std::string join(const std::string& dir, const std::string& filename); }; #endif // HV_PATH_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hscope.h000066400000000000000000000026411520575453600265620ustar00rootroot00000000000000#ifndef HV_SCOPE_H_ #define HV_SCOPE_H_ #include typedef std::function Function; #include "hdef.h" // same as golang defer class Defer { public: Defer(Function&& fn) : _fn(std::move(fn)) {} ~Defer() { if(_fn) _fn();} private: Function _fn; }; #define defer(code) Defer STRINGCAT(_defer_, __LINE__)([&](){code}); class ScopeCleanup { public: template ScopeCleanup(Fn&& fn, Args&&... args) { _cleanup = std::bind(std::forward(fn), std::forward(args)...); } ~ScopeCleanup() { _cleanup(); } private: Function _cleanup; }; template class ScopeFree { public: ScopeFree(T* p) : _p(p) {} ~ScopeFree() {SAFE_FREE(_p);} private: T* _p; }; template class ScopeDelete { public: ScopeDelete(T* p) : _p(p) {} ~ScopeDelete() {SAFE_DELETE(_p);} private: T* _p; }; template class ScopeDeleteArray { public: ScopeDeleteArray(T* p) : _p(p) {} ~ScopeDeleteArray() {SAFE_DELETE_ARRAY(_p);} private: T* _p; }; template class ScopeRelease { public: ScopeRelease(T* p) : _p(p) {} ~ScopeRelease() {SAFE_RELEASE(_p);} private: T* _p; }; template class ScopeLock { public: ScopeLock(T& mutex) : _mutex(mutex) {_mutex.lock();} ~ScopeLock() {_mutex.unlock();} private: T& _mutex; }; #endif // HV_SCOPE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hstring.cpp000066400000000000000000000134431520575453600273140ustar00rootroot00000000000000#include "hstring.h" #include #include #include #include namespace hv { std::string empty_string; std::map empty_map; std::string& toupper(std::string& str) { // std::transform(str.begin(), str.end(), str.begin(), ::toupper); char* p = (char*)str.c_str(); while (*p != '\0') { if (*p >= 'a' && *p <= 'z') { *p &= ~0x20; } ++p; } return str; } std::string& tolower(std::string& str) { // std::transform(str.begin(), str.end(), str.begin(), ::tolower); char* p = (char*)str.c_str(); while (*p != '\0') { if (*p >= 'A' && *p <= 'Z') { *p |= 0x20; } ++p; } return str; } std::string& reverse(std::string& str) { // std::reverse(str.begin(), str.end()); char* b = (char*)str.c_str(); char* e = b + str.length() - 1; char tmp; while (e > b) { tmp = *e; *e = *b; *b = tmp; --e; ++b; } return str; } bool startswith(const std::string& str, const std::string& start) { if (str.length() < start.length()) return false; return str.compare(0, start.length(), start) == 0; } bool endswith(const std::string& str, const std::string& end) { if (str.length() < end.length()) return false; return str.compare(str.length() - end.length(), end.length(), end) == 0; } bool contains(const std::string& str, const std::string& sub) { if (str.length() < sub.length()) return false; return str.find(sub) != std::string::npos; } static inline int vscprintf(const char* fmt, va_list ap) { return vsnprintf(NULL, 0, fmt, ap); } std::string asprintf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); int len = vscprintf(fmt, ap); va_end(ap); std::string str; str.reserve(len+1); // must resize to set str.size str.resize(len); // must recall va_start on unix va_start(ap, fmt); vsnprintf((char*)str.data(), len+1, fmt, ap); va_end(ap); return str; } StringList split(const std::string& str, char delim) { /* std::stringstream ss; ss << str; string item; StringList res; while (std::getline(ss, item, delim)) { res.push_back(item); } return res; */ const char* p = str.c_str(); const char* value = p; StringList res; while (*p != '\0') { if (*p == delim) { res.push_back(std::string(value, p-value)); value = p+1; } ++p; } res.push_back(value); return res; } hv::KeyValue splitKV(const std::string& str, char kv_kv, char k_v) { enum { s_key, s_value, } state = s_key; const char* p = str.c_str(); const char* key = p; const char* value = NULL; int key_len = 0; int value_len = 0; hv::KeyValue kvs; while (*p != '\0') { if (*p == kv_kv) { if (key_len && value_len) { kvs[std::string(key, key_len)] = std::string(value, value_len); key_len = value_len = 0; } state = s_key; key = p+1; } else if (*p == k_v && state != s_value) { state = s_value; value = p+1; } else { state == s_key ? ++key_len : ++value_len; } ++p; } if (key_len && value_len) { kvs[std::string(key, key_len)] = std::string(value, value_len); } return kvs; } std::string trim(const std::string& str, const char* chars) { std::string::size_type pos1 = str.find_first_not_of(chars); if (pos1 == std::string::npos) return ""; std::string::size_type pos2 = str.find_last_not_of(chars); return str.substr(pos1, pos2-pos1+1); } std::string ltrim(const std::string& str, const char* chars) { std::string::size_type pos = str.find_first_not_of(chars); if (pos == std::string::npos) return ""; return str.substr(pos); } std::string rtrim(const std::string& str, const char* chars) { std::string::size_type pos = str.find_last_not_of(chars); return str.substr(0, pos+1); } std::string trim_pairs(const std::string& str, const char* pairs) { const char* s = str.c_str(); const char* e = str.c_str() + str.size() - 1; const char* p = pairs; bool is_pair = false; while (*p != '\0' && *(p+1) != '\0') { if (*s == *p && *e == *(p+1)) { is_pair = true; break; } p += 2; } return is_pair ? str.substr(1, str.size()-2) : str; } std::string replace(const std::string& str, const std::string& find, const std::string& rep) { std::string res(str); std::string::size_type pos = res.find(find); if (pos != std::string::npos) { res.replace(pos, find.size(), rep); } return res; } std::string replaceAll(const std::string& str, const std::string& find, const std::string& rep) { std::string::size_type pos = 0; std::string::size_type a = find.size(); std::string::size_type b = rep.size(); std::string res(str); while ((pos = res.find(find, pos)) != std::string::npos) { res.replace(pos, a, rep); pos += b; } return res; } void NetAddr::from_string(const std::string& ipport) { auto pos = ipport.find_last_of(':'); if (pos != std::string::npos) { ip = trim_pairs(ipport.substr(0, pos), "[]"); std::string strPort = ipport.substr(pos + 1); port = atoi(strPort.c_str()); } else if (ipport.find('.') != std::string::npos) { ip = ipport; port = 0; } else { port = atoi(ipport.c_str()); } } std::string NetAddr::to_string() { const char* fmt = "%s:%d"; if (ip.find(':') != std::string::npos) { fmt = "[%s]:%d"; } return hv::asprintf(fmt, ip.c_str(), port); } } // end namespace hv kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hstring.h000066400000000000000000000053111520575453600267540ustar00rootroot00000000000000#ifndef HV_STRING_H_ #define HV_STRING_H_ #include #include #include #include #include "hexport.h" #include "hplatform.h" #include "hmap.h" #define SPACE_CHARS " \t\r\n" #define PAIR_CHARS "{}[]()<>\"\"\'\'``" namespace hv { HV_EXPORT extern std::string empty_string; HV_EXPORT extern std::map empty_map; typedef std::vector StringList; // std::map class StringCaseLess : public std::less { public: bool operator()(const std::string& lhs, const std::string& rhs) const { return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; } }; // NOTE: low-version NDK not provide std::to_string template HV_INLINE std::string to_string(const T& t) { std::ostringstream oss; oss << t; return oss.str(); } template HV_INLINE T from_string(const std::string& str) { T t; std::istringstream iss(str); iss >> t; return t; } template HV_INLINE void print(const T& t) { std::cout << t; } template HV_INLINE void println(const T& t) { std::cout << t << std::endl; } HV_EXPORT std::string& toupper(std::string& str); HV_EXPORT std::string& tolower(std::string& str); HV_EXPORT std::string& reverse(std::string& str); HV_EXPORT bool startswith(const std::string& str, const std::string& start); HV_EXPORT bool endswith(const std::string& str, const std::string& end); HV_EXPORT bool contains(const std::string& str, const std::string& sub); HV_EXPORT std::string asprintf(const char* fmt, ...); // x,y,z HV_EXPORT StringList split(const std::string& str, char delim = ','); // k1=v1&k2=v2 HV_EXPORT hv::KeyValue splitKV(const std::string& str, char kv_kv = '&', char k_v = '='); HV_EXPORT std::string trim(const std::string& str, const char* chars = SPACE_CHARS); HV_EXPORT std::string ltrim(const std::string& str, const char* chars = SPACE_CHARS); HV_EXPORT std::string rtrim(const std::string& str, const char* chars = SPACE_CHARS); HV_EXPORT std::string trim_pairs(const std::string& str, const char* pairs = PAIR_CHARS); HV_EXPORT std::string replace(const std::string& str, const std::string& find, const std::string& rep); HV_EXPORT std::string replaceAll(const std::string& str, const std::string& find, const std::string& rep); struct HV_EXPORT NetAddr { std::string ip; int port; NetAddr() : port(0) {} NetAddr(const std::string& _ip, int _port) : ip(_ip), port(_port) {} NetAddr(const std::string& ipport) { from_string(ipport); } void from_string(const std::string& ipport); std::string to_string(); }; } // end namespace hv #endif // HV_STRING_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hthreadpool.h000066400000000000000000000153731520575453600276200ustar00rootroot00000000000000#ifndef HV_THREAD_POOL_H_ #define HV_THREAD_POOL_H_ /* * @usage unittest/threadpool_test.cpp */ #include #include #include #include #include #include #include #include #include #include #include #include #define DEFAULT_THREAD_POOL_MIN_THREAD_NUM 1 #define DEFAULT_THREAD_POOL_MAX_THREAD_NUM std::thread::hardware_concurrency() #define DEFAULT_THREAD_POOL_MAX_IDLE_TIME 60000 // ms class HThreadPool { public: using Task = std::function; HThreadPool(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM, int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM, int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) : min_thread_num(min_threads) , max_thread_num(max_threads) , max_idle_time(max_idle_ms) , status(STOP) , cur_thread_num(0) , idle_thread_num(0) {} virtual ~HThreadPool() { stop(); } void setMinThreadNum(int min_threads) { min_thread_num = min_threads; } void setMaxThreadNum(int max_threads) { max_thread_num = max_threads; } void setMaxIdleTime(int ms) { max_idle_time = ms; } int currentThreadNum() { return cur_thread_num; } int idleThreadNum() { return idle_thread_num; } size_t taskNum() { std::lock_guard locker(task_mutex); return tasks.size(); } bool isStarted() { return status != STOP; } bool isStopped() { return status == STOP; } int start(int start_threads = 0) { if (status != STOP) return -1; status = RUNNING; if (start_threads < min_thread_num) start_threads = min_thread_num; if (start_threads > max_thread_num) start_threads = max_thread_num; for (int i = 0; i < start_threads; ++i) { createThread(); } return 0; } int stop() { if (status == STOP) return -1; status = STOP; task_cond.notify_all(); for (auto& i : threads) { if (i.thread->joinable()) { i.thread->join(); } } threads.clear(); cur_thread_num = 0; idle_thread_num = 0; return 0; } int pause() { if (status == RUNNING) { status = PAUSE; } return 0; } int resume() { if (status == PAUSE) { status = RUNNING; } return 0; } int wait() { while (status != STOP) { if (tasks.empty() && idle_thread_num == cur_thread_num) { break; } std::this_thread::yield(); } return 0; } /* * return a future, calling future.get() will wait task done and return RetType. * commit(fn, args...) * commit(std::bind(&Class::mem_fn, &obj)) * commit(std::mem_fn(&Class::mem_fn, &obj)) * */ template auto commit(Fn&& fn, Args&&... args) -> std::future { if (status == STOP) start(); if (idle_thread_num <= tasks.size() && cur_thread_num < max_thread_num) { createThread(); } using RetType = decltype(fn(args...)); auto task = std::make_shared >( std::bind(std::forward(fn), std::forward(args)...)); std::future future = task->get_future(); { std::lock_guard locker(task_mutex); tasks.emplace([task]{ (*task)(); }); } task_cond.notify_one(); return future; } protected: bool createThread() { if (cur_thread_num >= max_thread_num) return false; std::thread* thread = new std::thread([this] { while (status != STOP) { while (status == PAUSE) { std::this_thread::yield(); } Task task; { std::unique_lock locker(task_mutex); task_cond.wait_for(locker, std::chrono::milliseconds(max_idle_time), [this]() { return status == STOP || !tasks.empty(); }); if (status == STOP) return; if (tasks.empty()) { if (cur_thread_num > min_thread_num) { delThread(std::this_thread::get_id()); return; } continue; } --idle_thread_num; task = std::move(tasks.front()); tasks.pop(); } if (task) { task(); ++idle_thread_num; } } }); addThread(thread); return true; } void addThread(std::thread* thread) { thread_mutex.lock(); ++cur_thread_num; ++idle_thread_num; ThreadData data; data.thread = std::shared_ptr(thread); data.id = thread->get_id(); data.status = RUNNING; data.start_time = time(NULL); data.stop_time = 0; threads.emplace_back(data); thread_mutex.unlock(); } void delThread(std::thread::id id) { time_t now = time(NULL); thread_mutex.lock(); --cur_thread_num; --idle_thread_num; auto iter = threads.begin(); while (iter != threads.end()) { if (iter->status == STOP && now > iter->stop_time) { if (iter->thread->joinable()) { iter->thread->join(); iter = threads.erase(iter); continue; } } else if (iter->id == id) { iter->status = STOP; iter->stop_time = time(NULL); } ++iter; } thread_mutex.unlock(); } public: int min_thread_num; int max_thread_num; int max_idle_time; protected: enum Status { STOP, RUNNING, PAUSE, }; struct ThreadData { std::shared_ptr thread; std::thread::id id; Status status; time_t start_time; time_t stop_time; }; std::atomic status; std::atomic cur_thread_num; std::atomic idle_thread_num; std::list threads; std::mutex thread_mutex; std::queue tasks; std::mutex task_mutex; std::condition_variable task_cond; }; #endif // HV_THREAD_POOL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hurl.cpp000066400000000000000000000121521520575453600266040ustar00rootroot00000000000000#include "hurl.h" #include "hdef.h" #include "hbase.h" /* static bool Curl_isunreserved(unsigned char in) { switch(in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return TRUE; default: break; } return FLASE; } */ static inline bool is_unambiguous(char c) { return IS_ALPHANUM(c) || c == '-' || c == '_' || c == '.' || c == '~'; } static inline bool char_in_str(char c, const char* str) { const char* p = str; while (*p && *p != c) ++p; return *p != '\0'; } static inline unsigned char hex2i(char hex) { return hex <= '9' ? hex - '0' : hex <= 'F' ? hex - 'A' + 10 : hex - 'a' + 10; } std::string HUrl::escape(const std::string& str, const char* unescaped_chars) { std::string ostr; static char tab[] = "0123456789ABCDEF"; const unsigned char* p = reinterpret_cast(str.c_str()); char szHex[4] = "%00"; while (*p != '\0') { if (is_unambiguous(*p) || char_in_str(*p, unescaped_chars)) { ostr += *p; } else { szHex[1] = tab[*p >> 4]; szHex[2] = tab[*p & 0xF]; ostr += szHex; } ++p; } return ostr; } std::string HUrl::unescape(const std::string& str) { std::string ostr; const char* p = str.c_str(); while (*p != '\0') { if (*p == '%' && IS_HEX(p[1]) && IS_HEX(p[2])) { ostr += ((hex2i(p[1]) << 4) | hex2i(p[2])); p += 3; } else { if (*p == '+') { ostr += ' '; } else { ostr += *p; } ++p; } } return ostr; } void HUrl::reset() { url.clear(); scheme.clear(); username.clear(); password.clear(); host.clear(); port = 0; path.clear(); query.clear(); fragment.clear(); } bool HUrl::parse(const std::string& url) { reset(); this->url = url; hurl_t stURL; if (hv_parse_url(&stURL, url.c_str()) != 0) { return false; } int len = stURL.fields[HV_URL_SCHEME].len; if (len > 0) { scheme = url.substr(stURL.fields[HV_URL_SCHEME].off, len); } len = stURL.fields[HV_URL_USERNAME].len; if (len > 0) { username = url.substr(stURL.fields[HV_URL_USERNAME].off, len); len = stURL.fields[HV_URL_PASSWORD].len; if (len > 0) { password = url.substr(stURL.fields[HV_URL_PASSWORD].off, len); } } len = stURL.fields[HV_URL_HOST].len; if (len > 0) { host = url.substr(stURL.fields[HV_URL_HOST].off, len); } port = stURL.port; len = stURL.fields[HV_URL_PATH].len; if (len > 0) { path = url.substr(stURL.fields[HV_URL_PATH].off, len); } else { path = "/"; } len = stURL.fields[HV_URL_QUERY].len; if (len > 0) { query = url.substr(stURL.fields[HV_URL_QUERY].off, len); } len = stURL.fields[HV_URL_FRAGMENT].len; if (len > 0) { fragment = url.substr(stURL.fields[HV_URL_FRAGMENT].off, len); } return true; } const std::string& HUrl::dump() { url.clear(); // scheme:// if (!scheme.empty()) { url += scheme; url += "://"; } // user:pswd@ if (!username.empty()) { url += username; if (!password.empty()) { url += ":"; url += password; } url += "@"; } // host:port if (!host.empty()) { url += host; if (port != 80 && port != 443) { char buf[16] = {0}; snprintf(buf, sizeof(buf), ":%d", port); url += port; } } // /path if (!path.empty()) { url += path; } // ?query if (!query.empty()) { url += '?'; url += query; } // #fragment if (!fragment.empty()) { url += '#'; url += fragment; } return url; } namespace hv { std::string escapeHTML(const std::string& str) { std::string ostr; const char* p = str.c_str(); while (*p != '\0') { switch (*p) { case '<': ostr += "<"; break; case '>': ostr += ">"; break; case '&': ostr += "&"; break; case '\"': ostr += """; break; case '\'': ostr += "'"; break; // case ' ': ostr += " "; break; default: ostr += *p; break; } ++p; } return ostr; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/hurl.h000066400000000000000000000015151520575453600262520ustar00rootroot00000000000000#ifndef HV_URL_H_ #define HV_URL_H_ #include // import std::string #include "hexport.h" class HV_EXPORT HUrl { public: static std::string escape(const std::string& str, const char* unescaped_chars = ""); static std::string unescape(const std::string& str); HUrl() : port(0) {} ~HUrl() {} void reset(); bool parse(const std::string& url); const std::string& dump(); std::string url; std::string scheme; std::string username; std::string password; std::string host; int port; std::string path; std::string query; std::string fragment; }; namespace hv { HV_INLINE std::string escapeURL(const std::string& url) { return HUrl::escape(url, ":/@?=&#+"); } HV_EXPORT std::string escapeHTML(const std::string& str); } // end namespace hv #endif // HV_URL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/ifconfig.cpp000066400000000000000000000160111520575453600274140ustar00rootroot00000000000000#include "ifconfig.h" #include "hplatform.h" #ifdef OS_LINUX #include #include #include #include #include #include #include int ifconfig(std::vector& ifcs) { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { return -10; } struct ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; int iRet = ioctl(sock, SIOCGIFCONF, &ifc); if (iRet != 0) { close(sock); return iRet; } int cnt = ifc.ifc_len / sizeof(struct ifreq); //printf("ifc.size=%d\n", cnt); if (cnt == 0) { close(sock); return -20; } struct ifreq ifr; ifcs.clear(); ifconfig_t tmp; for (int i = 0; i < cnt; ++i) { // name strcpy(ifr.ifr_name, ifc.ifc_req[i].ifr_name); //printf("name: %s\n", ifr.ifr_name); strncpy(tmp.name, ifr.ifr_name, sizeof(tmp.name)); // flags //iRet = ioctl(sock, SIOCGIFFLAGS, &ifr); //short flags = ifr.ifr_flags; // addr iRet = ioctl(sock, SIOCGIFADDR, &ifr); struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr; char* ip = inet_ntoa(addr->sin_addr); //printf("ip: %s\n", ip); strncpy(tmp.ip, ip, sizeof(tmp.ip)); // netmask iRet = ioctl(sock, SIOCGIFNETMASK, &ifr); addr = (struct sockaddr_in*)&ifr.ifr_netmask; char* netmask = inet_ntoa(addr->sin_addr); //printf("netmask: %s\n", netmask); strncpy(tmp.mask, netmask, sizeof(tmp.mask)); // broadaddr iRet = ioctl(sock, SIOCGIFBRDADDR, &ifr); addr = (struct sockaddr_in*)&ifr.ifr_broadaddr; char* broadaddr = inet_ntoa(addr->sin_addr); //printf("broadaddr: %s\n", broadaddr); strncpy(tmp.broadcast, broadaddr, sizeof(tmp.broadcast)); // hwaddr iRet = ioctl(sock, SIOCGIFHWADDR, &ifr); snprintf(tmp.mac, sizeof(tmp.mac), "%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char)ifr.ifr_hwaddr.sa_data[0], (unsigned char)ifr.ifr_hwaddr.sa_data[1], (unsigned char)ifr.ifr_hwaddr.sa_data[2], (unsigned char)ifr.ifr_hwaddr.sa_data[3], (unsigned char)ifr.ifr_hwaddr.sa_data[4], (unsigned char)ifr.ifr_hwaddr.sa_data[5]); //printf("mac: %s\n", tmp.mac); //printf("\n"); if (strcmp(tmp.ip, "0.0.0.0") == 0 || strcmp(tmp.ip, "127.0.0.1") == 0 || strcmp(tmp.mac, "00:00:00:00:00:00") == 0) { continue; } ifcs.push_back(tmp); } close(sock); return 0; } #elif defined(OS_WIN) #include #include #include #include int ifconfig(std::vector& ifcs) { PIP_ADAPTER_ADDRESSES pAddrs = NULL; ULONG buflen = 0; GetAdaptersAddresses(AF_INET, 0, NULL, pAddrs, &buflen); pAddrs = (PIP_ADAPTER_ADDRESSES)malloc(buflen); GetAdaptersAddresses(AF_INET, 0, NULL, pAddrs, &buflen); PIP_ADAPTER_INFO pInfos = NULL; buflen = 0; GetAdaptersInfo(pInfos, &buflen); pInfos = (PIP_ADAPTER_INFO)malloc(buflen); GetAdaptersInfo(pInfos, &buflen); ifconfig_t ifc; std::vector tmp_ifcs; PIP_ADAPTER_ADDRESSES pAddr = pAddrs; char mac[32] = {'\0'}; while (pAddr) { snprintf(mac, sizeof(mac), "%02x:%02x:%02x:%02x:%02x:%02x", pAddr->PhysicalAddress[0], pAddr->PhysicalAddress[1], pAddr->PhysicalAddress[2], pAddr->PhysicalAddress[3], pAddr->PhysicalAddress[4], pAddr->PhysicalAddress[5]); memset(&ifc, 0, sizeof(ifc)); strncpy(ifc.name, pAddr->AdapterName, sizeof(ifc.name)); strncpy(ifc.ip, "0.0.0.0", sizeof(ifc.ip)); strncpy(ifc.mask, "255.255.255.255", sizeof(ifc.mask)); strncpy(ifc.mac, mac, sizeof(ifc.mac)); tmp_ifcs.push_back(ifc); pAddr = pAddr->Next; } PIP_ADAPTER_INFO pInfo = pInfos; while (pInfo) { for (auto& item : tmp_ifcs) { if (strcmp(item.name, pInfo->AdapterName) == 0) { // description more friendly strncpy(item.name, pInfo->Description, sizeof(item.name)); strncpy(item.ip, pInfo->IpAddressList.IpAddress.String, sizeof(item.ip)); strncpy(item.mask, pInfo->IpAddressList.IpMask.String, sizeof(item.mask)); } } pInfo = pInfo->Next; } free(pAddrs); free(pInfos); // filter ifcs.clear(); for (auto& item : tmp_ifcs) { if (strcmp(item.ip, "0.0.0.0") == 0 || strcmp(item.ip, "127.0.0.1") == 0 || strcmp(item.mac, "00:00:00:00:00:00") == 0) { continue; } ifcs.push_back(item); } return 0; } #elif defined(OS_MAC) #include #include int ifconfig(std::vector& ifcs) { struct ifaddrs *ifas, *ifap; int ret = getifaddrs(&ifas); if (ret != 0) return ret; ifconfig_s tmp; for (ifap = ifas; ifap != NULL; ifap = ifap->ifa_next) { if (ifap->ifa_addr->sa_family == AF_INET) { // ipv4 struct sockaddr_in* addr = (struct sockaddr_in*)ifap->ifa_addr; char* ip = inet_ntoa(addr->sin_addr); // filter if (strcmp(ip, "0.0.0.0") == 0 || strcmp(ip, "127.0.0.1") == 0) { continue; } memset(&tmp, 0, sizeof(tmp)); strncpy(tmp.name, ifap->ifa_name, sizeof(tmp.name)); strncpy(tmp.ip, ip, sizeof(tmp.ip)); // netmask addr = (struct sockaddr_in*)ifap->ifa_netmask; char* netmask = inet_ntoa(addr->sin_addr); strncpy(tmp.mask, netmask, sizeof(tmp.mask)); // broadaddr addr = (struct sockaddr_in*)ifap->ifa_broadaddr; char* broadaddr = inet_ntoa(addr->sin_addr); strncpy(tmp.broadcast, broadaddr, sizeof(tmp.broadcast)); // push_back ifcs.push_back(tmp); } } for (ifap = ifas; ifap != NULL; ifap = ifap->ifa_next) { if (ifap->ifa_addr->sa_family == AF_LINK) { // hwaddr for (auto iter = ifcs.begin(); iter != ifcs.end(); ++iter) { if (strcmp(iter->name, ifap->ifa_name) == 0) { struct sockaddr_dl* addr = (struct sockaddr_dl*)ifap->ifa_addr; unsigned char* pmac = (unsigned char*)LLADDR(addr); snprintf(iter->mac, sizeof(iter->mac), "%02x:%02x:%02x:%02x:%02x:%02x", pmac[0], pmac[1], pmac[2], pmac[3], pmac[4], pmac[5]); // filter if (strcmp(iter->mac, "00:00:00:00:00:00") == 0) { ifcs.erase(iter); } break; } } } } freeifaddrs(ifas); return 0; } #else int ifconfig(std::vector& ifcs) { return -10; // unimplemented } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/ifconfig.h000066400000000000000000000013161520575453600270630ustar00rootroot00000000000000#ifndef HV_IFCONFIG_H_ #define HV_IFCONFIG_H_ #include #include "hexport.h" #ifdef _MSC_VER #pragma comment(lib, "iphlpapi.lib") #pragma comment(lib, "ws2_32.lib") #endif typedef struct ifconfig_s { char name[128]; char ip[16]; char mask[16]; char broadcast[16]; char mac[20]; } ifconfig_t; /* * @test std::vector ifcs; ifconfig(ifcs); for (auto& item : ifcs) { printf("%s\nip: %s\nmask: %s\nbroadcast: %s\nmac: %s\n\n", item.name, item.ip, item.mask, item.broadcast, item.mac); } */ HV_EXPORT int ifconfig(std::vector& ifcs); #endif // HV_IFCONFIG_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/iniparser.cpp000066400000000000000000000232761520575453600276370ustar00rootroot00000000000000#include "iniparser.h" #include #include "hdef.h" #include "herr.h" #include "hstring.h" #include "hfile.h" #include "hbase.h" using namespace hv; /********************************** # div [section] key = value # span # div ***********************************/ class IniNode { public: enum Type { INI_NODE_TYPE_UNKNOWN, INI_NODE_TYPE_ROOT, INI_NODE_TYPE_SECTION, INI_NODE_TYPE_KEY_VALUE, INI_NODE_TYPE_DIV, INI_NODE_TYPE_SPAN, } type; std::string label; // section|key|comment std::string value; std::list children; virtual ~IniNode() { for (auto pNode : children) { if (pNode) { delete pNode; } } children.clear(); } void Add(IniNode* pNode) { children.push_back(pNode); } void Del(IniNode* pNode) { for (auto iter = children.begin(); iter != children.end(); ++iter) { if ((*iter) == pNode) { delete (*iter); children.erase(iter); return; } } } IniNode* Get(const std::string& label, Type type = INI_NODE_TYPE_KEY_VALUE) { for (auto pNode : children) { if (pNode->type == type && pNode->label == label) { return pNode; } } return NULL; } }; class IniSection : public IniNode { public: IniSection() : IniNode(), section(label) { type = INI_NODE_TYPE_SECTION; } std::string §ion; }; class IniKeyValue : public IniNode { public: IniKeyValue() : IniNode(), key(label) { type = INI_NODE_TYPE_KEY_VALUE; } std::string &key; }; class IniComment : public IniNode { public: IniComment() : IniNode(), comment(label) { } std::string &comment; }; IniParser::IniParser() { _comment = DEFAULT_INI_COMMENT; _delim = DEFAULT_INI_DELIM; root_ = NULL; } IniParser::~IniParser() { Unload(); } int IniParser::Unload() { SAFE_DELETE(root_); return 0; } int IniParser::Reload() { return LoadFromFile(_filepath.c_str()); } int IniParser::LoadFromFile(const char* filepath) { _filepath = filepath; HFile file; if (file.open(filepath, "r") != 0) { return ERR_OPEN_FILE; } std::string str; file.readall(str); const char* c_str = str.c_str(); unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF }; if (str.size() >= 3 && memcmp(c_str, utf8_bom, 3) == 0) { c_str += 3; } return LoadFromMem(c_str); } int IniParser::LoadFromMem(const char* data) { Unload(); root_ = new IniNode; root_->type = IniNode::INI_NODE_TYPE_ROOT; std::stringstream ss; ss << data; std::string strLine; int line = 0; std::string::size_type pos; std::string content, comment, strDiv; IniNode* pScopeNode = root_; IniNode* pNewNode = NULL; while (std::getline(ss, strLine)) { ++line; content = ltrim(strLine); if (content.length() == 0) { // blank line strDiv += '\n'; continue; } // trim_comment comment = ""; pos = content.find_first_of(_comment); if (pos != std::string::npos) { comment = content.substr(pos); content = content.substr(0, pos); } content = rtrim(content); if (content.length() == 0) { strDiv += strLine; strDiv += '\n'; continue; } else if (strDiv.length() != 0) { IniNode* pNode = new IniNode; pNode->type = IniNode::INI_NODE_TYPE_DIV; pNode->label = strDiv; pScopeNode->Add(pNode); strDiv = ""; } if (content[0] == '[') { if (content[content.length()-1] == ']') { // section content = trim(content.substr(1, content.length()-2)); pNewNode = new IniNode; pNewNode->type = IniNode::INI_NODE_TYPE_SECTION; pNewNode->label = content; root_->Add(pNewNode); pScopeNode = pNewNode; } else { // hlogw("format error, line:%d", line); continue; // ignore } } else { pos = content.find_first_of(_delim); if (pos != std::string::npos) { // key-value pNewNode = new IniNode; pNewNode->type = IniNode::INI_NODE_TYPE_KEY_VALUE; pNewNode->label = trim(content.substr(0, pos)); pNewNode->value = trim(content.substr(pos+_delim.length())); pScopeNode->Add(pNewNode); } else { // hlogw("format error, line:%d", line); continue; // ignore } } if (comment.length() != 0) { // tail_comment IniNode* pNode = new IniNode; pNode->type = IniNode::INI_NODE_TYPE_SPAN; pNode->label = comment; pNewNode->Add(pNode); comment = ""; } } // file end comment if (strDiv.length() != 0) { IniNode* pNode = new IniNode; pNode->type = IniNode::INI_NODE_TYPE_DIV; pNode->label = strDiv; root_->Add(pNode); } return 0; } void IniParser::DumpString(IniNode* pNode, std::string& str) { if (pNode == NULL) return; if (pNode->type != IniNode::INI_NODE_TYPE_SPAN) { if (str.length() > 0 && str[str.length()-1] != '\n') { str += '\n'; } } switch (pNode->type) { case IniNode::INI_NODE_TYPE_SECTION: { str += '['; str += pNode->label; str += ']'; } break; case IniNode::INI_NODE_TYPE_KEY_VALUE: { str += asprintf("%s %s %s", pNode->label.c_str(), _delim.c_str(), pNode->value.c_str()); } break; case IniNode::INI_NODE_TYPE_DIV: { str += pNode->label; } break; case IniNode::INI_NODE_TYPE_SPAN: { str += '\t'; str += pNode->label; } break; default: break; } for (auto p : pNode->children) { DumpString(p, str); } } std::string IniParser::DumpString() { std::string str; DumpString(root_, str); return str; } int IniParser::Save() { return SaveAs(_filepath.c_str()); } int IniParser::SaveAs(const char* filepath) { std::string str = DumpString(); if (str.length() == 0) { return 0; } HFile file; if (file.open(filepath, "w") != 0) { return ERR_SAVE_FILE; } file.write(str.c_str(), str.length()); return 0; } std::list IniParser::GetSections() { std::list ret; if (root_ == NULL) return ret; for (auto pNode : root_->children) { if (pNode->type == IniNode::INI_NODE_TYPE_SECTION) { ret.push_back(pNode->label); } } return ret; } std::list IniParser::GetKeys(const std::string& section) { std::list ret; if (root_ == NULL) return ret; IniNode* pSection = root_; if (section.length() != 0) { pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); if (pSection == NULL) return ret; } for (auto pNode : pSection->children) { if (pNode->type == IniNode::INI_NODE_TYPE_KEY_VALUE) { ret.push_back(pNode->label); } } return ret; } std::string IniParser::GetValue(const std::string& key, const std::string& section) { if (root_ == NULL) return ""; IniNode* pSection = root_; if (section.length() != 0) { pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); if (pSection == NULL) return ""; } IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE); if (pKV == NULL) return ""; return pKV->value; } void IniParser::SetValue(const std::string& key, const std::string& value, const std::string& section) { if (root_ == NULL) { root_ = new IniNode; } IniNode* pSection = root_; if (section.length() != 0) { pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); if (pSection == NULL) { pSection = new IniNode; pSection->type = IniNode::INI_NODE_TYPE_SECTION; pSection->label = section; root_->Add(pSection); } } IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE); if (pKV == NULL) { pKV = new IniNode; pKV->type = IniNode::INI_NODE_TYPE_KEY_VALUE; pKV->label = key; pSection->Add(pKV); } pKV->value = value; } template<> HV_EXPORT bool IniParser::Get(const std::string& key, const std::string& section, bool defvalue) { std::string str = GetValue(key, section); return str.empty() ? defvalue : hv_getboolean(str.c_str()); } template<> HV_EXPORT int IniParser::Get(const std::string& key, const std::string& section, int defvalue) { std::string str = GetValue(key, section); return str.empty() ? defvalue : atoi(str.c_str()); } template<> HV_EXPORT float IniParser::Get(const std::string& key, const std::string& section, float defvalue) { std::string str = GetValue(key, section); return str.empty() ? defvalue : atof(str.c_str()); } template<> HV_EXPORT void IniParser::Set(const std::string& key, const bool& value, const std::string& section) { SetValue(key, value ? "true" : "false", section); } template<> HV_EXPORT void IniParser::Set(const std::string& key, const int& value, const std::string& section) { SetValue(key, asprintf("%d", value), section); } template<> HV_EXPORT void IniParser::Set(const std::string& key, const float& value, const std::string& section) { SetValue(key, asprintf("%f", value), section); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/iniparser.h000066400000000000000000000023701520575453600272740ustar00rootroot00000000000000#ifndef HV_INI_PARSER_H_ #define HV_INI_PARSER_H_ #include #include #include "hexport.h" #define DEFAULT_INI_COMMENT "#" #define DEFAULT_INI_DELIM "=" // fwd class IniNode; class HV_EXPORT IniParser { public: IniParser(); ~IniParser(); int LoadFromFile(const char* filepath); int LoadFromMem(const char* data); int Unload(); int Reload(); std::string DumpString(); int Save(); int SaveAs(const char* filepath); std::list GetSections(); std::list GetKeys(const std::string& section = ""); std::string GetValue(const std::string& key, const std::string& section = ""); void SetValue(const std::string& key, const std::string& value, const std::string& section = ""); // T = [bool, int, float] template T Get(const std::string& key, const std::string& section = "", T defvalue = 0); // T = [bool, int, float] template void Set(const std::string& key, const T& value, const std::string& section = ""); protected: void DumpString(IniNode* pNode, std::string& str); public: std::string _comment; std::string _delim; std::string _filepath; private: IniNode* root_; }; #endif // HV_INI_PARSER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/json.hpp000066400000000000000000034210311520575453600266130ustar00rootroot00000000000000/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.9.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . SPDX-License-Identifier: MIT Copyright (c) 2013-2019 Niels Lohmann . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 9 #define NLOHMANN_JSON_VERSION_PATCH 1 #include // all_of, find, for_each #include // nullptr_t, ptrdiff_t, size_t #include // hash, less #include // initializer_list #include // istream, ostream #include // random_access_iterator_tag #include // unique_ptr #include // accumulate #include // string, stoi, to_string #include // declval, forward, move, pair, swap #include // vector // #include #include // #include #include // transform #include // array #include // forward_list #include // inserter, front_inserter, end #include // map #include // string #include // tuple, make_tuple #include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible #include // unordered_map #include // pair, declval #include // valarray // #include #include // exception #include // runtime_error #include // to_string // #include #include // size_t namespace nlohmann { namespace detail { /// struct to capture the start position of the current token struct position_t { /// the total number of characters read std::size_t chars_read_total = 0; /// the number of characters read in the current line std::size_t chars_read_current_line = 0; /// the number of lines read std::size_t lines_read = 0; /// conversion to size_t to preserve SAX interface constexpr operator size_t() const { return chars_read_total; } }; } // namespace detail } // namespace nlohmann // #include #include // pair // #include /* Hedley - https://nemequ.github.io/hedley * Created by Evan Nemerson * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to * the public domain worldwide. This software is distributed without * any warranty. * * For details, see . * SPDX-License-Identifier: CC0-1.0 */ #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 13) #if defined(JSON_HEDLEY_VERSION) #undef JSON_HEDLEY_VERSION #endif #define JSON_HEDLEY_VERSION 13 #if defined(JSON_HEDLEY_STRINGIFY_EX) #undef JSON_HEDLEY_STRINGIFY_EX #endif #define JSON_HEDLEY_STRINGIFY_EX(x) #x #if defined(JSON_HEDLEY_STRINGIFY) #undef JSON_HEDLEY_STRINGIFY #endif #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) #if defined(JSON_HEDLEY_CONCAT_EX) #undef JSON_HEDLEY_CONCAT_EX #endif #define JSON_HEDLEY_CONCAT_EX(a,b) a##b #if defined(JSON_HEDLEY_CONCAT) #undef JSON_HEDLEY_CONCAT #endif #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) #if defined(JSON_HEDLEY_CONCAT3_EX) #undef JSON_HEDLEY_CONCAT3_EX #endif #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c #if defined(JSON_HEDLEY_CONCAT3) #undef JSON_HEDLEY_CONCAT3 #endif #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) #if defined(JSON_HEDLEY_VERSION_ENCODE) #undef JSON_HEDLEY_VERSION_ENCODE #endif #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #endif #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) #undef JSON_HEDLEY_VERSION_DECODE_MINOR #endif #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) #undef JSON_HEDLEY_VERSION_DECODE_REVISION #endif #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) #if defined(JSON_HEDLEY_GNUC_VERSION) #undef JSON_HEDLEY_GNUC_VERSION #endif #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #elif defined(__GNUC__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) #endif #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) #undef JSON_HEDLEY_GNUC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GNUC_VERSION) #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION) #undef JSON_HEDLEY_MSVC_VERSION #endif #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) #elif defined(_MSC_FULL_VER) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) #elif defined(_MSC_VER) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) #undef JSON_HEDLEY_MSVC_VERSION_CHECK #endif #if !defined(_MSC_VER) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) #elif defined(_MSC_VER) && (_MSC_VER >= 1400) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) #elif defined(_MSC_VER) && (_MSC_VER >= 1200) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) #else #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #undef JSON_HEDLEY_INTEL_VERSION #endif #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) #elif defined(__INTEL_COMPILER) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) #undef JSON_HEDLEY_INTEL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PGI_VERSION) #undef JSON_HEDLEY_PGI_VERSION #endif #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) #endif #if defined(JSON_HEDLEY_PGI_VERSION_CHECK) #undef JSON_HEDLEY_PGI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PGI_VERSION) #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #undef JSON_HEDLEY_SUNPRO_VERSION #endif #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) #elif defined(__SUNPRO_C) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) #elif defined(__SUNPRO_CC) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #endif #if defined(__EMSCRIPTEN__) #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_ARM_VERSION) #undef JSON_HEDLEY_ARM_VERSION #endif #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) #elif defined(__CC_ARM) && defined(__ARMCC_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) #endif #if defined(JSON_HEDLEY_ARM_VERSION_CHECK) #undef JSON_HEDLEY_ARM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_ARM_VERSION) #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IBM_VERSION) #undef JSON_HEDLEY_IBM_VERSION #endif #if defined(__ibmxl__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) #elif defined(__xlC__) && defined(__xlC_ver__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) #elif defined(__xlC__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) #endif #if defined(JSON_HEDLEY_IBM_VERSION_CHECK) #undef JSON_HEDLEY_IBM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IBM_VERSION) #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_VERSION) #undef JSON_HEDLEY_TI_VERSION #endif #if \ defined(__TI_COMPILER_VERSION__) && \ ( \ defined(__TMS470__) || defined(__TI_ARM__) || \ defined(__MSP430__) || \ defined(__TMS320C2000__) \ ) #if (__TI_COMPILER_VERSION__ >= 16000000) #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #endif #if defined(JSON_HEDLEY_TI_VERSION_CHECK) #undef JSON_HEDLEY_TI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_VERSION) #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #undef JSON_HEDLEY_TI_CL2000_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #undef JSON_HEDLEY_TI_CL430_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #undef JSON_HEDLEY_TI_ARMCL_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #undef JSON_HEDLEY_TI_CL6X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #undef JSON_HEDLEY_TI_CL7X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #undef JSON_HEDLEY_TI_CLPRU_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #undef JSON_HEDLEY_CRAY_VERSION #endif #if defined(_CRAYC) #if defined(_RELEASE_PATCHLEVEL) #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) #else #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) #endif #endif #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) #undef JSON_HEDLEY_CRAY_VERSION_CHECK #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IAR_VERSION) #undef JSON_HEDLEY_IAR_VERSION #endif #if defined(__IAR_SYSTEMS_ICC__) #if __VER__ > 1000 #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) #else #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0) #endif #endif #if defined(JSON_HEDLEY_IAR_VERSION_CHECK) #undef JSON_HEDLEY_IAR_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IAR_VERSION) #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #undef JSON_HEDLEY_TINYC_VERSION #endif #if defined(__TINYC__) #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) #endif #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) #undef JSON_HEDLEY_TINYC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_DMC_VERSION) #undef JSON_HEDLEY_DMC_VERSION #endif #if defined(__DMC__) #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) #endif #if defined(JSON_HEDLEY_DMC_VERSION_CHECK) #undef JSON_HEDLEY_DMC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_DMC_VERSION) #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #undef JSON_HEDLEY_COMPCERT_VERSION #endif #if defined(__COMPCERT_VERSION__) #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #undef JSON_HEDLEY_PELLES_VERSION #endif #if defined(__POCC__) #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) #undef JSON_HEDLEY_PELLES_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_GCC_VERSION) #undef JSON_HEDLEY_GCC_VERSION #endif #if \ defined(JSON_HEDLEY_GNUC_VERSION) && \ !defined(__clang__) && \ !defined(JSON_HEDLEY_INTEL_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_ARM_VERSION) && \ !defined(JSON_HEDLEY_TI_VERSION) && \ !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ !defined(__COMPCERT__) #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION #endif #if defined(JSON_HEDLEY_GCC_VERSION_CHECK) #undef JSON_HEDLEY_GCC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GCC_VERSION) #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_HAS_ATTRIBUTE) #undef JSON_HEDLEY_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) #else #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #endif #if \ defined(__has_cpp_attribute) && \ defined(__cplusplus) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #endif #if !defined(__cplusplus) || !defined(__has_cpp_attribute) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #elif \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_BUILTIN) #undef JSON_HEDLEY_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) #else #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) #undef JSON_HEDLEY_GCC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_FEATURE) #undef JSON_HEDLEY_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) #else #define JSON_HEDLEY_HAS_FEATURE(feature) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) #undef JSON_HEDLEY_GNUC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_FEATURE) #undef JSON_HEDLEY_GCC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_EXTENSION) #undef JSON_HEDLEY_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) #else #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) #undef JSON_HEDLEY_GCC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_WARNING) #undef JSON_HEDLEY_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) #else #define JSON_HEDLEY_HAS_WARNING(warning) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_WARNING) #undef JSON_HEDLEY_GNUC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_WARNING) #undef JSON_HEDLEY_GCC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # endif # endif #endif #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x #endif #if defined(JSON_HEDLEY_CONST_CAST) #undef JSON_HEDLEY_CONST_CAST #endif #if defined(__cplusplus) # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) #elif \ JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_REINTERPRET_CAST) #undef JSON_HEDLEY_REINTERPRET_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) #else #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_STATIC_CAST) #undef JSON_HEDLEY_STATIC_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) #else #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_CPP_CAST) #undef JSON_HEDLEY_CPP_CAST #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ ((T) (expr)) \ JSON_HEDLEY_DIAGNOSTIC_POP # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("diag_suppress=Pe137") \ JSON_HEDLEY_DIAGNOSTIC_POP \ # else # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) # endif #else # define JSON_HEDLEY_CPP_CAST(T, expr) (expr) #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ defined(__clang__) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_PRAGMA(value) __pragma(value) #else #define JSON_HEDLEY_PRAGMA(value) #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_POP) #undef JSON_HEDLEY_DIAGNOSTIC_POP #endif #if defined(__clang__) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #else #define JSON_HEDLEY_DIAGNOSTIC_PUSH #define JSON_HEDLEY_DIAGNOSTIC_POP #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) #elif \ JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if defined(JSON_HEDLEY_DEPRECATED) #undef JSON_HEDLEY_DEPRECATED #endif #if defined(JSON_HEDLEY_DEPRECATED_FOR) #undef JSON_HEDLEY_DEPRECATED_FOR #endif #if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) #elif defined(__cplusplus) && (__cplusplus >= 201402L) #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) #elif \ JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") #else #define JSON_HEDLEY_DEPRECATED(since) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) #endif #if defined(JSON_HEDLEY_UNAVAILABLE) #undef JSON_HEDLEY_UNAVAILABLE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) #else #define JSON_HEDLEY_UNAVAILABLE(available_since) #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) #undef JSON_HEDLEY_WARN_UNUSED_RESULT #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #endif #if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) #elif defined(_Check_return_) /* SAL */ #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ #else #define JSON_HEDLEY_WARN_UNUSED_RESULT #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) #endif #if defined(JSON_HEDLEY_SENTINEL) #undef JSON_HEDLEY_SENTINEL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) #else #define JSON_HEDLEY_SENTINEL(position) #endif #if defined(JSON_HEDLEY_NO_RETURN) #undef JSON_HEDLEY_NO_RETURN #endif #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NO_RETURN __noreturn #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L #define JSON_HEDLEY_NO_RETURN _Noreturn #elif defined(__cplusplus) && (__cplusplus >= 201103L) #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #else #define JSON_HEDLEY_NO_RETURN #endif #if defined(JSON_HEDLEY_NO_ESCAPE) #undef JSON_HEDLEY_NO_ESCAPE #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) #else #define JSON_HEDLEY_NO_ESCAPE #endif #if defined(JSON_HEDLEY_UNREACHABLE) #undef JSON_HEDLEY_UNREACHABLE #endif #if defined(JSON_HEDLEY_UNREACHABLE_RETURN) #undef JSON_HEDLEY_UNREACHABLE_RETURN #endif #if defined(JSON_HEDLEY_ASSUME) #undef JSON_HEDLEY_ASSUME #endif #if \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_ASSUME(expr) __assume(expr) #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) #elif \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #if defined(__cplusplus) #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) #else #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) #endif #endif #if \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() #elif defined(JSON_HEDLEY_ASSUME) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif #if !defined(JSON_HEDLEY_ASSUME) #if defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) #else #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) #endif #endif #if defined(JSON_HEDLEY_UNREACHABLE) #if \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() #endif #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) #endif #if !defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif JSON_HEDLEY_DIAGNOSTIC_PUSH #if JSON_HEDLEY_HAS_WARNING("-Wpedantic") #pragma clang diagnostic ignored "-Wpedantic" #endif #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #endif #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) #if defined(__clang__) #pragma clang diagnostic ignored "-Wvariadic-macros" #elif defined(JSON_HEDLEY_GCC_VERSION) #pragma GCC diagnostic ignored "-Wvariadic-macros" #endif #endif #if defined(JSON_HEDLEY_NON_NULL) #undef JSON_HEDLEY_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) #else #define JSON_HEDLEY_NON_NULL(...) #endif JSON_HEDLEY_DIAGNOSTIC_POP #if defined(JSON_HEDLEY_PRINTF_FORMAT) #undef JSON_HEDLEY_PRINTF_FORMAT #endif #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) #else #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) #endif #if defined(JSON_HEDLEY_CONSTEXPR) #undef JSON_HEDLEY_CONSTEXPR #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) #endif #endif #if !defined(JSON_HEDLEY_CONSTEXPR) #define JSON_HEDLEY_CONSTEXPR #endif #if defined(JSON_HEDLEY_PREDICT) #undef JSON_HEDLEY_PREDICT #endif #if defined(JSON_HEDLEY_LIKELY) #undef JSON_HEDLEY_LIKELY #endif #if defined(JSON_HEDLEY_UNLIKELY) #undef JSON_HEDLEY_UNLIKELY #endif #if defined(JSON_HEDLEY_UNPREDICTABLE) #undef JSON_HEDLEY_UNPREDICTABLE #endif #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) #endif #if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \ JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) #elif \ JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) # define JSON_HEDLEY_PREDICT(expr, expected, probability) \ (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ })) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ })) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) #else # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) # define JSON_HEDLEY_LIKELY(expr) (!!(expr)) # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) #endif #if !defined(JSON_HEDLEY_UNPREDICTABLE) #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) #endif #if defined(JSON_HEDLEY_MALLOC) #undef JSON_HEDLEY_MALLOC #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0) #define JSON_HEDLEY_MALLOC __declspec(restrict) #else #define JSON_HEDLEY_MALLOC #endif #if defined(JSON_HEDLEY_PURE) #undef JSON_HEDLEY_PURE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) # define JSON_HEDLEY_PURE __attribute__((__pure__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ ) # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") #else # define JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_CONST) #undef JSON_HEDLEY_CONST #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_CONST __attribute__((__const__)) #elif \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_CONST _Pragma("no_side_effect") #else #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_RESTRICT) #undef JSON_HEDLEY_RESTRICT #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT restrict #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ defined(__clang__) #define JSON_HEDLEY_RESTRICT __restrict #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT _Restrict #else #define JSON_HEDLEY_RESTRICT #endif #if defined(JSON_HEDLEY_INLINE) #undef JSON_HEDLEY_INLINE #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ (defined(__cplusplus) && (__cplusplus >= 199711L)) #define JSON_HEDLEY_INLINE inline #elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) #define JSON_HEDLEY_INLINE __inline__ #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_INLINE __inline #else #define JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_ALWAYS_INLINE) #undef JSON_HEDLEY_ALWAYS_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) # define JSON_HEDLEY_ALWAYS_INLINE __forceinline #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ ) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") #else # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_NEVER_INLINE) #undef JSON_HEDLEY_NEVER_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #else #define JSON_HEDLEY_NEVER_INLINE #endif #if defined(JSON_HEDLEY_PRIVATE) #undef JSON_HEDLEY_PRIVATE #endif #if defined(JSON_HEDLEY_PUBLIC) #undef JSON_HEDLEY_PUBLIC #endif #if defined(JSON_HEDLEY_IMPORT) #undef JSON_HEDLEY_IMPORT #endif #if defined(_WIN32) || defined(__CYGWIN__) # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC __declspec(dllexport) # define JSON_HEDLEY_IMPORT __declspec(dllimport) #else # if \ JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ ( \ defined(__TI_EABI__) && \ ( \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ ) \ ) # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) # else # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC # endif # define JSON_HEDLEY_IMPORT extern #endif #if defined(JSON_HEDLEY_NO_THROW) #undef JSON_HEDLEY_NO_THROW #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NO_THROW __declspec(nothrow) #else #define JSON_HEDLEY_NO_THROW #endif #if defined(JSON_HEDLEY_FALL_THROUGH) #undef JSON_HEDLEY_FALL_THROUGH #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) #elif defined(__fallthrough) /* SAL */ #define JSON_HEDLEY_FALL_THROUGH __fallthrough #else #define JSON_HEDLEY_FALL_THROUGH #endif #if defined(JSON_HEDLEY_RETURNS_NON_NULL) #undef JSON_HEDLEY_RETURNS_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) #elif defined(_Ret_notnull_) /* SAL */ #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ #else #define JSON_HEDLEY_RETURNS_NON_NULL #endif #if defined(JSON_HEDLEY_ARRAY_PARAM) #undef JSON_HEDLEY_ARRAY_PARAM #endif #if \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(__STDC_NO_VLA__) && \ !defined(__cplusplus) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_ARRAY_PARAM(name) (name) #else #define JSON_HEDLEY_ARRAY_PARAM(name) #endif #if defined(JSON_HEDLEY_IS_CONSTANT) #undef JSON_HEDLEY_IS_CONSTANT #endif #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #endif /* JSON_HEDLEY_IS_CONSTEXPR_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #undef JSON_HEDLEY_IS_CONSTEXPR_ #endif #if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) #endif #if !defined(__cplusplus) # if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) #else #include #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) #endif # elif \ ( \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION)) || \ JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) #else #include #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) #endif # elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ defined(JSON_HEDLEY_INTEL_VERSION) || \ defined(JSON_HEDLEY_TINYC_VERSION) || \ defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ defined(__clang__) # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ sizeof(void) != \ sizeof(*( \ 1 ? \ ((void*) ((expr) * 0L) ) : \ ((struct { char v[sizeof(void) * 2]; } *) 1) \ ) \ ) \ ) # endif #endif #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) #else #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) (0) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) #endif #if defined(JSON_HEDLEY_BEGIN_C_DECLS) #undef JSON_HEDLEY_BEGIN_C_DECLS #endif #if defined(JSON_HEDLEY_END_C_DECLS) #undef JSON_HEDLEY_END_C_DECLS #endif #if defined(JSON_HEDLEY_C_DECL) #undef JSON_HEDLEY_C_DECL #endif #if defined(__cplusplus) #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { #define JSON_HEDLEY_END_C_DECLS } #define JSON_HEDLEY_C_DECL extern "C" #else #define JSON_HEDLEY_BEGIN_C_DECLS #define JSON_HEDLEY_END_C_DECLS #define JSON_HEDLEY_C_DECL #endif #if defined(JSON_HEDLEY_STATIC_ASSERT) #undef JSON_HEDLEY_STATIC_ASSERT #endif #if \ !defined(__cplusplus) && ( \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \ JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ defined(_Static_assert) \ ) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) #elif \ (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) #else # define JSON_HEDLEY_STATIC_ASSERT(expr, message) #endif #if defined(JSON_HEDLEY_NULL) #undef JSON_HEDLEY_NULL #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) #endif #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL ((void*) 0) #endif #if defined(JSON_HEDLEY_MESSAGE) #undef JSON_HEDLEY_MESSAGE #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_MESSAGE(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(message msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_WARNING) #undef JSON_HEDLEY_WARNING #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_WARNING(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(clang warning msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_REQUIRE) #undef JSON_HEDLEY_REQUIRE #endif #if defined(JSON_HEDLEY_REQUIRE_MSG) #undef JSON_HEDLEY_REQUIRE_MSG #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") # define JSON_HEDLEY_REQUIRE(expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), #expr, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), msg, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) # endif #else # define JSON_HEDLEY_REQUIRE(expr) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) #endif #if defined(JSON_HEDLEY_FLAGS) #undef JSON_HEDLEY_FLAGS #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) #endif #if defined(JSON_HEDLEY_FLAGS_CAST) #undef JSON_HEDLEY_FLAGS_CAST #endif #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("warning(disable:188)") \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) #endif #if defined(JSON_HEDLEY_EMPTY_BASES) #undef JSON_HEDLEY_EMPTY_BASES #endif #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0) #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) #else #define JSON_HEDLEY_EMPTY_BASES #endif /* Remaining macros are deprecated. */ #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #endif #if defined(__clang__) #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) #else #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #endif #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) #undef JSON_HEDLEY_CLANG_HAS_FEATURE #endif #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #endif #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_WARNING) #undef JSON_HEDLEY_CLANG_HAS_WARNING #endif #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ // This file contains all internal macro definitions // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // C++ language standard detection #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) #define JSON_HAS_CPP_20 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #include #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // allow to override assert #if !defined(JSON_ASSERT) #include // assert #define JSON_ASSERT(x) assert(x) #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [&j](const std::pair& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template class ObjectType, \ template class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template class AllocatorType, \ template class JSONSerializer, \ class BinaryType> #define NLOHMANN_BASIC_JSON_TPL \ basic_json // Macros to simplify conversion from/to types #define NLOHMANN_JSON_EXPAND( x ) x #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ NLOHMANN_JSON_PASTE64, \ NLOHMANN_JSON_PASTE63, \ NLOHMANN_JSON_PASTE62, \ NLOHMANN_JSON_PASTE61, \ NLOHMANN_JSON_PASTE60, \ NLOHMANN_JSON_PASTE59, \ NLOHMANN_JSON_PASTE58, \ NLOHMANN_JSON_PASTE57, \ NLOHMANN_JSON_PASTE56, \ NLOHMANN_JSON_PASTE55, \ NLOHMANN_JSON_PASTE54, \ NLOHMANN_JSON_PASTE53, \ NLOHMANN_JSON_PASTE52, \ NLOHMANN_JSON_PASTE51, \ NLOHMANN_JSON_PASTE50, \ NLOHMANN_JSON_PASTE49, \ NLOHMANN_JSON_PASTE48, \ NLOHMANN_JSON_PASTE47, \ NLOHMANN_JSON_PASTE46, \ NLOHMANN_JSON_PASTE45, \ NLOHMANN_JSON_PASTE44, \ NLOHMANN_JSON_PASTE43, \ NLOHMANN_JSON_PASTE42, \ NLOHMANN_JSON_PASTE41, \ NLOHMANN_JSON_PASTE40, \ NLOHMANN_JSON_PASTE39, \ NLOHMANN_JSON_PASTE38, \ NLOHMANN_JSON_PASTE37, \ NLOHMANN_JSON_PASTE36, \ NLOHMANN_JSON_PASTE35, \ NLOHMANN_JSON_PASTE34, \ NLOHMANN_JSON_PASTE33, \ NLOHMANN_JSON_PASTE32, \ NLOHMANN_JSON_PASTE31, \ NLOHMANN_JSON_PASTE30, \ NLOHMANN_JSON_PASTE29, \ NLOHMANN_JSON_PASTE28, \ NLOHMANN_JSON_PASTE27, \ NLOHMANN_JSON_PASTE26, \ NLOHMANN_JSON_PASTE25, \ NLOHMANN_JSON_PASTE24, \ NLOHMANN_JSON_PASTE23, \ NLOHMANN_JSON_PASTE22, \ NLOHMANN_JSON_PASTE21, \ NLOHMANN_JSON_PASTE20, \ NLOHMANN_JSON_PASTE19, \ NLOHMANN_JSON_PASTE18, \ NLOHMANN_JSON_PASTE17, \ NLOHMANN_JSON_PASTE16, \ NLOHMANN_JSON_PASTE15, \ NLOHMANN_JSON_PASTE14, \ NLOHMANN_JSON_PASTE13, \ NLOHMANN_JSON_PASTE12, \ NLOHMANN_JSON_PASTE11, \ NLOHMANN_JSON_PASTE10, \ NLOHMANN_JSON_PASTE9, \ NLOHMANN_JSON_PASTE8, \ NLOHMANN_JSON_PASTE7, \ NLOHMANN_JSON_PASTE6, \ NLOHMANN_JSON_PASTE5, \ NLOHMANN_JSON_PASTE4, \ NLOHMANN_JSON_PASTE3, \ NLOHMANN_JSON_PASTE2, \ NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) #define NLOHMANN_JSON_PASTE2(func, v1) func(v1) #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); /*! @brief macro @def NLOHMANN_DEFINE_TYPE_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } /*! @brief macro @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } #ifndef JSON_USE_IMPLICIT_CONVERSIONS #define JSON_USE_IMPLICIT_CONVERSIONS 1 #endif #if JSON_USE_IMPLICIT_CONVERSIONS #define JSON_EXPLICIT #else #define JSON_EXPLICIT explicit #endif namespace nlohmann { namespace detail { //////////////// // exceptions // //////////////// /*! @brief general exception of the @ref basic_json class This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators - @ref type_error for exceptions indicating executing a member function with a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} @since version 3.0.0 */ class exception : public std::exception { public: /// returns the explanatory string JSON_HEDLEY_RETURNS_NON_NULL const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; protected: JSON_HEDLEY_NON_NULL(3) exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} static std::string name(const std::string& ename, int id_) { return "[json.exception." + ename + "." + std::to_string(id_) + "] "; } private: /// an exception object as storage for error messages std::runtime_error m; }; /*! @brief exception indicating a parse error This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Member @a byte holds the byte index of the last read character in the input file. Exceptions have ids 1xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} @sa - @ref exception for the base class of the library exceptions @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] pos the position where the error occurred (or with chars_read_total=0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ static parse_error create(int id_, const position_t& pos, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + position_string(pos) + ": " + what_arg; return parse_error(id_, pos.chars_read_total, w.c_str()); } static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} static std::string position_string(const position_t& pos) { return " at line " + std::to_string(pos.lines_read + 1) + ", column " + std::to_string(pos.chars_read_current_line); } }; /*! @brief exception indicating errors with iterators This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class invalid_iterator : public exception { public: static invalid_iterator create(int id_, const std::string& what_arg) { std::string w = exception::name("invalid_iterator", id_) + what_arg; return invalid_iterator(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating executing a member function with a wrong type This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref out_of_range for exceptions indicating access out of the defined range @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class type_error : public exception { public: static type_error create(int id_, const std::string& what_arg) { std::string w = exception::name("type_error", id_) + what_arg; return type_error(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating access out of the defined range This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) | json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class out_of_range : public exception { public: static out_of_range create(int id_, const std::string& what_arg) { std::string w = exception::name("out_of_range", id_) + what_arg; return out_of_range(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating other library errors This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. @sa - @ref exception for the base class of the library exceptions @sa - @ref parse_error for exceptions indicating a parse error @sa - @ref invalid_iterator for exceptions indicating errors with iterators @sa - @ref type_error for exceptions indicating executing a member function with a wrong type @sa - @ref out_of_range for exceptions indicating access out of the defined range @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} @since version 3.0.0 */ class other_error : public exception { public: static other_error create(int id_, const std::string& what_arg) { std::string w = exception::name("other_error", id_) + what_arg; return other_error(id_, w.c_str()); } private: JSON_HEDLEY_NON_NULL(3) other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; } // namespace detail } // namespace nlohmann // #include // #include #include // size_t #include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type namespace nlohmann { namespace detail { // alias templates to reduce boilerplate template using enable_if_t = typename std::enable_if::type; template using uncvref_t = typename std::remove_cv::type>::type; // implementation of C++14 index_sequence and affiliates // source: https://stackoverflow.com/a/32223343 template struct index_sequence { using type = index_sequence; using value_type = std::size_t; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; template struct merge_and_renumber; template struct merge_and_renumber, index_sequence> : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, typename make_index_sequence < N - N / 2 >::type > {}; template<> struct make_index_sequence<0> : index_sequence<> {}; template<> struct make_index_sequence<1> : index_sequence<0> {}; template using index_sequence_for = make_index_sequence; // dispatch utility (taken from ranges-v3) template struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template struct static_const { static constexpr T value{}; }; template constexpr T static_const::value; } // namespace detail } // namespace nlohmann // #include #include // numeric_limits #include // false_type, is_constructible, is_integral, is_same, true_type #include // declval // #include #include // random_access_iterator_tag // #include namespace nlohmann { namespace detail { template struct make_void { using type = void; }; template using void_t = typename make_void::type; } // namespace detail } // namespace nlohmann // #include namespace nlohmann { namespace detail { template struct iterator_types {}; template struct iterator_types < It, void_t> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template struct iterator_traits { }; template struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> : iterator_types { }; template struct iterator_traits::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } // namespace detail } // namespace nlohmann // #include // #include // #include #include // #include // https://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { namespace detail { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; nonesuch(nonesuch const&&) = delete; void operator=(nonesuch const&) = delete; void operator=(nonesuch&&) = delete; }; template class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template class Op, class... Args> struct detector>, Op, Args...> { using value_t = std::true_type; using type = Op; }; template class Op, class... Args> using is_detected = typename detector::value_t; template class Op, class... Args> using detected_t = typename detector::type; template class Op, class... Args> using detected_or = detector; template class Op, class... Args> using detected_or_t = typename detected_or::type; template class Op, class... Args> using is_detected_exact = std::is_same>; template class Op, class... Args> using is_detected_convertible = std::is_convertible, To>; } // namespace detail } // namespace nlohmann // #include #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ #include // int64_t, uint64_t #include // map #include // allocator #include // string #include // vector /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template struct adl_serializer; template class ObjectType = std::map, template class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template class AllocatorType = std::allocator, template class JSONSerializer = adl_serializer, class BinaryType = std::vector> class basic_json; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ template class json_pointer; /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; template struct ordered_map; /*! @brief ordered JSON class This type preserves the insertion order of object keys. @since version 3.9.0 */ using ordered_json = basic_json; } // namespace nlohmann #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ namespace nlohmann { /*! @brief detail namespace with internal helper functions This namespace collects functions that should not be exposed, implementations of some @ref basic_json methods, and meta-programming helpers. @since version 2.1.0 */ namespace detail { ///////////// // helpers // ///////////// // Note to maintainers: // // Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section // (i.e. those of the form: decltype(T::member_function(std::declval()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments // (e.g. to_json(BasicJsonType&, const T&)) template struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json : std::true_type {}; ////////////////////// // json_ref helpers // ////////////////////// template class json_ref; template struct is_json_ref : std::false_type {}; template struct is_json_ref> : std::true_type {}; ////////////////////////// // aliases for detected // ////////////////////////// template using mapped_type_t = typename T::mapped_type; template using key_type_t = typename T::key_type; template using value_type_t = typename T::value_type; template using difference_type_t = typename T::difference_type; template using pointer_t = typename T::pointer; template using reference_t = typename T::reference; template using iterator_category_t = typename T::iterator_category; template using iterator_t = typename T::iterator; template using to_json_function = decltype(T::to_json(std::declval()...)); template using from_json_function = decltype(T::from_json(std::declval()...)); template using get_template_function = decltype(std::declval().template get()); // trait checking if JSONSerializer::from_json(json const&, udt&) exists template struct has_from_json : std::false_type {}; // trait checking if j.get is valid // use this trait instead of std::is_constructible or std::is_convertible, // both rely on, or make use of implicit conversions, and thus fail when T // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) template struct is_getable { static constexpr bool value = is_detected::value; }; template struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if JSONSerializer::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template struct has_non_default_from_json : std::false_type {}; template struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if BasicJsonType::json_serializer::to_json exists // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. template struct has_to_json : std::false_type {}; template struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; /////////////////// // is_ functions // /////////////////// template struct is_iterator_traits : std::false_type {}; template struct is_iterator_traits> { private: using traits = iterator_traits; public: static constexpr auto value = is_detected::value && is_detected::value && is_detected::value && is_detected::value && is_detected::value; }; // source: https://stackoverflow.com/a/37193089/4116453 template struct is_complete_type : std::false_type {}; template struct is_complete_type : std::true_type {}; template struct is_compatible_object_type_impl : std::false_type {}; template struct is_compatible_object_type_impl < BasicJsonType, CompatibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; // macOS's is_constructible does not play well with nonesuch... static constexpr bool value = std::is_constructible::value && std::is_constructible::value; }; template struct is_compatible_object_type : is_compatible_object_type_impl {}; template struct is_constructible_object_type_impl : std::false_type {}; template struct is_constructible_object_type_impl < BasicJsonType, ConstructibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; static constexpr bool value = (std::is_default_constructible::value && (std::is_move_assignable::value || std::is_copy_assignable::value) && (std::is_constructible::value && std::is_same < typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type >::value)) || (has_from_json::value || has_non_default_from_json < BasicJsonType, typename ConstructibleObjectType::mapped_type >::value); }; template struct is_constructible_object_type : is_constructible_object_type_impl {}; template struct is_compatible_string_type_impl : std::false_type {}; template struct is_compatible_string_type_impl < BasicJsonType, CompatibleStringType, enable_if_t::value >> { static constexpr auto value = std::is_constructible::value; }; template struct is_compatible_string_type : is_compatible_string_type_impl {}; template struct is_constructible_string_type_impl : std::false_type {}; template struct is_constructible_string_type_impl < BasicJsonType, ConstructibleStringType, enable_if_t::value >> { static constexpr auto value = std::is_constructible::value; }; template struct is_constructible_string_type : is_constructible_string_type_impl {}; template struct is_compatible_array_type_impl : std::false_type {}; template struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, enable_if_t < is_detected::value&& is_detected::value&& // This is needed because json_reverse_iterator has a ::iterator type... // Therefore it is detected as a CompatibleArrayType. // The real fix would be to have an Iterable concept. !is_iterator_traits < iterator_traits>::value >> { static constexpr bool value = std::is_constructible::value; }; template struct is_compatible_array_type : is_compatible_array_type_impl {}; template struct is_constructible_array_type_impl : std::false_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t::value >> : std::true_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t < !std::is_same::value&& std::is_default_constructible::value&& (std::is_move_assignable::value || std::is_copy_assignable::value)&& is_detected::value&& is_detected::value&& is_complete_type < detected_t>::value >> { static constexpr bool value = // This is needed because json_reverse_iterator has a ::iterator type, // furthermore, std::back_insert_iterator (and other iterators) have a // base class `iterator`... Therefore it is detected as a // ConstructibleArrayType. The real fix would be to have an Iterable // concept. !is_iterator_traits>::value && (std::is_same::value || has_from_json::value || has_non_default_from_json < BasicJsonType, typename ConstructibleArrayType::value_type >::value); }; template struct is_constructible_array_type : is_constructible_array_type_impl {}; template struct is_compatible_integer_type_impl : std::false_type {}; template struct is_compatible_integer_type_impl < RealIntegerType, CompatibleNumberIntegerType, enable_if_t < std::is_integral::value&& std::is_integral::value&& !std::is_same::value >> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits; using CompatibleLimits = std::numeric_limits; static constexpr auto value = std::is_constructible::value && CompatibleLimits::is_integer && RealLimits::is_signed == CompatibleLimits::is_signed; }; template struct is_compatible_integer_type : is_compatible_integer_type_impl {}; template struct is_compatible_type_impl: std::false_type {}; template struct is_compatible_type_impl < BasicJsonType, CompatibleType, enable_if_t::value >> { static constexpr bool value = has_to_json::value; }; template struct is_compatible_type : is_compatible_type_impl {}; // https://en.cppreference.com/w/cpp/types/conjunction template struct conjunction : std::true_type { }; template struct conjunction : B1 { }; template struct conjunction : std::conditional, B1>::type {}; template struct is_constructible_tuple : std::false_type {}; template struct is_constructible_tuple> : conjunction...> {}; } // namespace detail } // namespace nlohmann // #include #include // array #include // size_t #include // uint8_t #include // string namespace nlohmann { namespace detail { /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : std::uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) binary, ///< binary array (ordered collection of bytes) discarded ///< discarded by the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string < binary - furthermore, each type is not smaller than itself - discarded values are not comparable - binary is represented as a b"" string in python and directly comparable to a string; however, making a binary array directly comparable with a string would be surprising behavior in a JSON file. @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array order = {{ 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, 6 /* binary */ } }; const auto l_index = static_cast(lhs); const auto r_index = static_cast(rhs); return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; } } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { template void from_json(const BasicJsonType& j, typename std::nullptr_t& n) { if (JSON_HEDLEY_UNLIKELY(!j.is_null())) { JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()))); } n = nullptr; } // overloads for basic_json template parameters template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value, int > = 0 > void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); } b = *j.template get_ptr(); } template void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr(); } template < typename BasicJsonType, typename ConstructibleStringType, enable_if_t < is_constructible_string_type::value&& !std::is_same::value, int > = 0 > void from_json(const BasicJsonType& j, ConstructibleStringType& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr(); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type::type val; get_arithmetic_value(j, val); e = static_cast(val); } // forward_list doesn't have an insert method template::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } l.clear(); std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get(); }); } // valarray doesn't have an insert method template::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } l.resize(j.size()); std::transform(j.begin(), j.end(), std::begin(l), [](const BasicJsonType & elem) { return elem.template get(); }); } template auto from_json(const BasicJsonType& j, T (&arr)[N]) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) { arr = *j.template get_ptr(); } template auto from_json_array_impl(const BasicJsonType& j, std::array& arr, priority_tag<2> /*unused*/) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval()), j.template get(), void()) { using std::end; ConstructibleArrayType ret; ret.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; ConstructibleArrayType ret; std::transform( j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template < typename BasicJsonType, typename ConstructibleArrayType, enable_if_t < is_constructible_array_type::value&& !is_constructible_object_type::value&& !is_constructible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), j.template get(), void()) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } from_json_array_impl(j, arr, priority_tag<3> {}); } template void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) { if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()))); } bin = *j.template get_ptr(); } template::value, int> = 0> void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) { if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); } ConstructibleObjectType ret; auto inner_object = j.template get_ptr(); using value_type = typename ConstructibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(ret, ret.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get()); }); obj = std::move(ret); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value, int > = 0 > void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } case value_t::boolean: { val = static_cast(*j.template get_ptr()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template void from_json(const BasicJsonType& j, std::pair& p) { p = {j.at(0).template get(), j.at(1).template get()}; } template void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence /*unused*/) { t = std::make_tuple(j.at(Idx).template get::type>()...); } template void from_json(const BasicJsonType& j, std::tuple& t) { from_json_tuple_impl(j, t, index_sequence_for {}); } template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::unordered_map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } struct from_json_fn { template auto operator()(const BasicJsonType& j, T& val) const noexcept(noexcept(from_json(j, val))) -> decltype(from_json(j, val), void()) { return from_json(j, val); } }; } // namespace detail /// namespace to hold default `from_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace { constexpr const auto& from_json = detail::static_const::value; } // namespace } // namespace nlohmann // #include #include // copy #include // begin, end #include // string #include // tuple, get #include // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include // move, forward, declval, pair #include // valarray #include // vector // #include #include // size_t #include // input_iterator_tag #include // string, to_string #include // tuple_size, get, tuple_element // #include // #include namespace nlohmann { namespace detail { template void int_to_string( string_type& target, std::size_t value ) { // For ADL using std::to_string; target = to_string(value); } template class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::input_iterator_tag; using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable string_type array_index_str = "0"; /// an empty string (to return a reference for primitive values) const string_type empty_str = ""; public: explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_value& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const string_type& key() const { JSON_ASSERT(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { int_to_string( array_index_str, array_index ); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template class iteration_proxy { private: /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_value begin() noexcept { return iteration_proxy_value(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value end() noexcept { return iteration_proxy_value(container.end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) { return i.value(); } } // namespace detail } // namespace nlohmann // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { #if defined(__clang__) // Fix: https://github.com/nlohmann/json/issues/1401 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmismatched-tags" #endif template class tuple_size<::nlohmann::detail::iteration_proxy_value> : public std::integral_constant {}; template class tuple_element> { public: using type = decltype( get(std::declval < ::nlohmann::detail::iteration_proxy_value> ())); }; #if defined(__clang__) #pragma clang diagnostic pop #endif } // namespace std // #include // #include // #include namespace nlohmann { namespace detail { ////////////////// // constructors // ////////////////// template struct external_constructor; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleStringType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleStringType& str) { j.m_type = value_t::string; j.m_value.string = j.template create(str); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) { j.m_type = value_t::binary; typename BasicJsonType::binary_t value{b}; j.m_value = value; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) { j.m_type = value_t::binary; typename BasicJsonType::binary_t value{std::move(b)}; j.m_value = value; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_type = value_t::array; j.m_value = arr; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_type = value_t::array; j.m_value = std::move(arr); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value.array = j.template create(begin(arr), end(arr)); j.assert_invariant(); } template static void construct(BasicJsonType& j, const std::vector& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (const bool x : arr) { j.m_value.array->push_back(x); } j.assert_invariant(); } template::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->resize(arr.size()); if (arr.size() > 0) { std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); } j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_type = value_t::object; j.m_value = obj; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_type = value_t::object; j.m_value = std::move(obj); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_type = value_t::object; j.m_value.object = j.template create(begin(obj), end(obj)); j.assert_invariant(); } }; ///////////// // to_json // ///////////// template::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor::construct(j, b); } template::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor::construct(j, s); } template void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor::construct(j, std::move(s)); } template::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type::type; external_constructor::construct(j, static_cast(e)); } template void to_json(BasicJsonType& j, const std::vector& e) { external_constructor::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type::value&& !is_compatible_object_type::value&& !is_compatible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor::construct(j, arr); } template void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) { external_constructor::construct(j, bin); } template::value, int> = 0> void to_json(BasicJsonType& j, const std::valarray& arr) { external_constructor::construct(j, std::move(arr)); } template void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor::construct(j, obj); } template void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor::construct(j, std::move(obj)); } template < typename BasicJsonType, typename T, std::size_t N, enable_if_t < !std::is_constructible::value, int > = 0 > void to_json(BasicJsonType& j, const T(&arr)[N]) { external_constructor::construct(j, arr); } template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > void to_json(BasicJsonType& j, const std::pair& p) { j = { p.first, p.second }; } // for https://github.com/nlohmann/json/pull/1134 template>::value, int> = 0> void to_json(BasicJsonType& j, const T& b) { j = { {b.key(), b.value()} }; } template void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) { j = { std::get(t)... }; } template::value, int > = 0> void to_json(BasicJsonType& j, const T& t) { to_json_tuple_impl(j, t, make_index_sequence::value> {}); } struct to_json_fn { template auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) -> decltype(to_json(j, std::forward(val)), void()) { return to_json(j, std::forward(val)); } }; } // namespace detail /// namespace to hold default `to_json` function namespace { constexpr const auto& to_json = detail::static_const::value; } // namespace } // namespace nlohmann namespace nlohmann { template struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @param[in] j JSON value to read from @param[in,out] val value to write to */ template static auto from_json(BasicJsonType&& j, ValueType& val) noexcept( noexcept(::nlohmann::from_json(std::forward(j), val))) -> decltype(::nlohmann::from_json(std::forward(j), val), void()) { ::nlohmann::from_json(std::forward(j), val); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template static auto to_json(BasicJsonType& j, ValueType&& val) noexcept( noexcept(::nlohmann::to_json(j, std::forward(val)))) -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) { ::nlohmann::to_json(j, std::forward(val)); } }; } // namespace nlohmann // #include #include // uint8_t #include // tie #include // move namespace nlohmann { /*! @brief an internal type for a backed binary type This type extends the template parameter @a BinaryType provided to `basic_json` with a subtype used by BSON and MessagePack. This type exists so that the user does not have to specify a type themselves with a specific naming scheme in order to override the binary type. @tparam BinaryType container to store bytes (`std::vector` by default) @since version 3.8.0 */ template class byte_container_with_subtype : public BinaryType { public: /// the type of the underlying container using container_type = BinaryType; byte_container_with_subtype() noexcept(noexcept(container_type())) : container_type() {} byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) : container_type(b) {} byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) {} byte_container_with_subtype(const container_type& b, std::uint8_t subtype) noexcept(noexcept(container_type(b))) : container_type(b) , m_subtype(subtype) , m_has_subtype(true) {} byte_container_with_subtype(container_type&& b, std::uint8_t subtype) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) , m_subtype(subtype) , m_has_subtype(true) {} bool operator==(const byte_container_with_subtype& rhs) const { return std::tie(static_cast(*this), m_subtype, m_has_subtype) == std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); } bool operator!=(const byte_container_with_subtype& rhs) const { return !(rhs == *this); } /*! @brief sets the binary subtype Sets the binary subtype of the value, also flags a binary JSON value as having a subtype, which has implications for serialization. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa @ref subtype() -- return the binary subtype @sa @ref clear_subtype() -- clears the binary subtype @sa @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ void set_subtype(std::uint8_t subtype) noexcept { m_subtype = subtype; m_has_subtype = true; } /*! @brief return the binary subtype Returns the numerical subtype of the value if it has a subtype. If it does not have a subtype, this function will return size_t(-1) as a sentinel value. @return the numerical subtype of the binary value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa @ref set_subtype() -- sets the binary subtype @sa @ref clear_subtype() -- clears the binary subtype @sa @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ constexpr std::uint8_t subtype() const noexcept { return m_subtype; } /*! @brief return whether the value has a subtype @return whether the value has a subtype @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa @ref subtype() -- return the binary subtype @sa @ref set_subtype() -- sets the binary subtype @sa @ref clear_subtype() -- clears the binary subtype @since version 3.8.0 */ constexpr bool has_subtype() const noexcept { return m_has_subtype; } /*! @brief clears the binary subtype Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for instance MessagePack will prefer the bin family over the ext family. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @sa @ref subtype() -- return the binary subtype @sa @ref set_subtype() -- sets the binary subtype @sa @ref has_subtype() -- returns whether or not the binary value has a subtype @since version 3.8.0 */ void clear_subtype() noexcept { m_subtype = 0; m_has_subtype = false; } private: std::uint8_t m_subtype = 0; bool m_has_subtype = false; }; } // namespace nlohmann // #include // #include // #include // #include #include // size_t, uint8_t #include // hash namespace nlohmann { namespace detail { // boost::hash_combine inline std::size_t combine(std::size_t seed, std::size_t h) noexcept { seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); return seed; } /*! @brief hash a JSON value The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc. @tparam BasicJsonType basic_json specialization @param j JSON value to hash @return hash value of j */ template std::size_t hash(const BasicJsonType& j) { using string_t = typename BasicJsonType::string_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; const auto type = static_cast(j.type()); switch (j.type()) { case BasicJsonType::value_t::null: case BasicJsonType::value_t::discarded: { return combine(type, 0); } case BasicJsonType::value_t::object: { auto seed = combine(type, j.size()); for (const auto& element : j.items()) { const auto h = std::hash {}(element.key()); seed = combine(seed, h); seed = combine(seed, hash(element.value())); } return seed; } case BasicJsonType::value_t::array: { auto seed = combine(type, j.size()); for (const auto& element : j) { seed = combine(seed, hash(element)); } return seed; } case BasicJsonType::value_t::string: { const auto h = std::hash {}(j.template get_ref()); return combine(type, h); } case BasicJsonType::value_t::boolean: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_integer: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case nlohmann::detail::value_t::number_unsigned: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case nlohmann::detail::value_t::number_float: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case nlohmann::detail::value_t::binary: { auto seed = combine(type, j.get_binary().size()); const auto h = std::hash {}(j.get_binary().has_subtype()); seed = combine(seed, h); seed = combine(seed, j.get_binary().subtype()); for (const auto byte : j.get_binary()) { seed = combine(seed, std::hash {}(byte)); } return seed; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } } } // namespace detail } // namespace nlohmann // #include #include // generate_n #include // array #include // ldexp #include // size_t #include // uint8_t, uint16_t, uint32_t, uint64_t #include // snprintf #include // memcpy #include // back_inserter #include // numeric_limits #include // char_traits, string #include // make_pair, move // #include // #include #include // array #include // size_t #include //FILE * #include // strlen #include // istream #include // begin, end, iterator_traits, random_access_iterator_tag, distance, next #include // shared_ptr, make_shared, addressof #include // accumulate #include // string, char_traits #include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer #include // pair, declval // #include // #include namespace nlohmann { namespace detail { /// the supported input formats enum class input_format_t { json, cbor, msgpack, ubjson, bson }; //////////////////// // input adapters // //////////////////// /*! Input adapter for stdio file access. This adapter read only 1 byte and do not use any buffer. This adapter is a very low level adapter. */ class file_input_adapter { public: using char_type = char; JSON_HEDLEY_NON_NULL(2) explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) {} // make class move-only file_input_adapter(const file_input_adapter&) = delete; file_input_adapter(file_input_adapter&&) = default; file_input_adapter& operator=(const file_input_adapter&) = delete; file_input_adapter& operator=(file_input_adapter&&) = delete; std::char_traits::int_type get_character() noexcept { return std::fgetc(m_file); } private: /// the file pointer to read from std::FILE* m_file; }; /*! Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at beginning of input. Does not support changing the underlying std::streambuf in mid-input. Maintains underlying std::istream and std::streambuf to support subsequent use of standard std::istream operations to process any input characters following those used in parsing the JSON input. Clears the std::istream flags; any input errors (e.g., EOF) will be detected by the first subsequent call for input from the std::istream. */ class input_stream_adapter { public: using char_type = char; ~input_stream_adapter() { // clear stream flags; we use underlying streambuf I/O, do not // maintain ifstream flags, except eof if (is != nullptr) { is->clear(is->rdstate() & std::ios::eofbit); } } explicit input_stream_adapter(std::istream& i) : is(&i), sb(i.rdbuf()) {} // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete; input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) { rhs.is = nullptr; rhs.sb = nullptr; } // std::istream/std::streambuf use std::char_traits::to_int_type, to // ensure that std::char_traits::eof() and the character 0xFF do not // end up as the same value, eg. 0xFFFFFFFF. std::char_traits::int_type get_character() { auto res = sb->sbumpc(); // set eof manually, as we don't use the istream interface. if (JSON_HEDLEY_UNLIKELY(res == EOF)) { is->clear(is->rdstate() | std::ios::eofbit); } return res; } private: /// the associated input stream std::istream* is = nullptr; std::streambuf* sb = nullptr; }; // General-purpose iterator-based adapter. It might not be as fast as // theoretically possible for some containers, but it is extremely versatile. template class iterator_input_adapter { public: using char_type = typename std::iterator_traits::value_type; iterator_input_adapter(IteratorType first, IteratorType last) : current(std::move(first)), end(std::move(last)) {} typename std::char_traits::int_type get_character() { if (JSON_HEDLEY_LIKELY(current != end)) { auto result = std::char_traits::to_int_type(*current); std::advance(current, 1); return result; } else { return std::char_traits::eof(); } } private: IteratorType current; IteratorType end; template friend struct wide_string_input_helper; bool empty() const { return current == end; } }; template struct wide_string_input_helper; template struct wide_string_input_helper { // UTF-32 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-32 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (wc <= 0xFFFF) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else if (wc <= 0x10FFFF) { utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 4; } else { // unknown character utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } }; template struct wide_string_input_helper { // UTF-16 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-16 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (0xD800 > wc || wc >= 0xE000) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else { if (JSON_HEDLEY_UNLIKELY(!input.empty())) { const auto wc2 = static_cast(input.get_character()); const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); utf8_bytes_filled = 4; } else { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } } }; // Wraps another input apdater to convert wide character types into individual bytes. template class wide_string_input_adapter { public: using char_type = char; wide_string_input_adapter(BaseInputAdapter base) : base_adapter(base) {} typename std::char_traits::int_type get_character() noexcept { // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer(); JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index == 0); } // use buffer JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); return utf8_bytes[utf8_bytes_index++]; } private: BaseInputAdapter base_adapter; template void fill_buffer() { wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); } /// a buffer for UTF-8 bytes std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; /// index to the utf8_codes array for the next valid byte std::size_t utf8_bytes_index = 0; /// number of valid bytes in the utf8_codes array std::size_t utf8_bytes_filled = 0; }; template struct iterator_input_adapter_factory { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using adapter_type = iterator_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(std::move(first), std::move(last)); } }; template struct is_iterator_of_multibyte { using value_type = typename std::iterator_traits::value_type; enum { value = sizeof(value_type) > 1 }; }; template struct iterator_input_adapter_factory::value>> { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using base_adapter_type = iterator_input_adapter; using adapter_type = wide_string_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(base_adapter_type(std::move(first), std::move(last))); } }; // General purpose iterator-based input template typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) { using factory_type = iterator_input_adapter_factory; return factory_type::create(first, last); } // Convenience shorthand from container to iterator template auto input_adapter(const ContainerType& container) -> decltype(input_adapter(begin(container), end(container))) { // Enable ADL using std::begin; using std::end; return input_adapter(begin(container), end(container)); } // Special cases with fast paths inline file_input_adapter input_adapter(std::FILE* file) { return file_input_adapter(file); } inline input_stream_adapter input_adapter(std::istream& stream) { return input_stream_adapter(stream); } inline input_stream_adapter input_adapter(std::istream&& stream) { return input_stream_adapter(stream); } using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); // Null-delimited strings, and the like. template < typename CharT, typename std::enable_if < std::is_pointer::value&& !std::is_array::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > contiguous_bytes_input_adapter input_adapter(CharT b) { auto length = std::strlen(reinterpret_cast(b)); const auto* ptr = reinterpret_cast(b); return input_adapter(ptr, ptr + length); } template auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) { return input_adapter(array, array + N); } // This class only handles inputs of input_buffer_adapter type. // It's required so that expressions like {ptr, len} can be implicitely casted // to the correct adapter. class span_input_adapter { public: template < typename CharT, typename std::enable_if < std::is_pointer::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > span_input_adapter(CharT b, std::size_t l) : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} template::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> span_input_adapter(IteratorType first, IteratorType last) : ia(input_adapter(first, last)) {} contiguous_bytes_input_adapter&& get() { return std::move(ia); } private: contiguous_bytes_input_adapter ia; }; } // namespace detail } // namespace nlohmann // #include #include #include // string #include // move #include // vector // #include // #include namespace nlohmann { /*! @brief SAX interface This class describes the SAX interface used by @ref nlohmann::json::sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input. */ template struct json_sax { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @brief a null value was read @return whether parsing should proceed */ virtual bool null() = 0; /*! @brief a boolean value was read @param[in] val boolean value @return whether parsing should proceed */ virtual bool boolean(bool val) = 0; /*! @brief an integer number was read @param[in] val integer value @return whether parsing should proceed */ virtual bool number_integer(number_integer_t val) = 0; /*! @brief an unsigned integer number was read @param[in] val unsigned integer value @return whether parsing should proceed */ virtual bool number_unsigned(number_unsigned_t val) = 0; /*! @brief an floating-point number was read @param[in] val floating-point value @param[in] s raw token value @return whether parsing should proceed */ virtual bool number_float(number_float_t val, const string_t& s) = 0; /*! @brief a string was read @param[in] val string value @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool string(string_t& val) = 0; /*! @brief a binary string was read @param[in] val binary value @return whether parsing should proceed @note It is safe to move the passed binary. */ virtual bool binary(binary_t& val) = 0; /*! @brief the beginning of an object was read @param[in] elements number of object elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_object(std::size_t elements) = 0; /*! @brief an object key was read @param[in] val object key @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool key(string_t& val) = 0; /*! @brief the end of an object was read @return whether parsing should proceed */ virtual bool end_object() = 0; /*! @brief the beginning of an array was read @param[in] elements number of array elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_array(std::size_t elements) = 0; /*! @brief the end of an array was read @return whether parsing should proceed */ virtual bool end_array() = 0; /*! @brief a parse error occurred @param[in] position the position in the input where the error occurs @param[in] last_token the last read token @param[in] ex an exception object describing the error @return whether parsing should proceed (must return false) */ virtual bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0; virtual ~json_sax() = default; }; namespace detail { /*! @brief SAX implementation to create a JSON value from SAX events This class implements the @ref json_sax interface and processes the SAX events to create a JSON value which makes it basically a DOM parser. The structure or hierarchy of the JSON value is managed by the stack `ref_stack` which contains a pointer to the respective array or object for each recursion depth. After successful parsing, the value that is passed by reference to the constructor contains the parsed value. @tparam BasicJsonType the JSON type */ template class json_sax_dom_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @param[in, out] r reference to a JSON value that is manipulated while parsing @param[in] allow_exceptions_ whether parse errors yield exceptions */ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) : root(r), allow_exceptions(allow_exceptions_) {} // make class move-only json_sax_dom_parser(const json_sax_dom_parser&) = delete; json_sax_dom_parser(json_sax_dom_parser&&) = default; json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; ~json_sax_dom_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len))); } return true; } bool key(string_t& val) { // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_value.object->operator[](val)); return true; } bool end_object() { ref_stack.pop_back(); return true; } bool start_array(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len))); } return true; } bool end_array() { ref_stack.pop_back(); return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements */ template JSON_HEDLEY_RETURNS_NON_NULL BasicJsonType* handle_value(Value&& v) { if (ref_stack.empty()) { root = BasicJsonType(std::forward(v)); return &root; } JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::forward(v)); return &(ref_stack.back()->m_value.array->back()); } JSON_ASSERT(ref_stack.back()->is_object()); JSON_ASSERT(object_element); *object_element = BasicJsonType(std::forward(v)); return object_element; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; template class json_sax_dom_callback_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using parser_callback_t = typename BasicJsonType::parser_callback_t; using parse_event_t = typename BasicJsonType::parse_event_t; json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true) : root(r), callback(cb), allow_exceptions(allow_exceptions_) { keep_stack.push_back(true); } // make class move-only json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; ~json_sax_dom_callback_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { // check callback for object start const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::object, true); ref_stack.push_back(val.second); // check object limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len))); } return true; } bool key(string_t& val) { BasicJsonType k = BasicJsonType(val); // check callback for key const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); // add discarded value at given key and store the reference for later if (keep && ref_stack.back()) { object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); } return true; } bool end_object() { if (ref_stack.back() && !callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) { // discard object *ref_stack.back() = discarded; } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) { // remove discarded value for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) { if (it->is_discarded()) { ref_stack.back()->erase(it); break; } } } return true; } bool start_array(std::size_t len) { const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::array, true); ref_stack.push_back(val.second); // check array limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len))); } return true; } bool end_array() { bool keep = true; if (ref_stack.back()) { keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); if (!keep) { // discard array *ref_stack.back() = discarded; } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); // remove discarded value if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->pop_back(); } return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @param[in] v value to add to the JSON value we build during parsing @param[in] skip_callback whether we should skip calling the callback function; this is required after start_array() and start_object() SAX events, because otherwise we would call the callback function with an empty array or object, respectively. @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements @return pair of boolean (whether value should be kept) and pointer (to the passed value in the ref_stack hierarchy; nullptr if not kept) */ template std::pair handle_value(Value&& v, const bool skip_callback = false) { JSON_ASSERT(!keep_stack.empty()); // do not handle this value if we know it would be added to a discarded // container if (!keep_stack.back()) { return {false, nullptr}; } // create value auto value = BasicJsonType(std::forward(v)); // check callback const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); // do not handle this value if we just learnt it shall be discarded if (!keep) { return {false, nullptr}; } if (ref_stack.empty()) { root = std::move(value); return {true, &root}; } // skip this value if we already decided to skip the parent // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) if (!ref_stack.back()) { return {false, nullptr}; } // we now only expect arrays and objects JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); // array if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->push_back(std::move(value)); return {true, &(ref_stack.back()->m_value.array->back())}; } // object JSON_ASSERT(ref_stack.back()->is_object()); // check if we should store an element for the current key JSON_ASSERT(!key_keep_stack.empty()); const bool store_element = key_keep_stack.back(); key_keep_stack.pop_back(); if (!store_element) { return {false, nullptr}; } JSON_ASSERT(object_element); *object_element = std::move(value); return {true, object_element}; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// stack to manage which values to keep std::vector keep_stack {}; /// stack to manage which object keys to keep std::vector key_keep_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// callback function const parser_callback_t callback = nullptr; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; /// a discarded value for the callback BasicJsonType discarded = BasicJsonType::value_t::discarded; }; template class json_sax_acceptor { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; bool null() { return true; } bool boolean(bool /*unused*/) { return true; } bool number_integer(number_integer_t /*unused*/) { return true; } bool number_unsigned(number_unsigned_t /*unused*/) { return true; } bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) { return true; } bool string(string_t& /*unused*/) { return true; } bool binary(binary_t& /*unused*/) { return true; } bool start_object(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool key(string_t& /*unused*/) { return true; } bool end_object() { return true; } bool start_array(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool end_array() { return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) { return false; } }; } // namespace detail } // namespace nlohmann // #include #include // array #include // localeconv #include // size_t #include // snprintf #include // strtof, strtod, strtold, strtoll, strtoull #include // initializer_list #include // char_traits, string #include // move #include // vector // #include // #include // #include namespace nlohmann { namespace detail { /////////// // lexer // /////////// template class lexer_base { public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_CONST static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return ""; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case token_type::value_unsigned: case token_type::value_integer: case token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return ""; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; // LCOV_EXCL_START default: // catch non-enum values return "unknown token"; // LCOV_EXCL_STOP } } }; /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template class lexer : public lexer_base { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits::int_type; public: using token_type = typename lexer_base::token_type; explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) : ia(std::move(adapter)) , ignore_comments(ignore_comments_) , decimal_point_char(static_cast(get_decimal_point())) {} // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = default; lexer& operator=(lexer&) = delete; lexer& operator=(lexer&&) = default; ~lexer() = default; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point JSON_HEDLEY_PURE static char get_decimal_point() noexcept { const auto* loc = localeconv(); JSON_ASSERT(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` JSON_ASSERT(current == 'u'); int codepoint = 0; const auto factors = { 12u, 8u, 4u, 0u }; for (const auto factor : factors) { get(); if (current >= '0' && current <= '9') { codepoint += static_cast((static_cast(current) - 0x30u) << factor); } else if (current >= 'A' && current <= 'F') { codepoint += static_cast((static_cast(current) - 0x37u) << factor); } else if (current >= 'a' && current <= 'f') { codepoint += static_cast((static_cast(current) - 0x57u) << factor); } else { return -1; } } JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @param[in] ranges list of integers; interpreted as list of pairs of inclusive lower and upper bound, respectively @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, 1, 2, or 3 pairs. This precondition is enforced by an assertion. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list ranges) { JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 7159. While scanning, bytes are escaped and copied into buffer token_buffer. Then the function returns successfully, token_buffer is *not* null-terminated (as it may contain \0 bytes), and token_buffer.size() is the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset token_buffer (ignore opening quote) reset(); // we entered the function by reading an open quote JSON_ASSERT(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { const int codepoint1 = get_codepoint(); int codepoint = codepoint1; // start with codepoint1 if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) { // overwrite codepoint codepoint = static_cast( // high surrogate occupies the most significant 22 bits (static_cast(codepoint1) << 10u) // low surrogate occupies the least significant 15 bits + static_cast(codepoint2) // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00u); } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } } // result of the above calculation yields a proper codepoint JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); // translate codepoint into bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(static_cast(codepoint)); } else if (codepoint <= 0x7FF) { // 2-byte characters: 110xxxxx 10xxxxxx add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else if (codepoint <= 0xFFFF) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: { error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; return token_type::parse_error; } case 0x01: { error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; return token_type::parse_error; } case 0x02: { error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; return token_type::parse_error; } case 0x03: { error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; return token_type::parse_error; } case 0x04: { error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; return token_type::parse_error; } case 0x05: { error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; return token_type::parse_error; } case 0x06: { error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; return token_type::parse_error; } case 0x07: { error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; return token_type::parse_error; } case 0x08: { error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; return token_type::parse_error; } case 0x09: { error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; return token_type::parse_error; } case 0x0A: { error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; return token_type::parse_error; } case 0x0B: { error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; return token_type::parse_error; } case 0x0C: { error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; return token_type::parse_error; } case 0x0D: { error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; return token_type::parse_error; } case 0x0E: { error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; return token_type::parse_error; } case 0x0F: { error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; return token_type::parse_error; } case 0x10: { error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; return token_type::parse_error; } case 0x11: { error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; return token_type::parse_error; } case 0x12: { error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; return token_type::parse_error; } case 0x13: { error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; return token_type::parse_error; } case 0x14: { error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; return token_type::parse_error; } case 0x15: { error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; return token_type::parse_error; } case 0x16: { error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; return token_type::parse_error; } case 0x17: { error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; return token_type::parse_error; } case 0x18: { error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; return token_type::parse_error; } case 0x19: { error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; return token_type::parse_error; } case 0x1A: { error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; return token_type::parse_error; } case 0x1B: { error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; return token_type::parse_error; } case 0x1C: { error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; return token_type::parse_error; } case 0x1D: { error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; return token_type::parse_error; } case 0x1E: { error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; return token_type::parse_error; } case 0x1F: { error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xE0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xEE: case 0xEF: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xED: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xF0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xF1: case 0xF2: case 0xF3: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xF4: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } /*! * @brief scan a comment * @return whether comment could be scanned successfully */ bool scan_comment() { switch (get()) { // single-line comments skip input until a newline or EOF is read case '/': { while (true) { switch (get()) { case '\n': case '\r': case std::char_traits::eof(): case '\0': return true; default: break; } } } // multi-line comments skip input until */ is read case '*': { while (true) { switch (get()) { case std::char_traits::eof(): case '\0': { error_message = "invalid comment; missing closing '*/'"; return false; } case '*': { switch (get()) { case '/': return true; default: { unget(); continue; } } } default: continue; } } } // unexpected character after reading '/' default: { error_message = "invalid comment; expecting '/' or '*' after '/'"; return false; } } } JSON_HEDLEY_NON_NULL(2) static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 7159. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 7159. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in token_buffer. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() // lgtm [cpp/use-of-goto] { // reset token_buffer to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } // all other characters are rejected outside scan_number() default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) unget(); char* endptr = nullptr; errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_unsigned = static_cast(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_integer = static_cast(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, token_buffer.data(), &endptr); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ JSON_HEDLEY_NON_NULL(2) token_type scan_literal(const char_type* literal_text, const std::size_t length, token_type return_type) { JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset token_buffer; current character is beginning of token void reset() noexcept { token_buffer.clear(); token_string.clear(); token_string.push_back(std::char_traits::to_char_type(current)); } /* @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a `std::char_traits::eof()` in that case. Stores the scanned characters for use in error messages. @return character read from the input */ char_int_type get() { ++position.chars_read_total; ++position.chars_read_current_line; if (next_unget) { // just reset the next_unget variable and work with current next_unget = false; } else { current = ia.get_character(); } if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) { token_string.push_back(std::char_traits::to_char_type(current)); } if (current == '\n') { ++position.lines_read; position.chars_read_current_line = 0; } return current; } /*! @brief unget current character (read it again on next get) We implement unget by setting variable next_unget to true. The input is not changed - we just simulate ungetting by modifying chars_read_total, chars_read_current_line, and token_string. The next call to get() will behave as if the unget character is read again. */ void unget() { next_unget = true; --position.chars_read_total; // in case we "unget" a newline, we have to also decrement the lines_read if (position.chars_read_current_line == 0) { if (position.lines_read > 0) { --position.lines_read; } } else { --position.chars_read_current_line; } if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) { JSON_ASSERT(!token_string.empty()); token_string.pop_back(); } } /// add a character to token_buffer void add(char_int_type c) { token_buffer.push_back(static_cast(c)); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return current string value (implicitly resets the token; useful only once) string_t& get_string() { return token_buffer; } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr position_t get_position() const noexcept { return position; } /// return the last read token (for errors only). Will never contain EOF /// (an arbitrary value that is not a valid char value, often -1), because /// 255 may legitimately occur. May contain NUL, which should be escaped. std::string get_token_string() const { // escape control characters std::string result; for (const auto c : token_string) { if (static_cast(c) <= '\x1F') { // escape control characters std::array cs{{}}; (std::snprintf)(cs.data(), cs.size(), "", static_cast(c)); result += cs.data(); } else { // add character as is result.push_back(static_cast(c)); } } return result; } /// return syntax error message JSON_HEDLEY_RETURNS_NON_NULL constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// /*! @brief skip the UTF-8 byte order mark @return true iff there is no BOM or the correct BOM has been skipped */ bool skip_bom() { if (get() == 0xEF) { // check if we completely parse the BOM return get() == 0xBB && get() == 0xBF; } // the first character is not the beginning of the BOM; unget it to // process is later unget(); return true; } void skip_whitespace() { do { get(); } while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); } token_type scan() { // initially, skip the BOM if (position.chars_read_total == 0 && !skip_bom()) { error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; return token_type::parse_error; } // read next character and ignore whitespace skip_whitespace(); // ignore comments while (ignore_comments && current == '/') { if (!scan_comment()) { return token_type::parse_error; } // skip following whitespace skip_whitespace(); } switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': { std::array true_literal = {{'t', 'r', 'u', 'e'}}; return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); } case 'f': { std::array false_literal = {{'f', 'a', 'l', 's', 'e'}}; return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); } case 'n': { std::array null_literal = {{'n', 'u', 'l', 'l'}}; return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); } // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter InputAdapterType ia; /// whether comments should be ignored (true) or signaled as errors (false) const bool ignore_comments = false; /// the current character char_int_type current = std::char_traits::eof(); /// whether the next get() call should just return current bool next_unget = false; /// the start position of the current token position_t position {}; /// raw input token string (for error messages) std::vector token_string {}; /// buffer for variable-length tokens (numbers, strings) string_t token_buffer {}; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char_int_type decimal_point_char = '.'; }; } // namespace detail } // namespace nlohmann // #include // #include #include // size_t #include // declval #include // string // #include // #include namespace nlohmann { namespace detail { template using null_function_t = decltype(std::declval().null()); template using boolean_function_t = decltype(std::declval().boolean(std::declval())); template using number_integer_function_t = decltype(std::declval().number_integer(std::declval())); template using number_unsigned_function_t = decltype(std::declval().number_unsigned(std::declval())); template using number_float_function_t = decltype(std::declval().number_float( std::declval(), std::declval())); template using string_function_t = decltype(std::declval().string(std::declval())); template using binary_function_t = decltype(std::declval().binary(std::declval())); template using start_object_function_t = decltype(std::declval().start_object(std::declval())); template using key_function_t = decltype(std::declval().key(std::declval())); template using end_object_function_t = decltype(std::declval().end_object()); template using start_array_function_t = decltype(std::declval().start_array(std::declval())); template using end_array_function_t = decltype(std::declval().end_array()); template using parse_error_function_t = decltype(std::declval().parse_error( std::declval(), std::declval(), std::declval())); template struct is_sax { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static constexpr bool value = is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value; }; template struct is_sax_static_asserts { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static_assert(is_detected_exact::value, "Missing/invalid function: bool null()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_integer(number_integer_t)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool string(string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool binary(binary_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_object(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool key(string_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_object()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_array(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_array()"); static_assert( is_detected_exact::value, "Missing/invalid function: bool parse_error(std::size_t, const " "std::string&, const exception&)"); }; } // namespace detail } // namespace nlohmann // #include namespace nlohmann { namespace detail { /// how to treat CBOR tags enum class cbor_tag_handler_t { error, ///< throw a parse_error exception in case of a tag ignore ///< ignore tags }; /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from https://stackoverflow.com/a/1001328/266378 */ static inline bool little_endianess(int num = 1) noexcept { return *reinterpret_cast(&num) == 1; } /////////////////// // binary reader // /////////////////// /*! @brief deserialization of CBOR, MessagePack, and UBJSON values */ template> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using json_sax_t = SAX; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits::int_type; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter)) { (void)detail::is_sax_static_asserts {}; } // make class move-only binary_reader(const binary_reader&) = delete; binary_reader(binary_reader&&) = default; binary_reader& operator=(const binary_reader&) = delete; binary_reader& operator=(binary_reader&&) = default; ~binary_reader() = default; /*! @param[in] format the binary format to parse @param[in] sax_ a SAX event processor @param[in] strict whether to expect the input to be consumed completed @param[in] tag_handler how to treat CBOR tags @return */ JSON_HEDLEY_NON_NULL(3) bool sax_parse(const input_format_t format, json_sax_t* sax_, const bool strict = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { sax = sax_; bool result = false; switch (format) { case input_format_t::bson: result = parse_bson_internal(); break; case input_format_t::cbor: result = parse_cbor_internal(true, tag_handler); break; case input_format_t::msgpack: result = parse_msgpack_internal(); break; case input_format_t::ubjson: result = parse_ubjson_internal(); break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } // strict mode: next byte must be EOF if (result && strict) { if (format == input_format_t::ubjson) { get_ignore_noop(); } else { get(); } if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"))); } } return result; } private: ////////// // BSON // ////////// /*! @brief Reads in a BSON-object and passes it to the SAX-parser. @return whether a valid BSON-value was passed to the SAX parser */ bool parse_bson_internal() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) { return false; } return sax->end_object(); } /*! @brief Parses a C-style string from the BSON input. @param[in, out] result A reference to the string variable where the read string is to be stored. @return `true` if the \x00-byte indicating the end of the string was encountered before the EOF; false` indicates an unexpected EOF. */ bool get_bson_cstr(string_t& result) { auto out = std::back_inserter(result); while (true) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) { return false; } if (current == 0x00) { return true; } *out++ = static_cast(current); } } /*! @brief Parses a zero-terminated string of length @a len from the BSON input. @param[in] len The length (including the zero-byte at the end) of the string to be read. @param[in, out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len @pre len >= 1 @return `true` if the string was successfully parsed */ template bool get_bson_string(const NumberType len, string_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 1)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"))); } return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); } /*! @brief Parses a byte array input of length @a len from the BSON input. @param[in] len The length of the byte array to be read. @param[in, out] result A reference to the binary variable where the read array is to be stored. @tparam NumberType The type of the length @a len @pre len >= 0 @return `true` if the byte array was successfully parsed */ template bool get_bson_binary(const NumberType len, binary_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 0)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"))); } // All BSON binary values have a subtype std::uint8_t subtype{}; get_number(input_format_t::bson, subtype); result.set_subtype(subtype); return get_binary(input_format_t::bson, len, result); } /*! @brief Read a BSON document element of the given @a element_type. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html @param[in] element_type_parse_position The position in the input stream, where the `element_type` was read. @warning Not all BSON element types are supported yet. An unsupported @a element_type will give rise to a parse_error.114: Unsupported BSON record type 0x... @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_internal(const char_int_type element_type, const std::size_t element_type_parse_position) { switch (element_type) { case 0x01: // double { double number{}; return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); } case 0x02: // string { std::int32_t len{}; string_t value; return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); } case 0x03: // object { return parse_bson_internal(); } case 0x04: // array { return parse_bson_array(); } case 0x05: // binary { std::int32_t len{}; binary_t value; return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); } case 0x08: // boolean { return sax->boolean(get() != 0); } case 0x0A: // null { return sax->null(); } case 0x10: // int32 { std::int32_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } case 0x12: // int64 { std::int64_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } default: // anything else not supported (yet) { std::array cr{{}}; (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type)); return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()))); } } } /*! @brief Read a BSON element list (as specified in the BSON-spec) The same binary layout is used for objects and arrays, hence it must be indicated with the argument @a is_array which one is expected (true --> array, false --> object). @param[in] is_array Determines if the element list being read is to be treated as an object (@a is_array == false), or as an array (@a is_array == true). @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_list(const bool is_array) { string_t key; while (auto element_type = get()) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) { return false; } const std::size_t element_type_parse_position = chars_read; if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) { return false; } if (!is_array && !sax->key(key)) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) { return false; } // get_bson_cstr only appends key.clear(); } return true; } /*! @brief Reads an array from the BSON input and passes it to the SAX-parser. @return whether a valid BSON-array was passed to the SAX parser */ bool parse_bson_array() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) { return false; } return sax->end_array(); } ////////// // CBOR // ////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true) or whether the last read character should be considered instead (false) @param[in] tag_handler how CBOR tags should be treated @return whether a valid CBOR value was passed to the SAX parser */ bool parse_cbor_internal(const bool get_char, const cbor_tag_handler_t tag_handler) { switch (get_char ? get() : current) { // EOF case std::char_traits::eof(): return unexpect_eof(input_format_t::cbor, "value"); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return sax->number_unsigned(static_cast(current)); case 0x18: // Unsigned integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1A: // Unsigned integer (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1B: // Unsigned integer (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return sax->number_integer(static_cast(0x20 - 1 - current)); case 0x38: // Negative integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - static_cast(number)); } // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: // Binary data (one-byte uint8_t for n follows) case 0x59: // Binary data (two-byte uint16_t for n follow) case 0x5A: // Binary data (four-byte uint32_t for n follow) case 0x5B: // Binary data (eight-byte uint64_t for n follow) case 0x5F: // Binary data (indefinite length) { binary_t b; return get_cbor_binary(b) && sax->binary(b); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7F: // UTF-8 string (indefinite length) { string_t s; return get_cbor_string(s) && sax->string(s); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0x98: // array (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x99: // array (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9A: // array (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9B: // array (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9F: // array (indefinite length) return get_cbor_array(std::size_t(-1), tag_handler); // map (0x00..0x17 pairs of data items follow) case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0xB8: // map (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xB9: // map (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBA: // map (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBB: // map (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBF: // map (indefinite length) return get_cbor_object(std::size_t(-1), tag_handler); case 0xC6: // tagged item case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD8: // tagged item (1 bytes follow) case 0xD9: // tagged item (2 bytes follow) case 0xDA: // tagged item (4 bytes follow) case 0xDB: // tagged item (8 bytes follow) { switch (tag_handler) { case cbor_tag_handler_t::error: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"))); } case cbor_tag_handler_t::ignore: { switch (current) { case 0xD8: { std::uint8_t len{}; get_number(input_format_t::cbor, len); break; } case 0xD9: { std::uint16_t len{}; get_number(input_format_t::cbor, len); break; } case 0xDA: { std::uint32_t len{}; get_number(input_format_t::cbor, len); break; } case 0xDB: { std::uint64_t len{}; get_number(input_format_t::cbor, len); break; } default: break; } return parse_cbor_internal(true, tag_handler); } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } } case 0xF4: // false return sax->boolean(false); case 0xF5: // true return sax->boolean(true); case 0xF6: // null return sax->null(); case 0xF9: // Half-Precision Float (two-byte IEEE 754) { const auto byte1_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte2_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const auto half = static_cast((byte1 << 8u) + byte2); const double val = [&half] { const int exp = (half >> 10u) & 0x1Fu; const unsigned int mant = half & 0x3FFu; JSON_ASSERT(0 <= exp&& exp <= 32); JSON_ASSERT(mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits::infinity() : std::numeric_limits::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000u) != 0 ? static_cast(-val) : static_cast(val), ""); } case 0xFA: // Single-Precision Float (four-byte IEEE 754) { float number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } case 0xFB: // Double-Precision Float (eight-byte IEEE 754) { double number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } default: // anything else (0xFF is handled inside the other types) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"))); } } } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @param[out] result created string @return whether string creation completed */ bool get_cbor_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) { return false; } switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7F: // UTF-8 string (indefinite length) { while (get() != 0xFF) { string_t chunk; if (!get_cbor_string(chunk)) { return false; } result.append(chunk); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"))); } } } /*! @brief reads a CBOR byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into the byte array. Additionally, CBOR's byte arrays with indefinite lengths are supported. @param[out] result created byte array @return whether byte array creation completed */ bool get_cbor_binary(binary_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) { return false; } switch (current) { // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: { return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x58: // Binary data (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x59: // Binary data (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5A: // Binary data (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5B: // Binary data (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5F: // Binary data (indefinite length) { while (get() != 0xFF) { binary_t chunk; if (!get_cbor_binary(chunk)) { return false; } result.insert(result.end(), chunk.begin(), chunk.end()); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"))); } } } /*! @param[in] len the length of the array or std::size_t(-1) for an array of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether array creation completed */ bool get_cbor_array(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) { return false; } } } return sax->end_array(); } /*! @param[in] len the length of the object or std::size_t(-1) for an object of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether object creation completed */ bool get_cbor_object(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } string_t key; if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } return sax->end_object(); } ///////////// // MsgPack // ///////////// /*! @return whether a valid MessagePack value was passed to the SAX parser */ bool parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits::eof(): return unexpect_eof(input_format_t::msgpack, "value"); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: return sax->number_unsigned(static_cast(current)); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: case 0xD9: // str 8 case 0xDA: // str 16 case 0xDB: // str 32 { string_t s; return get_msgpack_string(s) && sax->string(s); } case 0xC0: // nil return sax->null(); case 0xC2: // false return sax->boolean(false); case 0xC3: // true return sax->boolean(true); case 0xC4: // bin 8 case 0xC5: // bin 16 case 0xC6: // bin 32 case 0xC7: // ext 8 case 0xC8: // ext 16 case 0xC9: // ext 32 case 0xD4: // fixext 1 case 0xD5: // fixext 2 case 0xD6: // fixext 4 case 0xD7: // fixext 8 case 0xD8: // fixext 16 { binary_t b; return get_msgpack_binary(b) && sax->binary(b); } case 0xCA: // float 32 { float number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCB: // float 64 { double number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCC: // uint 8 { std::uint8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCD: // uint 16 { std::uint16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCE: // uint 32 { std::uint32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCF: // uint 64 { std::uint64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xD0: // int 8 { std::int8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD1: // int 16 { std::int16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD2: // int 32 { std::int32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD3: // int 64 { std::int64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xDC: // array 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); } case 0xDD: // array 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); } case 0xDE: // map 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); } case 0xDF: // map 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); } // negative fixint case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: return sax->number_integer(static_cast(current)); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"))); } } } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @param[out] result created string @return whether string creation completed */ bool get_msgpack_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) { return false; } switch (current) { // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); } case 0xD9: // str 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDA: // str 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDB: // str 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"))); } } } /*! @brief reads a MessagePack byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into a byte array. @param[out] result created byte array @return whether byte array creation completed */ bool get_msgpack_binary(binary_t& result) { // helper function to set the subtype auto assign_and_return_true = [&result](std::int8_t subtype) { result.set_subtype(static_cast(subtype)); return true; }; switch (current) { case 0xC4: // bin 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC5: // bin 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC6: // bin 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC7: // ext 8 { std::uint8_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC8: // ext 16 { std::uint16_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC9: // ext 32 { std::uint32_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xD4: // fixext 1 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 1, result) && assign_and_return_true(subtype); } case 0xD5: // fixext 2 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 2, result) && assign_and_return_true(subtype); } case 0xD6: // fixext 4 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 4, result) && assign_and_return_true(subtype); } case 0xD7: // fixext 8 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 8, result) && assign_and_return_true(subtype); } case 0xD8: // fixext 16 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 16, result) && assign_and_return_true(subtype); } default: // LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } /*! @param[in] len the length of the array @return whether array creation completed */ bool get_msgpack_array(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } } return sax->end_array(); } /*! @param[in] len the length of the object @return whether object creation completed */ bool get_msgpack_object(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } string_t key; for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } key.clear(); } return sax->end_object(); } //////////// // UBJSON // //////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid UBJSON value was passed to the SAX parser */ bool parse_ubjson_internal(const bool get_char = true) { return get_ubjson_value(get_char ? get_ignore_noop() : current); } /*! @brief reads a UBJSON string This function is either called after reading the 'S' byte explicitly indicating a string, or in case of an object key where the 'S' byte can be left out. @param[out] result created string @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether string creation completed */ bool get_ubjson_string(string_t& result, const bool get_char = true) { if (get_char) { get(); // TODO(niels): may we ignore N here? } if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } switch (current) { case 'U': { std::uint8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'i': { std::int8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'I': { std::int16_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'l': { std::int32_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'L': { std::int64_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } default: auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"))); } } /*! @param[out] result determined size @return whether size determination completed */ bool get_ubjson_size_value(std::size_t& result) { switch (get_ignore_noop()) { case 'U': { std::uint8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'i': { std::int8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'I': { std::int16_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'l': { std::int32_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'L': { std::int64_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"))); } } } /*! @brief determine the type and size for a container In the optimized UBJSON format, a type and a size can be provided to allow for a more compact representation. @param[out] result pair of the size and the type @return whether pair creation completed */ bool get_ubjson_size_type(std::pair& result) { result.first = string_t::npos; // size result.second = 0; // type get_ignore_noop(); if (current == '$') { result.second = get(); // must not ignore 'N', because 'N' maybe the type if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) { return false; } get_ignore_noop(); if (JSON_HEDLEY_UNLIKELY(current != '#')) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"))); } return get_ubjson_size_value(result.first); } if (current == '#') { return get_ubjson_size_value(result.first); } return true; } /*! @param prefix the previously read or set type prefix @return whether value creation completed */ bool get_ubjson_value(const char_int_type prefix) { switch (prefix) { case std::char_traits::eof(): // EOF return unexpect_eof(input_format_t::ubjson, "value"); case 'T': // true return sax->boolean(true); case 'F': // false return sax->boolean(false); case 'Z': // null return sax->null(); case 'U': { std::uint8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); } case 'i': { std::int8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'I': { std::int16_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'l': { std::int32_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'L': { std::int64_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'd': { float number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); } case 'D': { double number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); } case 'H': { return get_ubjson_high_precision_number(); } case 'C': // char { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) { return false; } if (JSON_HEDLEY_UNLIKELY(current > 127)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"))); } string_t s(1, static_cast(current)); return sax->string(s); } case 'S': // string { string_t s; return get_ubjson_string(s) && sax->string(s); } case '[': // array return get_ubjson_array(); case '{': // object return get_ubjson_object(); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"))); } } } /*! @return whether array creation completed */ bool get_ubjson_array() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) { return false; } if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } while (current != ']') { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) { return false; } get_ignore_noop(); } } return sax->end_array(); } /*! @return whether object creation completed */ bool get_ubjson_object() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } string_t key; if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) { return false; } if (size_and_type.second != 0) { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } key.clear(); } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } key.clear(); } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } while (current != '}') { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } get_ignore_noop(); key.clear(); } } return sax->end_object(); } // Note, no reader for UBJSON binary types is implemented because they do // not exist bool get_ubjson_high_precision_number() { // get size of following number string std::size_t size{}; auto res = get_ubjson_size_value(size); if (JSON_HEDLEY_UNLIKELY(!res)) { return res; } // get number string std::vector number_vector; for (std::size_t i = 0; i < size; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) { return false; } number_vector.push_back(static_cast(current)); } // parse number string auto number_ia = detail::input_adapter(std::forward(number_vector)); auto number_lexer = detail::lexer(std::move(number_ia), false); const auto result_number = number_lexer.scan(); const auto number_string = number_lexer.get_token_string(); const auto result_remainder = number_lexer.scan(); using token_type = typename detail::lexer_base::token_type; if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) { return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"))); } switch (result_number) { case token_type::value_integer: return sax->number_integer(number_lexer.get_number_integer()); case token_type::value_unsigned: return sax->number_unsigned(number_lexer.get_number_unsigned()); case token_type::value_float: return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); default: return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"))); } } /////////////////////// // Utility functions // /////////////////////// /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a -'ve valued `std::char_traits::eof()` in that case. @return character read from the input */ char_int_type get() { ++chars_read; return current = ia.get_character(); } /*! @return character read from the input after ignoring all 'N' entries */ char_int_type get_ignore_noop() { do { get(); } while (current == 'N'); return current; } /* @brief read a number from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[out] result number of type @a NumberType @return whether conversion completed @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template bool get_number(const input_format_t format, NumberType& result) { // step 1: read input into array with system's byte order std::array vec; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) { return false; } // reverse byte order prior to conversion if necessary if (is_little_endian != InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast(current); } else { vec[i] = static_cast(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return std::memcpy(&result, vec.data(), sizeof(NumberType)); return true; } /*! @brief create a string by reading characters from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of characters to read @param[out] result string created by reading @a len bytes @return whether string creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of string memory. */ template bool get_string(const input_format_t format, const NumberType len, string_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) { success = false; break; } result.push_back(static_cast(current)); }; return success; } /*! @brief create a byte array by reading bytes from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of bytes to read @param[out] result byte array created by reading @a len bytes @return whether byte array creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of memory. */ template bool get_binary(const input_format_t format, const NumberType len, binary_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) { success = false; break; } result.push_back(static_cast(current)); } return success; } /*! @param[in] format the current format (for diagnostics) @param[in] context further context information (for diagnostics) @return whether the last read character is not EOF */ JSON_HEDLEY_NON_NULL(3) bool unexpect_eof(const input_format_t format, const char* context) const { if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) { return sax->parse_error(chars_read, "", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context))); } return true; } /*! @return a string representation of the last read byte */ std::string get_token_string() const { std::array cr{{}}; (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current)); return std::string{cr.data()}; } /*! @param[in] format the current format @param[in] detail a detailed error message @param[in] context further context information @return a message string to use in the parse_error exceptions */ std::string exception_message(const input_format_t format, const std::string& detail, const std::string& context) const { std::string error_msg = "syntax error while parsing "; switch (format) { case input_format_t::cbor: error_msg += "CBOR"; break; case input_format_t::msgpack: error_msg += "MessagePack"; break; case input_format_t::ubjson: error_msg += "UBJSON"; break; case input_format_t::bson: error_msg += "BSON"; break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } return error_msg + " " + context + ": " + detail; } private: /// input adapter InputAdapterType ia; /// the current character char_int_type current = std::char_traits::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianess const bool is_little_endian = little_endianess(); /// the SAX parser json_sax_t* sax = nullptr; }; } // namespace detail } // namespace nlohmann // #include // #include // #include #include // isfinite #include // uint8_t #include // function #include // string #include // move #include // vector // #include // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { //////////// // parser // //////////// enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; template using parser_callback_t = std::function; /*! @brief syntax analysis This class implements a recursive descent parser. */ template class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using lexer_t = lexer; using token_type = typename lexer_t::token_type; public: /// a parser reading from an input adapter explicit parser(InputAdapterType&& adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true, const bool skip_comments = false) : callback(cb) , m_lexer(std::move(adapter), skip_comments) , allow_exceptions(allow_exceptions_) { // read first token get_token(); } /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { if (callback) { json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); sax_parse_internal(&sdp); result.assert_invariant(); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } else { json_sax_dom_parser sdp(result, allow_exceptions); sax_parse_internal(&sdp); result.assert_invariant(); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } } } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { json_sax_acceptor sax_acceptor; return sax_parse(&sax_acceptor, strict); } template JSON_HEDLEY_NON_NULL(2) bool sax_parse(SAX* sax, const bool strict = true) { (void)detail::is_sax_static_asserts {}; const bool result = sax_parse_internal(sax); // strict mode: next byte must be EOF if (result && strict && (get_token() != token_type::end_of_input)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } return result; } private: template JSON_HEDLEY_NON_NULL(2) bool sax_parse_internal(SAX* sax) { // stack to remember the hierarchy of structured values we are parsing // true = array; false = object std::vector states; // value to avoid a goto (see comment where set to true) bool skip_to_state_evaluation = false; while (true) { if (!skip_to_state_evaluation) { // invariant: get_token() was called before each iteration switch (last_token) { case token_type::begin_object: { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) { return false; } // closing } -> we are done if (get_token() == token_type::end_object) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } break; } // parse key if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"))); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"))); } // remember we are now inside an object states.push_back(false); // parse values get_token(); continue; } case token_type::begin_array: { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) { return false; } // closing ] -> we are done if (get_token() == token_type::end_array) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } break; } // remember we are now inside an array states.push_back(true); // parse values (no need to call get_token) continue; } case token_type::value_float: { const auto res = m_lexer.get_number_float(); if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); } if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) { return false; } break; } case token_type::literal_false: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) { return false; } break; } case token_type::literal_null: { if (JSON_HEDLEY_UNLIKELY(!sax->null())) { return false; } break; } case token_type::literal_true: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) { return false; } break; } case token_type::value_integer: { if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) { return false; } break; } case token_type::value_string: { if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) { return false; } break; } case token_type::value_unsigned: { if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) { return false; } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"))); } default: // the last token was unexpected { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"))); } } } else { skip_to_state_evaluation = false; } // we reached this line after we successfully parsed a value if (states.empty()) { // empty stack: we reached the end of the hierarchy: done return true; } if (states.back()) // array { // comma -> next value if (get_token() == token_type::value_separator) { // parse a new value get_token(); continue; } // closing ] if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } // We are done with this array. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"))); } else // object { // comma -> next value if (get_token() == token_type::value_separator) { // parse key if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"))); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"))); } // parse values get_token(); continue; } // closing } if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } // We are done with this object. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"))); } } } /// get next token from lexer token_type get_token() { return last_token = m_lexer.scan(); } std::string exception_message(const token_type expected, const std::string& context) { std::string error_msg = "syntax error "; if (!context.empty()) { error_msg += "while parsing " + context + " "; } error_msg += "- "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } return error_msg; } private: /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; } // namespace detail } // namespace nlohmann // #include // #include #include // ptrdiff_t #include // numeric_limits namespace nlohmann { namespace detail { /* @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { private: using difference_type = std::ptrdiff_t; static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; /// iterator as signed integer type difference_type m_it = (std::numeric_limits::min)(); public: constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type n) noexcept { auto result = *this; result += n; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } primitive_iterator_t& operator++() noexcept { ++m_it; return *this; } primitive_iterator_t const operator++(int) noexcept { auto result = *this; ++m_it; return result; } primitive_iterator_t& operator--() noexcept { --m_it; return *this; } primitive_iterator_t const operator--(int) noexcept { auto result = *this; --m_it; return result; } primitive_iterator_t& operator+=(difference_type n) noexcept { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) noexcept { m_it -= n; return *this; } }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; } // namespace detail } // namespace nlohmann // #include #include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next #include // conditional, is_const, remove_const // #include // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { // forward declare, to be able to friend it later on template class iteration_proxy; template class iteration_proxy_value; /*! @brief a template for a bidirectional iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). @since version 1.0.0, simplified in version 2.0.9, change to bidirectional iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) */ template class iter_impl { /// allow basic_json to access private members friend iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; friend BasicJsonType; friend iteration_proxy; friend iteration_proxy_value; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json::type>::value, "iter_impl only accepts (const) basic_json"); public: /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. /// The C++ Standard has never required user-defined iterators to derive from std::iterator. /// A user-defined iterator should provide publicly accessible typedefs named /// iterator_category, value_type, difference_type, pointer, and reference. /// Note that value_type is required to be non-const, even for constant iterators. using iterator_category = std::bidirectional_iterator_tag; /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; /// default constructor iter_impl() = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief const copy constructor @param[in] other const iterator to copy from @note This copy constructor had to be defined explicitly to circumvent a bug occurring on msvc v19.0 compiler (VS 2015) debug build. For more information refer to: https://github.com/nlohmann/json/issues/1608 */ iter_impl(const iter_impl& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl& other) noexcept { m_object = other.m_object; m_it = other.m_it; return *this; } /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl::type>& other) noexcept { m_object = other.m_object; m_it = other.m_it; return *this; } private: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator++(int) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator--(int) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator==(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator!=(const iter_impl& other) const { return !operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return !other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return !operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return !operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ const typename object_t::key_type& key() const { JSON_ASSERT(m_object != nullptr); if (JSON_HEDLEY_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } private: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator::type> m_it {}; }; } // namespace detail } // namespace nlohmann // #include // #include #include // ptrdiff_t #include // reverse_iterator #include // declval namespace nlohmann { namespace detail { ////////////////////// // reverse_iterator // ////////////////////// /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template class json_reverse_iterator : public std::reverse_iterator { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adapter using base_iterator = std::reverse_iterator; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator const operator++(int) { return static_cast(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator const operator--(int) { return static_cast(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; } // namespace detail } // namespace nlohmann // #include // #include #include // all_of #include // isdigit #include // max #include // accumulate #include // string #include // move #include // vector // #include // #include // #include namespace nlohmann { template class json_pointer { // allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw parse_error.107 if the given JSON pointer @a s is nonempty and does not begin with a slash (`/`); see example below @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is not followed by `0` (representing `~`) or `1` (representing `/`); see example below @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`.,json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } /*! @brief append another JSON pointer at the end of this JSON pointer @param[in] ptr JSON pointer to append @return JSON pointer with @a ptr appended @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Linear in the length of @a ptr. @sa @ref operator/=(std::string) to append a reference token @sa @ref operator/=(std::size_t) to append an array index @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(const json_pointer& ptr) { reference_tokens.insert(reference_tokens.end(), ptr.reference_tokens.begin(), ptr.reference_tokens.end()); return *this; } /*! @brief append an unescaped reference token at the end of this JSON pointer @param[in] token reference token to append @return JSON pointer with @a token appended without escaping @a token @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Amortized constant. @sa @ref operator/=(const json_pointer&) to append a JSON pointer @sa @ref operator/=(std::size_t) to append an array index @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(std::string token) { push_back(std::move(token)); return *this; } /*! @brief append an array index at the end of this JSON pointer @param[in] array_idx array index to append @return JSON pointer with @a array_idx appended @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} @complexity Amortized constant. @sa @ref operator/=(const json_pointer&) to append a JSON pointer @sa @ref operator/=(std::string) to append a reference token @sa @ref operator/(const json_pointer&, std::string) for a binary operator @since version 3.6.0 */ json_pointer& operator/=(std::size_t array_idx) { return *this /= std::to_string(array_idx); } /*! @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer @param[in] lhs JSON pointer @param[in] rhs JSON pointer @return a new JSON pointer with @a rhs appended to @a lhs @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a lhs and @a rhs. @sa @ref operator/=(const json_pointer&) to append a JSON pointer @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& lhs, const json_pointer& rhs) { return json_pointer(lhs) /= rhs; } /*! @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer @param[in] ptr JSON pointer @param[in] token reference token @return a new JSON pointer with unescaped @a token appended to @a ptr @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a ptr. @sa @ref operator/=(std::string) to append a reference token @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& ptr, std::string token) { return json_pointer(ptr) /= std::move(token); } /*! @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer @param[in] ptr JSON pointer @param[in] array_idx array index @return a new JSON pointer with @a array_idx appended to @a ptr @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} @complexity Linear in the length of @a ptr. @sa @ref operator/=(std::size_t) to append an array index @since version 3.6.0 */ friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx) { return json_pointer(ptr) /= array_idx; } /*! @brief returns the parent of this JSON pointer @return parent of this JSON pointer; in case this JSON pointer is the root, the root itself is returned @complexity Linear in the length of the JSON pointer. @liveexample{The example shows the result of `parent_pointer` for different JSON Pointers.,json_pointer__parent_pointer} @since version 3.6.0 */ json_pointer parent_pointer() const { if (empty()) { return *this; } json_pointer res = *this; res.pop_back(); return res; } /*! @brief remove last reference token @pre not `empty()` @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back} @complexity Constant. @throw out_of_range.405 if JSON pointer has no parent @since version 3.6.0 */ void pop_back() { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } reference_tokens.pop_back(); } /*! @brief return last reference token @pre not `empty()` @return last reference token @liveexample{The example shows the usage of `back`.,json_pointer__back} @complexity Constant. @throw out_of_range.405 if JSON pointer has no parent @since version 3.6.0 */ const std::string& back() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } return reference_tokens.back(); } /*! @brief append an unescaped token at the end of the reference pointer @param[in] token token to add @complexity Amortized constant. @liveexample{The example shows the result of `push_back` for different JSON Pointers.,json_pointer__push_back} @since version 3.6.0 */ void push_back(const std::string& token) { reference_tokens.push_back(token); } /// @copydoc push_back(const std::string&) void push_back(std::string&& token) { reference_tokens.push_back(std::move(token)); } /*! @brief return whether pointer points to the root document @return true iff the JSON pointer points to the root document @complexity Constant. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example shows the result of `empty` for different JSON Pointers.,json_pointer__empty} @since version 3.6.0 */ bool empty() const noexcept { return reference_tokens.empty(); } private: /*! @param[in] s reference token to be converted into an array index @return integer representation of @a s @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index begins not with a digit @throw out_of_range.404 if string @a s could not be converted to an integer @throw out_of_range.410 if an array index exceeds size_type */ static typename BasicJsonType::size_type array_index(const std::string& s) { using size_type = typename BasicJsonType::size_type; // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number")); } std::size_t processed_chars = 0; unsigned long long res = 0; JSON_TRY { res = std::stoull(s, &processed_chars); } JSON_CATCH(std::out_of_range&) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); } // check if the string was completely read if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); } // only triggered on special platforms (like 32bit), see also // https://github.com/nlohmann/json/pull/2203 if (res >= static_cast((std::numeric_limits::max)())) { JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type")); // LCOV_EXCL_LINE } return static_cast(res); } json_pointer top() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ BasicJsonType& get_and_create(BasicJsonType& j) const { auto result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->type()) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array result = &result->operator[](array_index(reference_token)); break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_unchecked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->is_null()) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const unsigned char x) { return std::isdigit(x); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access ptr = &ptr->operator[](array_index(reference_token)); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_checked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // use unchecked array access ptr = &ptr->operator[](array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_checked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number */ bool contains(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { if (!ptr->contains(reference_token)) { // we did not find the key in the object return false; } ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) { // invalid char return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) { if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) { // first char should be between '1' and '9' return false; } for (std::size_t i = 1; i < reference_token.size(); i++) { if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) { // other char should be between '0' and '9' return false; } } } const auto idx = array_index(reference_token); if (idx >= ptr->size()) { // index out of range return false; } ptr = &ptr->operator[](idx); break; } default: { // we do not expect primitive values if there is still a // reference token to process return false; } } } // no reference token left means we found a primitive value return true; } /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector split(const std::string& reference_string) { std::vector result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'")); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == 0 (if slash == std::string::npos) start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = (slash == std::string::npos) ? 0 : slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { JSON_ASSERT(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || (reference_token[pos + 1] != '0' && reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); } } // finally, store the reference token unescape(reference_token); result.push_back(reference_token); } return result; } /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ static void replace_substring(std::string& s, const std::string& f, const std::string& t) { JSON_ASSERT(!f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /// escape "~" to "~0" and "/" to "~1" static std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /// unescape "~1" to tilde and "~0" to slash (order is important!) static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ static void flatten(const std::string& reference_string, const BasicJsonType& value, BasicJsonType& result) { switch (value.type()) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ static BasicJsonType unflatten(const BasicJsonType& value) { if (JSON_HEDLEY_UNLIKELY(!value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); } BasicJsonType result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } /*! @brief compares two JSON pointers for equality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is equal to @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return lhs.reference_tokens == rhs.reference_tokens; } /*! @brief compares two JSON pointers for inequality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is not equal @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return !(lhs == rhs); } /// the reference tokens std::vector reference_tokens; }; } // namespace nlohmann // #include #include #include // #include namespace nlohmann { namespace detail { template class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)) , value_ref(&owned_value) , is_rvalue(true) {} json_ref(const value_type& value) : value_ref(const_cast(&value)) , is_rvalue(false) {} json_ref(std::initializer_list init) : owned_value(init) , value_ref(&owned_value) , is_rvalue(true) {} template < class... Args, enable_if_t::value, int> = 0 > json_ref(Args && ... args) : owned_value(std::forward(args)...) , value_ref(&owned_value) , is_rvalue(true) {} // class should be movable only json_ref(json_ref&&) = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; json_ref& operator=(json_ref&&) = delete; ~json_ref() = default; value_type moved_or_copied() const { if (is_rvalue) { return std::move(*value_ref); } return *value_ref; } value_type const& operator*() const { return *static_cast(value_ref); } value_type const* operator->() const { return static_cast(value_ref); } private: mutable value_type owned_value = nullptr; value_type* value_ref = nullptr; const bool is_rvalue = true; }; } // namespace detail } // namespace nlohmann // #include // #include // #include // #include #include // reverse #include // array #include // uint8_t, uint16_t, uint32_t, uint64_t #include // memcpy #include // numeric_limits #include // string #include // isnan, isinf // #include // #include // #include #include // copy #include // size_t #include // streamsize #include // back_inserter #include // shared_ptr, make_shared #include // basic_ostream #include // basic_string #include // vector // #include namespace nlohmann { namespace detail { /// abstract output adapter interface template struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; }; /// a type to simplify interfaces template using output_adapter_t = std::shared_ptr>; /// output adapter for byte vectors template class output_vector_adapter : public output_adapter_protocol { public: explicit output_vector_adapter(std::vector& vec) noexcept : v(vec) {} void write_character(CharType c) override { v.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector& v; }; /// output adapter for output streams template class output_stream_adapter : public output_adapter_protocol { public: explicit output_stream_adapter(std::basic_ostream& s) noexcept : stream(s) {} void write_character(CharType c) override { stream.put(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast(length)); } private: std::basic_ostream& stream; }; /// output adapter for basic_string template> class output_string_adapter : public output_adapter_protocol { public: explicit output_string_adapter(StringType& s) noexcept : str(s) {} void write_character(CharType c) override { str.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: StringType& str; }; template> class output_adapter { public: output_adapter(std::vector& vec) : oa(std::make_shared>(vec)) {} output_adapter(std::basic_ostream& s) : oa(std::make_shared>(s)) {} output_adapter(StringType& s) : oa(std::make_shared>(s)) {} operator output_adapter_t() { return oa; } private: output_adapter_t oa = nullptr; }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /////////////////// // binary writer // /////////////////// /*! @brief serialization to CBOR and MessagePack values */ template class binary_writer { using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using number_float_t = typename BasicJsonType::number_float_t; public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t adapter) : oa(adapter) { JSON_ASSERT(oa); } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson(const BasicJsonType& j) { switch (j.type()) { case value_t::object: { write_bson_object(*j.m_value.object); break; } default: { JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()))); } } } /*! @param[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(to_char_type(0xF6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast(j.m_value.number_integer)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x38)); write_number(static_cast(positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x39)); write_number(static_cast(positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x3A)); write_number(static_cast(positive_number)); } else { oa->write_character(to_char_type(0x3B)); write_number(static_cast(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast(j.m_value.number_unsigned)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast(j.m_value.number_unsigned)); } break; } case value_t::number_float: { if (std::isnan(j.m_value.number_float)) { // NaN is 0xf97e00 in CBOR oa->write_character(to_char_type(0xF9)); oa->write_character(to_char_type(0x7E)); oa->write_character(to_char_type(0x00)); } else if (std::isinf(j.m_value.number_float)) { // Infinity is 0xf97c00, -Infinity is 0xf9fc00 oa->write_character(to_char_type(0xf9)); oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); oa->write_character(to_char_type(0x00)); } else { write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); } break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast(0x60 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x78)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x79)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x7A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x7B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast(0x80 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x98)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x99)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x9A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x9B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::binary: { if (j.m_value.binary->has_subtype()) { write_number(static_cast(0xd8)); write_number(j.m_value.binary->subtype()); } // step 1: write control byte and the binary array size const auto N = j.m_value.binary->size(); if (N <= 0x17) { write_number(static_cast(0x40 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x58)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x59)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x5A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x5B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element oa->write_characters( reinterpret_cast(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast(0xA0 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xB8)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xB9)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xBA)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xBB)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(to_char_type(0xC0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 8 oa->write_character(to_char_type(0xD0)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 16 oa->write_character(to_char_type(0xD1)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 32 oa->write_character(to_char_type(0xD2)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 64 oa->write_character(to_char_type(0xD3)); write_number(static_cast(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast(j.m_value.number_integer)); } break; } case value_t::number_float: { write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast(0xA0 | N)); } else if (N <= (std::numeric_limits::max)()) { // str 8 oa->write_character(to_char_type(0xD9)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // str 16 oa->write_character(to_char_type(0xDA)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // str 32 oa->write_character(to_char_type(0xDB)); write_number(static_cast(N)); } // step 2: write the string oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast(0x90 | N)); } else if (N <= (std::numeric_limits::max)()) { // array 16 oa->write_character(to_char_type(0xDC)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // array 32 oa->write_character(to_char_type(0xDD)); write_number(static_cast(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::binary: { // step 0: determine if the binary type has a set subtype to // determine whether or not to use the ext or fixext types const bool use_ext = j.m_value.binary->has_subtype(); // step 1: write control byte and the byte string length const auto N = j.m_value.binary->size(); if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type{}; bool fixed = true; if (use_ext) { switch (N) { case 1: output_type = 0xD4; // fixext 1 break; case 2: output_type = 0xD5; // fixext 2 break; case 4: output_type = 0xD6; // fixext 4 break; case 8: output_type = 0xD7; // fixext 8 break; case 16: output_type = 0xD8; // fixext 16 break; default: output_type = 0xC7; // ext 8 fixed = false; break; } } else { output_type = 0xC4; // bin 8 fixed = false; } oa->write_character(to_char_type(output_type)); if (!fixed) { write_number(static_cast(N)); } } else if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type = use_ext ? 0xC8 // ext 16 : 0xC5; // bin 16 oa->write_character(to_char_type(output_type)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type = use_ext ? 0xC9 // ext 32 : 0xC6; // bin 32 oa->write_character(to_char_type(output_type)); write_number(static_cast(N)); } // step 1.5: if this is an ext type, write the subtype if (use_ext) { write_number(static_cast(j.m_value.binary->subtype())); } // step 2: write the byte string oa->write_characters( reinterpret_cast(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast(0x80 | (N & 0xF))); } else if (N <= (std::numeric_limits::max)()) { // map 16 oa->write_character(to_char_type(0xDE)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // map 32 oa->write_character(to_char_type(0xDF)); write_number(static_cast(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize @param[in] use_count whether to use '#' prefixes (optimized format) @param[in] use_type whether to use '$' prefixes (optimized format) @param[in] add_prefix whether prefixes need to be used for this value */ void write_ubjson(const BasicJsonType& j, const bool use_count, const bool use_type, const bool add_prefix = true) { switch (j.type()) { case value_t::null: { if (add_prefix) { oa->write_character(to_char_type('Z')); } break; } case value_t::boolean: { if (add_prefix) { oa->write_character(j.m_value.boolean ? to_char_type('T') : to_char_type('F')); } break; } case value_t::number_integer: { write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); break; } case value_t::number_unsigned: { write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); break; } case value_t::number_float: { write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); break; } case value_t::string: { if (add_prefix) { oa->write_character(to_char_type('S')); } write_number_with_ubjson_prefix(j.m_value.string->size(), true); oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { if (add_prefix) { oa->write_character(to_char_type('[')); } bool prefix_required = true; if (use_type && !j.m_value.array->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin() + 1, j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.array->size(), true); } for (const auto& el : *j.m_value.array) { write_ubjson(el, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::binary: { if (add_prefix) { oa->write_character(to_char_type('[')); } if (use_type && !j.m_value.binary->empty()) { JSON_ASSERT(use_count); oa->write_character(to_char_type('$')); oa->write_character('U'); } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.binary->size(), true); } if (use_type) { oa->write_characters( reinterpret_cast(j.m_value.binary->data()), j.m_value.binary->size()); } else { for (size_t i = 0; i < j.m_value.binary->size(); ++i) { oa->write_character(to_char_type('U')); oa->write_character(j.m_value.binary->data()[i]); } } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::object: { if (add_prefix) { oa->write_character(to_char_type('{')); } bool prefix_required = true; if (use_type && !j.m_value.object->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin(), j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.object->size(), true); } for (const auto& el : *j.m_value.object) { write_number_with_ubjson_prefix(el.first.size(), true); oa->write_characters( reinterpret_cast(el.first.c_str()), el.first.size()); write_ubjson(el.second, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type('}')); } break; } default: break; } } private: ////////// // BSON // ////////// /*! @return The size of a BSON document entry header, including the id marker and the entry name size (and its null-terminator). */ static std::size_t calc_bson_entry_header_size(const string_t& name) { const auto it = name.find(static_cast(0)); if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) { JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")")); } return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; } /*! @brief Writes the given @a element_type and @a name to the output adapter */ void write_bson_entry_header(const string_t& name, const std::uint8_t element_type) { oa->write_character(to_char_type(element_type)); // boolean oa->write_characters( reinterpret_cast(name.c_str()), name.size() + 1u); } /*! @brief Writes a BSON element with key @a name and boolean value @a value */ void write_bson_boolean(const string_t& name, const bool value) { write_bson_entry_header(name, 0x08); oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and double value @a value */ void write_bson_double(const string_t& name, const double value) { write_bson_entry_header(name, 0x01); write_number(value); } /*! @return The size of the BSON-encoded string in @a value */ static std::size_t calc_bson_string_size(const string_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and string value @a value */ void write_bson_string(const string_t& name, const string_t& value) { write_bson_entry_header(name, 0x02); write_number(static_cast(value.size() + 1ul)); oa->write_characters( reinterpret_cast(value.c_str()), value.size() + 1); } /*! @brief Writes a BSON element with key @a name and null value */ void write_bson_null(const string_t& name) { write_bson_entry_header(name, 0x0A); } /*! @return The size of the BSON-encoded integer @a value */ static std::size_t calc_bson_integer_size(const std::int64_t value) { return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and integer @a value */ void write_bson_integer(const string_t& name, const std::int64_t value) { if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) { write_bson_entry_header(name, 0x10); // int32 write_number(static_cast(value)); } else { write_bson_entry_header(name, 0x12); // int64 write_number(static_cast(value)); } } /*! @return The size of the BSON-encoded unsigned integer in @a j */ static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept { return (value <= static_cast((std::numeric_limits::max)())) ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and unsigned @a value */ void write_bson_unsigned(const string_t& name, const std::uint64_t value) { if (value <= static_cast((std::numeric_limits::max)())) { write_bson_entry_header(name, 0x10 /* int32 */); write_number(static_cast(value)); } else if (value <= static_cast((std::numeric_limits::max)())) { write_bson_entry_header(name, 0x12 /* int64 */); write_number(static_cast(value)); } else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64")); } } /*! @brief Writes a BSON element with key @a name and object @a value */ void write_bson_object_entry(const string_t& name, const typename BasicJsonType::object_t& value) { write_bson_entry_header(name, 0x03); // object write_bson_object(value); } /*! @return The size of the BSON-encoded array @a value */ static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) { std::size_t array_index = 0ul; const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) { return result + calc_bson_element_size(std::to_string(array_index++), el); }); return sizeof(std::int32_t) + embedded_document_size + 1ul; } /*! @return The size of the BSON-encoded binary array @a value */ static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and array @a value */ void write_bson_array(const string_t& name, const typename BasicJsonType::array_t& value) { write_bson_entry_header(name, 0x04); // array write_number(static_cast(calc_bson_array_size(value))); std::size_t array_index = 0ul; for (const auto& el : value) { write_bson_element(std::to_string(array_index++), el); } oa->write_character(to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and binary value @a value */ void write_bson_binary(const string_t& name, const binary_t& value) { write_bson_entry_header(name, 0x05); write_number(static_cast(value.size())); write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00)); oa->write_characters(reinterpret_cast(value.data()), value.size()); } /*! @brief Calculates the size necessary to serialize the JSON value @a j with its @a name @return The calculated size for the BSON document entry for @a j with the given @a name. */ static std::size_t calc_bson_element_size(const string_t& name, const BasicJsonType& j) { const auto header_size = calc_bson_entry_header_size(name); switch (j.type()) { case value_t::object: return header_size + calc_bson_object_size(*j.m_value.object); case value_t::array: return header_size + calc_bson_array_size(*j.m_value.array); case value_t::binary: return header_size + calc_bson_binary_size(*j.m_value.binary); case value_t::boolean: return header_size + 1ul; case value_t::number_float: return header_size + 8ul; case value_t::number_integer: return header_size + calc_bson_integer_size(j.m_value.number_integer); case value_t::number_unsigned: return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); case value_t::string: return header_size + calc_bson_string_size(*j.m_value.string); case value_t::null: return header_size + 0ul; // LCOV_EXCL_START default: JSON_ASSERT(false); return 0ul; // LCOV_EXCL_STOP } } /*! @brief Serializes the JSON value @a j to BSON and associates it with the key @a name. @param name The name to associate with the JSON entity @a j within the current BSON document @return The size of the BSON entry */ void write_bson_element(const string_t& name, const BasicJsonType& j) { switch (j.type()) { case value_t::object: return write_bson_object_entry(name, *j.m_value.object); case value_t::array: return write_bson_array(name, *j.m_value.array); case value_t::binary: return write_bson_binary(name, *j.m_value.binary); case value_t::boolean: return write_bson_boolean(name, j.m_value.boolean); case value_t::number_float: return write_bson_double(name, j.m_value.number_float); case value_t::number_integer: return write_bson_integer(name, j.m_value.number_integer); case value_t::number_unsigned: return write_bson_unsigned(name, j.m_value.number_unsigned); case value_t::string: return write_bson_string(name, *j.m_value.string); case value_t::null: return write_bson_null(name); // LCOV_EXCL_START default: JSON_ASSERT(false); return; // LCOV_EXCL_STOP } } /*! @brief Calculates the size of the BSON serialization of the given JSON-object @a j. @param[in] j JSON value to serialize @pre j.type() == value_t::object */ static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) { std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0), [](size_t result, const typename BasicJsonType::object_t::value_type & el) { return result += calc_bson_element_size(el.first, el.second); }); return sizeof(std::int32_t) + document_size + 1ul; } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson_object(const typename BasicJsonType::object_t& value) { write_number(static_cast(calc_bson_object_size(value))); for (const auto& el : value) { write_bson_element(el.first, el.second); } oa->write_character(to_char_type(0x00)); } ////////// // CBOR // ////////// static constexpr CharType get_cbor_float_prefix(float /*unused*/) { return to_char_type(0xFA); // Single-Precision Float } static constexpr CharType get_cbor_float_prefix(double /*unused*/) { return to_char_type(0xFB); // Double-Precision Float } ///////////// // MsgPack // ///////////// static constexpr CharType get_msgpack_float_prefix(float /*unused*/) { return to_char_type(0xCA); // float 32 } static constexpr CharType get_msgpack_float_prefix(double /*unused*/) { return to_char_type(0xCB); // float 64 } //////////// // UBJSON // //////////// // UBJSON: write number (floating point) template::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (add_prefix) { oa->write_character(get_ubjson_float_prefix(n)); } write_number(n); } // UBJSON: write number (unsigned integer) template::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast(n)); } else if (n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast(n)); } else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast(number[i]))); } } } // UBJSON: write number (signed integer) template < typename NumberType, typename std::enable_if < std::is_signed::value&& !std::is_floating_point::value, int >::type = 0 > void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast(n)); } else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast(n)); } // LCOV_EXCL_START else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast(number[i]))); } } // LCOV_EXCL_STOP } /*! @brief determine the type prefix of container values */ CharType ubjson_prefix(const BasicJsonType& j) const noexcept { switch (j.type()) { case value_t::null: return 'Z'; case value_t::boolean: return j.m_value.boolean ? 'T' : 'F'; case value_t::number_integer: { if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'i'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'U'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'I'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'l'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'i'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'U'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'I'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'l'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_float: return get_ubjson_float_prefix(j.m_value.number_float); case value_t::string: return 'S'; case value_t::array: // fallthrough case value_t::binary: return '['; case value_t::object: return '{'; default: // discarded values return 'N'; } } static constexpr CharType get_ubjson_float_prefix(float /*unused*/) { return 'd'; // float 32 } static constexpr CharType get_ubjson_float_prefix(double /*unused*/) { return 'D'; // float 64 } /////////////////////// // Utility functions // /////////////////////// /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @tparam OutputIsLittleEndian Set to true if output data is required to be little endian @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template void write_number(const NumberType n) { // step 1: write number to array of length NumberType std::array vec; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } void write_compact_float(const number_float_t n, detail::input_format_t format) { if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && static_cast(n) <= static_cast((std::numeric_limits::max)()) && static_cast(static_cast(n)) == static_cast(n)) { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(static_cast(n)) : get_msgpack_float_prefix(static_cast(n))); write_number(static_cast(n)); } else { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(n) : get_msgpack_float_prefix(n)); write_number(n); } } public: // The following to_char_type functions are implement the conversion // between uint8_t and CharType. In case CharType is not unsigned, // such a conversion is required to allow values greater than 128. // See for a discussion. template < typename C = CharType, enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > static constexpr CharType to_char_type(std::uint8_t x) noexcept { return *reinterpret_cast(&x); } template < typename C = CharType, enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > static CharType to_char_type(std::uint8_t x) noexcept { static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); static_assert(std::is_trivial::value, "CharType must be trivial"); CharType result; std::memcpy(&result, &x, sizeof(x)); return result; } template::value>* = nullptr> static constexpr CharType to_char_type(std::uint8_t x) noexcept { return x; } template < typename InputCharType, typename C = CharType, enable_if_t < std::is_signed::value && std::is_signed::value && std::is_same::type>::value > * = nullptr > static constexpr CharType to_char_type(InputCharType x) noexcept { return x; } private: /// whether we can assume little endianess const bool is_little_endian = little_endianess(); /// the output output_adapter_t oa = nullptr; }; } // namespace detail } // namespace nlohmann // #include // #include #include // reverse, remove, fill, find, none_of #include // array #include // localeconv, lconv #include // labs, isfinite, isnan, signbit #include // size_t, ptrdiff_t #include // uint8_t #include // snprintf #include // numeric_limits #include // string, char_traits #include // is_same #include // move // #include #include // array #include // signbit, isfinite #include // intN_t, uintN_t #include // memcpy, memmove #include // numeric_limits #include // conditional // #include namespace nlohmann { namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q std::uint64_t f = 0; int e = 0; constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { JSON_ASSERT(x.e == y.e); JSON_ASSERT(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; const std::uint64_t u_hi = x.f >> 32u; const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; const std::uint64_t v_hi = y.f >> 32u; const std::uint64_t p0 = u_lo * v_lo; const std::uint64_t p1 = u_lo * v_hi; const std::uint64_t p2 = u_hi * v_lo; const std::uint64_t p3 = u_hi * v_hi; const std::uint64_t p0_hi = p0 >> 32u; const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; const std::uint64_t p1_hi = p1 >> 32u; const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; const std::uint64_t p2_hi = p2 >> 32u; std::uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { JSON_ASSERT(x.f != 0); while ((x.f >> 63u) == 0) { x.f <<= 1u; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; JSON_ASSERT(delta >= 0); JSON_ASSERT(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template boundaries compute_boundaries(FloatType value) { JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional::type; const std::uint64_t bits = reinterpret_bits(value); const std::uint64_t E = bits >> (kPrecision - 1); const std::uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = E == 0; const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = F == 0 && E > 1; const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { std::uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exact power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr std::array kCachedPowers = { { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, } }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 JSON_ASSERT(e >= -1500); JSON_ASSERT(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; JSON_ASSERT(index >= 0); JSON_ASSERT(static_cast(index) < kCachedPowers.size()); const cached_power cached = kCachedPowers[static_cast(index)]; JSON_ASSERT(kAlpha <= cached.e + e + 64); JSON_ASSERT(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP else if (n >= 100000000) { pow10 = 100000000; return 9; } else if (n >= 10000000) { pow10 = 10000000; return 8; } else if (n >= 1000000) { pow10 = 1000000; return 7; } else if (n >= 100000) { pow10 = 100000; return 6; } else if (n >= 10000) { pow10 = 10000; return 5; } else if (n >= 1000) { pow10 = 1000; return 4; } else if (n >= 100) { pow10 = 100; return 3; } else if (n >= 10) { pow10 = 10; return 2; } else { pow10 = 1; return 1; } } inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) { JSON_ASSERT(len >= 1); JSON_ASSERT(dist <= delta); JSON_ASSERT(rest <= delta); JSON_ASSERT(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) { JSON_ASSERT(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. JSON_ASSERT(M_plus.e >= kAlpha); JSON_ASSERT(M_plus.e <= kGamma); std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] JSON_ASSERT(p1 > 0); std::uint32_t pow10; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e JSON_ASSERT(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); p2 *= 10; const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const std::uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ JSON_HEDLEY_NON_NULL(1) inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { JSON_ASSERT(m_plus.e == m_minus.e); JSON_ASSERT(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template JSON_HEDLEY_NON_NULL(1) void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, "internal error: not enough precision"); JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 const boundaries w = compute_boundaries(static_cast(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* append_exponent(char* buf, int e) { JSON_ASSERT(e > -1000); JSON_ASSERT(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast('0' + k); } else if (k < 100) { *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } else { *buf++ = static_cast('0' + k / 100); k %= 100; *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { JSON_ASSERT(min_exp < 0); JSON_ASSERT(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n && n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast(n) - static_cast(k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (static_cast(n) + 2); } if (0 < n && n <= max_exp) { // dig.its // len <= max_digits10 + 1 JSON_ASSERT(k > n); std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); buf[n] = '.'; return buf + (static_cast(k) + 1U); } if (min_exp < n && n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast(-n)); return buf + (2U + static_cast(-n) + static_cast(k)); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast(k) - 1); buf[1] = '.'; buf += 1 + static_cast(k); } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) { static_cast(last); // maybe unused - fix warning JSON_ASSERT(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); JSON_ASSERT(len <= std::numeric_limits::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits::digits10; JSON_ASSERT(last - first >= kMaxExp + 2); JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail } // namespace nlohmann // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { /////////////////// // serialization // /////////////////// /// how to treat decoding errors enum class error_handler_t { strict, ///< throw a type_error exception in case of invalid UTF-8 replace, ///< replace invalid UTF-8 sequences with U+FFFD ignore ///< ignore invalid UTF-8 sequences }; template class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using binary_char_t = typename BasicJsonType::binary_t::value_type; static constexpr std::uint8_t UTF8_ACCEPT = 0; static constexpr std::uint8_t UTF8_REJECT = 1; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use @param[in] error_handler_ how to react on decoding errors */ serializer(output_adapter_t s, const char ichar, error_handler_t error_handler_ = error_handler_t::strict) : o(std::move(s)) , loc(std::localeconv()) , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) , indent_char(ichar) , indent_string(512, indent_char) , error_handler(error_handler_) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; serializer(serializer&&) = delete; serializer& operator=(serializer&&) = delete; ~serializer() = default; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format - binary values are serialized as objects containing the subtype and the byte array @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(!val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(!val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::binary: { if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"bytes\": [", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_characters(", ", 2); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\n", 3); o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"subtype\": ", 11); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); } else { o->write_characters("null", 4); } o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_characters("{\"bytes\":[", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_character(','); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\"subtype\":", 12); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); o->write_character('}'); } else { o->write_characters("null}", 5); } } return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } } private: /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) { std::uint32_t codepoint; std::uint8_t state = UTF8_ACCEPT; std::size_t bytes = 0; // number of bytes written to string_buffer // number of bytes written at the point of the last valid byte std::size_t bytes_after_last_accept = 0; std::size_t undumped_chars = 0; for (std::size_t i = 0; i < s.size(); ++i) { const auto byte = static_cast(s[i]); switch (decode(state, codepoint, byte)) { case UTF8_ACCEPT: // decode found a new code point { switch (codepoint) { case 0x08: // backspace { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'b'; break; } case 0x09: // horizontal tab { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 't'; break; } case 0x0A: // newline { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'n'; break; } case 0x0C: // formfeed { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'f'; break; } case 0x0D: // carriage return { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'r'; break; } case 0x22: // quotation mark { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\"'; break; } case 0x5C: // reverse solidus { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\\'; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) { if (codepoint <= 0xFFFF) { (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", static_cast(codepoint)); bytes += 6; } else { (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", static_cast(0xD7C0u + (codepoint >> 10u)), static_cast(0xDC00u + (codepoint & 0x3FFu))); bytes += 12; } } else { // copy byte to buffer (all previous bytes // been copied have in default case above) string_buffer[bytes++] = s[i]; } break; } } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } // remember the byte position of this accept bytes_after_last_accept = bytes; undumped_chars = 0; break; } case UTF8_REJECT: // decode found invalid UTF-8 byte { switch (error_handler) { case error_handler_t::strict: { std::string sn(3, '\0'); (std::snprintf)(&sn[0], sn.size(), "%.2X", byte); JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn)); } case error_handler_t::ignore: case error_handler_t::replace: { // in case we saw this character the first time, we // would like to read it again, because the byte // may be OK for itself, but just not OK for the // previous sequence if (undumped_chars > 0) { --i; } // reset length buffer to the last accepted index; // thus removing/ignoring the invalid characters bytes = bytes_after_last_accept; if (error_handler == error_handler_t::replace) { // add a replacement character if (ensure_ascii) { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'u'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'd'; } else { string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } bytes_after_last_accept = bytes; } undumped_chars = 0; // continue processing the string state = UTF8_ACCEPT; break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } break; } default: // decode found yet incomplete multi-byte code point { if (!ensure_ascii) { // code point will not be escaped - copy byte to buffer string_buffer[bytes++] = s[i]; } ++undumped_chars; break; } } } // we finished processing the string if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) { // write buffer if (bytes > 0) { o->write_characters(string_buffer.data(), bytes); } } else { // we finish reading, but do not accept: string was incomplete switch (error_handler) { case error_handler_t::strict: { std::string sn(3, '\0'); (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast(s.back())); JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn)); } case error_handler_t::ignore: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); break; } case error_handler_t::replace: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); // add a replacement character if (ensure_ascii) { o->write_characters("\\ufffd", 6); } else { o->write_characters("\xEF\xBF\xBD", 3); } break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } } } /*! @brief count digits Count the number of decimal (base 10) digits for an input unsigned integer. @param[in] x unsigned integer number to count its digits @return number of decimal digits */ inline unsigned int count_digits(number_unsigned_t x) noexcept { unsigned int n_digits = 1; for (;;) { if (x < 10) { return n_digits; } if (x < 100) { return n_digits + 1; } if (x < 1000) { return n_digits + 2; } if (x < 10000) { return n_digits + 3; } x = x / 10000u; n_digits += 4; } } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template < typename NumberType, detail::enable_if_t < std::is_same::value || std::is_same::value || std::is_same::value, int > = 0 > void dump_integer(NumberType x) { static constexpr std::array, 100> digits_to_99 { { {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, } }; // special case for "0" if (x == 0) { o->write_character('0'); return; } // use a pointer to fill the buffer auto buffer_ptr = number_buffer.begin(); const bool is_negative = std::is_same::value && !(x >= 0); // see issue #755 number_unsigned_t abs_value; unsigned int n_chars; if (is_negative) { *buffer_ptr = '-'; abs_value = remove_sign(static_cast(x)); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); } else { abs_value = static_cast(x); n_chars = count_digits(abs_value); } // spare 1 byte for '\0' JSON_ASSERT(n_chars < number_buffer.size() - 1); // jump to the end to generate the string from backward // so we later avoid reversing the result buffer_ptr += n_chars; // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu // See: https://www.youtube.com/watch?v=o4-CwDo2zpg while (abs_value >= 100) { const auto digits_index = static_cast((abs_value % 100)); abs_value /= 100; *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } if (abs_value >= 10) { const auto digits_index = static_cast(abs_value); *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } else { *(--buffer_ptr) = static_cast('0' + abs_value); } o->write_characters(number_buffer.data(), n_chars); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (!std::isfinite(x)) { o->write_characters("null", 4); return; } // If number_float_t is an IEEE-754 single or double precision number, // use the Grisu2 algorithm to produce short numbers which are // guaranteed to round-trip, using strtof and strtod, resp. // // NB: The test below works if == . static constexpr bool is_ieee_single_or_double = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); dump_float(x, std::integral_constant()); } void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) { char* begin = number_buffer.data(); char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); o->write_characters(begin, static_cast(end - begin)); } void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) { // get number of digits for a float -> text -> float round-trip static constexpr auto d = std::numeric_limits::max_digits10; // the actual conversion std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error JSON_ASSERT(len > 0); // check if buffer was large enough JSON_ASSERT(static_cast(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); JSON_ASSERT((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' && decimal_point != '.') { const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast(len)); // determine if need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return c == '.' || c == 'e'; }); if (value_is_int_like) { o->write_characters(".0", 2); } } /*! @brief check whether a string is UTF-8 encoded The function checks each byte of a string whether it is UTF-8 encoded. The result of the check is stored in the @a state parameter. The function must be called initially with state 0 (accept). State 1 means the string must be rejected, because the current byte is not allowed. If the string is completely processed, but the state is non-zero, the string ended prematurely; that is, the last byte indicated more bytes should have followed. @param[in,out] state the state of the decoding @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) @param[in] byte next byte to decode @return new state @note The function has been edited: a std::array is used. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */ static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept { static const std::array utf8d = { { 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, // 00..1F 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, // 20..3F 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, // 40..5F 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, // 60..7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 } }; const std::uint8_t type = utf8d[byte]; codep = (state != UTF8_ACCEPT) ? (byte & 0x3fu) | (codep << 6u) : (0xFFu >> type) & (byte); std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); JSON_ASSERT(index < 400); state = utf8d[index]; return state; } /* * Overload to make the compiler happy while it is instantiating * dump_integer for number_unsigned_t. * Must never be called. */ number_unsigned_t remove_sign(number_unsigned_t x) { JSON_ASSERT(false); // LCOV_EXCL_LINE return x; // LCOV_EXCL_LINE } /* * Helper function for dump_integer * * This function takes a negative signed integer and returns its absolute * value as unsigned integer. The plus/minus shuffling is necessary as we can * not directly remove the sign of an arbitrary signed integer as the * absolute values of INT_MIN and INT_MAX are usually not the same. See * #1708 for details. */ inline number_unsigned_t remove_sign(number_integer_t x) noexcept { JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); return static_cast(-(x + 1)) + 1; } private: /// the output of the serializer output_adapter_t o = nullptr; /// a (hopefully) large enough character buffer std::array number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// string buffer std::array string_buffer{{}}; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; /// error_handler how to react on decoding errors const error_handler_t error_handler; }; } // namespace detail } // namespace nlohmann // #include // #include // #include #include // less #include // allocator #include // pair #include // vector namespace nlohmann { /// ordered_map: a minimal map-like container that preserves insertion order /// for use within nlohmann::basic_json template , class Allocator = std::allocator>> struct ordered_map : std::vector, Allocator> { using key_type = Key; using mapped_type = T; using Container = std::vector, Allocator>; using typename Container::iterator; using typename Container::const_iterator; using typename Container::size_type; using typename Container::value_type; // Explicit constructors instead of `using Container::Container` // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} template ordered_map(It first, It last, const Allocator& alloc = Allocator()) : Container{first, last, alloc} {} ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) : Container{init, alloc} {} std::pair emplace(const key_type& key, T&& t) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return {it, false}; } } Container::emplace_back(key, t); return {--this->end(), true}; } T& operator[](const Key& key) { return emplace(key, T{}).first->second; } const T& operator[](const Key& key) const { return at(key); } T& at(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } throw std::out_of_range("key not found"); } const T& at(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } throw std::out_of_range("key not found"); } size_type erase(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { // Since we cannot move const Keys, re-construct them in place for (auto next = it; ++next != this->end(); ++it) { it->~value_type(); // Destroy but keep allocation new (&*it) value_type{std::move(*next)}; } Container::pop_back(); return 1; } } return 0; } iterator erase(iterator pos) { auto it = pos; // Since we cannot move const Keys, re-construct them in place for (auto next = it; ++next != this->end(); ++it) { it->~value_type(); // Destroy but keep allocation new (&*it) value_type{std::move(*next)}; } Container::pop_back(); return pos; } size_type count(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return 1; } } return 0; } iterator find(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } const_iterator find(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } std::pair insert( value_type&& value ) { return emplace(value.first, std::move(value.second)); } std::pair insert( const value_type& value ) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == value.first) { return {it, false}; } } Container::push_back(value); return {--this->end(), true}; } }; } // namespace nlohmann /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam BinaryType type for packed binary data for compatibility with binary serialization formats (`std::vector` by default; will be used in @ref binary_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): JSON values have [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](https://en.cppreference.com/w/cpp/named_req/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from https://stackoverflow.com/a/9860911 @endinternal @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://rfc7159.net/rfc7159) @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json { private: template friend struct detail::external_constructor; friend ::nlohmann::json_pointer; template friend class ::nlohmann::detail::parser; friend ::nlohmann::detail::serializer; template friend class ::nlohmann::detail::iter_impl; template friend class ::nlohmann::detail::binary_writer; template friend class ::nlohmann::detail::binary_reader; template friend class ::nlohmann::detail::json_sax_dom_parser; template friend class ::nlohmann::detail::json_sax_dom_callback_parser; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer_base; template static ::nlohmann::detail::parser parser( InputAdapterType adapter, detail::parser_callback_tcb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false ) { return ::nlohmann::detail::parser(std::move(adapter), std::move(cb), allow_exceptions, ignore_comments); } using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template using internal_iterator = ::nlohmann::detail::internal_iterator; template using iter_impl = ::nlohmann::detail::iter_impl; template using iteration_proxy = ::nlohmann::detail::iteration_proxy; template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; template using output_adapter_t = ::nlohmann::detail::output_adapter_t; template using binary_reader = ::nlohmann::detail::binary_reader; template using binary_writer = ::nlohmann::detail::binary_writer; using serializer = ::nlohmann::detail::serializer; public: using value_t = detail::value_t; /// JSON Pointer, see @ref nlohmann::json_pointer using json_pointer = ::nlohmann::json_pointer; template using json_serializer = JSONSerializer; /// how to treat decoding errors using error_handler_t = detail::error_handler_t; /// how to treat CBOR tags using cbor_tag_handler_t = detail::cbor_tag_handler_t; /// helper type for initializer lists of basic_json values using initializer_list_t = std::initializer_list>; using input_format_t = detail::input_format_t; /// SAX interface type, see @ref nlohmann::json_sax using json_sax_t = json_sax; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ /// @copydoc detail::exception using exception = detail::exception; /// @copydoc detail::parse_error using parse_error = detail::parse_error; /// @copydoc detail::invalid_iterator using invalid_iterator = detail::invalid_iterator; /// @copydoc detail::type_error using type_error = detail::type_error; /// @copydoc detail::out_of_range using out_of_range = detail::out_of_range; /// @copydoc detail::other_error using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType; /// the type of an element pointer using pointer = typename std::allocator_traits::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl; /// a const iterator for a basic_json container using const_iterator = iter_impl; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @complexity Constant. @since 2.1.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2020 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"]["string"] = std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_PATCH); result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ #if defined(JSON_HAS_CPP_14) // Use transparent comparator if possible, combined with perfect forwarding // on find() and count() calls prevents unnecessary string construction. using object_comparator_t = std::less<>; #else using object_comparator_t = std::less; #endif /*! @brief a type for an object [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less, // key_compare std::allocator> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or `{"key": 2}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 7159](http://rfc7159.net/rfc7159), because any order implements the specified "unordered" nature of JSON objects. */ using object_t = ObjectType>>; /*! @brief a type for an array [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator // allocator_type > @endcode #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType>; /*! @brief a type for a string [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 7159](http://rfc7159.net/rfc7159) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa @ref number_integer_t -- type for number values (integer) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /*! @brief a type for a packed binary type This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values. Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint8_t`, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as: > Major type 2: a byte string. The string's length in bytes is represented > following the rules for positive integers (major type 0). [MessagePack's documentation on the bin type family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) describes this type as: > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes > in addition to the size of the byte array. [BSON's specifications](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to represent the generic binary type which has the description: > Generic binary subtype - This is the most commonly used binary subtype and > should be the 'default' for drivers and tools. None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes. The default representation of this binary format is a `std::vector`, which is a very common way to represent a byte array in modern C++. #### Default type The default values for @a BinaryType is `std::vector` #### Storage Binary Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of the type `binary_t*` must be dereferenced. #### Notes on subtypes - CBOR - Binary values are represented as byte strings. No subtypes are supported and will be ignored when CBOR is written. - MessagePack - If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as singed 8-bit integer. - If no subtype is given, the bin family (bin8, bin16, bin32) is used. - BSON - If a subtype is given, it is used and added as unsigned 8-bit integer. - If no subtype is given, the generic binary subtype 0x00 is used. @sa @ref binary -- create a binary array @since version 3.8.0 */ using binary_t = nlohmann::byte_container_with_subtype; /// @} private: /// helper for exception-safe object creation template JSON_HEDLEY_RETURNS_NON_NULL static T* create(Args&& ... args) { AllocatorType alloc; using AllocatorTraits = std::allocator_traits>; auto deleter = [&](T * object) { AllocatorTraits::deallocate(alloc, object, 1); }; std::unique_ptr object(AllocatorTraits::allocate(alloc, 1), deleter); AllocatorTraits::construct(alloc, object.get(), std::forward(args)...); JSON_ASSERT(object != nullptr); return object.release(); } //////////////////////// // JSON value storage // //////////////////////// /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t binary | binary | pointer to @ref binary_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// binary (stored with pointer to save storage) binary_t* binary; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create(); break; } case value_t::array: { array = create(); break; } case value_t::string: { string = create(""); break; } case value_t::binary: { binary = create(); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { object = nullptr; // silence warning, see #821 break; } default: { object = nullptr; // silence warning, see #821 if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.9.1")); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create(value); } /// constructor for rvalue strings json_value(string_t&& value) { string = create(std::move(value)); } /// constructor for objects json_value(const object_t& value) { object = create(value); } /// constructor for rvalue objects json_value(object_t&& value) { object = create(std::move(value)); } /// constructor for arrays json_value(const array_t& value) { array = create(value); } /// constructor for rvalue arrays json_value(array_t&& value) { array = create(std::move(value)); } /// constructor for binary arrays json_value(const typename binary_t::container_type& value) { binary = create(value); } /// constructor for rvalue binary arrays json_value(typename binary_t::container_type&& value) { binary = create(std::move(value)); } /// constructor for binary arrays (internal type) json_value(const binary_t& value) { binary = create(value); } /// constructor for rvalue binary arrays (internal type) json_value(binary_t&& value) { binary = create(std::move(value)); } void destroy(value_t t) noexcept { // flatten the current json_value to a heap-allocated stack std::vector stack; // move the top-level items to stack if (t == value_t::array) { stack.reserve(array->size()); std::move(array->begin(), array->end(), std::back_inserter(stack)); } else if (t == value_t::object) { stack.reserve(object->size()); for (auto&& it : *object) { stack.push_back(std::move(it.second)); } } while (!stack.empty()) { // move the last item to local variable to be processed basic_json current_item(std::move(stack.back())); stack.pop_back(); // if current_item is array/object, move // its children to the stack to be processed later if (current_item.is_array()) { std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); current_item.m_value.array->clear(); } else if (current_item.is_object()) { for (auto&& it : *current_item.m_value.object) { stack.push_back(std::move(it.second)); } current_item.m_value.object->clear(); } // it's now safe that current_item get destructed // since it doesn't have any children } switch (t) { case value_t::object: { AllocatorType alloc; std::allocator_traits::destroy(alloc, object); std::allocator_traits::deallocate(alloc, object, 1); break; } case value_t::array: { AllocatorType alloc; std::allocator_traits::destroy(alloc, array); std::allocator_traits::deallocate(alloc, array, 1); break; } case value_t::string: { AllocatorType alloc; std::allocator_traits::destroy(alloc, string); std::allocator_traits::deallocate(alloc, string, 1); break; } case value_t::binary: { AllocatorType alloc; std::allocator_traits::destroy(alloc, binary); std::allocator_traits::deallocate(alloc, binary, 1); break; } default: { break; } } } }; /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. */ void assert_invariant() const noexcept { JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); } public: ////////////////////////// // JSON parser callback // ////////////////////////// /*! @brief parser event types The parser callback distinguishes the following events: - `object_start`: the parser read `{` and started to process a JSON object - `key`: the parser read a key of a value in an object - `object_end`: the parser read `}` and finished processing a JSON object - `array_start`: the parser read `[` and started to process a JSON array - `array_end`: the parser read `]` and finished processing a JSON array - `value`: the parser finished reading a JSON value @image html callback_events.png "Example when certain parse events are triggered" @sa @ref parser_callback_t for more information and examples */ using parse_event_t = detail::parse_event_t; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse, it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa @ref parse for examples @since version 1.0.0 */ using parser_callback_t = detail::parser_callback_t; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` binary | empty array @param[in] v the type of the value to create @complexity Constant. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @sa @ref clear() -- restores the postcondition of this constructor @since version 1.0.0 */ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exists. The constructor forwards the parameter @a val to that method (to `json_serializer::to_json` method with `U = uncvref_t`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. - **binary**: @ref binary_t / `std::vector` may be used, unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - @ref @ref json_serializer has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t` @param[in] val the value to be forwarded to the respective constructor @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template < typename CompatibleType, typename U = detail::uncvref_t, detail::enable_if_t < !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > basic_json(CompatibleType && val) noexcept(noexcept( JSONSerializer::to_json(std::declval(), std::forward(val)))) { JSONSerializer::to_json(*this, std::forward(val)); assert_invariant(); } /*! @brief create a JSON value from an existing one This is a constructor for existing @ref basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones. The constructor tries to convert the internal @ref m_value of the parameter. @tparam BasicJsonType a type such that: - @a BasicJsonType is a @ref basic_json type. - @a BasicJsonType has different template arguments than @ref basic_json_t. @param[in] val the @ref basic_json value to be converted. @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @since version 3.2.0 */ template < typename BasicJsonType, detail::enable_if_t < detail::is_basic_json::value&& !std::is_same::value, int > = 0 > basic_json(const BasicJsonType& val) { using other_boolean_t = typename BasicJsonType::boolean_t; using other_number_float_t = typename BasicJsonType::number_float_t; using other_number_integer_t = typename BasicJsonType::number_integer_t; using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; using other_string_t = typename BasicJsonType::string_t; using other_object_t = typename BasicJsonType::object_t; using other_array_t = typename BasicJsonType::array_t; using other_binary_t = typename BasicJsonType::binary_t; switch (val.type()) { case value_t::boolean: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_float: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_integer: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_unsigned: JSONSerializer::to_json(*this, val.template get()); break; case value_t::string: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::object: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::array: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::binary: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::null: *this = nullptr; break; case value_t::discarded: m_type = value_t::discarded; break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(initializer_list_t) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(initializer_list_t) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(initializer_list_t) and @ref object(initializer_list_t). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw type_error.301 if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If @a type_deduction would have be `true`, an array would have been created. See @ref object(initializer_list_t) for an example. @complexity Linear in the size of the initializer list @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref& element_ref) { return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); }); // adjust type if type deduction is not wanted if (!type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list")); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; std::for_each(init.begin(), init.end(), [this](const detail::json_ref& element_ref) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); }); } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create(init.begin(), init.end()); } assert_invariant(); } /*! @brief explicitly create a binary array (without subtype) Creates a JSON binary array value from a given binary container. Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats. @note Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident. @param[in] init container containing bytes to use as binary type @return JSON binary array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @since version 3.8.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = init; return res; } /*! @brief explicitly create a binary array (with subtype) Creates a JSON binary array value from a given binary container. Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats. @note Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident. @param[in] init container containing bytes to use as binary type @param[in] subtype subtype to use in MessagePack and BSON @return JSON binary array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @since version 3.8.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(init, subtype); return res; } /// @copydoc binary(const typename binary_t::container_type&) JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = std::move(init); return res; } /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t) JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(std::move(init), subtype); return res; } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(initializer_list_t, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `array` function.,array} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(initializer_list_t, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw type_error.301 if @a init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to @ref basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list @a init. See example below. @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `object` function.,object} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @since version 1.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @post `std::distance(begin(),end()) == cnt` holds. @complexity Linear in @a cnt. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create(cnt, val); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a null type, invalid_iterator.206 is thrown. - In case of other primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion (see warning).** If assertions are switched off, a violation of this precondition yields undefined behavior. @pre Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below. A violation of this precondition yields undefined behavior. @warning A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See https://en.cppreference.com/w/cpp/error/assert for more information. @throw invalid_iterator.201 if iterators @a first and @a last are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. @throw invalid_iterator.204 if iterators @a first and @a last belong to a primitive type (number, boolean, or string), but @a first does not point to the first element any more. In this case, the range `[first, last)` is undefined. See example code below. @throw invalid_iterator.206 if iterators @a first and @a last belong to a null value. In this case, the range `[first, last)` is undefined. @complexity Linear in distance between @a first and @a last. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template < class InputIT, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > basic_json(InputIT first, InputIT last) { JSON_ASSERT(first.m_object != nullptr); JSON_ASSERT(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } break; } default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create(first.m_it.array_iterator, last.m_it.array_iterator); break; } case value_t::binary: { m_value = *first.m_object->m_value.binary; break; } default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()))); } assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// template, std::is_same>::value, int> = 0 > basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @post `*this == other` @complexity Linear in the size of @a other. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } case value_t::binary: { m_value = *other.m_value.binary; break; } default: break; } assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post `*this` has the same value as @a other before the call. @post @a other is a JSON null value. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @requirement This function helps `basic_json` satisfying the [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) requirements. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(); // invalidate payload other.m_type = value_t::null; other.m_value = {}; assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ basic_json& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() noexcept { assert_invariant(); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent and @a ensure_ascii parameters. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @param[in] indent_char The character to use for indentation if @a indent is greater than `0`. The default is ` ` (space). @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] error_handler how to react on decoding errors; there are three possible values: `strict` (throws and exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all bytes are copied to the output unchanged). @return string containing the serialization of the JSON value @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded and @a error_handler is set to strict @note Binary values are serialized as object containing two keys: - "bytes": an array of bytes as integers - "subtype": the subtype as integer or "null" if the binary has no subtype @complexity Linear. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @liveexample{The following example shows the effect of different @a indent\, @a indent_char\, and @a ensure_ascii parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0; indentation character @a indent_char, option @a ensure_ascii and exceptions added in version 3.0.0; error handlers added in version 3.4.0; serialization of binary values added in version 3.8.0. */ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler = error_handler_t::strict) const { string_t result; serializer s(detail::output_adapter(result), indent_char, error_handler); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value Value type | return value ------------------------- | ------------------------- null | value_t::null boolean | value_t::boolean string | value_t::string number (integer) | value_t::number_integer number (unsigned integer) | value_t::number_unsigned number (floating-point) | value_t::number_float object | value_t::object array | value_t::array binary | value_t::binary discarded | value_t::discarded @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @sa @ref operator value_t() -- return the type of the JSON value (implicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true if and only if the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa @ref is_structured() -- returns whether JSON value is structured @sa @ref is_null() -- returns whether JSON value is `null` @sa @ref is_string() -- returns whether JSON value is a string @sa @ref is_boolean() -- returns whether JSON value is a boolean @sa @ref is_number() -- returns whether JSON value is a number @sa @ref is_binary() -- returns whether JSON value is a binary array @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() || is_string() || is_boolean() || is_number() || is_binary(); } /*! @brief return whether type is structured This function returns true if and only if the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa @ref is_primitive() -- returns whether value is primitive @sa @ref is_array() -- returns whether value is an array @sa @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() || is_object(); } /*! @brief return whether value is null This function returns true if and only if the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return m_type == value_t::null; } /*! @brief return whether value is a boolean This function returns true if and only if the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return m_type == value_t::boolean; } /*! @brief return whether value is a number This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() || is_number_float(); } /*! @brief return whether value is an integer number This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa @ref is_number() -- check if value is a number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return m_type == value_t::number_integer || m_type == value_t::number_unsigned; } /*! @brief return whether value is an unsigned integer number This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa @ref is_number() -- check if value is a number @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return m_type == value_t::number_unsigned; } /*! @brief return whether value is a floating-point number This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa @ref is_number() -- check if value is number @sa @ref is_number_integer() -- check if value is an integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return m_type == value_t::number_float; } /*! @brief return whether value is an object This function returns true if and only if the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return m_type == value_t::object; } /*! @brief return whether value is an array This function returns true if and only if the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return m_type == value_t::array; } /*! @brief return whether value is a string This function returns true if and only if the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return m_type == value_t::string; } /*! @brief return whether value is a binary array This function returns true if and only if the JSON value is a binary array. @return `true` if type is binary array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_binary()` for all JSON types.,is_binary} @since version 3.8.0 */ constexpr bool is_binary() const noexcept { return m_type == value_t::binary; } /*! @brief return whether value is discarded This function returns true if and only if the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return m_type == value_t::discarded; } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @sa @ref type() -- return the type of the JSON value (explicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_HEDLEY_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (binary) binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept { return is_binary() ? m_value.binary : nullptr; } /// get a pointer to the value (binary) constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept { return is_binary() ? m_value.binary : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto ptr = obj.template get_ptr::type>(); if (JSON_HEDLEY_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template::type, basic_json_t>::value, int> = 0> basic_json get() const { return *this; } /*! @brief get special-case overload This overloads converts the current @ref basic_json in a different @ref basic_json type @tparam BasicJsonType == @ref basic_json @return a copy of *this, converted into @tparam BasicJsonType @complexity Depending on the implementation of the called `from_json()` method. @since version 3.2.0 */ template < typename BasicJsonType, detail::enable_if_t < !std::is_same::value&& detail::is_basic_json::value, int > = 0 > BasicJsonType get() const { return *this; } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t, detail::enable_if_t < !detail::is_basic_json::value && detail::has_from_json::value && !detail::has_non_default_from_json::value, int > = 0 > ValueType get() const noexcept(noexcept( JSONSerializer::from_json(std::declval(), std::declval()))) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get(), which is why we // still need the uncvref static_assert(!std::is_reference::value, "get() cannot be used with reference types, you might want to use get_ref()"); static_assert(std::is_default_constructible::value, "types must be DefaultConstructible when used with get()"); ValueType ret; JSONSerializer::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer has both overloads of `from_json()`, this one is chosen. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer `from_json()` method throws @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t, detail::enable_if_t < !std::is_same::value && detail::has_non_default_from_json::value, int > = 0 > ValueType get() const noexcept(noexcept( JSONSerializer::from_json(std::declval()))) { static_assert(!std::is_reference::value, "get() cannot be used with reference types, you might want to use get_ref()"); return JSONSerializer::from_json(*this); } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the @ref json_serializer `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType v; JSONSerializer::from_json(*this, v); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and @tparam ValueType the input parameter type. @return the input parameter, allowing chaining calls. @throw what @ref json_serializer `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map`.,get_to} @since version 3.3.0 */ template < typename ValueType, detail::enable_if_t < !detail::is_basic_json::value&& detail::has_from_json::value, int > = 0 > ValueType & get_to(ValueType& v) const noexcept(noexcept( JSONSerializer::from_json(std::declval(), v))) { JSONSerializer::from_json(*this, v); return v; } // specialization to allow to call get_to with a basic_json value // see https://github.com/nlohmann/json/issues/2175 template::value, int> = 0> ValueType & get_to(ValueType& v) const { v = *this; return v; } template < typename T, std::size_t N, typename Array = T (&)[N], detail::enable_if_t < detail::has_from_json::value, int > = 0 > Array get_to(T (&v)[N]) const noexcept(noexcept(JSONSerializer::from_json( std::declval(), v))) { JSONSerializer::from_json(*this, v); return v; } /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template::value, int>::type = 0> auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) { // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template < typename PointerType, typename std::enable_if < std::is_pointer::value&& std::is_const::type>::value, int >::type = 0 > constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) { // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast(nullptr)); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template::value, int>::type = 0> auto get() noexcept -> decltype(std::declval().template get_ptr()) { // delegate the call to get_ptr return get_ptr(); } /*! @brief get a pointer value (explicit) @copydoc get() */ template::value, int>::type = 0> constexpr auto get() const noexcept -> decltype(std::declval().template get_ptr()) { // delegate the call to get_ptr return get_ptr(); } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws type_error.303 otherwise @throw type_error.303 in case passed type @a ReferenceType is incompatible with the stored JSON value; see example below @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template < typename ReferenceType, typename std::enable_if < std::is_reference::value&& std::is_const::type>::value, int >::type = 0 > ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < !std::is_pointer::value&& !std::is_same>::value&& !std::is_same::value&& !detail::is_basic_json::value && !std::is_same>::value #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) && !std::is_same::value #endif && detail::is_detected::value , int >::type = 0 > JSON_EXPLICIT operator ValueType() const { // delegate the call to get<>() const return get(); } /*! @return reference to the binary value @throw type_error.302 if the value is not binary @sa @ref is_binary() to check if the value is binary @since version 3.8.0 */ binary_t& get_binary() { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()))); } return *get_ptr(); } /// @copydoc get_binary() const binary_t& get_binary() const { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()))); } return *get_ptr(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__size_type} */ reference at(size_type idx) { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__size_type_const} */ const_reference at(size_type idx) const { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type} */ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const} */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense. @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create(); assert_invariant(); } // operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { m_value.array->insert(m_value.array->end(), idx - m_value.array->size() + 1, basic_json()); } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array; in that case, using the [] operator with an index makes no sense. @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create(); assert_invariant(); } // operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template JSON_HEDLEY_NON_NULL(2) reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template JSON_HEDLEY_NON_NULL(2) const_reference operator[](T* key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.302 if @a default_value does not match the type of the value at @a key @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ // using std::is_convertible in a std::enable_if will fail when using explicit conversions template < class ValueType, typename std::enable_if < detail::is_getable::value && !std::is_same::value, int >::type = 0 > ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return it->template get(); } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.302 if @a default_value does not match the type of the value at @a ptr @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this).template get(); } JSON_INTERNAL_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ JSON_HEDLEY_NON_NULL(3) string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on a `null` value. See example below. @liveexample{The following code shows an example for `back()`.,back} @sa @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings and binary: linear in the length of the member - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template < class IteratorType, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range")); } if (is_string()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.string); std::allocator_traits::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.binary); std::allocator_traits::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings and binary: linear in the length of the member - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template < class IteratorType, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } if (is_string()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.string); std::allocator_traits::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.binary); std::allocator_traits::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { if (JSON_HEDLEY_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } m_value.array->erase(m_value.array->begin() + static_cast(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for. @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @sa @ref contains(KeyT&&) const -- checks whether a key exists @since version 1.0.0 */ template iterator find(KeyT&& key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward(key)); } return result; } /*! @brief find an element in a JSON object @copydoc find(KeyT&&) */ template const_iterator find(KeyT&& key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward(key)); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ template size_type count(KeyT&& key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(std::forward(key)) : 0; } /*! @brief check the existence of an element in a JSON object Check whether an element exists in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, false is returned. @note This method always returns false when executed on a JSON type that is not an object. @param[in] key key value to check its existence. @return true if an element with specified @a key exists. If no such element with such key is found or the JSON value is not an object, false is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The following code shows an example for `contains()`.,contains} @sa @ref find(KeyT&&) -- returns an iterator to an object element @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer @since version 3.6.0 */ template < typename KeyT, typename std::enable_if < !std::is_same::type, json_pointer>::value, int >::type = 0 > bool contains(KeyT && key) const { return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); } /*! @brief check the existence of an element in a JSON object given a JSON pointer Check whether the given JSON pointer @a ptr can be resolved in the current JSON value. @note This method can be executed on any JSON value type. @param[in] ptr JSON pointer to check its existence. @return true if the JSON pointer can be resolved to a stored value, false otherwise. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @complexity Logarithmic in the size of the JSON object. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer} @sa @ref contains(KeyT &&) const -- checks the existence of a key @since version 3.7.0 */ bool contains(const json_pointer& ptr) const { return ptr.contains(this); } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa @ref cbegin() -- returns a const iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa @ref begin() -- returns an iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa @ref cend() -- returns a const iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa @ref end() -- returns an iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa @ref crbegin() -- returns a const reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa @ref crend() -- returns a const reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa @ref rend() -- returns a reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without iterator_wrapper: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without iterator proxy: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with iterator proxy: @code{cpp} for (auto it : json::iterator_wrapper(j_object)) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). @param[in] ref reference to a JSON value @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the wrapper is used,iterator_wrapper} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @note The name of this function is not yet final and may change in the future. @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref items() instead; that is, replace `json::iterator_wrapper(j)` with `j.items()`. */ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy iterator_wrapper(reference ref) noexcept { return ref.items(); } /*! @copydoc iterator_wrapper(reference) */ JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy iterator_wrapper(const_reference ref) noexcept { return ref.items(); } /*! @brief helper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without `items()` function: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without `items()` function: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with `items()` function: @code{cpp} for (auto& el : j_object.items()) { std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; } @endcode The `items()` function also allows to use [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17): @code{cpp} for (auto& [key, val] : j_object.items()) { std::cout << "key: " << key << ", value:" << val << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types (e.g., numbers), `key()` returns an empty string. @warning Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exeeds the iteration. See for more information. @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the function is used.,items} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 3.1.0, structured bindings support since 3.5.0. */ iteration_proxy items() noexcept { return iteration_proxy(*this); } /*! @copydoc items() */ iteration_proxy items() const noexcept { return iteration_proxy(*this); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` binary | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` binary | `1` object | result of function object_t::size() array | result of function array_t::size() @liveexample{The following code calls `size()` on the different value types.,size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @sa @ref empty() -- checks whether the container is empty @sa @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) binary | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called with the current value type from @ref type(): Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` binary | An empty byte vector object | `{}` array | `[]` @post Has the same effect as calling @code {.cpp} *this = basic_json(type()); @endcode @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @complexity Linear in the size of the JSON value. @iterators All iterators, pointers and references related to this container are invalidated. @exceptionsafety No-throw guarantee: this function never throws exceptions. @sa @ref basic_json(value_t) -- constructor that creates an object with the same value than calling `clear()` @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::binary: { m_value.binary->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: break; } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw type_error.308 when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) m_value.array->push_back(std::move(val)); // if val is moved from, basic_json move constructor marks it null so we do not call the destructor } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array m_value.array->push_back(val); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw type_error.308 when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array m_value.object->insert(val); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param[in] init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(initializer_list_t init) { if (is_object() && init.size() == 2 && (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(initializer_list_t) */ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return reference to the inserted element @throw type_error.311 when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8, returns reference since 3.7.0 */ template reference emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) #ifdef JSON_HAS_CPP_17 return m_value.array->emplace_back(std::forward(args)...); #else m_value.array->emplace_back(std::forward(args)...); return m_value.array->back(); #endif } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw type_error.311 when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template std::pair emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward(args)...); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /// Helper for insertion of an iterator /// @note: This uses std::distance to support GCC 4.8, /// see https://github.com/nlohmann/json/pull/1257 template iterator insert_iterator(const_iterator pos, Args&& ... args) { iterator result(this); JSON_ASSERT(m_value.array != nullptr); auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); result.m_it.array_iterator = m_value.array->begin() + insert_pos; // This could have been written as: // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); // but the return value of insert is missing in GCC 4.8, so it is written this way instead. return result; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, cnt, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw invalid_iterator.211 if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); } // insert to array and return iterator return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, ilist.begin(), ilist.end()); } /*! @brief inserts elements Inserts elements from range `[first, last)`. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than objects; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert. @liveexample{The example shows how `insert()` is used.,insert__range_object} @since version 3.0.0 */ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from JSON object @a j and overwrites existing keys. @param[in] j JSON object to read values from @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_reference j) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create(); assert_invariant(); } if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); } for (auto it = j.cbegin(); it != j.cend(); ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from from range `[first, last)` and overwrites existing keys. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used__range.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_iterator first, const_iterator last) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create(); assert_invariant(); } if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object() || !last.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } for (auto it = first; it != last; ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of the JSON value from @a left with those of @a right. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. implemented as a friend function callable via ADL. @param[in,out] left JSON value to exchange the contents with @param[in,out] right JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ friend void swap(reference left, reference right) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { left.swap(right); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw type_error.310 when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) { // swap only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw type_error.310 when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) { // swap only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other binary to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__binary_t} @since version 3.8.0 */ void swap(binary_t& other) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /// @copydoc swap(binary_t) void swap(typename binary_t::container_type& other) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective `operator==`. - Integer and floating-point numbers are automatically converted before comparison. Note that two NaN values are always treated as unequal. - Two JSON null values are equal. @note Floating-point inside JSON values numbers are compared with `json::number_float_t::operator==` which is `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance @code {.cpp} template::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } @endcode Or you can self-defined operator equal function like this: @code {.cpp} bool my_equal(const_reference lhs, const_reference rhs) { const auto lhs_type lhs.type(); const auto rhs_type rhs.type(); if (lhs_type == rhs_type) { switch(lhs_type) // self_defined case case value_t::number_float: return std::abs(lhs - rhs) <= std::numeric_limits::epsilon(); // other cases remain the same with the original ... } ... } @endcode @note NaN values never compare equal to themselves or to other NaN values. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return *lhs.m_value.array == *rhs.m_value.array; case value_t::object: return *lhs.m_value.object == *rhs.m_value.object; case value_t::null: return true; case value_t::string: return *lhs.m_value.string == *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean == rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer == rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float == rhs.m_value.number_float; case value_t::binary: return *lhs.m_value.binary == *rhs.m_value.binary; default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept { return lhs == basic_json(rhs); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) == rhs; } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return !(lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept { return lhs != basic_json(rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) != rhs; } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: // note parentheses are necessary, see // https://github.com/nlohmann/json/issues/1530 return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return (*lhs.m_value.object) < (*rhs.m_value.object); case value_t::null: return false; case value_t::string: return (*lhs.m_value.string) < (*rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean) < (rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float) < (rhs.m_value.number_float); case value_t::binary: return (*lhs.m_value.binary) < (*rhs.m_value.binary); default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept { return lhs < basic_json(rhs); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) < rhs; } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return !(rhs < lhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept { return lhs <= basic_json(rhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) <= rhs; } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return !(lhs <= rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept { return lhs > basic_json(rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) > rhs; } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return !(lhs < rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept { return lhs >= basic_json(rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template::value, int>::type = 0> friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) >= rhs; } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. - The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. - The indentation character can be controlled with the member variable `fill` of the output stream @a o. For instance, the manipulator `std::setfill('\\t')` sets indentation to use a tab character rather than the default space character. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0; indentation character added in version 3.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = o.width() > 0; const auto indentation = pretty_print ? o.width() : 0; // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter(o), o.fill()); s.dump(j, pretty_print, false, static_cast(indentation)); return o; } /*! @brief serialize to stream @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref operator<<(std::ostream&, const basic_json&) instead; that is, replace calls like `j >> o;` with `o << j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from a compatible input @tparam InputType A compatible input, for instance - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb or reading from the input @a i has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to ignore comments. */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(InputType&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /*! @brief deserialize from a pair of character iterators The value_type of the iterator must be a integral type with size of 1, 2 or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. @param[in] first iterator to start of character range @param[in] last iterator to end of character range @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) static basic_json parse(detail::span_input_adapter&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /*! @brief check if the input is valid JSON Unlike the @ref parse(InputType&&, const parser_callback_t,const bool) function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information. @tparam InputType A compatible input, for instance - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default) @return Whether the input read from @a i is valid JSON. @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `accept()` function reading from a string.,accept__string} */ template static bool accept(InputType&& i, const bool ignore_comments = false) { return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); } template static bool accept(IteratorType first, IteratorType last, const bool ignore_comments = false) { return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) static bool accept(detail::span_input_adapter&& i, const bool ignore_comments = false) { return parser(i.get(), nullptr, false, ignore_comments).accept(true); } /*! @brief generate SAX events The SAX event lister must follow the interface of @ref json_sax. This function reads from a compatible input. Examples are: - an std::istream object - a FILE pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object obj for which begin(obj) and end(obj) produces a valid pair of iterators. @param[in] i input to read from @param[in,out] sax SAX event listener @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON) @param[in] strict whether the input has to be consumed completely @param[in] ignore_comments whether comments should be ignored and treated like whitespace (true) or yield a parse error (true); (optional, false by default); only applies to the JSON file format. @return return value of the last processed SAX event @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer @a sax has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `sax_parse()` function reading from string and processing the events with a user-defined SAX event consumer.,sax_parse} @since version 3.2.0 */ template JSON_HEDLEY_NON_NULL(2) static bool sax_parse(InputType&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::forward(i)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } template JSON_HEDLEY_NON_NULL(3) static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::move(first), std::move(last)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } template JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) JSON_HEDLEY_NON_NULL(2) static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = i.get(); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } /*! @brief deserialize from stream @deprecated This stream operator is deprecated and will be removed in version 4.0.0 of the library. Please use @ref operator>>(std::istream&, basic_json&) instead; that is, replace calls like `j << i;` with `i >> j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return a string representation of a the @a m_type member: Value type | return value ----------- | ------------- null | `"null"` boolean | `"boolean"` string | `"string"` number | `"number"` (for all number types) object | `"object"` array | `"array"` binary | `"binary"` discarded | `"discarded"` @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @sa @ref type() -- return the type of the JSON value @sa @ref operator value_t() -- return the type of the JSON value (implicit) @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` since 3.0.0 */ JSON_HEDLEY_RETURNS_NON_NULL const char* type_name() const noexcept { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::binary: return "binary"; case value_t::discarded: return "discarded"; default: return "number"; } } } private: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /*! @brief create a CBOR serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049): JSON value type | value/range | CBOR type | first byte --------------- | ------------------------------------------ | ---------------------------------- | --------------- null | `null` | Null | 0xF6 boolean | `true` | True | 0xF5 boolean | `false` | False | 0xF4 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 number_integer | -24..-1 | Negative integer | 0x20..0x37 number_integer | 0..23 | Integer | 0x00..0x17 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_unsigned | 0..23 | Integer | 0x00..0x17 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_float | *any value representable by a float* | Single-Precision Float | 0xFA number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB string | *length*: 0..23 | UTF-8 string | 0x60..0x77 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B array | *size*: 0..23 | array | 0x80..0x97 array | *size*: 23..255 | array (1 byte follow) | 0x98 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B object | *size*: 0..23 | map | 0xA0..0xB7 object | *size*: 23..255 | map (1 byte follow) | 0xB8 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB binary | *size*: 0..23 | byte string | 0x40..0x57 binary | *size*: 23..255 | byte string (1 byte follow) | 0x58 binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59 binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B @note The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The following CBOR types are not used in the conversion: - UTF-8 strings terminated by "break" (0x7F) - arrays terminated by "break" (0x9F) - maps terminated by "break" (0xBF) - byte strings terminated by "break" (0x5F) - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) - half-precision floats (0xF9) - break (0xFF) @param[in] j JSON value to serialize @return CBOR serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the analogous deserialization @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9; compact representation of floating-point numbers since version 3.8.0 */ static std::vector to_cbor(const basic_json& j) { std::vector result; to_cbor(j, result); return result; } static void to_cbor(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_cbor(j); } static void to_cbor(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_cbor(j); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type | value/range | MessagePack type | first byte --------------- | --------------------------------- | ---------------- | ---------- null | `null` | nil | 0xC0 boolean | `true` | true | 0xC3 boolean | `false` | false | 0xC2 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 number_integer | -2147483648..-32769 | int32 | 0xD2 number_integer | -32768..-129 | int16 | 0xD1 number_integer | -128..-33 | int8 | 0xD0 number_integer | -32..-1 | negative fixint | 0xE0..0xFF number_integer | 0..127 | positive fixint | 0x00..0x7F number_integer | 128..255 | uint 8 | 0xCC number_integer | 256..65535 | uint 16 | 0xCD number_integer | 65536..4294967295 | uint 32 | 0xCE number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF number_unsigned | 0..127 | positive fixint | 0x00..0x7F number_unsigned | 128..255 | uint 8 | 0xCC number_unsigned | 256..65535 | uint 16 | 0xCD number_unsigned | 65536..4294967295 | uint 32 | 0xCE number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF number_float | *any value representable by a float* | float 32 | 0xCA number_float | *any value NOT representable by a float* | float 64 | 0xCB string | *length*: 0..31 | fixstr | 0xA0..0xBF string | *length*: 32..255 | str 8 | 0xD9 string | *length*: 256..65535 | str 16 | 0xDA string | *length*: 65536..4294967295 | str 32 | 0xDB array | *size*: 0..15 | fixarray | 0x90..0x9F array | *size*: 16..65535 | array 16 | 0xDC array | *size*: 65536..4294967295 | array 32 | 0xDD object | *size*: 0..15 | fix map | 0x80..0x8F object | *size*: 16..65535 | map 16 | 0xDE object | *size*: 65536..4294967295 | map 32 | 0xDF binary | *size*: 0..255 | bin 8 | 0xC4 binary | *size*: 256..65535 | bin 16 | 0xC5 binary | *size*: 65536..4294967295 | bin 32 | 0xC6 @note The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. @note The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - byte strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa @ref from_msgpack for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9 */ static std::vector to_msgpack(const basic_json& j) { std::vector result; to_msgpack(j, result); return result; } static void to_msgpack(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_msgpack(j); } static void to_msgpack(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_msgpack(j); } /*! @brief create a UBJSON serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: JSON value type | value/range | UBJSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | `Z` boolean | `true` | true | `T` boolean | `false` | false | `F` number_integer | -9223372036854775808..-2147483649 | int64 | `L` number_integer | -2147483648..-32769 | int32 | `l` number_integer | -32768..-129 | int16 | `I` number_integer | -128..127 | int8 | `i` number_integer | 128..255 | uint8 | `U` number_integer | 256..32767 | int16 | `I` number_integer | 32768..2147483647 | int32 | `l` number_integer | 2147483648..9223372036854775807 | int64 | `L` number_unsigned | 0..127 | int8 | `i` number_unsigned | 128..255 | uint8 | `U` number_unsigned | 256..32767 | int16 | `I` number_unsigned | 32768..2147483647 | int32 | `l` number_unsigned | 2147483648..9223372036854775807 | int64 | `L` number_unsigned | 2147483649..18446744073709551615 | high-precision | `H` number_float | *any value* | float64 | `D` string | *with shortest length indicator* | string | `S` array | *see notes on optimized format* | array | `[` object | *see notes on optimized format* | map | `{` @note The mapping is **complete** in the sense that any JSON value type can be converted to a UBJSON value. @note The following values can **not** be converted to a UBJSON value: - strings with more than 9223372036854775807 bytes (theoretical) @note The following markers are not used in the conversion: - `Z`: no-op values are not created. - `C`: single-byte strings are serialized with `S` markers. @note Any UBJSON output created @ref to_ubjson can be successfully parsed by @ref from_ubjson. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The optimized formats for containers are supported: Parameter @a use_size adds size information to the beginning of a container and removes the closing marker. Parameter @a use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The @a use_type parameter must only be used together with @a use_size = true. Note that @a use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container. @note If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object. @param[in] j JSON value to serialize @param[in] use_size whether to add size annotations to container types @param[in] use_type whether to add type annotations to container types (must be combined with @a use_size = true) @return UBJSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in UBJSON format.,to_ubjson} @sa http://ubjson.org @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @since version 3.1.0 */ static std::vector to_ubjson(const basic_json& j, const bool use_size = false, const bool use_type = false) { std::vector result; to_ubjson(j, result, use_size, use_type); return result; } static void to_ubjson(const basic_json& j, detail::output_adapter o, const bool use_size = false, const bool use_type = false) { binary_writer(o).write_ubjson(j, use_size, use_type); } static void to_ubjson(const basic_json& j, detail::output_adapter o, const bool use_size = false, const bool use_type = false) { binary_writer(o).write_ubjson(j, use_size, use_type); } /*! @brief Serializes the given JSON object `j` to BSON and returns a vector containing the corresponding BSON-representation. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document). The library uses the following mapping from JSON values types to BSON types: JSON value type | value/range | BSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | 0x0A boolean | `true`, `false` | boolean | 0x08 number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 number_integer | -2147483648..2147483647 | int32 | 0x10 number_integer | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 0..2147483647 | int32 | 0x10 number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 9223372036854775808..18446744073709551615| -- | -- number_float | *any value* | double | 0x01 string | *any value* | string | 0x02 array | *any value* | document | 0x04 object | *any value* | document | 0x03 binary | *any value* | binary | 0x05 @warning The mapping is **incomplete**, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. @throw out_of_range.407 if `j.is_number_unsigned() && j.get() > 9223372036854775807` @throw out_of_range.409 if a key in `j` contains a NULL (U+0000) @throw type_error.317 if `!j.is_object()` @pre The input `j` is required to be an object: `j.is_object() == true`. @note Any BSON output created via @ref to_bson can be successfully parsed by @ref from_bson. @param[in] j JSON value to serialize @return BSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in BSON format.,to_bson} @sa http://bsonspec.org/spec.html @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the analogous deserialization @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @sa @ref to_cbor(const basic_json&) for the related CBOR format @sa @ref to_msgpack(const basic_json&) for the related MessagePack format */ static std::vector to_bson(const basic_json& j) { std::vector result; to_bson(j, result); return result; } /*! @brief Serializes the given JSON object `j` to BSON and forwards the corresponding BSON-representation to the given output_adapter `o`. @param j The JSON object to convert to BSON. @param o The output adapter that receives the binary BSON representation. @pre The input `j` shall be an object: `j.is_object() == true` @sa @ref to_bson(const basic_json&) */ static void to_bson(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_bson(j); } /*! @copydoc to_bson(const basic_json&, detail::output_adapter) */ static void to_bson(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_bson(j); } /*! @brief create a JSON value from an input in CBOR format Deserializes a given input @a i to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. The library maps CBOR types to JSON value types as follows: CBOR type | JSON value type | first byte ---------------------- | --------------- | ---------- Integer | number_unsigned | 0x00..0x17 Unsigned integer | number_unsigned | 0x18 Unsigned integer | number_unsigned | 0x19 Unsigned integer | number_unsigned | 0x1A Unsigned integer | number_unsigned | 0x1B Negative integer | number_integer | 0x20..0x37 Negative integer | number_integer | 0x38 Negative integer | number_integer | 0x39 Negative integer | number_integer | 0x3A Negative integer | number_integer | 0x3B Byte string | binary | 0x40..0x57 Byte string | binary | 0x58 Byte string | binary | 0x59 Byte string | binary | 0x5A Byte string | binary | 0x5B UTF-8 string | string | 0x60..0x77 UTF-8 string | string | 0x78 UTF-8 string | string | 0x79 UTF-8 string | string | 0x7A UTF-8 string | string | 0x7B UTF-8 string | string | 0x7F array | array | 0x80..0x97 array | array | 0x98 array | array | 0x99 array | array | 0x9A array | array | 0x9B array | array | 0x9F map | object | 0xA0..0xB7 map | object | 0xB8 map | object | 0xB9 map | object | 0xBA map | object | 0xBB map | object | 0xBF False | `false` | 0xF4 True | `true` | 0xF5 Null | `null` | 0xF6 Half-Precision Float | number_float | 0xF9 Single-Precision Float | number_float | 0xFA Double-Precision Float | number_float | 0xFB @warning The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112): - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) @warning CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113). @note Any CBOR output created @ref to_cbor can be successfully parsed by @ref from_cbor. @param[in] i an input in CBOR format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @param[in] tag_handler how to treat CBOR tags (optional, error by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from CBOR were used in the given input @a v or if the input is not valid CBOR @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa @ref to_cbor(const basic_json&) for the analogous serialization @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0; added @a tag_handler parameter since 3.9.0. */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(InputType&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in MessagePack format Deserializes a given input @a i to a JSON value using the MessagePack serialization format. The library maps MessagePack types to JSON value types as follows: MessagePack type | JSON value type | first byte ---------------- | --------------- | ---------- positive fixint | number_unsigned | 0x00..0x7F fixmap | object | 0x80..0x8F fixarray | array | 0x90..0x9F fixstr | string | 0xA0..0xBF nil | `null` | 0xC0 false | `false` | 0xC2 true | `true` | 0xC3 float 32 | number_float | 0xCA float 64 | number_float | 0xCB uint 8 | number_unsigned | 0xCC uint 16 | number_unsigned | 0xCD uint 32 | number_unsigned | 0xCE uint 64 | number_unsigned | 0xCF int 8 | number_integer | 0xD0 int 16 | number_integer | 0xD1 int 32 | number_integer | 0xD2 int 64 | number_integer | 0xD3 str 8 | string | 0xD9 str 16 | string | 0xDA str 32 | string | 0xDB array 16 | array | 0xDC array 32 | array | 0xDD map 16 | object | 0xDE map 32 | object | 0xDF bin 8 | binary | 0xC4 bin 16 | binary | 0xC5 bin 32 | binary | 0xC6 ext 8 | binary | 0xC7 ext 16 | binary | 0xC8 ext 32 | binary | 0xC9 fixext 1 | binary | 0xD4 fixext 2 | binary | 0xD5 fixext 4 | binary | 0xD6 fixext 8 | binary | 0xD7 fixext 16 | binary | 0xD8 negative fixint | number_integer | 0xE0-0xFF @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @param[in] i an input in MessagePack format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from MessagePack were used in the given input @a i or if the input is not valid MessagePack @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa @ref to_msgpack(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for the related BSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0 */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool) */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_msgpack(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in UBJSON format Deserializes a given input @a i to a JSON value using the UBJSON (Universal Binary JSON) serialization format. The library maps UBJSON types to JSON value types as follows: UBJSON type | JSON value type | marker ----------- | --------------------------------------- | ------ no-op | *no value, next value is read* | `N` null | `null` | `Z` false | `false` | `F` true | `true` | `T` float32 | number_float | `d` float64 | number_float | `D` uint8 | number_unsigned | `U` int8 | number_integer | `i` int16 | number_integer | `I` int32 | number_integer | `l` int64 | number_integer | `L` high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H' string | string | `S` char | string | `C` array | array (optimized values are supported) | `[` object | object (optimized values are supported) | `{` @note The mapping is **complete** in the sense that any UBJSON value can be converted to a JSON value. @param[in] i an input in UBJSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if a parse error occurs @throw parse_error.113 if a string could not be parsed successfully @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in UBJSON format to a JSON value.,from_ubjson} @sa http://ubjson.org @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for the related BSON format @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0 */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool) */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_ubjson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief Create a JSON value from an input in BSON format Deserializes a given input @a i to a JSON value using the BSON (Binary JSON) serialization format. The library maps BSON record types to JSON value types as follows: BSON type | BSON marker byte | JSON value type --------------- | ---------------- | --------------------------- double | 0x01 | number_float string | 0x02 | string document | 0x03 | object array | 0x04 | array binary | 0x05 | still unsupported undefined | 0x06 | still unsupported ObjectId | 0x07 | still unsupported boolean | 0x08 | boolean UTC Date-Time | 0x09 | still unsupported null | 0x0A | null Regular Expr. | 0x0B | still unsupported DB Pointer | 0x0C | still unsupported JavaScript Code | 0x0D | still unsupported Symbol | 0x0E | still unsupported JavaScript Code | 0x0F | still unsupported int32 | 0x10 | number_integer Timestamp | 0x11 | still unsupported 128-bit decimal float | 0x13 | still unsupported Max Key | 0x7F | still unsupported Min Key | 0xFF | still unsupported @warning The mapping is **incomplete**. The unsupported mappings are indicated in the table above. @param[in] i an input in BSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.114 if an unsupported BSON record type is encountered @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in BSON format to a JSON value.,from_bson} @sa http://bsonspec.org/spec.html @sa @ref to_bson(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the related CBOR format @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_bson(detail::input_adapter&&, const bool, const bool) */ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_bson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer} */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer_const} */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw parse_error.104 if the JSON patch does not consist of an array of objects @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @throw out_of_range.401 if an array index is out of range. @throw out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", "move") @throw other_error.501 if "test" operation was unsuccessful @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.empty()) { result = val; return; } // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = json_pointer::array_index(last_path); if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } // default case: insert add offset parent.insert(parent.begin() + static_cast(idx), val); } break; } // if there exists a parent it cannot be primitive default: // LCOV_EXCL_LINE JSON_ASSERT(false); // LCOV_EXCL_LINE } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [&result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_HEDLEY_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); } } else if (parent.is_array()) { // note erase performs range check parent.erase(json_pointer::array_index(last_path)); } }; // type check: top level value must be an array if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json & { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); } // check if result is of type string if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_HEDLEY_UNLIKELY(!val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // collect mandatory members const auto op = get_value("op", "op", true).template get(); const auto path = get_value(op, "path", true).template get(); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const auto from_path = get_value("move", "from", true).template get(); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const auto from_path = get_value("copy", "from", true).template get(); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The copy is functionally identical to an "add" // operation at the target location using the value // specified in the "from" member. operation_add(ptr, v); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_INTERNAL_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_HEDLEY_UNLIKELY(!success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); } break; } default: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa @ref patch -- apply a JSON patch @sa @ref merge_patch -- apply a JSON Merge Patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); return result; } switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() && i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/-"}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.cbegin(); it != source.cend(); ++it) { // escape the key name to be used in a JSON patch const auto key = json_pointer::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path + "/" + key} })); } } // second pass: traverse other object's elements for (auto it = target.cbegin(); it != target.cend(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto key = json_pointer::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } return result; } /// @} //////////////////////////////// // JSON Merge Patch functions // //////////////////////////////// /// @name JSON Merge Patch functions /// @{ /*! @brief applies a JSON Merge Patch The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. The function implements the following algorithm from Section 2 of [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): ``` define MergePatch(Target, Patch): if Patch is an Object: if Target is not an Object: Target = {} // Ignore the contents and set it to an empty Object for each Name/Value pair in Patch: if Value is null: if Name exists in Target: remove the Name/Value pair from Target else: Target[Name] = MergePatch(Target[Name], Value) return Target else: return Patch ``` Thereby, `Target` is the current object; that is, the patch is applied to the current value. @param[in] apply_patch the patch to apply @complexity Linear in the lengths of @a patch. @liveexample{The following code shows how a JSON Merge Patch is applied to a JSON document.,merge_patch} @sa @ref patch -- apply a JSON patch @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) @since version 3.0.0 */ void merge_patch(const basic_json& apply_patch) { if (apply_patch.is_object()) { if (!is_object()) { *this = object(); } for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) { if (it.value().is_null()) { erase(it.key()); } else { operator[](it.key()).merge_patch(it.value()); } } } else { *this = apply_patch; } } /// @} }; /*! @brief user-defined to_string function for JSON values This function implements a user-defined to_string for JSON objects. @param[in] j a JSON object @return a std::string object */ NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) { return j.dump(); } } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /// hash value for JSON objects template<> struct hash { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { return nlohmann::detail::hash(j); } }; /// specialization for std::less /// @note: do not remove the space after '<', /// see https://github.com/nlohmann/json/pull/679 template<> struct less<::nlohmann::detail::value_t> { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; // C++20 prohibit function specialization in the std namespace. #ifndef JSON_HAS_CPP_20 /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( is_nothrow_move_constructible::value&& is_nothrow_move_assignable::value ) { j1.swap(j2); } #endif } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // #include // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_ASSERT #undef JSON_INTERNAL_CATCH #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #undef JSON_EXPLICIT // #include #undef JSON_HEDLEY_ALWAYS_INLINE #undef JSON_HEDLEY_ARM_VERSION #undef JSON_HEDLEY_ARM_VERSION_CHECK #undef JSON_HEDLEY_ARRAY_PARAM #undef JSON_HEDLEY_ASSUME #undef JSON_HEDLEY_BEGIN_C_DECLS #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #undef JSON_HEDLEY_CLANG_HAS_FEATURE #undef JSON_HEDLEY_CLANG_HAS_WARNING #undef JSON_HEDLEY_COMPCERT_VERSION #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #undef JSON_HEDLEY_CONCAT #undef JSON_HEDLEY_CONCAT3 #undef JSON_HEDLEY_CONCAT3_EX #undef JSON_HEDLEY_CONCAT_EX #undef JSON_HEDLEY_CONST #undef JSON_HEDLEY_CONSTEXPR #undef JSON_HEDLEY_CONST_CAST #undef JSON_HEDLEY_CPP_CAST #undef JSON_HEDLEY_CRAY_VERSION #undef JSON_HEDLEY_CRAY_VERSION_CHECK #undef JSON_HEDLEY_C_DECL #undef JSON_HEDLEY_DEPRECATED #undef JSON_HEDLEY_DEPRECATED_FOR #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #undef JSON_HEDLEY_DIAGNOSTIC_POP #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #undef JSON_HEDLEY_DMC_VERSION #undef JSON_HEDLEY_DMC_VERSION_CHECK #undef JSON_HEDLEY_EMPTY_BASES #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #undef JSON_HEDLEY_END_C_DECLS #undef JSON_HEDLEY_FLAGS #undef JSON_HEDLEY_FLAGS_CAST #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_BUILTIN #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_EXTENSION #undef JSON_HEDLEY_GCC_HAS_FEATURE #undef JSON_HEDLEY_GCC_HAS_WARNING #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #undef JSON_HEDLEY_GCC_VERSION #undef JSON_HEDLEY_GCC_VERSION_CHECK #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #undef JSON_HEDLEY_GNUC_HAS_FEATURE #undef JSON_HEDLEY_GNUC_HAS_WARNING #undef JSON_HEDLEY_GNUC_VERSION #undef JSON_HEDLEY_GNUC_VERSION_CHECK #undef JSON_HEDLEY_HAS_ATTRIBUTE #undef JSON_HEDLEY_HAS_BUILTIN #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_HAS_EXTENSION #undef JSON_HEDLEY_HAS_FEATURE #undef JSON_HEDLEY_HAS_WARNING #undef JSON_HEDLEY_IAR_VERSION #undef JSON_HEDLEY_IAR_VERSION_CHECK #undef JSON_HEDLEY_IBM_VERSION #undef JSON_HEDLEY_IBM_VERSION_CHECK #undef JSON_HEDLEY_IMPORT #undef JSON_HEDLEY_INLINE #undef JSON_HEDLEY_INTEL_VERSION #undef JSON_HEDLEY_INTEL_VERSION_CHECK #undef JSON_HEDLEY_IS_CONSTANT #undef JSON_HEDLEY_IS_CONSTEXPR_ #undef JSON_HEDLEY_LIKELY #undef JSON_HEDLEY_MALLOC #undef JSON_HEDLEY_MESSAGE #undef JSON_HEDLEY_MSVC_VERSION #undef JSON_HEDLEY_MSVC_VERSION_CHECK #undef JSON_HEDLEY_NEVER_INLINE #undef JSON_HEDLEY_NON_NULL #undef JSON_HEDLEY_NO_ESCAPE #undef JSON_HEDLEY_NO_RETURN #undef JSON_HEDLEY_NO_THROW #undef JSON_HEDLEY_NULL #undef JSON_HEDLEY_PELLES_VERSION #undef JSON_HEDLEY_PELLES_VERSION_CHECK #undef JSON_HEDLEY_PGI_VERSION #undef JSON_HEDLEY_PGI_VERSION_CHECK #undef JSON_HEDLEY_PREDICT #undef JSON_HEDLEY_PRINTF_FORMAT #undef JSON_HEDLEY_PRIVATE #undef JSON_HEDLEY_PUBLIC #undef JSON_HEDLEY_PURE #undef JSON_HEDLEY_REINTERPRET_CAST #undef JSON_HEDLEY_REQUIRE #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #undef JSON_HEDLEY_REQUIRE_MSG #undef JSON_HEDLEY_RESTRICT #undef JSON_HEDLEY_RETURNS_NON_NULL #undef JSON_HEDLEY_SENTINEL #undef JSON_HEDLEY_STATIC_ASSERT #undef JSON_HEDLEY_STATIC_CAST #undef JSON_HEDLEY_STRINGIFY #undef JSON_HEDLEY_STRINGIFY_EX #undef JSON_HEDLEY_SUNPRO_VERSION #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #undef JSON_HEDLEY_TINYC_VERSION #undef JSON_HEDLEY_TINYC_VERSION_CHECK #undef JSON_HEDLEY_TI_ARMCL_VERSION #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #undef JSON_HEDLEY_TI_CL2000_VERSION #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #undef JSON_HEDLEY_TI_CL430_VERSION #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #undef JSON_HEDLEY_TI_CL6X_VERSION #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #undef JSON_HEDLEY_TI_CL7X_VERSION #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #undef JSON_HEDLEY_TI_CLPRU_VERSION #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #undef JSON_HEDLEY_TI_VERSION #undef JSON_HEDLEY_TI_VERSION_CHECK #undef JSON_HEDLEY_UNAVAILABLE #undef JSON_HEDLEY_UNLIKELY #undef JSON_HEDLEY_UNPREDICTABLE #undef JSON_HEDLEY_UNREACHABLE #undef JSON_HEDLEY_UNREACHABLE_RETURN #undef JSON_HEDLEY_VERSION #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #undef JSON_HEDLEY_VERSION_DECODE_MINOR #undef JSON_HEDLEY_VERSION_DECODE_REVISION #undef JSON_HEDLEY_VERSION_ENCODE #undef JSON_HEDLEY_WARNING #undef JSON_HEDLEY_WARN_UNUSED_RESULT #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #undef JSON_HEDLEY_FALL_THROUGH #endif // INCLUDE_NLOHMANN_JSON_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/cpputil/singleton.h000066400000000000000000000017221520575453600273020ustar00rootroot00000000000000#ifndef HV_SINGLETON_H_ #define HV_SINGLETON_H_ #include #define DISABLE_COPY(Class) \ Class(const Class&) = delete; \ Class& operator=(const Class&) = delete; #define SINGLETON_DECL(Class) \ public: \ static Class* instance(); \ static void exitInstance(); \ private: \ DISABLE_COPY(Class) \ static Class* s_pInstance; \ static std::once_flag s_initFlag; \ static std::mutex s_mutex; #define SINGLETON_IMPL(Class) \ Class* Class::s_pInstance = NULL; \ std::once_flag Class::s_initFlag; \ std::mutex Class::s_mutex; \ Class* Class::instance() { \ std::call_once(s_initFlag, []() {s_pInstance = new Class;}); \ return s_pInstance; \ } \ void Class::exitInstance() { \ std::lock_guard lock(s_mutex); \ if (s_pInstance) { \ delete s_pInstance; \ s_pInstance = nullptr; \ } \ } #endif // HV_SINGLETON_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/000077500000000000000000000000001520575453600243755ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/API.md000066400000000000000000000242031520575453600253310ustar00rootroot00000000000000# libhv API Manual ## base ### hplatform.h - OS: OS_WIN, OS_UNIX (OS_LINUX, OS_ANDROID, OS_DARWIN ...) - ARCH: ARCH_X86, ARCH_X64, ARCH_ARM, ARCH_ARM64 - COMPILER: COMPILER_MSVC, COMPILER_MINGW, COMPILER_GCC, COMPILER_CLANG - BYTE_ORDER: BIG_ENDIAN, LITTLE_ENDIAN - stdbool.h: bool, true, false - stdint.h: int8_t, int16_t, int32_t, int64_t - hv_sleep, hv_msleep, hv_usleep, hv_delay - hv_mkdir - stricmp, strcasecmp ### hexport.h - HV_EXPORT, HV_INLINE - HV_SOURCE, HV_STATICLIB, HV_DYNAMICLIB - HV_DEPRECATED - HV_UNUSED - EXTERN_C, BEGIN_EXTERN_C, END_EXTERN_C - BEGIN_NAMESPACE, END_NAMESPACE, USING_NAMESPACE - DEFAULT - ENUM, STRUCT - IN, OUT, INOUT - OPTIONAL, REQUIRED, REPEATED ### hdef.h - ABS, NABS - ARRAY_SIZE - BITSET, BITCLR, BITGET - CR, LF, CRLF - FLOAT_EQUAL_ZERO - INFINITE - IS_ALPHA, IS_DIGIT, IS_ALPHANUM - IS_CNTRL, IS_GRAPH - IS_HEX - IS_LOWER, IS_UPPER - LOWER, UPPER - MAKEWORD, LOBYTE, HIBYTE - MAKELONG, LOWORD, HIWORD - MAKEINT64, LOINT, HIINT - MAKE_FOURCC - MAX, MIN, LIMIT - MAX_PATH - NULL, TRUE, FALSE - SAFE_FREE, SAFE_DELETE, SAFE_DELETE_ARRAY, SAFE_RELEASE - STRINGCAT - STRINGIFY - offsetof, offsetofend - container_of - prefetch - printd, printe ### hatomic.h - hatomic_flag_t, hatomic_t - hatomic_flag_test_and_set - hatomic_flag_clear - hatomic_add - hatomic_sub - hatomic_inc - hatomic_dec ### herr.h - hv_strerror ### htime.h - IS_LEAP_YEAR - datetime_t - gettick_ms - gettimeofday - gettimeofday_ms - gettimeofday_us - gethrtime_us - datetime_now - datetime_localtime - datetime_mktime - datetime_past - datetime_future - duration_fmt - datetime_fmt - gmtime_fmt - days_of_month - month_atoi - month_itoa - weekday_atoi - weekday_itoa - hv_compile_datetime - cron_next_timeout ### hmath.h - floor2e - ceil2e - varint_encode - varint_decode ### hbase.h - hv_malloc - hv_calloc - hv_realloc - hv_zalloc - hv_strncpy - hv_strncat - hv_strlower - hv_strupper - hv_strreverse - hv_strstartswith - hv_strendswith - hv_strcontains - hv_wildcard_match - hv_strnchr - hv_strrchr_dot - hv_strrchr_dir - hv_basename - hv_suffixname - hv_mkdir_p - hv_rmdir_p - hv_exists - hv_isdir - hv_isfile - hv_islink - hv_filesize - get_executable_path - get_executable_dir - get_executable_file - get_run_dir - hv_rand - hv_random_string - hv_getboolean - hv_parse_size - hv_parse_time - hv_parse_url ### hversion.h - hv_version - hv_compile_version - version_atoi - version_itoa ### hsysinfo.h - get_ncpu - get_meminfo ### hproc.h - hproc_spawn ### hthread.h - hv_getpid - hv_gettid - HTHREAD_RETTYPE - HTHREAD_ROUTINE - hthread_create - hthread_join - class HThread ### hmutex.h - hmutex_t - hmutex_init - hmutex_destroy - hmutex_lock - hmutex_unlock - hspinlock_t - hspinlock_init - hspinlock_destroy - hspinlock_lock - hspinlock_unlock - hrwlock_t - hrwlock_init - hrwlock_destroy - hrwlock_rdlock - hrwlock_rdunlock - hrwlock_wrlock - hrwlock_wrunlock - htimed_mutex_t - htimed_mutex_init - htimed_mutex_destroy - htimed_mutex_lock - htimed_mutex_lock_for - htimed_mutex_unlock - hcondvar_t - hcondvar_init - hcondvar_destroy - hcondvar_wait - hcondvar_wait_for - hcondvar_signal - hcondvar_broadcast - hsem_init - hsem_destroy - hsem_wait - hsem_post - hsem_timedwait - honce_t - HONCE_INIT - honce - class `hv::MutexLock` - class `hv::SpinLock` - class `hv::RWLock` - class `hv::LockGuard` - synchronized ### hsocket.h - INVALID_SOCKET - closesocket - blocking - nonblocking - Bind - Listen - Connect - ConnectNonblock - ConnectTimeout - ResolveAddr - Socketpair - socket_errno - socket_strerror - sockaddr_u - sockaddr_ip - sockaddr_port - sockaddr_set_ip - sockaddr_set_port - sockaddr_set_ipport - sockaddr_len - sockaddr_str - sockaddr_print - SOCKADDR_LEN - SOCKADDR_STR - SOCKADDR_PRINT - tcp_nodelay - tcp_nopush - tcp_keepalive - udp_broadcast - ip_v6only - so_sndtimeo - so_rcvtimeo - so_sndbuf - so_rcvbuf - so_reuseaddr - so_reuseport - so_linger ### hlog.h - default_logger - file_logger - stderr_logger - stdout_logger - logger_create - logger_destroy - logger_enable_color - logger_enable_fsync - logger_fsync - logger_print - logger_set_file - logger_set_handler - logger_set_level - logger_set_max_bufsize - logger_set_max_filesize - logger_set_remain_days - logger_get_cur_file - hlogd, hlogi, hlogw, hloge, hlogf - LOGD, LOGI, LOGW, LOGE, LOGF ### hbuf.h - hbuf_t - offset_buf_t - class HBuf - class HVLBuf - class HRingBuf ### hmain.h - main_ctx_init - parse_opt - parse_opt_long - dump_opt_long - get_arg - get_env - setproctitle - signal_init - signal_handle - create_pidfile - delete_pidfile - getpid_form_pidfile - master_workers_run ### hstring.h - to_string - from_string - toupper - tolower - reverse - startswith - endswith - contains - asprintf - trim - ltrim - rtrim - trim_pairs - split - splitKV - replace - replaceAll ### hfile.h - class HFile ### hpath.h - exists - isdir - isfile - islink - basename - dirname - filename - suffixname - join ### hdir.h - listdir ### hurl.h - HUrl::escape - HUrl::unescape - HUrl::parse - HUrl::dump ### hscope.h - defer - template ScopeCleanup - template ScopeFree - template ScopeDelete - template ScopeDeleteArray - template ScopeRelease - template ScopeLock ### ifconfig.h - ifconfig ## utils ### md5.h - HV_MD5Init - HV_MD5Update - HV_MD5Final - hv_md5 - hv_md5_hex ### sha1.h - HV_SHA1Init - HV_SHA1Update - HV_SHA1Final - HV_SHA1 - hv_sha1 - hv_sha1_hex ### base64.h - hv_base64_decode - hv_base64_encode ### json.hpp - json::parse - json::dump ### singleton.h - DISABLE_COPY - SINGLETON_DECL - SINGLETON_IMPL ## event ### hloop.h - hloop_create_tcp_client - hloop_create_tcp_server - hloop_create_udp_client - hloop_create_udp_server - hloop_create_ssl_client - hloop_create_ssl_server - hloop_new - hloop_free - hloop_run - hloop_stop - hloop_pause - hloop_resume - hloop_status - hloop_pid - hloop_tid - hloop_now - hloop_now_ms - hloop_now_us - hloop_update_time - hloop_set_userdata - hloop_userdata - hloop_wakeup - hloop_post_event - hevent_loop - hevent_type - hevent_id - hevent_priority - hevent_userdata - hevent_set_priority - hevent_ser_userdata - haccept - hconnect - hread - hwrite - hrecv - hsend - hrecvfrom - hsendto - hio_add - hio_del - hio_get - hio_detach - hio_attach - hio_read - hio_read_start - hio_read_stop - hio_read_once - hio_read_until - hio_read_until_length - hio_read_until_delim - hio_read_readline - hio_read_readstring - hio_read_readbytes - hio_write - hio_close - hio_accept - hio_connect - hio_fd - hio_id - hio_type - hio_error - hio_localaddr - hio_peeraddr - hio_events - hio_revents - hio_is_opened - hio_is_closed - hio_enable_ssl - hio_is_ssl - hio_get_ssl - hio_set_ssl - hio_get_ssl_ctx - hio_set_ssl_ctx - hio_new_ssl_ctx - hio_setcb_accept - hio_setcb_connect - hio_setcb_read - hio_setcb_write - hio_setcb_close - hio_getcb_accept - hio_getcb_connect - hio_getcb_read - hio_getcb_write - hio_getcb_close - hio_set_type - hio_set_localaddr - hio_set_peeraddr - hio_set_readbuf - hio_set_connect_timeout - hio_set_close_timeout - hio_set_read_timeout - hio_set_write_timeout - hio_set_keepalive_timeout - hio_set_heartbeat - hio_set_unpack - hio_unset_unpack - hio_read_upstream - hio_write_upstream - hio_close_upstream - hio_setup_upstream - hio_get_upstream - hio_setup_tcp_upstream - hio_setup_ssl_upstream - hio_setup_udp_upstream - hio_create_socket - hio_create_pipe - hio_context - hio_set_context - htimer_add - htimer_add_period - htimer_del - htimer_reset - hidle_add - hidle_del - hsignal_add - hsignal_del ### nlog.h - network_logger - nlog_listen ## evpp - class Buffer - class Channel - class Event - class EventLoop - class EventLoopThread - class EventLoopThreadPool - class TcpClient - class TcpServer - class UdpClient - class UdpServer ## ssl - hssl_ctx_init - hssl_ctx_cleanup - hssl_ctx_instance - hssl_ctx_new - hssl_ctx_free - hssl_new - hssl_free - hssl_accept - hssl_connnect - hssl_read - hssl_write - hssl_close - hssl_set_sni_hostname ## protocol ### dns.h - dns_name_decode - dns_name_encode - dns_pack - dns_unpack - dns_rr_pack - dns_rr_unpack - dns_query - dns_free - nslookup ### ftp.h - ftp_command_str - ftp_connect - ftp_login - ftp_exec - ftp_upload - ftp_download - ftp_download_with_cb - ftp_quit - ftp_status_str ### smtp.h - smtp_command_str - smtp_status_str - smtp_build_command - sendmail ### icmp.h - ping ## http - class HttpMessage - class HttpRequest - class HttpResponse - class HttpParser ### httpdef.h - http_content_type_enum - http_content_type_enum_by_suffix - http_content_type_str - http_content_type_str_by_suffix - http_content_type_suffix - http_errno_description - http_errno_name - http_method_enum - http_method_str - http_status_enum - http_status_str ### http_content.h - parse_query_params - parse_json - parse_multipart - dump_query_params - dump_json - dump_multipart ### HttpClient.h - http_client_new - http_client_del - http_client_send - http_client_send_async - http_client_strerror - http_client_set_timeout - http_client_set_header - http_client_del_header - http_client_get_header - http_client_clear_headers - http_client_set_http_proxy - http_client_set_https_proxy - http_client_add_no_proxy - class HttpClient ### requests.h - requests::request - requests::get - requests::post - requests::put - requests::patch - requests::Delete - requests::head - requests::async ### axios.h - axios::axios - axios::get - axios::post - axios::put - axios::patch - axios::Delete - axios::head - axios::async ### HttpServer.h - http_server_run - http_server_stop - class HttpService - class HttpServer ### WebSocketClient.h - class WebSocketClient ### WebSocketServer.h - websocket_server_run - websocket_server_stop - class WebSocketService - class WebSocketServer ## mqtt - mqtt_client_new - mqtt_client_free - mqtt_client_run - mqtt_client_stop - mqtt_client_set_id - mqtt_client_set_will - mqtt_client_set_auth - mqtt_client_set_callback - mqtt_client_set_userdata - mqtt_client_get_userdata - mqtt_client_get_last_error - mqtt_client_set_ssl_ctx - mqtt_client_new_ssl_ctx - mqtt_client_set_reconnect - mqtt_client_reconnect - mqtt_client_set_connect_timeout - mqtt_client_connect - mqtt_client_is_connected - mqtt_client_disconnect - mqtt_client_publish - mqtt_client_subscribe - mqtt_client_unsubscribe - class MqttClient ## other - class HThreadPool - class HObjectPool - class ThreadLocalStorage kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/PLAN.md000066400000000000000000000011461520575453600254530ustar00rootroot00000000000000## Done - base: cross platfrom infrastructure - event: select/poll/epoll/wepoll/kqueue/port - ssl: openssl/gnutls/mbedtls/wintls/appletls - rudp: KCP - evpp: c++ EventLoop interface similar to muduo and evpp - http client/server: include https http1/x http2 - websocket client/server - mqtt client ## Improving - Path router: optimized matching via trie? - FileCache use LRUCache ## Plan - redis client - async DNS - lua binding - js binding - hrpc = libhv + protobuf - rudp: FEC, ARQ, UDT, QUIC - kcptun - have a taste of io_uring - coroutine - cppsocket.io - IM-libhv - MediaServer-libhv - GameServer-libhv kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/000077500000000000000000000000001520575453600247755ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/Channel.md000066400000000000000000000076271520575453600267030ustar00rootroot00000000000000通道类 ```c++ class Channel { // 返回底层的io结构体指针 hio_t* io() { return io_; } // 返回socket文件描述符 int fd() { return fd_; } // 返回一个唯一标示id uint32_t id() { return id_; } // 返回错误码 int error() { return hio_error(io_); } // 获取/设置/新建/删除 上下文 void* context(); void setContext(void* ctx); template T* newContext(); template T* getContext(); template void deleteContext(); // 获取/设置/新建/删除 上下文智能指针 std::shared_ptr contextPtr(); void setContextPtr(const std::shared_ptr& ctx); void setContextPtr(std::shared_ptr&& ctx); template std::shared_ptr newContextPtr(); template std::shared_ptr getContextPtr(); void deleteContextPtr(); // 是否打开状态 bool isOpened(); // 是否关闭状态 bool isClosed(); // 开始读 int startRead(); // 停止读 int stopRead(); // 读一次 int readOnce(); // 读一个字符串 int readString(); // 读一行 int readLine(); // 读取N个字节 int readBytes(int len); // 写 int write(const void* data, int size); int write(Buffer* buf); int write(const std::string& str); // 设置最大读缓存 void setMaxReadBufsize(uint32_t size); // 设置最大写缓存 void setMaxWriteBufsize(uint32_t size); // 获取当前写缓存大小 size_t writeBufsize(); // 是否写完成 bool isWriteComplete(); // 关闭 int close(bool async = false); // 读回调 std::function onread; // 写回调 std::function onwrite; // 关闭回调 std::function onclose; }; // SocketChannel 继承自 Channel class SocketChannel : public Channel { // 连接状态回调 std::function onconnect; // 心跳回调 std::function heartbeat; // 启用SSL/TLS加密通信 int enableSSL(); // 是否是SSL/TLS加密通信 bool isSSL(); // 设置SSL int setSSL(hssl_t ssl); // 设置SSL_CTX int setSslCtx(hssl_ctx_t ssl_ctx); // 新建SSL_CTX int newSslCtx(hssl_ctx_opt_t* opt); // 设置主机名 int setHostname(const std::string& hostname); // 设置连接超时 void setConnectTimeout(int timeout_ms); // 设置关闭超时 (说明:非阻塞写队列非空时,需要等待写完成再关闭) void setCloseTimeout(int timeout_ms); // 设置读超时 (一段时间没有数据到来便自动关闭连接) void setReadTimeout(int timeout_ms); // 设置写超时 (一段时间没有数据发送便自动关闭连接) void setWriteTimeout(int timeout_ms); // 设置keepalive超时 (一段时间没有数据收发便自动关闭连接) void setKeepaliveTimeout(int timeout_ms); // 设置心跳 (定时发送心跳包) void setHeartbeat(int interval_ms, std::function fn); // 设置拆包规则 void setUnpack(unpack_setting_t* setting); // 开始连接 int startConnect(int port, const char* host = "127.0.0.1"); int startConnect(struct sockaddr* peeraddr); int startConnect(); // 是否已连接 bool isConnected(); // 返回本地地址 std::string localaddr(); // 返回对端地址 std::string peeraddr(); }; // WebSocketChannel 继承自 SocketChannel class WebSocketChannel : public SocketChannel { // 发送文本帧 int send(const std::string& msg, enum ws_opcode opcode = WS_OPCODE_TEXT, bool fin = true); // 发送二进制帧 int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); // 分片发送 int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY); // 关闭 int close(); }; ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/EventLoop.md000066400000000000000000000056031520575453600272360ustar00rootroot00000000000000事件循环类 ```c++ class EventLoop { // 返回底层的loop结构体指针 hloop_t* loop(); // 运行 void run(); // 停止 void stop(); // 暂停 void pause(); // 继续 void resume(); // 设置定时器 TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID); // 设置一次性定时器 TimerID setTimeout(int timeout_ms, TimerCallback cb); // 设置永久性定时器 TimerID setInterval(int interval_ms, TimerCallback cb); // 杀掉定时器 void killTimer(TimerID timerID); // 重置定时器 void resetTimer(TimerID timerID, int timeout_ms = 0); // 返回事件循环所在的线程ID long tid(); // 是否在事件循环所在线程 bool isInLoopThread(); // 断言在事件循环所在线程 void assertInLoopThread(); // 运行在事件循环里 void runInLoop(Functor fn); // 队列在事件循环里 void queueInLoop(Functor fn); // 投递一个事件到事件循环 void postEvent(EventCallback cb); }; class EventLoopThread { // 返回事件循环指针 const EventLoopPtr& loop(); // 返回底层的loop结构体指针 hloop_t* hloop(); // 是否运行中 bool isRunning(); /* 开始运行 * wait_thread_started: 是否阻塞等待线程开始 * pre: 线程开始后执行的函数 * post: 线程结束前执行的函数 */ void start(bool wait_thread_started = true, Functor pre = Functor(), Functor post = Functor()); // 停止运行 void stop(bool wait_thread_stopped = false); // 等待线程退出 void join(); }; class EventLoopThreadPool { // 获取线程数量 int threadNum(); // 设置线程数量 void setThreadNum(int num); // 返回下一个事件循环对象 // 支持轮询、随机、最少连接数等负载均衡策略 EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin); // 返回索引的事件循环对象 EventLoopPtr loop(int idx = -1); // 返回索引的底层loop结构体指针 hloop_t* hloop(int idx = -1); /* 开始运行 * wait_threads_started: 是否阻塞等待所有线程开始 * pre: 线程开始后执行的函数 * post: 线程结束前执行的函数 */ void start(bool wait_threads_started = false, std::function pre = NULL, std::function post = NULL); // 停止运行 void stop(bool wait_threads_stopped = false); // 等待所有线程退出 void join(); }; ``` 测试代码见: - [evpp/EventLoop_test.cpp](../../evpp/EventLoop_test.cpp) - [evpp/EventLoopThread_test.cpp](../../evpp/EventLoopThread_test.cpp) - [evpp/EventLoopThreadPool_test.cpp](../../evpp/EventLoopThreadPool_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/HttpClient.md000066400000000000000000000055521520575453600274040ustar00rootroot00000000000000HTTP 客户端类 ```c++ class HttpClient { // 设置超时 int setTimeout(int timeout); // 设置SSL/TLS int setSslCtx(hssl_ctx_t ssl_ctx); // 新建SSL/TLS int newSslCtx(hssl_ctx_opt_t* opt); // 清除全部请求头部 int clearHeaders(); // 设置请求头部 int setHeader(const char* key, const char* value); // 删除请求头部 int delHeader(const char* key); // 获取请求头部 const char* getHeader(const char* key); // 设置http代理 int setHttpProxy(const char* host, int port); // 设置https代理 int setHttpsProxy(const char* host, int port); // 添加不走代理 int addNoProxy(const char* host); // 同步发送 int send(HttpRequest* req, HttpResponse* resp); // 异步发送 int sendAsync(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); // 关闭连接 (HttpClient对象析构时会自动调用) int close(); }; namespace requests { // 同步请求 Response request(Request req); Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); // 上传文件 Response uploadFile(const char* url, const char* filepath, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); // 通过 `multipart/form-data` 格式上传文件 Response uploadFormFile(const char* url, const char* name, const char* filepath, std::map& params = hv::empty_map, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); // 上传大文件(带上传进度回调) Response uploadLargeFile(const char* url, const char* filepath, upload_progress_cb progress_cb = NULL, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); // 下载文件 (更详细的断点续传示例代码见`examples/wget.cpp`) size_t downloadFile(const char* url, const char* filepath, download_progress_cb progress_cb = NULL); // HEAD 请求 Response head(const char* url, const http_headers& headers = DefaultHeaders); // GET 请求 Response get(const char* url, const http_headers& headers = DefaultHeaders); // POST 请求 Response post(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); // PUT 请求 Response put(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); // PATCH 请求 Response patch(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); // DELETE 请求 Response Delete(const char* url, const http_headers& headers = DefaultHeaders); // 异步请求 int async(Request req, ResponseCallback resp_cb); } ``` 测试代码见 [examples/http_client_test.cpp](../../examples/http_client_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/HttpContext.md000066400000000000000000000052321520575453600276050ustar00rootroot00000000000000```c++ class HttpContext { /* 获取请求信息 */ // 获取客户端IP std::string ip(); // 获取客户端端口 int port(); // 获取请求method http_method method(); // 获取请求url std::string url(); // 获取请求path std::string path(); // 获取请求host std::string host(); // 获取请求头部 const http_headers& headers(); std::string header(const char* key, const std::string& defvalue = hv::empty_string); // 获取请求参数 const hv::QueryParams& params(); std::string param(const char* key, const std::string& defvalue = hv::empty_string); // 获取请求cookie const HttpCookie& cookie(const char* name); // 获取请求 `Content-Length` int length(); // 获取请求 `Content-Type` http_content_type type(); // 判断请求 `Content-Type` bool is(http_content_type content_type); // 获取请求body std::string& body(); // 获取 `application/json` 格式数据 const hv::Json& json(); // 获取 `multipart/form-data` 格式数据 const hv::MultiPart& form(); std::string form(const char* name, const std::string& defvalue = hv::empty_string); // 获取 `application/x-www-urlencoded` 格式数据 const hv::KeyValue& urlencoded(); std::string urlencoded(const char* key, const std::string& defvalue = hv::empty_string); // 根据 `Content-Type` 获取对应格式数据 template T get(const char* key, T defvalue = 0); std::string get(const char* key, const std::string& defvalue = hv::empty_string); /* 设置响应信息 */ // 设置响应状态码 void setStatus(http_status status); // 设置响应 `Content-Type` void setContentType(http_content_type type); // 设置响应头部 void setHeader(const char* key, const std::string& value); // 设置响应cookie void setCookie(const HttpCookie& cookie); // 设置响应body void setBody(const std::string& body); template // 根据 `Content-Type` 设置对应格式数据 void set(const char* key, const T& value); // 发送 int send(); int send(const std::string& str, http_content_type type = APPLICATION_JSON); // 发送文本数据 int sendString(const std::string& str); // 发送二进制数据 int sendData(void* data, int len, bool nocopy = true); // 发送文件 int sendFile(const char* filepath); // 发送json数据 template int sendJson(const T& t); // 重定向 int redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND); // 主动关闭连接 int close(); }; ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/HttpMessage.md000066400000000000000000000070311520575453600275440ustar00rootroot00000000000000```c++ class HttpMessage { // 设置/获取头部 void SetHeader(const char* key, const std::string& value); std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string); // 添加/获取cookie void AddCookie(const HttpCookie& cookie); const HttpCookie& GetCookie(const std::string& name); // 设置/获取 `Content-Type` void SetContentType(http_content_type type); http_content_type ContentType(); // 获取 `Content-Length` size_t ContentLength(); // 填充数据 void SetBody(const std::string& body); // 获取数据 const std::string& Body(); // 解析数据 int ParseBody(); // 填充/获取 `application/json` 格式数据 template int Json(const T& t); const hv::Json& GetJson(); // 填充/获取 `multipart/form-data` 格式数据 template void SetFormData(const char* name, const T& t); void SetFormFile(const char* name, const char* filepath); std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string); int SaveFormFile(const char* name, const char* path); // 填充/获取 `application/x-www-urlencoded` 格式数据 template void SetUrlEncoded(const char* key, const T& t); std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string); // 根据 `Content-Type` 填充对应格式数据 template void Set(const char* key, const T& value); // 根据 `Content-Type` 获取对应格式数据 template T Get(const char* key, T defvalue = 0); // 根据 `Content-Type` 获取对应格式数据并转换成字符串 std::string GetString(const char* key, const std::string& = ""); // 根据 `Content-Type` 获取对应格式数据并转换成Boolean类型 bool GetBool(const char* key, bool defvalue = 0); // 根据 `Content-Type` 获取对应格式数据并转换成整型 int64_t GetInt(const char* key, int64_t defvalue = 0); // 根据 `Content-Type` 获取对应格式数据并转换成浮点数 double GetFloat(const char* key, double defvalue = 0); }; // HttpRequest 继承自 HttpMessage class HttpRequest : public HttpMessage { // 设置/获取method void SetMethod(const char* method); const char* Method(); // 设置URL void SetUrl(const char* url); // 获取URL const std::string& Url(); // 解析URL void ParseUrl(); // 获取Host std::string Host(); // 获取Path std::string Path(); // 设置/获取参数 template void SetParam(const char* key, const T& t); std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string); // 设置代理 void SetProxy(const char* host, int port); // 设置认证 void SetAuth(const std::string& auth); void SetBasicAuth(const std::string& username, const std::string& password); void SetBearerTokenAuth(const std::string& token); // 设置请求超时 void SetTimeout(int sec); // 设置连接超时 void SetConnectTimeout(int sec); // 允许重定向 void AllowRedirect(bool on = true); // 设置重试 void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT, int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY); // 取消 void Cancel(); }; // HttpResponse 继承自 HttpMessage class HttpResponse : public HttpMessage { // 状态码 http_status status_code; // 状态字符串 const char* status_message(); }; ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/HttpServer.md000066400000000000000000000107151520575453600274310ustar00rootroot00000000000000HTTP 服务端类 ```c++ // HTTP服务类 class HttpServer { // 注册HTTP业务类 void registerHttpService(HttpService* service); // 设置监听主机 void setHost(const char* host = "0.0.0.0"); // 设置监听端口 void setPort(int port = 0, int ssl_port = 0); // 设置监听文件描述符 void setListenFD(int fd = -1, int ssl_fd = -1); // 设置IO进程数 (仅`linux`下有效) void setProcessNum(int num); // 设置IO线程数 void setThreadNum(int num); // 设置SSL/TLS int setSslCtx(hssl_ctx_t ssl_ctx); // 新建SSL/TLS int newSslCtx(hssl_ctx_opt_t* opt); // hooks // 事件循环开始时执行的回调函数 std::function onWorkerStart; // 事件循环结束时执行的回调函数 std::function onWorkerStop; // 占用当前线程运行 int run(bool wait = true); // 不占用当前线程运行 int start(); // 停止服务 int stop(); }; // HTTP业务类 class HttpService { // 添加静态资源映射 void Static(const char* path, const char* dir); // 允许跨域访问 void AllowCORS(); // 添加可信代理 (代理白名单) void AddTrustProxy(const char* host); // 添加不可信代理 (代理黑名单) void AddNoProxy(const char* host); // 开启正向转发代理 void EnableForwardProxy(); // 添加反向代理映射 void Proxy(const char* path, const char* url); // 添加中间件 void Use(Handler handlerFunc); // 添加路由处理器 void Handle(const char* httpMethod, const char* relativePath, Handler handlerFunc); // 添加`HEAD`路由 void HEAD(const char* relativePath, Handler handlerFunc); // 添加`GET`路由 void GET(const char* relativePath, Handler handlerFunc); // 添加`POST`路由 void POST(const char* relativePath, Handler handlerFunc); // 添加`PUT`路由 void PUT(const char* relativePath, Handler handlerFunc); // 添加`DELETE`路由 void Delete(const char* relativePath, Handler handlerFunc); // 添加`PATCH`路由 void PATCH(const char* relativePath, Handler handlerFunc); // 添加任意`HTTP method`路由 void Any(const char* relativePath, Handler handlerFunc); // 返回注册的路由路径列表 hv::StringList Paths(); // 处理流程:前处理器 -> 中间件 -> 处理器 -> 后处理器 // preprocessor -> middleware -> processor -> postprocessor // 数据成员 http_handler preprocessor; // 前处理器 http_handlers middleware; // 中间件 http_handler processor; // 处理器 http_handler postprocessor; // 后处理器 std::string base_url; // 基本路径 std::string document_root; // 文档根目录 std::string home_page; // 主页 std::string error_page; // 默认错误页 std::string index_of; // 目录 http_handler errorHandler; // 错误处理器 int proxy_connect_timeout; // 代理连接超时 int proxy_read_timeout; // 代理读超时 int proxy_write_timeout; // 代理写超时 int keepalive_timeout; // 长连接保活超时 int max_file_cache_size; // 文件缓存最大尺寸 int file_cache_stat_interval; // 文件缓存stat间隔,查询文件是否修改 int file_cache_expired_time; // 文件缓存过期时间,过期自动释放 int limit_rate; // 下载速度限制 }; /* 几种`handler`处理函数区别说明: */ // 同步`handler`运行在IO线程 typedef std::function http_sync_handler; // 异步`handler`运行在`hv::async`全局线程池,可通过`hv::async::startup`设置线程池属性 typedef std::function http_async_handler; // 上下文`handler`运行在IO线程,你可以很方便的将`HttpContextPtr`智能指针抛到你的消费者线程/线程池去处理 typedef std::function http_ctx_handler; // 中间状态`handler`运行在IO线程,用来实现大数据量的边接收边处理 typedef std::function http_state_handler; ``` 测试代码见 [examples/http_server_test.cpp](../../examples/http_server_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/README.md000066400000000000000000000012301520575453600262500ustar00rootroot00000000000000## c接口 - [hloop: 事件循环](hloop.md) - [hbase: 基础函数](hbase.md) - [hlog: 日志](hlog.md) ## c++接口 - [class EventLoop: 事件循环类](EventLoop.md) - [class Channel: 通道类](Channel.md) - [class TcpServer: TCP服务端类](TcpServer.md) - [class TcpClient: TCP客户端类](TcpClient.md) - [class UdpServer: UDP服务端类](UdpServer.md) - [class UdpClient: UDP客户端类](UdpClient.md) - [class HttpServer: HTTP服务端类](HttpServer.md) - [class HttpClient: HTTP客户端类](HttpClient.md) - [class WebSocketServer: WebSocket服务端类](WebSocketServer.md) - [class WebSocketClient: WebSocket客户端类](WebSocketClient.md) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/TcpClient.md000066400000000000000000000026731520575453600272140ustar00rootroot00000000000000TCP 客户端类 ```c++ class TcpClient { // 返回所在的事件循环 const EventLoopPtr& loop(); // 创建套接字 int createsocket(int remote_port, const char* remote_host = "127.0.0.1"); int createsocket(struct sockaddr* remote_addr); // 绑定端口 int bind(int local_port, const char* local_host = "0.0.0.0"); int bind(struct sockaddr* local_addr); // 关闭套接字 void closesocket(); // 开始运行 void start(bool wait_threads_started = true); // 停止运行 void stop(bool wait_threads_stopped = true); // 是否已连接 bool isConnected(); // 发送 int send(const void* data, int size); int send(Buffer* buf); int send(const std::string& str); // 设置SSL/TLS加密通信 int withTLS(hssl_ctx_opt_t* opt = NULL); // 设置连接超时 void setConnectTimeout(int ms); // 设置重连 void setReconnect(reconn_setting_t* setting); // 是否是重连 bool isReconnect(); // 设置拆包规则 void setUnpack(unpack_setting_t* setting); // 连接状态回调 std::function onConnection; // 消息回调 std::function onMessage; // 写完成回调 std::function onWriteComplete; }; ``` 测试代码见 [evpp/TcpClient_test.cpp](../../evpp/TcpClient_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/TcpServer.md000066400000000000000000000026001520575453600272320ustar00rootroot00000000000000TCP 服务端类 ```c++ class TcpServer { // 返回索引的事件循环 EventLoopPtr loop(int idx = -1); // 创建套接字 int createsocket(int port, const char* host = "0.0.0.0"); // 关闭套接字 void closesocket(); // 设置最大连接数 void setMaxConnectionNum(uint32_t num); // 设置负载均衡策略 void setLoadBalance(load_balance_e lb); // 设置线程数 void setThreadNum(int num); // 开始运行 void start(bool wait_threads_started = true); // 停止运行 void stop(bool wait_threads_stopped = true); // 设置SSL/TLS加密通信 int withTLS(hssl_ctx_opt_t* opt = NULL); // 设置拆包规则 void setUnpack(unpack_setting_t* setting); // 返回当前连接数 size_t connectionNum(); // 遍历连接 int foreachChannel(std::function fn); // 广播消息 int broadcast(const void* data, int size); int broadcast(const std::string& str); // 连接到来/断开回调 std::function onConnection; // 消息回调 std::function onMessage; // 写完成回调 std::function onWriteComplete; }; ``` 测试代码见 [evpp/TcpServer_test.cpp](../../evpp/TcpServer_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/UdpClient.md000066400000000000000000000020361520575453600272070ustar00rootroot00000000000000UDP 客户端类 ```c++ class UdpClient { // 返回所在的事件循环 const EventLoopPtr& loop(); // 创建套接字 int createsocket(int remote_port, const char* remote_host = "127.0.0.1"); // 绑定端口 int bind(int local_port, const char* local_host = "0.0.0.0"); // 关闭套接字 void closesocket(); // 开始运行 void start(bool wait_threads_started = true); // 停止运行 void stop(bool wait_threads_stopped = true); // 发送 int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL); int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL); int sendto(const std::string& str, struct sockaddr* peeraddr = NULL); // 设置KCP void setKcp(kcp_setting_t* setting); // 消息回调 std::function onMessage; // 写完成回调 std::function onWriteComplete; }; ``` 测试代码见 [evpp/UdpClient_test.cpp](../../evpp/UdpClient_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/UdpServer.md000066400000000000000000000016671520575453600272500ustar00rootroot00000000000000UDP 服务端类 ```c++ class UdpServer { // 返回所在的事件循环 const EventLoopPtr& loop(); // 创建套接字 int createsocket(int port, const char* host = "0.0.0.0"); // 关闭套接字 void closesocket(); // 开始运行 void start(bool wait_threads_started = true); // 停止运行 void stop(bool wait_threads_stopped = true); // 发送 int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL); int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL); int sendto(const std::string& str, struct sockaddr* peeraddr = NULL); // 设置KCP void setKcp(kcp_setting_t* setting); // 消息回调 std::function onMessage; // 写完成回调 std::function onWriteComplete; }; ``` 测试代码见 [evpp/UdpServer_test.cpp](../../evpp/UdpServer_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/WebSocketClient.md000066400000000000000000000015421520575453600303460ustar00rootroot00000000000000WebSocket 客户端类 ```c++ class WebSocketClient { // 打开回调 std::function onopen; // 关闭回调 std::function onclose; // 消息回调 std::function onmessage; // 打开 int open(const char* url, const http_headers& headers = DefaultHeaders); // 关闭 int close(); // 发送 int send(const std::string& msg); int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY); // 设置心跳间隔 void setPingInterval(int ms); // 设置WebSocket握手阶段的HTTP请求 void setHttpRequest(const HttpRequestPtr& req); // 获取WebSocket握手阶段的HTTP响应 const HttpResponsePtr& getHttpResponse(); }; ``` 测试代码见 [examples/websocket_client_test.cpp](../../examples/websocket_client_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/WebSocketServer.md000066400000000000000000000013321520575453600303730ustar00rootroot00000000000000WebSocket 服务端类 ```c++ // WebSocketServer 继承自 HttpServer class WebSocketServer : public HttpServer { // 注册WebSocket业务类 void registerWebSocketService(WebSocketService* service); }; // WebSocket业务类 struct WebSocketService { // 打开回调 std::function onopen; // 消息回调 std::function onmessage; // 关闭回调 std::function onclose; // 心跳间隔 int ping_interval; }; ``` 测试代码见 [examples/websocket_server_test.cpp](../../examples/websocket_server_test.cpp) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/hbase.md000066400000000000000000000054751520575453600264140ustar00rootroot00000000000000一些基础函数 ```c /* hv内存分配/释放函数 */ void* hv_malloc(size_t size); void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize); void* hv_calloc(size_t nmemb, size_t size); void* hv_zalloc(size_t size); void hv_free(void* ptr); // 使用hv分配内存次数 long hv_alloc_cnt(); // 使用hv释放内存次数 long hv_free_cnt(); /* 字符串操作 */ // 字符串转大写 char* hv_strupper(char* str); // 字符串转小写 char* hv_strlower(char* str); // 字符串翻转 char* hv_strreverse(char* str); // 判断字符串是否以xxx开头 bool hv_strstartswith(const char* str, const char* start); // 判断字符串是否以xxx结尾 bool hv_strendswith(const char* str, const char* end); // 判断字符串是否包含xxx bool hv_strcontains(const char* str, const char* sub); // 安全的strncpy char* hv_strncpy(char* dest, const char* src, size_t n); // 安全的strncat char* hv_strncat(char* dest, const char* src, size_t n); // 字符查找 char* hv_strnchr(const char* s, char c, size_t n); // 查找最后一个点(通常用于提取文件后缀) #define hv_strrchr_dot(str) strrchr(str, '.') // 查找最后的路径(通常用于分离目录和文件) char* hv_strrchr_dir(const char* filepath); // 获取文件名(利用了上面的strrchr_dir) const char* hv_basename(const char* filepath); // 获取文件后缀(利用了上面的strrchr_dot) const char* hv_suffixname(const char* filename); /* 文件&目录 */ // mkdir -p: 创建目录 int hv_mkdir_p(const char* dir); // rmdir -p: 删除目录 int hv_rmdir_p(const char* dir); // 判断路径是否存在 bool hv_exists(const char* path); // 判断是否是目录 bool hv_isdir(const char* path); // 判断是否是文件 bool hv_isfile(const char* path); // 判断是否是链接 bool hv_islink(const char* path); // 获取文件大小 size_t hv_filesize(const char* filepath); // 获取可执行文件绝对路径,例如/usr/local/bin/httpd char* get_executable_path(char* buf, int size); // 获取可执行文件所在目录,例如/usr/local/bin char* get_executable_dir(char* buf, int size); // 获取可执行文件名,例如httpd char* get_executable_file(char* buf, int size); // 获取运行目录,例如/home/www/html char* get_run_dir(char* buf, int size); // 返回一个随机数 int hv_rand(int min, int max); // 返回一个随机字符串 char* hv_random_string(char *buf, int len); // 1 y on yes true enable返回true(通常用于配置文件) bool hv_getboolean(const char* str); // 解析size字符串 // 1T2G3M4K5B => ?B size_t hv_parse_size(const char* str); // 解析时间字符串 // 1w2d3h4m5s => ?s time_t hv_parse_time(const char* str); // 解析url字符串 int hv_parse_url(hurl_t* stURL, const char* strURL); ``` 单元测试代码见 [unittest/hbase_test.c](../../unittest/hbase_test.c) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/hlog.md000066400000000000000000000101551520575453600262520ustar00rootroot00000000000000日志 ```c // 标准输出日志 void stdout_logger(int loglevel, const char* buf, int len); // 标准错误日志 void stderr_logger(int loglevel, const char* buf, int len); // 文件日志 void file_logger(int loglevel, const char* buf, int len); // 网络日志(定义在event/nlog.h头文件里) // void network_logger(int loglevel, const char* buf, int len); // 创建日志器 logger_t* logger_create(); // 销毁日志器 void logger_destroy(logger_t* logger); // 设置日志处理器 void logger_set_handler(logger_t* logger, logger_handler fn); // 设置日志等级 void logger_set_level(logger_t* logger, int level); // level = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] void logger_set_level_by_str(logger_t* logger, const char* level); /* * 设置日志格式 * format = "%y-%m-%d %H:%M:%S.%z %L %s" * message = "2020-01-02 03:04:05.067 DEBUG message" * %y year * %m month * %d day * %H hour * %M min * %S sec * %z ms * %Z us * %l First character of level * %L All characters of level * %s message * %% % */ void logger_set_format(logger_t* logger, const char* format); // 设置日志缓存大小 void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize); // 启用日志颜色 void logger_enable_color(logger_t* logger, int on); // 日志打印 int logger_print(logger_t* logger, int level, const char* fmt, ...); // 设置日志文件 void logger_set_file(logger_t* logger, const char* filepath); // 设置日志文件大小 void logger_set_max_filesize(logger_t* logger, unsigned long long filesize); // 16, 16M, 16MB void logger_set_max_filesize_by_str(logger_t* logger, const char* filesize); // 设置日志文件保留天数 void logger_set_remain_days(logger_t* logger, int days); // 启用每次写日志文件立即刷新到磁盘(即每次都调用fsync,会增加IO耗时,影响性能) void logger_enable_fsync(logger_t* logger, int on); // 刷新缓存到磁盘(如对日志文件实时性有必要的,可使用定时器定时刷新到磁盘) void logger_fsync(logger_t* logger); // 获取当前日志文件路径 const char* logger_get_cur_file(logger_t* logger); // hlog: 默认的日志器 logger_t* hv_default_logger(); // 销毁默认的日志器 void hv_destroy_default_logger(void); // 对默认日志器hlog的一些便利操作宏 #define hlog hv_default_logger() #define hlog_destory() hv_destroy_default_logger() /* 禁用hv的默认日志 */ #define hlog_disable() logger_set_level(hlog, LOG_LEVEL_SILENT) #define hlog_set_file(filepath) logger_set_file(hlog, filepath) #define hlog_set_level(level) logger_set_level(hlog, level) #define hlog_set_level_by_str(level) logger_set_level_by_str(hlog, level) #define hlog_set_handler(fn) logger_set_handler(hlog, fn) #define hlog_set_format(format) logger_set_format(hlog, format) #define hlog_set_max_filesize(filesize) logger_set_max_filesize(hlog, filesize) #define hlog_set_max_filesize_by_str(filesize) logger_set_max_filesize_by_str(hlog, filesize) #define hlog_set_remain_days(days) logger_set_remain_days(hlog, days) #define hlog_enable_fsync() logger_enable_fsync(hlog, 1) #define hlog_disable_fsync() logger_enable_fsync(hlog, 0) #define hlog_fsync() logger_fsync(hlog) #define hlog_get_cur_file() logger_get_cur_file(hlog) #define hlogd(fmt, ...) logger_print(hlog, LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogi(fmt, ...) logger_print(hlog, LOG_LEVEL_INFO, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogw(fmt, ...) logger_print(hlog, LOG_LEVEL_WARN, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hloge(fmt, ...) logger_print(hlog, LOG_LEVEL_ERROR, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) #define hlogf(fmt, ...) logger_print(hlog, LOG_LEVEL_FATAL, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) ``` 测试代码见 [examples/hloop_test.c](../../examples/hloop_test.c) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/docs/cn/hloop.md000066400000000000000000000561211520575453600264450ustar00rootroot00000000000000事件循环和IO多路复用机制介绍 事件循环是`libevent、libev、libuv、libhv`这类网络库里最核心的概念,即在事件循环里处理IO读写事件、定时器事件、自定义事件等各种事件;
IO多路复用即在一个IO线程监听多个fd,如最早期的`select`、后来的`poll`,`linux的epoll`、`windows的iocp`、`bsd的kqueue`、`solaris的port`等,都属于IO多路复用机制。
非阻塞NIO搭配IO多路复用机制就是高并发的钥匙。
`libhv`下的`event`模块正是封装了多种平台的IO多路复用机制,提供了统一的事件接口,是`libhv`的核心模块。
`hloop.h`: 事件循环模块对外头文件。
```c // 事件结构体 struct hevent_s { hloop_t* loop; // 事件所属循环 hevent_type_e event_type; // 事件类型 uint64_t event_id; // 事件ID hevent_cb cb; // 事件回调 void* userdata; // 用户数据 void* privdata; // 私有数据 struct hevent_s* pending_next; // 指向下一个事件,用于实现事件队列 int priority; // 事件优先级 }; // 设置事件ID #define hevent_set_id(ev, id) ((hevent_t*)(ev))->event_id = id // 设置事件回调 #define hevent_set_cb(ev, cb) ((hevent_t*)(ev))->cb = cb // 设置事件优先级 #define hevent_set_priority(ev, prio) ((hevent_t*)(ev))->priority = prio // 设置事件用户数据 #define hevent_set_userdata(ev, udata) ((hevent_t*)(ev))->userdata = (void*)udata // 获取事件所属循环 #define hevent_loop(ev) (((hevent_t*)(ev))->loop) // 获取事件类型 #define hevent_type(ev) (((hevent_t*)(ev))->event_type) // 获取事件ID #define hevent_id(ev) (((hevent_t*)(ev))->event_id) // 获取事件回调 #define hevent_cb(ev) (((hevent_t*)(ev))->cb) // 获取事件优先级 #define hevent_priority(ev) (((hevent_t*)(ev))->priority) // 获取事件用户数据 #define hevent_userdata(ev) (((hevent_t*)(ev))->userdata) // hio_t、htimer_t、hsignal_t、hidle_t皆是继承自hevent_t,继承上面的数据成员和函数方法 // 新建事件循环 hloop_t* hloop_new(int flags DEFAULT(HLOOP_FLAG_AUTO_FREE)); // 释放事件循环 void hloop_free(hloop_t** pp); // 运行事件循环 int hloop_run(hloop_t* loop); // 停止事件循环 int hloop_stop(hloop_t* loop); // 暂停事件循环 int hloop_pause(hloop_t* loop); // 继续事件循环 int hloop_resume(hloop_t* loop); // 唤醒事件循环 int hloop_wakeup(hloop_t* loop); // 返回事件循环状态 hloop_status_e hloop_status(hloop_t* loop); // 更新事件循环里的时间 void hloop_update_time(hloop_t* loop); // 返回事件循环里记录的时间 uint64_t hloop_now(hloop_t* loop); // s uint64_t hloop_now_ms(hloop_t* loop); // ms uint64_t hloop_now_us(hloop_t* loop); // us // 返回事件循环所在进程ID long hloop_pid(hloop_t* loop); // 返回事件循环所在线程ID long hloop_tid(hloop_t* loop); // 返回事件循环的循环次数 uint64_t hloop_count(hloop_t* loop); // 返回事件循环里激活的IO事件数量 uint32_t hloop_nios(hloop_t* loop); // 返回事件循环里激活的定时器事件数量 uint32_t hloop_ntimers(hloop_t* loop); // 返回事件循环里激活的空闲事件数量 uint32_t hloop_nidles(hloop_t* loop); // 返回事件循环里激活的事件数量 uint32_t hloop_nactives(hloop_t* loop); // 设置事件循环的用户数据 void hloop_set_userdata(hloop_t* loop, void* userdata); // 获取事件循环的用户数据 void* hloop_userdata(hloop_t* loop); // 投递事件 void hloop_post_event(hloop_t* loop, hevent_t* ev); // 添加信号处理 hsignal_t* hsignal_add(hloop_t* loop, hsignal_cb cb, int signo); // 删除信号处理 void hsignal_del(hsignal_t* sig); // 添加空闲事件 hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat DEFAULT(INFINITE)); // 删除空闲事件 void hidle_del(hidle_t* idle); // 添加超时定时器 htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat DEFAULT(INFINITE)); // 添加时间定时器 htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, int8_t minute DEFAULT(0), int8_t hour DEFAULT(-1), int8_t day DEFAULT(-1), int8_t week DEFAULT(-1), int8_t month DEFAULT(-1), uint32_t repeat DEFAULT(INFINITE)); // 删除定时器 void htimer_del(htimer_t* timer); // 重置定时器 void htimer_reset(htimer_t* timer, uint32_t timeout_ms DEFAULT(0)); // 返回IO多路复用引擎 (select、poll、epoll、etc.) const char* hio_engine(); // 获取IO对象 hio_t* hio_get(hloop_t* loop, int fd); // 添加IO读写事件 int hio_add(hio_t* io, hio_cb cb, int events DEFAULT(HV_READ)); // 删除IO读写事件 int hio_del(hio_t* io, int events DEFAULT(HV_RDWR)); // 将IO对象从当前所属事件循环中剥离 void hio_detach(/*hloop_t* loop,*/ hio_t* io); // 将IO对象关联到新的事件循环 void hio_attach(hloop_t* loop, hio_t* io); // hio_detach 和 hio_attach 的示例代码见 examples/multi-thread/one-acceptor-multi-workers.c /* void new_conn_event(hevent_t* ev) { hloop_t* loop = ev->loop; hio_t* io = (hio_t*)hevent_userdata(ev); // 关联到新的worker事件循环 hio_attach(loop, io); } void on_accpet(hio_t* io) { // 从acceptor所在事件循环中剥离 hio_detach(io); // 将新的连接按照负载均衡策略分发到worker线程 hloop_t* worker_loop = get_one_loop(); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.loop = worker_loop; ev.cb = new_conn_event; ev.userdata = io; hloop_post_event(worker_loop, &ev); } */ // 判断fd是否存在于事件循环 bool hio_exists(hloop_t* loop, int fd); // 返回一个唯一标示ID uint32_t hio_id (hio_t* io); // 返回文件描述符 int hio_fd (hio_t* io); // 返回错误码 int hio_error (hio_t* io); // 返回添加的事件 int hio_events (hio_t* io); // 获取返回的事件 int hio_revents (hio_t* io); // 返回IO类型 hio_type_e hio_type (hio_t* io); // 返回本地地址 struct sockaddr* hio_localaddr(hio_t* io); // 返回对端地址 struct sockaddr* hio_peeraddr (hio_t* io); // 设置上下文 void hio_set_context(hio_t* io, void* ctx); // 获取上下文 void* hio_context(hio_t* io); // 是否已打开 bool hio_is_opened(hio_t* io); // 是否已连接 bool hio_is_connected(hio_t* io); // 是否已关闭 bool hio_is_closed(hio_t* io); // 设置读缓存 void hio_set_readbuf(hio_t* io, void* buf, size_t len); // 获取读缓存 hio_readbuf_t* hio_get_readbuf(hio_t* io); // 设置最大读缓存 void hio_set_max_read_bufsize (hio_t* io, uint32_t size); // 设置最大写缓存 void hio_set_max_write_bufsize(hio_t* io, uint32_t size); // 获取当前写缓存大小 size_t hio_write_bufsize(hio_t* io); // 判断是否写完成 #define hio_write_is_complete(io) (hio_write_bufsize(io) == 0) // 获取最后读的时间 uint64_t hio_last_read_time(hio_t* io); // ms // 获取最后写的时间 uint64_t hio_last_write_time(hio_t* io); // ms // 设置accept回调 void hio_setcb_accept (hio_t* io, haccept_cb accept_cb); // 设置连接回调 void hio_setcb_connect (hio_t* io, hconnect_cb connect_cb); // 设置读回调 void hio_setcb_read (hio_t* io, hread_cb read_cb); // 设置写回调 void hio_setcb_write (hio_t* io, hwrite_cb write_cb); // 设置关闭回调 void hio_setcb_close (hio_t* io, hclose_cb close_cb); // 获取accept回调 haccept_cb hio_getcb_accept(hio_t* io); // 获取连接回调 hconnect_cb hio_getcb_connect(hio_t* io); // 获取读回调 hread_cb hio_getcb_read(hio_t* io); // 获取写回调 hwrite_cb hio_getcb_write(hio_t* io); // 获取关闭回调 hclose_cb hio_getcb_close(hio_t* io); // 开启SSL/TLS加密通信 int hio_enable_ssl(hio_t* io); // 是否SSL/TLS加密通信 bool hio_is_ssl(hio_t* io); // 设置SSL int hio_set_ssl (hio_t* io, hssl_t ssl); // 设置SSL_CTX int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx); // 新建SSL_CTX int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); // 获取SSL hssl_t hio_get_ssl(hio_t* io); // 获取SSL_CTX hssl_ctx_t hio_get_ssl_ctx(hio_t* io); // 设置主机名 int hio_set_hostname(hio_t* io, const char* hostname); // 获取主机名 const char* hio_get_hostname(hio_t* io); // 设置连接超时 void hio_set_connect_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CONNECT_TIMEOUT)); // 设置关闭超时 (说明:非阻塞写队列非空时,需要等待写完成再关闭) void hio_set_close_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CLOSE_TIMEOUT)); // 设置读超时 (一段时间没有数据到来便自动关闭连接) void hio_set_read_timeout(hio_t* io, int timeout_ms); // 设置写超时 (一段时间没有数据发送便自动关闭连接) void hio_set_write_timeout(hio_t* io, int timeout_ms); // 设置keepalive超时 (一段时间没有数据收发便自动关闭连接) void hio_set_keepalive_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_KEEPALIVE_TIMEOUT)); // 设置心跳 (定时发送心跳包) typedef void (*hio_send_heartbeat_fn)(hio_t* io); void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn); // 接收连接 // hio_add(io, HV_READ) => accept => haccept_cb int hio_accept (hio_t* io); // 连接 // connect => hio_add(io, HV_WRITE) => hconnect_cb int hio_connect(hio_t* io); // 读 // hio_add(io, HV_READ) => read => hread_cb int hio_read (hio_t* io); // 开始读 #define hio_read_start(io) hio_read(io) // 停止读 #define hio_read_stop(io) hio_del(io, HV_READ) // 读一次 // hio_read_start => hread_cb => hio_read_stop int hio_read_once (hio_t* io); // 读取直到指定长度 // hio_read_once => hread_cb(len) int hio_read_until_length(hio_t* io, unsigned int len); // 读取直到遇到分隔符 // hio_read_once => hread_cb(...delim) int hio_read_until_delim (hio_t* io, unsigned char delim); // 读取一行 #define hio_readline(io) hio_read_until_delim(io, '\n') // 读取字符串 #define hio_readstring(io) hio_read_until_delim(io, '\0') // 读取N个字节 #define hio_readbytes(io, len) hio_read_until_length(io, len) #define hio_read_until(io, len) hio_read_until_length(io, len) // 写 // hio_try_write => hio_add(io, HV_WRITE) => write => hwrite_cb int hio_write (hio_t* io, const void* buf, size_t len); // 关闭 // hio_del(io, HV_RDWR) => close => hclose_cb int hio_close (hio_t* io); // 异步关闭 (投递一个close事件) // NOTE: hloop_post_event(hio_close_event) int hio_close_async(hio_t* io); //------------------高等级的接口------------------------------------------- // 读 // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read hio_t* hread (hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb); // 写 // hio_get -> hio_setcb_write -> hio_write hio_t* hwrite (hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); // 关闭 // hio_get -> hio_close void hclose (hloop_t* loop, int fd); // tcp // 接收连接 // hio_get -> hio_setcb_accept -> hio_accept hio_t* haccept (hloop_t* loop, int listenfd, haccept_cb accept_cb); // 连接 // hio_get -> hio_setcb_connect -> hio_connect hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb); // 接收 // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb); // 发送 // hio_get -> hio_setcb_write -> hio_write hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); // udp // 设置IO类型 void hio_set_type(hio_t* io, hio_type_e type); // 设置本地地址 void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen); // 设置对端地址 void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen); // 接收 // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb); // 发送 // hio_get -> hio_setcb_write -> hio_write hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); //-----------------顶层的接口--------------------------------------------- // 创建socket套接字,返回IO对象 // @hio_create_socket: socket -> bind -> listen // sockaddr_set_ipport -> socket -> hio_get(loop, sockfd) -> // side == HIO_SERVER_SIDE ? bind -> // type & HIO_TYPE_SOCK_STREAM ? listen -> hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type DEFAULT(HIO_TYPE_TCP), hio_side_e side DEFAULT(HIO_SERVER_SIDE)); // @tcp_server: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept // 创建TCP服务,示例代码见 examples/tcp_echo_server.c hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); // @tcp_client: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect // 创建TCP客户端,示例代码见 examples/nc.c hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); // @ssl_server: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept // 创建SSL服务端,示例代码见 examples/tcp_echo_server.c => #define TEST_SSL 1 hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); // @ssl_client: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect // 创建SSL客户端,示例代码见 examples/nc.c => #define TEST_SSL 1 hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); // @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE) // 创建UDP服务端,示例代码见 examples/udp_echo_server.c hio_t* hloop_create_udp_server (hloop_t* loop, const char* host, int port); // @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE) // 创建UDP客户端,示例代码见 examples/nc.c hio_t* hloop_create_udp_client (hloop_t* loop, const char* host, int port); //-----------------pipe--------------------------------------------- // 创建pipe,示例代码见 examples/pipe_test.c int hio_create_pipe(hloop_t* loop, hio_t* pipeio[2]); //-----------------转发--------------------------------------------- // hio_read(io) // hio_read(io->upstream_io) void hio_read_upstream(hio_t* io); // on_write(io) -> hio_write_is_complete(io) -> hio_read(io->upstream_io) void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes); // hio_write(io->upstream_io, buf, bytes) void hio_write_upstream(hio_t* io, void* buf, int bytes); // hio_close(io->upstream_io) void hio_close_upstream(hio_t* io); // io1->upstream_io = io2; // io2->upstream_io = io1; // 建立转发,示例代码见 examples/socks5_proxy_server.c void hio_setup_upstream(hio_t* io1, hio_t* io2); // @return io->upstream_io hio_t* hio_get_upstream(hio_t* io); // @tcp_upstream: hio_create_socket -> hio_setup_upstream -> hio_connect -> on_connect -> hio_read_upstream // @return upstream_io // 建立TCP转发,示例代码见 examples/tcp_proxy_server.c hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl DEFAULT(0)); // 建立SSL转发 #define hio_setup_ssl_upstream(io, host, port) hio_setup_tcp_upstream(io, host, port, 1) // @udp_upstream: hio_create_socket -> hio_setup_upstream -> hio_read_upstream // @return upstream_io // 建立UDP转发,示例代码见 examples/udp_proxy_server.c hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port); //-----------------拆包--------------------------------------------- // 拆包模式 typedef enum { UNPACK_MODE_NONE = 0, UNPACK_BY_FIXED_LENGTH = 1, // 固定长度拆包,不建议 UNPACK_BY_DELIMITER = 2, // 根据分隔符拆包,适用于文本协议 UNPACK_BY_LENGTH_FIELD = 3, // 根据头部长度字段拆包,适用于二进制协议 } unpack_mode_e; // 拆包设置 typedef struct unpack_setting_s { unpack_mode_e mode; // 拆包模式 unsigned int package_max_length; // 最大的包长 union { // UNPACK_BY_FIXED_LENGTH: 固定长度拆包设置 struct { unsigned int fixed_length; // 固定长度 }; // UNPACK_BY_DELIMITER: 分隔符拆包设置 struct { unsigned char delimiter[PACKAGE_MAX_DELIMITER_BYTES]; // 分隔符 unsigned short delimiter_bytes; // 分隔符所占字节数 }; /* * UNPACK_BY_LENGTH_FIELD: 头部长度字段拆包设置 * * 包长 = 头部长度 + 数据长度 + 调整长度 * package_len = head_len + body_len + length_adjustment * * if (length_field_coding == ENCODE_BY_VARINT) head_len = body_offset + varint_bytes - length_field_bytes; * else head_len = body_offset; * * 注意:头部长度字段的值仅代表数据长度,不包括头部本身长度, * 如果你的头部长度字段代表总包长,那么应该将length_adjustment设置为负的头部长度 * length_field stores body length, exclude head length, * if length_field = head_len + body_len, then length_adjustment should be set to -head_len. * */ struct { unsigned short body_offset; // 到数据的偏移,通常等于头部长度 unsigned short length_field_offset; // 长度字段偏移 unsigned short length_field_bytes; // 长度字段所占字节数 short length_adjustment; // 调整长度 unpack_coding_e length_field_coding; // 长度字段编码方式 }; }; } unpack_setting_t; /* * 拆包示例代码见 examples/jsonrpc examples/protorpc * * 注意:多个IO对象的unpack_setting_t可能是一样的,所有hio_t里仅保存了unpack_setting_t的指针, * unpack_setting_t的生命周期应该被调用者所保证,不应该使用局部变量。 */ // 设置拆包 void hio_set_unpack(hio_t* io, unpack_setting_t* setting); // 取消拆包设置 void hio_unset_unpack(hio_t* io); // 拆包设置示例: /* // FTP协议通过\r\n分割符拆包 unpack_setting_t ftp_unpack_setting; memset(&ftp_unpack_setting, 0, sizeof(unpack_setting_t)); ftp_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; ftp_unpack_setting.mode = UNPACK_BY_DELIMITER; ftp_unpack_setting.delimiter[0] = '\r'; ftp_unpack_setting.delimiter[1] = '\n'; ftp_unpack_setting.delimiter_bytes = 2; // MQTT协议通过头部长度字段拆包,头部长度字段使用了varint编码 unpack_setting_t mqtt_unpack_setting = { .mode = UNPACK_BY_LENGTH_FIELD, .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, .body_offset = 2, .length_field_offset = 1, .length_field_bytes = 1, .length_field_coding = ENCODE_BY_VARINT, }; */ //-----------------重连---------------------------------------- // 重连设置 typedef struct reconn_setting_s { uint32_t min_delay; // ms 重连最小延时 uint32_t max_delay; // ms 重连最大延时 uint32_t cur_delay; // ms 当前延时 /* * @delay_policy: 延时策略 * 0: fixed 固定延时 * min_delay=3s => 3,3,3... * 1: linear 线性增长延时 * min_delay=3s max_delay=10s => 3,6,9,10,10... * other: exponential 指数增长延时 * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60... */ uint32_t delay_policy; // 延时策略 uint32_t max_retry_cnt; // 最大重试次数 uint32_t cur_retry_cnt; // 当前重试次数 } reconn_setting_t; // 重连设置初始化 void reconn_setting_init(reconn_setting_t* reconn); // 重连设置重置 void reconn_setting_reset(reconn_setting_t* reconn); // 增加重试次数并判断是否未超过最大重试次数 bool reconn_setting_can_retry(reconn_setting_t* reconn); // 计算当前重连延时 uint32_t reconn_setting_calc_delay(reconn_setting_t* reconn); //-----------------负载均衡------------------------------------- // 负载均衡策略枚举 typedef enum { LB_RoundRobin, // 轮询 LB_Random, // 随机 LB_LeastConnections,// 最少连接数 LB_IpHash, // IP hash LB_UrlHash, // URL hash } load_balance_e; //-----------------可靠UDP--------------------------------------------- // 关闭可靠UDP int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr DEFAULT(NULL)); // KCP设置 typedef struct kcp_setting_s { // ikcp_create(conv, ...) unsigned int conv; // ikcp_nodelay(kcp, nodelay, interval, fastresend, nocwnd) int nodelay; int interval; int fastresend; int nocwnd; // ikcp_wndsize(kcp, sndwnd, rcvwnd) int sndwnd; int rcvwnd; // ikcp_setmtu(kcp, mtu) int mtu; // ikcp_update int update_interval; } kcp_setting_t; // KCP 正常模式 HV_INLINE void kcp_setting_init_with_normal_mode(kcp_setting_t* setting); // KCP fast模式 void kcp_setting_init_with_fast_mode(kcp_setting_t* setting); // KCP fast2模式 void kcp_setting_init_with_fast2_mode(kcp_setting_t* setting); // KCP fast3模式 void kcp_setting_init_with_fast3_mode(kcp_setting_t* setting); // 设置KCP,示例代码见 examples/udp_echo_server.c => #define TEST_KCP 1 int hio_set_kcp(hio_t* io, kcp_setting_t* setting DEFAULT(NULL)); ``` 示例代码: - 事件循环: [examples/hloop_test.c](../../examples/hloop_test.c) - 定时器: [examples/htimer_test.c](../../examples/htimer_test.c) - TCP回显服务: [examples/tcp_echo_server.c](../../examples/tcp_echo_server.c) - TCP聊天服务: [examples/tcp_chat_server.c](../../examples/tcp_chat_server.c) - TCP代理服务: [examples/tcp_proxy_server.c](../../examples/tcp_proxy_server.c) - TCP客户端: [examples/tcp_client_test.c](../../examples/tcp_client_test.c) - UDP回显服务: [examples/udp_echo_server.c](../../examples/udp_echo_server.c) - UDP代理服务: [examples/udp_proxy_server.c](../../examples/udp_proxy_server.c) - 网络客户端: [examples/nc](../../examples/nc.c) - SOCKS5代理服务: [examples/socks5_proxy_server.c](../../examples/socks5_proxy_server.c) - HTTP服务: [examples/tinyhttpd.c](../../examples/tinyhttpd.c) - HTTP代理服务: [examples/tinyproxyd.c](../../examples/tinyproxyd.c) - jsonRPC示例: [examples/jsonrpc](../../examples/jsonrpc) - protobufRPC示例: [examples/protorpc](../../examples/protorpc) 多进程/多线程模式示例代码: - 多accept进程模式: [examples/multi-thread/multi-acceptor-processes.c](../../examples/multi-thread/multi-acceptor-processes.c) - 多accept线程模式: [examples/multi-thread/multi-acceptor-threads.c](../../examples/multi-thread/multi-acceptor-threads.c) - 一个accept线程+多worker线程: [examples/multi-thread/one-acceptor-multi-workers.c](../../examples/multi-thread/one-acceptor-multi-workers.c) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/000077500000000000000000000000001520575453600260525ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/asio_echo.cpp000066400000000000000000000057401520575453600305150ustar00rootroot00000000000000// // async_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include #include #include #include using boost::asio::ip::tcp; class session { public: session(boost::asio::io_service& io_service) : socket_(io_service) { } tcp::socket& socket() { return socket_; } void start() { socket_.async_read_some(boost::asio::buffer(data_, max_length), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { boost::asio::async_write(socket_, boost::asio::buffer(data_, bytes_transferred), boost::bind(&session::handle_write, this, boost::asio::placeholders::error)); } else { delete this; } } void handle_write(const boost::system::error_code& error) { if (!error) { socket_.async_read_some(boost::asio::buffer(data_, max_length), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { delete this; } } private: tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind( &server::handle_accept, this, new_session, boost::asio::placeholders::error)); } void handle_accept(session* new_session, const boost::system::error_code& error) { if (!error) { new_session->start(); new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind( &server::handle_accept, this, new_session, boost::asio::placeholders::error)); } else { delete new_session; } } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); boost::asio::io_service io_service; server s(io_service, port); io_service.run(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/benchmark.sh000077500000000000000000000034171520575453600303500ustar00rootroot00000000000000#!/bin/bash host=127.0.0.1 port=2000 connections=100 duration=10 threads=2 sendbytes=1024 while getopts 'h:p:c:d:t:' opt do case $opt in h) host=$OPTARG;; p) port=$OPTARG;; c) connections=$OPTARG;; d) duration=$OPTARG;; t) threads=$OPTARG;; *) exit -1;; esac done SCRIPT_DIR=$(cd `dirname $0`; pwd) cd ${SCRIPT_DIR}/.. killall_echo_servers() { #sudo killall libevent_echo libev_echo libuv_echo libhv_echo asio_echo poco_echo muduo_echo if [ $(ps aux | grep _echo | grep -v grep | wc -l) -gt 0 ]; then ps aux | grep _echo | grep -v grep | awk '{print $2}' | xargs sudo kill -9 fi } export LD_LIBRARY_PATH=lib:$LD_LIBRARY_PATH killall_echo_servers sport=$port if [ -x bin/libevent_echo ]; then let port++ bin/libevent_echo $port & echo "libevent running on port $port" fi if [ -x bin/libev_echo ]; then let port++ bin/libev_echo $port & echo "libev running on port $port" fi if [ -x bin/libuv_echo ]; then let port++ bin/libuv_echo $port & echo "libuv running on port $port" fi if [ -x bin/libhv_echo ]; then let port++ bin/libhv_echo $port & echo "libhv running on port $port" fi if [ -x bin/asio_echo ]; then let port++ bin/asio_echo $port & echo "asio running on port $port" fi if [ -x bin/poco_echo ]; then let port++ bin/poco_echo $port & echo "poco running on port $port" fi if [ -x bin/muduo_echo ]; then let port++ bin/muduo_echo $port & echo "muduo running on port $port" fi sleep 1 for ((p=$sport+1; p<=$port; ++p)); do echo -e "\n==============$p=====================================" bin/pingpong_client -H $host -p $p -c $connections -d $duration -t $threads -b $sendbytes sleep 1 done killall_echo_servers kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/build.sh000077500000000000000000000017361520575453600275170ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. # install libevent libev libuv asio poco UNAME=$(uname -a) case ${UNAME} in *Ubuntu*|*Debian*) sudo apt install libevent-dev libev-dev libuv1-dev libboost-dev libboost-system-dev libasio-dev libpoco-dev ;; *CentOS*) sudo yum install libevent-devel libev-devel libuv-devel boost-devel asio-devel poco-devel ;; *Darwin*) brew install libevent libev libuv boost asio poco ;; *) echo 'please install libevent libev libuv boost asio poco' ;; esac # install muduo => https://github.com/chenshuo/muduo.git TEST_MUDUO=false if [ "$TEST_MUDUO" == "true" ]; then cd ${ROOT_DIR}/.. git clone https://github.com/chenshuo/muduo.git cd muduo mkdir build && cd build cmake .. && make && sudo make install fi # install libhv cd ${ROOT_DIR} make libhv && sudo make install && sudo ldconfig # build echo-servers make echo-servers kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/libev_echo.c000066400000000000000000000034271520575453600303230ustar00rootroot00000000000000#include #include #include #include #include #include #include #include "ev.h" #define RECV_BUFSIZE 8192 static char recvbuf[RECV_BUFSIZE]; void do_recv(struct ev_loop *loop, struct ev_io *io, int revents) { int nread, nsend; nread = recv(io->fd, recvbuf, RECV_BUFSIZE, 0); if (nread <= 0) { goto error; } nsend = send(io->fd, recvbuf, nread, 0); if (nsend != nread) { goto error; } return; error: ev_io_stop(loop, io); close(io->fd); free(io); } void do_accept(struct ev_loop *loop, struct ev_io *listenio, int revents) { struct sockaddr_in peeraddr; socklen_t addrlen = sizeof(peeraddr); int connfd = accept(listenio->fd, (struct sockaddr*)&peeraddr, &addrlen); if (connfd <= 0) { return; } struct ev_io* io = (struct ev_io*)malloc(sizeof(struct ev_io)); ev_io_init(io, do_recv, connfd, EV_READ); ev_io_start(loop, io); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); struct sockaddr_in addr; int addrlen = sizeof(addr); memset(&addr, 0, addrlen); addr.sin_family = AF_INET; addr.sin_port = htons(port); int listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { return -20; } if (bind(listenfd, (struct sockaddr*)&addr, addrlen) < 0) { return -30; } if (listen(listenfd, SOMAXCONN) < 0) { return -40; } struct ev_loop* loop = ev_loop_new(0); struct ev_io listenio; ev_io_init(&listenio, do_accept, listenfd, EV_READ); ev_io_start(loop, &listenio); ev_run(loop, 0); ev_loop_destroy(loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/libevent_echo.c000066400000000000000000000034211520575453600310240ustar00rootroot00000000000000#include #include #include #include "event2/event.h" #include "event2/listener.h" #include "event2/bufferevent.h" #include "event2/buffer.h" //#define RECV_BUFSIZE 8192 void error_cb(struct bufferevent* bev, short event, void* userdata) { bufferevent_free(bev); } void read_cb(struct bufferevent* bev, void* userdata) { //static char recvbuf[RECV_BUFSIZE]; //int nread = bufferevent_read(bev, &recvbuf, RECV_BUFSIZE); //bufferevent_write(bev, recvbuf, nread); struct evbuffer* buf = evbuffer_new(); int ret = bufferevent_read_buffer(bev, buf); if (ret == 0) { bufferevent_write_buffer(bev, buf); } evbuffer_free(buf); } void on_accept(struct evconnlistener* listener, evutil_socket_t connfd, struct sockaddr* peeraddr, int addrlen, void* userdata) { struct event_base* loop = evconnlistener_get_base(listener); struct bufferevent* bev = bufferevent_socket_new(loop, connfd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(bev, read_cb, NULL, error_cb, NULL); bufferevent_enable(bev, EV_READ|EV_WRITE|EV_PERSIST); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); struct event_base* loop = event_base_new(); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); struct evconnlistener* listener = evconnlistener_new_bind( loop, on_accept, NULL, LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&addr, sizeof(addr)); if (listener == NULL) { return -20; } event_base_dispatch(loop); evconnlistener_free(listener); event_base_free(loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/libhv_echo.c000066400000000000000000000011751520575453600303240ustar00rootroot00000000000000#include "hv/hloop.h" void on_close(hio_t* io) { } void on_recv(hio_t* io, void* buf, int readbytes) { hio_write(io, buf, readbytes); } void on_accept(hio_t* io) { hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_read(io); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); if (listenio == NULL) { return -20; } hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/libuv_echo.c000066400000000000000000000034751520575453600303460ustar00rootroot00000000000000#define _GNU_SOURCE 1 #include #include #include #include "uv.h" typedef struct { uv_write_t req; uv_buf_t buf; } uv_write_req_t; void alloc_cb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { buf->base = (char*)malloc(suggested_size); buf->len = suggested_size; } void close_cb(uv_handle_t* handle) { free(handle); } void write_cb(uv_write_t* req, int status) { uv_write_req_t* wr = (uv_write_req_t*)req; free(wr->buf.base); free(wr); } void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { if (nread <= 0) { uv_close((uv_handle_t*)stream, close_cb); return; } uv_write_req_t* wr = (uv_write_req_t*)malloc(sizeof(uv_write_req_t)); wr->buf.base = buf->base; wr->buf.len = nread; uv_write(&wr->req, stream, &wr->buf, 1, write_cb); } void do_accept(uv_stream_t* server, int status) { uv_tcp_t* tcp_stream = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); uv_tcp_init(server->loop, tcp_stream); uv_accept(server, (uv_stream_t*)tcp_stream); uv_read_start((uv_stream_t*)tcp_stream, alloc_cb, read_cb); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); uv_loop_t loop; uv_loop_init(&loop); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); //addr.sin_family = AF_INET; //addr.sin_port = htons(port); uv_ip4_addr("0.0.0.0", port, &addr); uv_tcp_t tcp_server; uv_tcp_init(&loop, &tcp_server); int ret = uv_tcp_bind(&tcp_server, (struct sockaddr*)&addr, 0); if (ret) { return -20; } ret = uv_listen((uv_stream_t*)&tcp_server, SOMAXCONN, do_accept); if (ret) { return -30; } uv_run(&loop, UV_RUN_DEFAULT); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/muduo_echo.cpp000066400000000000000000000026561520575453600307160ustar00rootroot00000000000000// @see muduo/examples/simple/echo #include "muduo/base/Logging.h" #include "muduo/net/EventLoop.h" #include "muduo/net/InetAddress.h" #include "muduo/net/TcpServer.h" using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; using muduo::Timestamp; using muduo::net::EventLoop; using muduo::net::InetAddress; using muduo::net::TcpServer; using muduo::net::TcpConnectionPtr; using muduo::net::Buffer; class EchoTcpServer { public: EchoTcpServer(EventLoop* loop, const InetAddress& addr) : server_(loop, addr, "EchoTcpServer") { server_.setConnectionCallback(std::bind(&EchoTcpServer::onConnection, this, _1)); server_.setMessageCallback(std::bind(&EchoTcpServer::onMessage, this, _1, _2, _3)); } void start() { server_.start(); } private: void onConnection(const TcpConnectionPtr& conn) { } void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) { muduo::string msg(buf->retrieveAllAsString()); conn->send(msg); } TcpServer server_; }; int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int port = atoi(argv[1]); muduo::g_logLevel = muduo::Logger::ERROR; muduo::net::EventLoop loop; muduo::net::InetAddress addr(port); EchoTcpServer server(&loop, addr); server.start(); loop.loop(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/pingpong_client.cpp000066400000000000000000000076051520575453600317450ustar00rootroot00000000000000#include "hv/hmain.h" // import parse_opt #include "hv/hloop.h" #include "hv/hsocket.h" #include "hv/EventLoopThreadPool.h" using namespace hv; static const char options[] = "hvH:p:c:d:t:b:"; static const char detail_options[] = R"( -h Print help infomation -v Show verbose infomation -H default 127.0.0.1 -p -c Number of connections, default: 1000 -d Duration of test, default: 10s -t Number of threads, default: 4 -b Bytes of send buffer, default: 4096 )"; static int connections = 1000; static int duration = 10; static int threads = 4; static bool verbose = false; static const char* host = "127.0.0.1"; static int port = 0; static int sendbytes = 4096; static void* sendbuf = NULL; static std::atomic connected_num(0); static std::atomic disconnected_num(0); static std::atomic total_readcount(0); static std::atomic total_readbytes(0); static void print_help() { printf("Usage: %s [%s]\n", g_main_ctx.program_name, options); printf("Options:\n%s\n", detail_options); } static void print_cmd() { printf("Running %ds test @ %s:%d\n", duration, host, port); printf("%d threads and %d connections, send %d bytes each time\n", threads, connections, sendbytes); } static void print_result() { printf("total readcount=%llu readbytes=%llu\n", (unsigned long long)total_readcount, (unsigned long long)total_readbytes); printf("throughput = %llu MB/s\n", (total_readbytes) / ((unsigned long long)duration * 1024 * 1024)); } static void on_close(hio_t* io) { if (++disconnected_num == connections) { if (verbose) { printf("all disconnected\n"); } } } static void on_recv(hio_t* io, void* buf, int readbytes) { ++total_readcount; total_readbytes += readbytes; hio_write(io, buf, readbytes); } static void on_connect(hio_t* io) { if (++connected_num == connections) { if (verbose) { printf("all connected\n"); } } hio_write(io, sendbuf, sendbytes); hio_setcb_read(io, on_recv); hio_read_start(io); } static void start_connect(hloop_t* loop) { hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (io == NULL) { perror("socket"); exit(1); } tcp_nodelay(hio_fd(io), 1); hio_setcb_connect(io, on_connect); hio_setcb_close(io, on_close); hio_connect(io); } int main(int argc, char** argv) { // parse cmdline main_ctx_init(argc, argv); int ret = parse_opt(argc, argv, options); if (ret != 0) { print_help(); exit(ret); } const char* strHost = get_arg("H"); const char* strPort = get_arg("p"); const char* strConnections = get_arg("c"); const char* strDuration = get_arg("d"); const char* strThreads = get_arg("t"); const char* strBytes = get_arg("b"); if (strHost) host = strHost; if (strPort) port = atoi(strPort); if (strConnections) connections = atoi(strConnections); if (strDuration) duration = atoi(strDuration); if (strThreads) threads = atoi(strThreads); if (strBytes) sendbytes = atoi(strBytes); if (get_arg("h") || port == 0) { print_help(); exit(0); } if (get_arg("v")) { verbose = true; } sendbuf = malloc(sendbytes); print_cmd(); EventLoopThreadPool loop_threads(threads); loop_threads.start(true); for (int i = 0; i < connections; ++i) { EventLoopPtr loop = loop_threads.nextLoop(); loop->runInLoop(std::bind(start_connect, loop->loop())); } // stop after seconds loop_threads.loop()->setTimeout(duration * 1000, [&loop_threads](TimerID timerID){ loop_threads.stop(false); }); // wait loop_threads exit loop_threads.join(); print_result(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/echo-servers/poco_echo.cpp000066400000000000000000000162051520575453600305200ustar00rootroot00000000000000// // EchoServer.cpp // // $Id: //poco/1.3/Net/samples/EchoServer/src/EchoServer.cpp#1 $ // // This sample demonstrates the SocketReactor and SocketAcceptor classes. // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Net/SocketReactor.h" #include "Poco/Net/SocketAcceptor.h" #include "Poco/Net/SocketNotification.h" #include "Poco/Net/StreamSocket.h" #include "Poco/Net/ServerSocket.h" #include "Poco/NObserver.h" #include "Poco/Exception.h" #include "Poco/Thread.h" #include "Poco/Util/ServerApplication.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionSet.h" #include "Poco/Util/HelpFormatter.h" #include using Poco::Net::SocketReactor; using Poco::Net::SocketAcceptor; using Poco::Net::ReadableNotification; using Poco::Net::ShutdownNotification; using Poco::Net::ServerSocket; using Poco::Net::StreamSocket; using Poco::NObserver; using Poco::AutoPtr; using Poco::Thread; using Poco::Util::ServerApplication; using Poco::Util::Application; using Poco::Util::Option; using Poco::Util::OptionSet; using Poco::Util::HelpFormatter; class EchoServiceHandler { public: EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): _socket(socket), _reactor(reactor), _pBuffer(new char[BUFFER_SIZE]) { // Application& app = Application::instance(); // app.logger().information("Connection from " + socket.peerAddress().toString()); _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); } ~EchoServiceHandler() { // Application& app = Application::instance(); // app.logger().information("Disconnecting " + _socket.peerAddress().toString()); _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); delete [] _pBuffer; } void onReadable(const AutoPtr& pNf) { int n = _socket.receiveBytes(_pBuffer, BUFFER_SIZE); if (n > 0) _socket.sendBytes(_pBuffer, n); else delete this; } void onShutdown(const AutoPtr& pNf) { delete this; } private: enum { BUFFER_SIZE = 1024 }; StreamSocket _socket; SocketReactor& _reactor; char* _pBuffer; }; class EchoServer: public Poco::Util::ServerApplication /// The main application class. /// /// This class handles command-line arguments and /// configuration files. /// Start the EchoServer executable with the help /// option (/help on Windows, --help on Unix) for /// the available command line options. /// /// To use the sample configuration file (EchoServer.properties), /// copy the file to the directory where the EchoServer executable /// resides. If you start the debug version of the EchoServer /// (EchoServerd[.exe]), you must also create a copy of the configuration /// file named EchoServerd.properties. In the configuration file, you /// can specify the port on which the server is listening (default /// 9977) and the format of the date/time string sent back to the client. /// /// To test the EchoServer you can use any telnet client (telnet localhost 9977). { public: EchoServer(): _helpRequested(false) { } ~EchoServer() { } protected: void initialize(Application& self) { loadConfiguration(); // load default configuration files, if present ServerApplication::initialize(self); } void uninitialize() { ServerApplication::uninitialize(); } void defineOptions(OptionSet& options) { ServerApplication::defineOptions(options); options.addOption( Option("help", "h", "display help information on command line arguments") .required(false) .repeatable(false)); } void handleOption(const std::string& name, const std::string& value) { ServerApplication::handleOption(name, value); if (name == "help") _helpRequested = true; } void displayHelp() { HelpFormatter helpFormatter(options()); helpFormatter.setCommand(commandName()); helpFormatter.setUsage("OPTIONS"); helpFormatter.setHeader("An echo server implemented using the Reactor and Acceptor patterns."); helpFormatter.format(std::cout); } int main(const std::vector& args) { if (_helpRequested) { displayHelp(); } else { if (args.size() < 1) { printf("Usage: cmd port\n"); return -10; } int port = atoi(args[0].c_str()); // set-up a server socket ServerSocket svs(port); // set-up a SocketReactor... SocketReactor reactor; // ... and a SocketAcceptor SocketAcceptor acceptor(svs, reactor); // run the reactor in its own thread so that we can wait for // a termination request Thread thread; thread.start(reactor); // wait for CTRL-C or kill waitForTerminationRequest(); // Stop the SocketReactor reactor.stop(); thread.join(); } return Application::EXIT_OK; } private: bool _helpRequested; }; int main(int argc, char** argv) { EchoServer app; return app.run(argc, argv); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/etc/000077500000000000000000000000001520575453600242205ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/etc/hmain_test.conf000066400000000000000000000003671520575453600272300ustar00rootroot00000000000000# [root] # logfile = logs/test.log # loglevel = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] loglevel = DEBUG log_remain_days = 3 log_filesize = 16M # worker_processes = auto # auto = ncpu worker_processes = auto worker_threads = 2 port = 8086 kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/etc/httpd.conf000066400000000000000000000022231520575453600262110ustar00rootroot00000000000000# [root] # logfile = logs/httpd.log # loglevel = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] loglevel = INFO log_remain_days = 3 log_filesize = 64M # multi-processes mode # auto = ncpu worker_processes = auto worker_threads = 1 # multi-threads mode # worker_processes = 1 # worker_threads = auto # Disable multi-processes mode for debugging # worker_processes = 0 # max_connections = workers * worker_connections worker_connections = 1024 # http server http_port = 8080 https_port = 8443 #base_url = /api/v1 document_root = html home_page = index.html #error_page = error.html index_of = /downloads/ keepalive_timeout = 75000 # ms limit_rate = 500 # KB/s access_log = off cors = true # SSL/TLS ssl_certificate = cert/server.crt ssl_privatekey = cert/server.key ssl_ca_certificate = cert/cacert.pem # proxy [proxy] proxy_connect_timeout = 10000 # ms proxy_read_timeout = 60000 # ms proxy_write_timeout = 60000 # ms # forward proxy forward_proxy = true trust_proxies = *httpbin.org;*postman-echo.com;*apifox.com #no_proxies = * # reverse proxy /httpbin/ => http://httpbin.org/ /postman/ => http://postman-echo.com/ /apifox/ => https://echo.apifox.com/ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/etc/nginx.conf000066400000000000000000000012661520575453600262170ustar00rootroot00000000000000# cd libhv # sudo nginx -p . -c etc/nginx.conf # bin/httpd -c etc/httpd.conf -s restart -d # bin/curl -v http://127.0.0.1/api/v1/get worker_processes auto; pid logs/nginx.pid; error_log logs/error.log; events { worker_connections 1024; } http { access_log logs/access.log; server { listen 80; # static files service location / { root html; index index.html; } # autoindex service location /downloads/ { autoindex on; } # api service: nginx => libhv location /api/v1/ { proxy_pass http://127.0.0.1:8080/; } } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/000077500000000000000000000000001520575453600245665ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/README.md000066400000000000000000000012111520575453600260400ustar00rootroot00000000000000## 目录结构 ``` . ├── hloop.h 事件循环模块对外头文件 ├── hevent.h 事件结构体定义 ├── nlog.h 网络日志 ├── unpack.h 拆包 ├── rudp.h 可靠UDP ├── iowatcher.h IO多路复用统一抽象接口 ├── select.c EVENT_SELECT实现 ├── poll.c EVENT_POLL实现 ├── epoll.c EVENT_EPOLL实现 (for OS_LINUX) ├── iocp.c EVENT_IOCP实现 (for OS_WIN) ├── kqueue.c EVENT_KQUEUE实现(for OS_BSD/OS_MAC) ├── evport.c EVENT_PORT实现 (for OS_SOLARIS) ├── nio.c 非阻塞IO └── overlapio.c 重叠IO ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/epoll.c000066400000000000000000000075241520575453600260550ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_EPOLL #include "hplatform.h" #include "hdef.h" #include "hevent.h" #ifdef OS_WIN #include "wepoll/wepoll.h" typedef HANDLE epoll_handle_t; #else #include typedef int epoll_handle_t; #define epoll_close(epfd) close(epfd) #endif #include "array.h" #define EVENTS_INIT_SIZE 64 ARRAY_DECL(struct epoll_event, events); typedef struct epoll_ctx_s { epoll_handle_t epfd; struct events events; } epoll_ctx_t; int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; epoll_ctx_t* epoll_ctx; HV_ALLOC_SIZEOF(epoll_ctx); epoll_ctx->epfd = epoll_create(EVENTS_INIT_SIZE); events_init(&epoll_ctx->events, EVENTS_INIT_SIZE); loop->iowatcher = epoll_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { if (loop->iowatcher == NULL) return 0; epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; epoll_close(epoll_ctx->epfd); events_cleanup(&epoll_ctx->events); HV_FREE(loop->iowatcher); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; hio_t* io = loop->ios.ptr[fd]; struct epoll_event ee; memset(&ee, 0, sizeof(ee)); ee.data.fd = fd; // pre events if (io->events & HV_READ) { ee.events |= EPOLLIN; } if (io->events & HV_WRITE) { ee.events |= EPOLLOUT; } // now events if (events & HV_READ) { ee.events |= EPOLLIN; } if (events & HV_WRITE) { ee.events |= EPOLLOUT; } int op = io->events == 0 ? EPOLL_CTL_ADD : EPOLL_CTL_MOD; epoll_ctl(epoll_ctx->epfd, op, fd, &ee); if (op == EPOLL_CTL_ADD) { if (epoll_ctx->events.size == epoll_ctx->events.maxsize) { events_double_resize(&epoll_ctx->events); } epoll_ctx->events.size++; } return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; if (epoll_ctx == NULL) return 0; hio_t* io = loop->ios.ptr[fd]; struct epoll_event ee; memset(&ee, 0, sizeof(ee)); ee.data.fd = fd; // pre events if (io->events & HV_READ) { ee.events |= EPOLLIN; } if (io->events & HV_WRITE) { ee.events |= EPOLLOUT; } // now events if (events & HV_READ) { ee.events &= ~EPOLLIN; } if (events & HV_WRITE) { ee.events &= ~EPOLLOUT; } int op = ee.events == 0 ? EPOLL_CTL_DEL : EPOLL_CTL_MOD; epoll_ctl(epoll_ctx->epfd, op, fd, &ee); if (op == EPOLL_CTL_DEL) { epoll_ctx->events.size--; } return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; if (epoll_ctx == NULL) return 0; if (epoll_ctx->events.size == 0) return 0; int nepoll = epoll_wait(epoll_ctx->epfd, epoll_ctx->events.ptr, epoll_ctx->events.size, timeout); if (nepoll < 0) { if (errno == EINTR) { return 0; } perror("epoll"); return nepoll; } if (nepoll == 0) return 0; int nevents = 0; for (int i = 0; i < epoll_ctx->events.size; ++i) { struct epoll_event* ee = epoll_ctx->events.ptr + i; int fd = ee->data.fd; uint32_t revents = ee->events; if (revents) { ++nevents; hio_t* io = loop->ios.ptr[fd]; if (io) { if (revents & (EPOLLIN | EPOLLHUP | EPOLLERR)) { io->revents |= HV_READ; } if (revents & (EPOLLOUT | EPOLLHUP | EPOLLERR)) { io->revents |= HV_WRITE; } EVENT_PENDING(io); } } if (nevents == nepoll) break; } return nevents; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/evport.c000066400000000000000000000074671520575453600262670ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_PORT #include "hplatform.h" #include "hdef.h" #include "hevent.h" #include #define EVENTS_INIT_SIZE 64 typedef struct evport_ctx_s { int port; int capacity; int nevents; port_event_t* events; } evport_ctx_t; static void evport_ctx_resize(evport_ctx_t* evport_ctx, int size) { int bytes = sizeof(port_event_t) * size; int oldbytes = sizeof(port_event_t) * evport_ctx->capacity; evport_ctx->events = (port_event_t*)hv_realloc(evport_ctx->events, bytes, oldbytes); evport_ctx->capacity = size; } int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; evport_ctx_t* evport_ctx; HV_ALLOC_SIZEOF(evport_ctx); evport_ctx->port = port_create(); evport_ctx->capacity = EVENTS_INIT_SIZE; evport_ctx->nevents = 0; int bytes = sizeof(port_event_t) * evport_ctx->capacity; HV_ALLOC(evport_ctx->events, bytes); loop->iowatcher = evport_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { if (loop->iowatcher == NULL) return 0; evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; close(evport_ctx->port); HV_FREE(evport_ctx->events); HV_FREE(loop->iowatcher); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; hio_t* io = loop->ios.ptr[fd]; int evport_events = 0; if (io->events & HV_READ) { evport_events |= POLLIN; } if (io->events & HV_WRITE) { evport_events |= POLLOUT; } if (events & HV_READ) { evport_events |= POLLIN; } if (events & HV_WRITE) { evport_events |= POLLOUT; } port_associate(evport_ctx->port, PORT_SOURCE_FD, fd, evport_events, NULL); if (io->events == 0) { if (evport_ctx->nevents == evport_ctx->capacity) { evport_ctx_resize(evport_ctx, evport_ctx->capacity * 2); } ++evport_ctx->nevents; } return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; if (evport_ctx == NULL) return 0; hio_t* io = loop->ios.ptr[fd]; int evport_events = 0; if (io->events & HV_READ) { evport_events |= POLLIN; } if (io->events & HV_WRITE) { evport_events |= POLLOUT; } if (events & HV_READ) { evport_events &= ~POLLIN; } if (events & HV_WRITE) { evport_events &= ~POLLOUT; } if (evport_events == 0) { port_dissociate(evport_ctx->port, PORT_SOURCE_FD, fd); --evport_ctx->nevents; } else { port_associate(evport_ctx->port, PORT_SOURCE_FD, fd, evport_events, NULL); } return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; if (evport_ctx == NULL) return 0; struct timespec ts, *tp; if (timeout == INFINITE) { tp = NULL; } else { ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; tp = &ts; } unsigned nevents = 1; port_getn(evport_ctx->port, evport_ctx->events, evport_ctx->capacity, &nevents, tp); for (int i = 0; i < nevents; ++i) { int fd = evport_ctx->events[i].portev_object; int revents = evport_ctx->events[i].portev_events; hio_t* io = loop->ios.ptr[fd]; if (io) { if (revents & POLLIN) { io->revents |= HV_READ; } if (revents & POLLOUT) { io->revents |= HV_WRITE; } EVENT_PENDING(io); } // Upon retrieval, the event object is no longer associated with the port. iowatcher_add_event(loop, fd, io->events); } return nevents; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/hevent.c000066400000000000000000000640161520575453600262320ustar00rootroot00000000000000#include "hevent.h" #include "hsocket.h" #include "hatomic.h" #include "hlog.h" #include "herr.h" #include "unpack.h" uint64_t hloop_next_event_id() { static hatomic_t s_id = HATOMIC_VAR_INIT(0); return ++s_id; } uint32_t hio_next_id() { static hatomic_t s_id = HATOMIC_VAR_INIT(0); return ++s_id; } static void fill_io_type(hio_t* io) { int type = 0; socklen_t optlen = sizeof(int); int ret = getsockopt(io->fd, SOL_SOCKET, SO_TYPE, (char*)&type, &optlen); printd("getsockopt SO_TYPE fd=%d ret=%d type=%d errno=%d\n", io->fd, ret, type, socket_errno()); if (ret == 0) { switch (type) { case SOCK_STREAM: io->io_type = HIO_TYPE_TCP; break; case SOCK_DGRAM: io->io_type = HIO_TYPE_UDP; break; case SOCK_RAW: io->io_type = HIO_TYPE_IP; break; default: io->io_type = HIO_TYPE_SOCKET; break; } } else if (socket_errno() == ENOTSOCK) { switch (io->fd) { case 0: io->io_type = HIO_TYPE_STDIN; break; case 1: io->io_type = HIO_TYPE_STDOUT; break; case 2: io->io_type = HIO_TYPE_STDERR; break; default: io->io_type = HIO_TYPE_FILE; break; } } else { io->io_type = HIO_TYPE_TCP; } } static void hio_socket_init(hio_t* io) { if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { // NOTE: sendto multiple peeraddr cannot use io->write_queue blocking(io->fd); } else { nonblocking(io->fd); } // fill io->localaddr io->peeraddr if (io->localaddr == NULL) { HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); } if (io->peeraddr == NULL) { HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); } socklen_t addrlen = sizeof(sockaddr_u); int ret = getsockname(io->fd, io->localaddr, &addrlen); printd("getsockname fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno()); // NOTE: udp peeraddr set by recvfrom/sendto if (io->io_type & HIO_TYPE_SOCK_STREAM) { addrlen = sizeof(sockaddr_u); ret = getpeername(io->fd, io->peeraddr, &addrlen); printd("getpeername fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno()); } } void hio_init(hio_t* io) { // alloc localaddr,peeraddr when hio_socket_init /* if (io->localaddr == NULL) { HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); } if (io->peeraddr == NULL) { HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); } */ // write_queue init when hwrite try_write failed // write_queue_init(&io->write_queue, 4); hrecursive_mutex_init(&io->write_mutex); } void hio_ready(hio_t* io) { if (io->ready) return; // flags io->ready = 1; io->connected = 0; io->closed = 0; io->accept = io->connect = io->connectex = 0; io->recv = io->send = 0; io->recvfrom = io->sendto = 0; io->close = 0; // public: io->id = hio_next_id(); io->io_type = HIO_TYPE_UNKNOWN; io->error = 0; io->events = io->revents = 0; io->last_read_hrtime = io->last_write_hrtime = io->loop->cur_hrtime; // readbuf io->alloced_readbuf = 0; hio_use_loop_readbuf(io); io->readbuf.head = io->readbuf.tail = 0; io->read_flags = 0; io->read_until_length = 0; io->max_read_bufsize = MAX_READ_BUFSIZE; io->small_readbytes_cnt = 0; // write_queue io->write_bufsize = 0; io->max_write_bufsize = MAX_WRITE_BUFSIZE; // callbacks io->read_cb = NULL; io->write_cb = NULL; io->close_cb = NULL; io->accept_cb = NULL; io->connect_cb = NULL; // timers io->connect_timeout = 0; io->connect_timer = NULL; io->close_timeout = 0; io->close_timer = NULL; io->read_timeout = 0; io->read_timer = NULL; io->write_timeout = 0; io->write_timer = NULL; io->keepalive_timeout = 0; io->keepalive_timer = NULL; io->heartbeat_interval = 0; io->heartbeat_fn = NULL; io->heartbeat_timer = NULL; // upstream io->upstream_io = NULL; // unpack io->unpack_setting = NULL; // ssl io->ssl = NULL; io->ssl_ctx = NULL; io->alloced_ssl_ctx = 0; io->hostname = NULL; // context io->ctx = NULL; // private: #if defined(EVENT_POLL) || defined(EVENT_KQUEUE) io->event_index[0] = io->event_index[1] = -1; #endif #ifdef EVENT_IOCP io->hovlp = NULL; #endif // io_type fill_io_type(io); if (io->io_type & HIO_TYPE_SOCKET) { hio_socket_init(io); } #if WITH_RUDP if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { rudp_init(&io->rudp); } #endif } void hio_done(hio_t* io) { if (!io->ready) return; io->ready = 0; hio_del(io, HV_RDWR); // readbuf hio_free_readbuf(io); // write_queue offset_buf_t* pbuf = NULL; hrecursive_mutex_lock(&io->write_mutex); while (!write_queue_empty(&io->write_queue)) { pbuf = write_queue_front(&io->write_queue); HV_FREE(pbuf->base); write_queue_pop_front(&io->write_queue); } write_queue_cleanup(&io->write_queue); hrecursive_mutex_unlock(&io->write_mutex); #if WITH_RUDP if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { rudp_cleanup(&io->rudp); } #endif } void hio_free(hio_t* io) { if (io == NULL || io->destroy) return; io->destroy = 1; hio_close(io); hrecursive_mutex_destroy(&io->write_mutex); HV_FREE(io->localaddr); HV_FREE(io->peeraddr); HV_FREE(io); } bool hio_is_opened(hio_t* io) { if (io == NULL) return false; return io->ready == 1 && io->closed == 0; } bool hio_is_connected(hio_t* io) { if (io == NULL) return false; return io->ready == 1 && io->connected == 1 && io->closed == 0; } bool hio_is_closed(hio_t* io) { if (io == NULL) return true; return io->ready == 0 && io->closed == 1; } uint32_t hio_id (hio_t* io) { return io->id; } int hio_fd(hio_t* io) { return io->fd; } hio_type_e hio_type(hio_t* io) { return io->io_type; } int hio_error(hio_t* io) { return io->error; } int hio_events(hio_t* io) { return io->events; } int hio_revents(hio_t* io) { return io->revents; } struct sockaddr* hio_localaddr(hio_t* io) { return io->localaddr; } struct sockaddr* hio_peeraddr(hio_t* io) { return io->peeraddr; } void hio_set_context(hio_t* io, void* ctx) { io->ctx = ctx; } void* hio_context(hio_t* io) { return io->ctx; } haccept_cb hio_getcb_accept(hio_t* io) { return io->accept_cb; } hconnect_cb hio_getcb_connect(hio_t* io) { return io->connect_cb; } hread_cb hio_getcb_read(hio_t* io) { return io->read_cb; } hwrite_cb hio_getcb_write(hio_t* io) { return io->write_cb; } hclose_cb hio_getcb_close(hio_t* io) { return io->close_cb; } void hio_setcb_accept(hio_t* io, haccept_cb accept_cb) { io->accept_cb = accept_cb; } void hio_setcb_connect(hio_t* io, hconnect_cb connect_cb) { io->connect_cb = connect_cb; } void hio_setcb_read(hio_t* io, hread_cb read_cb) { io->read_cb = read_cb; } void hio_setcb_write(hio_t* io, hwrite_cb write_cb) { io->write_cb = write_cb; } void hio_setcb_close(hio_t* io, hclose_cb close_cb) { io->close_cb = close_cb; } void hio_accept_cb(hio_t* io) { /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("accept connfd=%d [%s] <= [%s]\n", io->fd, SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); */ if (io->accept_cb) { // printd("accept_cb------\n"); io->accept_cb(io); // printd("accept_cb======\n"); } } void hio_connect_cb(hio_t* io) { /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("connect connfd=%d [%s] => [%s]\n", io->fd, SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); */ io->connected = 1; if (io->connect_cb) { // printd("connect_cb------\n"); io->connect_cb(io); // printd("connect_cb======\n"); } } void hio_handle_read(hio_t* io, void* buf, int readbytes) { #if WITH_KCP if (io->io_type == HIO_TYPE_KCP) { hio_read_kcp(io, buf, readbytes); io->readbuf.head = io->readbuf.tail = 0; return; } #endif if (io->unpack_setting) { // hio_set_unpack hio_unpack(io, buf, readbytes); } else { const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; const unsigned char* ep = (const unsigned char*)buf + readbytes; if (io->read_flags & HIO_READ_UNTIL_LENGTH) { // hio_read_until_length if (ep - sp >= io->read_until_length) { io->readbuf.head += io->read_until_length; if (io->readbuf.head == io->readbuf.tail) { io->readbuf.head = io->readbuf.tail = 0; } io->read_flags &= ~HIO_READ_UNTIL_LENGTH; hio_read_cb(io, (void*)sp, io->read_until_length); } } else if (io->read_flags & HIO_READ_UNTIL_DELIM) { // hio_read_until_delim const unsigned char* p = (const unsigned char*)buf; for (int i = 0; i < readbytes; ++i, ++p) { if (*p == io->read_until_delim) { int len = p - sp + 1; io->readbuf.head += len; if (io->readbuf.head == io->readbuf.tail) { io->readbuf.head = io->readbuf.tail = 0; } io->read_flags &= ~HIO_READ_UNTIL_DELIM; hio_read_cb(io, (void*)sp, len); return; } } } else { // hio_read io->readbuf.head = io->readbuf.tail = 0; hio_read_cb(io, (void*)sp, ep - sp); } } if (io->readbuf.head == io->readbuf.tail) { io->readbuf.head = io->readbuf.tail = 0; } // readbuf autosize if (io->readbuf.tail == io->readbuf.len) { if (io->readbuf.head == 0) { // scale up * 2 hio_alloc_readbuf(io, io->readbuf.len * 2); } else { hio_memmove_readbuf(io); } } else { size_t small_size = io->readbuf.len / 2; if (io->readbuf.tail < small_size && io->small_readbytes_cnt >= 3) { // scale down / 2 hio_alloc_readbuf(io, small_size); } } } void hio_read_cb(hio_t* io, void* buf, int len) { if (io->read_flags & HIO_READ_ONCE) { io->read_flags &= ~HIO_READ_ONCE; hio_read_stop(io); } if (io->read_cb && !io->closed) { // printd("read_cb------\n"); io->read_cb(io, buf, len); // printd("read_cb======\n"); } // for readbuf autosize if (hio_is_alloced_readbuf(io) && io->readbuf.len > READ_BUFSIZE_HIGH_WATER) { size_t small_size = io->readbuf.len / 2; if (len < small_size) { ++io->small_readbytes_cnt; } else { io->small_readbytes_cnt = 0; } } } void hio_write_cb(hio_t* io, const void* buf, int len) { if (io->write_cb && !io->closed) { // printd("write_cb------\n"); io->write_cb(io, buf, len); // printd("write_cb======\n"); } } void hio_close_cb(hio_t* io) { io->connected = 0; io->closed = 1; if (io->close_cb) { // printd("close_cb------\n"); io->close_cb(io); // printd("close_cb======\n"); } } void hio_set_type(hio_t* io, hio_type_e type) { io->io_type = type; } void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen) { if (io->localaddr == NULL) { HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); } memcpy(io->localaddr, addr, addrlen); } void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen) { if (io->peeraddr == NULL) { HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); } memcpy(io->peeraddr, addr, addrlen); } int hio_enable_ssl(hio_t* io) { io->io_type = HIO_TYPE_SSL; return 0; } bool hio_is_ssl(hio_t* io) { return io->io_type == HIO_TYPE_SSL; } hssl_t hio_get_ssl(hio_t* io) { return io->ssl; } hssl_ctx_t hio_get_ssl_ctx(hio_t* io) { return io->ssl_ctx; } int hio_set_ssl(hio_t* io, hssl_t ssl) { io->io_type = HIO_TYPE_SSL; io->ssl = ssl; return 0; } int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx) { io->io_type = HIO_TYPE_SSL; io->ssl_ctx = ssl_ctx; return 0; } int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt) { hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; io->alloced_ssl_ctx = 1; return hio_set_ssl_ctx(io, ssl_ctx); } int hio_set_hostname(hio_t* io, const char* hostname) { SAFE_FREE(io->hostname); io->hostname = strdup(hostname); return 0; } const char* hio_get_hostname(hio_t* io) { return io->hostname; } void hio_del_connect_timer(hio_t* io) { if (io->connect_timer) { htimer_del(io->connect_timer); io->connect_timer = NULL; io->connect_timeout = 0; } } void hio_del_close_timer(hio_t* io) { if (io->close_timer) { htimer_del(io->close_timer); io->close_timer = NULL; io->close_timeout = 0; } } void hio_del_read_timer(hio_t* io) { if (io->read_timer) { htimer_del(io->read_timer); io->read_timer = NULL; io->read_timeout = 0; } } void hio_del_write_timer(hio_t* io) { if (io->write_timer) { htimer_del(io->write_timer); io->write_timer = NULL; io->write_timeout = 0; } } void hio_del_keepalive_timer(hio_t* io) { if (io->keepalive_timer) { htimer_del(io->keepalive_timer); io->keepalive_timer = NULL; io->keepalive_timeout = 0; } } void hio_del_heartbeat_timer(hio_t* io) { if (io->heartbeat_timer) { htimer_del(io->heartbeat_timer); io->heartbeat_timer = NULL; io->heartbeat_interval = 0; io->heartbeat_fn = NULL; } } void hio_set_connect_timeout(hio_t* io, int timeout_ms) { io->connect_timeout = timeout_ms; } void hio_set_close_timeout(hio_t* io, int timeout_ms) { io->close_timeout = timeout_ms; } static void __read_timeout_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; uint64_t inactive_ms = (io->loop->cur_hrtime - io->last_read_hrtime) / 1000; if (inactive_ms + 100 < io->read_timeout) { htimer_reset(io->read_timer, io->read_timeout - inactive_ms); } else { if (io->io_type & HIO_TYPE_SOCKET) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("read timeout [%s] <=> [%s]", SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); } io->error = ETIMEDOUT; hio_close(io); } } void hio_set_read_timeout(hio_t* io, int timeout_ms) { if (timeout_ms <= 0) { // del hio_del_read_timer(io); return; } if (io->read_timer) { // reset htimer_reset(io->read_timer, timeout_ms); } else { // add io->read_timer = htimer_add(io->loop, __read_timeout_cb, timeout_ms, 1); io->read_timer->privdata = io; } io->read_timeout = timeout_ms; } static void __write_timeout_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; uint64_t inactive_ms = (io->loop->cur_hrtime - io->last_write_hrtime) / 1000; if (inactive_ms + 100 < io->write_timeout) { htimer_reset(io->write_timer, io->write_timeout - inactive_ms); } else { if (io->io_type & HIO_TYPE_SOCKET) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("write timeout [%s] <=> [%s]", SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); } io->error = ETIMEDOUT; hio_close(io); } } void hio_set_write_timeout(hio_t* io, int timeout_ms) { if (timeout_ms <= 0) { // del hio_del_write_timer(io); return; } if (io->write_timer) { // reset htimer_reset(io->write_timer, timeout_ms); } else { // add io->write_timer = htimer_add(io->loop, __write_timeout_cb, timeout_ms, 1); io->write_timer->privdata = io; } io->write_timeout = timeout_ms; } static void __keepalive_timeout_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; uint64_t last_rw_hrtime = MAX(io->last_read_hrtime, io->last_write_hrtime); uint64_t inactive_ms = (io->loop->cur_hrtime - last_rw_hrtime) / 1000; if (inactive_ms + 100 < io->keepalive_timeout) { htimer_reset(io->keepalive_timer, io->keepalive_timeout - inactive_ms); } else { if (io->io_type & HIO_TYPE_SOCKET) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("keepalive timeout [%s] <=> [%s]", SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); } io->error = ETIMEDOUT; hio_close(io); } } void hio_set_keepalive_timeout(hio_t* io, int timeout_ms) { if (timeout_ms <= 0) { // del hio_del_keepalive_timer(io); return; } if (io->keepalive_timer) { // reset htimer_reset(io->keepalive_timer, timeout_ms); } else { // add io->keepalive_timer = htimer_add(io->loop, __keepalive_timeout_cb, timeout_ms, 1); io->keepalive_timer->privdata = io; } io->keepalive_timeout = timeout_ms; } static void __heartbeat_timer_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; if (io && io->heartbeat_fn) { io->heartbeat_fn(io); } } void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn) { if (interval_ms <= 0) { // del hio_del_heartbeat_timer(io); return; } if (io->heartbeat_timer) { // reset htimer_reset(io->heartbeat_timer, interval_ms); } else { // add io->heartbeat_timer = htimer_add(io->loop, __heartbeat_timer_cb, interval_ms, INFINITE); io->heartbeat_timer->privdata = io; } io->heartbeat_interval = interval_ms; io->heartbeat_fn = fn; } //-----------------iobuf--------------------------------------------- void hio_alloc_readbuf(hio_t* io, int len) { if (len > io->max_read_bufsize) { hloge("read bufsize > %u, close it!", io->max_read_bufsize); io->error = ERR_OVER_LIMIT; hio_close_async(io); return; } if (hio_is_alloced_readbuf(io)) { io->readbuf.base = (char*)hv_realloc(io->readbuf.base, len, io->readbuf.len); } else { HV_ALLOC(io->readbuf.base, len); } io->readbuf.len = len; io->alloced_readbuf = 1; io->small_readbytes_cnt = 0; } void hio_free_readbuf(hio_t* io) { if (hio_is_alloced_readbuf(io)) { HV_FREE(io->readbuf.base); io->alloced_readbuf = 0; // reset to loop->readbuf io->readbuf.base = io->loop->readbuf.base; io->readbuf.len = io->loop->readbuf.len; } } void hio_memmove_readbuf(hio_t* io) { fifo_buf_t* buf = &io->readbuf; if (buf->tail == buf->head) { buf->head = buf->tail = 0; return; } if (buf->tail > buf->head) { size_t size = buf->tail - buf->head; // [head, tail] => [0, tail - head] memmove(buf->base, buf->base + buf->head, size); buf->head = 0; buf->tail = size; } } void hio_set_readbuf(hio_t* io, void* buf, size_t len) { assert(io && buf && len != 0); hio_free_readbuf(io); io->readbuf.base = (char*)buf; io->readbuf.len = len; io->readbuf.head = io->readbuf.tail = 0; io->alloced_readbuf = 0; } hio_readbuf_t* hio_get_readbuf(hio_t* io) { return &io->readbuf; } void hio_set_max_read_bufsize (hio_t* io, uint32_t size) { io->max_read_bufsize = size; } void hio_set_max_write_bufsize(hio_t* io, uint32_t size) { io->max_write_bufsize = size; } size_t hio_write_bufsize(hio_t* io) { return io->write_bufsize; } int hio_read_once (hio_t* io) { io->read_flags |= HIO_READ_ONCE; return hio_read_start(io); } int hio_read_until_length(hio_t* io, unsigned int len) { if (len == 0) return 0; if (io->readbuf.tail - io->readbuf.head >= len) { void* buf = io->readbuf.base + io->readbuf.head; io->readbuf.head += len; if (io->readbuf.head == io->readbuf.tail) { io->readbuf.head = io->readbuf.tail = 0; } hio_read_cb(io, buf, len); return len; } io->read_flags = HIO_READ_UNTIL_LENGTH; io->read_until_length = len; if (io->readbuf.head > 1024 || io->readbuf.tail - io->readbuf.head < 1024) { hio_memmove_readbuf(io); } // NOTE: prepare readbuf int need_len = io->readbuf.head + len; if (hio_is_loop_readbuf(io) || io->readbuf.len < need_len) { hio_alloc_readbuf(io, need_len); } return hio_read_once(io); } int hio_read_until_delim(hio_t* io, unsigned char delim) { if (io->readbuf.tail - io->readbuf.head > 0) { const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; const unsigned char* ep = (const unsigned char*)io->readbuf.base + io->readbuf.tail; const unsigned char* p = sp; while (p <= ep) { if (*p == delim) { int len = p - sp + 1; io->readbuf.head += len; if (io->readbuf.head == io->readbuf.tail) { io->readbuf.head = io->readbuf.tail = 0; } hio_read_cb(io, (void*)sp, len); return len; } ++p; } } io->read_flags = HIO_READ_UNTIL_DELIM; io->read_until_length = delim; // NOTE: prepare readbuf if (hio_is_loop_readbuf(io) || io->readbuf.len < HLOOP_READ_BUFSIZE) { hio_alloc_readbuf(io, HLOOP_READ_BUFSIZE); } return hio_read_once(io); } int hio_read_remain(hio_t* io) { int remain = io->readbuf.tail - io->readbuf.head; if (remain > 0) { void* buf = io->readbuf.base + io->readbuf.head; io->readbuf.head = io->readbuf.tail = 0; hio_read_cb(io, buf, remain); } return remain; } //-----------------unpack--------------------------------------------- void hio_set_unpack(hio_t* io, unpack_setting_t* setting) { hio_unset_unpack(io); if (setting == NULL) return; io->unpack_setting = setting; if (io->unpack_setting->package_max_length == 0) { io->unpack_setting->package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; } if (io->unpack_setting->mode == UNPACK_BY_FIXED_LENGTH) { assert(io->unpack_setting->fixed_length != 0 && io->unpack_setting->fixed_length <= io->unpack_setting->package_max_length); } else if (io->unpack_setting->mode == UNPACK_BY_DELIMITER) { if (io->unpack_setting->delimiter_bytes == 0) { io->unpack_setting->delimiter_bytes = strlen((char*)io->unpack_setting->delimiter); } } else if (io->unpack_setting->mode == UNPACK_BY_LENGTH_FIELD) { assert(io->unpack_setting->body_offset >= io->unpack_setting->length_field_offset + io->unpack_setting->length_field_bytes); } // NOTE: unpack must have own readbuf if (io->unpack_setting->mode == UNPACK_BY_FIXED_LENGTH) { io->readbuf.len = io->unpack_setting->fixed_length; } else { io->readbuf.len = MIN(HLOOP_READ_BUFSIZE, io->unpack_setting->package_max_length); } io->max_read_bufsize = io->unpack_setting->package_max_length; hio_alloc_readbuf(io, io->readbuf.len); } void hio_unset_unpack(hio_t* io) { if (io->unpack_setting) { io->unpack_setting = NULL; // NOTE: unpack has own readbuf hio_free_readbuf(io); } } //-----------------upstream--------------------------------------------- void hio_read_upstream(hio_t* io) { hio_t* upstream_io = io->upstream_io; if (upstream_io) { hio_read(io); hio_read(upstream_io); } } void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes) { hio_t* upstream_io = io->upstream_io; if (upstream_io && hio_write_is_complete(io)) { hio_setcb_write(io, NULL); hio_read(upstream_io); } } void hio_write_upstream(hio_t* io, void* buf, int bytes) { hio_t* upstream_io = io->upstream_io; if (upstream_io) { int nwrite = hio_write(upstream_io, buf, bytes); // if (!hio_write_is_complete(upstream_io)) { if (nwrite >= 0 && nwrite < bytes) { hio_read_stop(io); hio_setcb_write(upstream_io, hio_read_upstream_on_write_complete); } } } void hio_close_upstream(hio_t* io) { hio_t* upstream_io = io->upstream_io; if (upstream_io) { hio_close(upstream_io); } } void hio_setup_upstream(hio_t* io1, hio_t* io2) { io1->upstream_io = io2; io2->upstream_io = io1; } hio_t* hio_get_upstream(hio_t* io) { return io->upstream_io; } hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl) { hio_t* upstream_io = hio_create_socket(io->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (upstream_io == NULL) return NULL; if (ssl) hio_enable_ssl(upstream_io); hio_setup_upstream(io, upstream_io); hio_setcb_read(io, hio_write_upstream); hio_setcb_read(upstream_io, hio_write_upstream); hio_setcb_close(io, hio_close_upstream); hio_setcb_close(upstream_io, hio_close_upstream); hio_setcb_connect(upstream_io, hio_read_upstream); hio_connect(upstream_io); return upstream_io; } hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port) { hio_t* upstream_io = hio_create_socket(io->loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE); if (upstream_io == NULL) return NULL; hio_setup_upstream(io, upstream_io); hio_setcb_read(io, hio_write_upstream); hio_setcb_read(upstream_io, hio_write_upstream); hio_read_upstream(io); return upstream_io; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/hevent.h000066400000000000000000000202251520575453600262310ustar00rootroot00000000000000#ifndef HV_EVENT_H_ #define HV_EVENT_H_ #include "hloop.h" #include "iowatcher.h" #include "rudp.h" #include "hbuf.h" #include "hmutex.h" #include "array.h" #include "list.h" #include "heap.h" #include "queue.h" #define HLOOP_READ_BUFSIZE 8192 // 8K #define READ_BUFSIZE_HIGH_WATER 65536 // 64K #define WRITE_BUFSIZE_HIGH_WATER (1U << 23) // 8M #define MAX_READ_BUFSIZE (1U << 24) // 16M #define MAX_WRITE_BUFSIZE (1U << 24) // 16M // hio_read_flags #define HIO_READ_ONCE 0x1 #define HIO_READ_UNTIL_LENGTH 0x2 #define HIO_READ_UNTIL_DELIM 0x4 ARRAY_DECL(hio_t*, io_array); ARRAY_DECL(hsignal_t*, signal_array); QUEUE_DECL(hevent_t, event_queue); struct hloop_s { uint32_t flags; hloop_status_e status; uint64_t start_ms; // ms uint64_t start_hrtime; // us uint64_t end_hrtime; uint64_t cur_hrtime; uint64_t loop_cnt; long pid; long tid; void* userdata; //private: // events uint32_t intern_nevents; uint32_t nactives; uint32_t npendings; // pendings: with priority as array.index hevent_t* pendings[HEVENT_PRIORITY_SIZE]; // signals struct signal_array signals; uint32_t nsignals; // idles struct list_head idles; uint32_t nidles; // timers struct heap timers; // monotonic time struct heap realtimers; // realtime uint32_t ntimers; // ios: with fd as array.index struct io_array ios; uint32_t nios; // one loop per thread, so one readbuf per loop is OK. hbuf_t readbuf; void* iowatcher; // custom_events int eventfds[2]; event_queue custom_events; hmutex_t custom_events_mutex; }; uint64_t hloop_next_event_id(); struct hidle_s { HEVENT_FIELDS uint32_t repeat; //private: struct list_node node; }; #define HTIMER_FIELDS \ HEVENT_FIELDS \ uint32_t repeat; \ uint64_t next_timeout; \ struct heap_node node; struct htimer_s { HTIMER_FIELDS }; struct htimeout_s { HTIMER_FIELDS uint32_t timeout; \ }; struct hperiod_s { HTIMER_FIELDS int8_t minute; int8_t hour; int8_t day; int8_t week; int8_t month; }; QUEUE_DECL(offset_buf_t, write_queue); // sizeof(struct hio_s)=416 on linux-x64 struct hio_s { HEVENT_FIELDS // flags unsigned ready :1; unsigned connected :1; unsigned closed :1; unsigned accept :1; unsigned connect :1; unsigned connectex :1; // for ConnectEx/DisconnectEx unsigned recv :1; unsigned send :1; unsigned recvfrom :1; unsigned sendto :1; unsigned close :1; unsigned alloced_readbuf :1; // for hio_alloc_readbuf unsigned alloced_ssl_ctx :1; // for hio_new_ssl_ctx // public: hio_type_e io_type; uint32_t id; // fd cannot be used as unique identifier, so we provide an id int fd; int error; int events; int revents; struct sockaddr* localaddr; struct sockaddr* peeraddr; uint64_t last_read_hrtime; uint64_t last_write_hrtime; // read fifo_buf_t readbuf; unsigned int read_flags; // for hio_read_until union { unsigned int read_until_length; unsigned char read_until_delim; }; uint32_t max_read_bufsize; uint32_t small_readbytes_cnt; // for readbuf autosize // write struct write_queue write_queue; hrecursive_mutex_t write_mutex; // lock write and write_queue uint32_t write_bufsize; uint32_t max_write_bufsize; // callbacks hread_cb read_cb; hwrite_cb write_cb; hclose_cb close_cb; haccept_cb accept_cb; hconnect_cb connect_cb; // timers int connect_timeout; // ms int close_timeout; // ms int read_timeout; // ms int write_timeout; // ms int keepalive_timeout; // ms int heartbeat_interval; // ms hio_send_heartbeat_fn heartbeat_fn; htimer_t* connect_timer; htimer_t* close_timer; htimer_t* read_timer; htimer_t* write_timer; htimer_t* keepalive_timer; htimer_t* heartbeat_timer; // upstream struct hio_s* upstream_io; // for hio_setup_upstream // unpack unpack_setting_t* unpack_setting; // for hio_set_unpack // ssl void* ssl; // for hio_set_ssl void* ssl_ctx; // for hio_set_ssl_ctx char* hostname; // for hssl_set_sni_hostname // context void* ctx; // for hio_context / hio_set_context // private: #if defined(EVENT_POLL) || defined(EVENT_KQUEUE) int event_index[2]; // for poll,kqueue #endif #ifdef EVENT_IOCP void* hovlp; // for iocp/overlapio #endif #if WITH_RUDP rudp_t rudp; #if WITH_KCP kcp_setting_t* kcp_setting; #endif #endif }; /* * hio lifeline: * * fd => * hio_get => HV_ALLOC_SIZEOF(io) => hio_init => hio_ready * * hio_read => hio_add(HV_READ) => hio_read_cb * hio_write => hio_add(HV_WRITE) => hio_write_cb * hio_close => hio_done => hio_del(HV_RDWR) => hio_close_cb * * hloop_stop => hloop_free => hio_free => HV_FREE(io) */ void hio_init(hio_t* io); void hio_ready(hio_t* io); void hio_done(hio_t* io); void hio_free(hio_t* io); uint32_t hio_next_id(); void hio_accept_cb(hio_t* io); void hio_connect_cb(hio_t* io); void hio_handle_read(hio_t* io, void* buf, int readbytes); void hio_read_cb(hio_t* io, void* buf, int len); void hio_write_cb(hio_t* io, const void* buf, int len); void hio_close_cb(hio_t* io); void hio_del_connect_timer(hio_t* io); void hio_del_close_timer(hio_t* io); void hio_del_read_timer(hio_t* io); void hio_del_write_timer(hio_t* io); void hio_del_keepalive_timer(hio_t* io); void hio_del_heartbeat_timer(hio_t* io); static inline void hio_use_loop_readbuf(hio_t* io) { hloop_t* loop = io->loop; if (loop->readbuf.len == 0) { loop->readbuf.len = HLOOP_READ_BUFSIZE; HV_ALLOC(loop->readbuf.base, loop->readbuf.len); } io->readbuf.base = loop->readbuf.base; io->readbuf.len = loop->readbuf.len; } static inline bool hio_is_loop_readbuf(hio_t* io) { return io->readbuf.base == io->loop->readbuf.base; } static inline bool hio_is_alloced_readbuf(hio_t* io) { return io->alloced_readbuf; } void hio_alloc_readbuf(hio_t* io, int len); void hio_free_readbuf(hio_t* io); void hio_memmove_readbuf(hio_t* io); #define EVENT_ENTRY(p) container_of(p, hevent_t, pending_node) #define IDLE_ENTRY(p) container_of(p, hidle_t, node) #define TIMER_ENTRY(p) container_of(p, htimer_t, node) #define EVENT_ACTIVE(ev) \ if (!ev->active) {\ ev->active = 1;\ ev->loop->nactives++;\ }\ #define EVENT_INACTIVE(ev) \ if (ev->active) {\ ev->active = 0;\ ev->loop->nactives--;\ }\ #define EVENT_PENDING(ev) \ do {\ if (!ev->pending) {\ ev->pending = 1;\ ev->loop->npendings++;\ hevent_t** phead = &ev->loop->pendings[HEVENT_PRIORITY_INDEX(ev->priority)];\ ev->pending_next = *phead;\ *phead = (hevent_t*)ev;\ }\ } while(0) #define EVENT_ADD(loop, ev, cb) \ do {\ ev->loop = loop;\ ev->event_id = hloop_next_event_id();\ ev->cb = (hevent_cb)cb;\ EVENT_ACTIVE(ev);\ } while(0) #define EVENT_DEL(ev) \ do {\ EVENT_INACTIVE(ev);\ if (!ev->pending) {\ HV_FREE(ev);\ }\ } while(0) #define EVENT_RESET(ev) \ do {\ ev->destroy = 0;\ EVENT_ACTIVE(ev);\ ev->pending = 0;\ } while(0) #endif // HV_EVENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/hloop.c000066400000000000000000000760561520575453600260710ustar00rootroot00000000000000#include "hloop.h" #include "hevent.h" #include "iowatcher.h" #include "hdef.h" #include "hbase.h" #include "hlog.h" #include "hmath.h" #include "htime.h" #include "hsocket.h" #include "hthread.h" #if defined(OS_UNIX) && HAVE_EVENTFD #include "sys/eventfd.h" #endif #define HLOOP_PAUSE_TIME 10 // ms #define HLOOP_MAX_BLOCK_TIME 100 // ms #define HLOOP_STAT_TIMEOUT 60000 // ms #define IO_ARRAY_INIT_SIZE 1024 #define CUSTOM_EVENT_QUEUE_INIT_SIZE 16 #define EVENTFDS_READ_INDEX 0 #define EVENTFDS_WRITE_INDEX 1 static void __hidle_del(hidle_t* idle); static void __htimer_del(htimer_t* timer); static int timers_compare(const struct heap_node* lhs, const struct heap_node* rhs) { return TIMER_ENTRY(lhs)->next_timeout < TIMER_ENTRY(rhs)->next_timeout; } static int hloop_process_idles(hloop_t* loop) { int nidles = 0; struct list_node* node = loop->idles.next; hidle_t* idle = NULL; while (node != &loop->idles) { idle = IDLE_ENTRY(node); node = node->next; if (idle->repeat != INFINITE) { --idle->repeat; } if (idle->repeat == 0) { // NOTE: Just mark it as destroy and remove from list. // Real deletion occurs after hloop_process_pendings. __hidle_del(idle); } EVENT_PENDING(idle); ++nidles; } return nidles; } static int __hloop_process_timers(struct heap* timers, uint64_t timeout) { int ntimers = 0; htimer_t* timer = NULL; while (timers->root) { // NOTE: root of minheap has min timeout. timer = TIMER_ENTRY(timers->root); if (timer->next_timeout > timeout) { break; } if (timer->repeat != INFINITE) { --timer->repeat; } if (timer->repeat == 0) { // NOTE: Just mark it as destroy and remove from heap. // Real deletion occurs after hloop_process_pendings. __htimer_del(timer); } else { // NOTE: calc next timeout, then re-insert heap. heap_dequeue(timers); if (timer->event_type == HEVENT_TYPE_TIMEOUT) { while (timer->next_timeout <= timeout) { timer->next_timeout += (uint64_t)((htimeout_t*)timer)->timeout * 1000; } } else if (timer->event_type == HEVENT_TYPE_PERIOD) { hperiod_t* period = (hperiod_t*)timer; timer->next_timeout = (uint64_t)cron_next_timeout(period->minute, period->hour, period->day, period->week, period->month) * 1000000; } heap_insert(timers, &timer->node); } EVENT_PENDING(timer); ++ntimers; } return ntimers; } static int hloop_process_timers(hloop_t* loop) { uint64_t now = hloop_now_us(loop); int ntimers = __hloop_process_timers(&loop->timers, loop->cur_hrtime); ntimers += __hloop_process_timers(&loop->realtimers, now); return ntimers; } static int hloop_process_ios(hloop_t* loop, int timeout) { // That is to call IO multiplexing function such as select, poll, epoll, etc. int nevents = iowatcher_poll_events(loop, timeout); if (nevents < 0) { hlogd("poll_events error=%d", -nevents); } return nevents < 0 ? 0 : nevents; } static int hloop_process_pendings(hloop_t* loop) { if (loop->npendings == 0) return 0; hevent_t* cur = NULL; hevent_t* next = NULL; int ncbs = 0; // NOTE: invoke event callback from high to low sorted by priority. for (int i = HEVENT_PRIORITY_SIZE-1; i >= 0; --i) { cur = loop->pendings[i]; while (cur) { next = cur->pending_next; if (cur->pending) { if (cur->active && cur->cb) { cur->cb(cur); ++ncbs; } cur->pending = 0; // NOTE: Now we can safely delete event marked as destroy. if (cur->destroy) { EVENT_DEL(cur); } } cur = next; } loop->pendings[i] = NULL; } loop->npendings = 0; return ncbs; } // hloop_process_ios -> hloop_process_timers -> hloop_process_idles -> hloop_process_pendings int hloop_process_events(hloop_t* loop, int timeout_ms) { // ios -> timers -> idles int nios, ntimers, nidles; nios = ntimers = nidles = 0; // calc blocktime int32_t blocktime_ms = timeout_ms; if (loop->ntimers) { hloop_update_time(loop); int64_t blocktime_us = blocktime_ms * 1000; if (loop->timers.root) { int64_t min_timeout = TIMER_ENTRY(loop->timers.root)->next_timeout - loop->cur_hrtime; blocktime_us = MIN(blocktime_us, min_timeout); } if (loop->realtimers.root) { int64_t min_timeout = TIMER_ENTRY(loop->realtimers.root)->next_timeout - hloop_now_us(loop); blocktime_us = MIN(blocktime_us, min_timeout); } if (blocktime_us < 0) goto process_timers; blocktime_ms = blocktime_us / 1000 + 1; blocktime_ms = MIN(blocktime_ms, timeout_ms); } if (loop->nios) { nios = hloop_process_ios(loop, blocktime_ms); } else { hv_msleep(blocktime_ms); } hloop_update_time(loop); // wakeup by hloop_stop if (loop->status == HLOOP_STATUS_STOP) { return 0; } process_timers: if (loop->ntimers) { ntimers = hloop_process_timers(loop); } int npendings = loop->npendings; if (npendings == 0) { if (loop->nidles) { nidles= hloop_process_idles(loop); } } int ncbs = hloop_process_pendings(loop); // printd("blocktime=%d nios=%d/%u ntimers=%d/%u nidles=%d/%u nactives=%d npendings=%d ncbs=%d\n", // blocktime, nios, loop->nios, ntimers, loop->ntimers, nidles, loop->nidles, // loop->nactives, npendings, ncbs); return ncbs; } static void hloop_stat_timer_cb(htimer_t* timer) { hloop_t* loop = timer->loop; // hlog_set_level(LOG_LEVEL_DEBUG); hlogd("[loop] pid=%ld tid=%ld uptime=%lluus cnt=%llu nactives=%u nios=%u ntimers=%u nidles=%u", loop->pid, loop->tid, (unsigned long long)loop->cur_hrtime - loop->start_hrtime, (unsigned long long)loop->loop_cnt, loop->nactives, loop->nios, loop->ntimers, loop->nidles); } static void eventfd_read_cb(hio_t* io, void* buf, int readbytes) { hloop_t* loop = io->loop; hevent_t* pev = NULL; hevent_t ev; uint64_t count = readbytes; #if defined(OS_UNIX) && HAVE_EVENTFD assert(readbytes == sizeof(count)); count = *(uint64_t*)buf; #endif for (uint64_t i = 0; i < count; ++i) { hmutex_lock(&loop->custom_events_mutex); if (event_queue_empty(&loop->custom_events)) { goto unlock; } pev = event_queue_front(&loop->custom_events); if (pev == NULL) { goto unlock; } ev = *pev; event_queue_pop_front(&loop->custom_events); // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb. hmutex_unlock(&loop->custom_events_mutex); if (ev.cb) { ev.cb(&ev); } } return; unlock: hmutex_unlock(&loop->custom_events_mutex); } static int hloop_create_eventfds(hloop_t* loop) { #if defined(OS_UNIX) && HAVE_EVENTFD int efd = eventfd(0, 0); if (efd < 0) { hloge("eventfd create failed!"); return -1; } loop->eventfds[0] = loop->eventfds[1] = efd; #elif defined(OS_UNIX) && HAVE_PIPE if (pipe(loop->eventfds) != 0) { hloge("pipe create failed!"); return -1; } #else if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->eventfds) != 0) { hloge("socketpair create failed!"); return -1; } #endif hio_t* io = hread(loop, loop->eventfds[EVENTFDS_READ_INDEX], NULL, 0, eventfd_read_cb); io->priority = HEVENT_HIGH_PRIORITY; ++loop->intern_nevents; return 0; } static void hloop_destroy_eventfds(hloop_t* loop) { #if defined(OS_UNIX) && HAVE_EVENTFD // NOTE: eventfd has only one fd SAFE_CLOSE(loop->eventfds[0]); #elif defined(OS_UNIX) && HAVE_PIPE SAFE_CLOSE(loop->eventfds[0]); SAFE_CLOSE(loop->eventfds[1]); #else // NOTE: Avoid duplication closesocket in hio_cleanup // SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_READ_INDEX]); SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_WRITE_INDEX]); #endif loop->eventfds[0] = loop->eventfds[1] = -1; } void hloop_post_event(hloop_t* loop, hevent_t* ev) { if (ev->loop == NULL) { ev->loop = loop; } if (ev->event_type == 0) { ev->event_type = HEVENT_TYPE_CUSTOM; } if (ev->event_id == 0) { ev->event_id = hloop_next_event_id(); } int nwrite = 0; uint64_t count = 1; hmutex_lock(&loop->custom_events_mutex); if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) { if (hloop_create_eventfds(loop) != 0) { goto unlock; } } #if defined(OS_UNIX) && HAVE_EVENTFD nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], &count, sizeof(count)); #elif defined(OS_UNIX) && HAVE_PIPE nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1); #else nwrite = send(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1, 0); #endif if (nwrite <= 0) { hloge("hloop_post_event failed!"); goto unlock; } if (loop->custom_events.maxsize == 0) { event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE); } event_queue_push_back(&loop->custom_events, ev); unlock: hmutex_unlock(&loop->custom_events_mutex); } static void hloop_init(hloop_t* loop) { #ifdef OS_WIN WSAInit(); #endif #ifdef SIGPIPE // NOTE: if not ignore SIGPIPE, write twice when peer close will lead to exit process by SIGPIPE. signal(SIGPIPE, SIG_IGN); #endif loop->status = HLOOP_STATUS_STOP; loop->pid = hv_getpid(); loop->tid = hv_gettid(); // idles list_init(&loop->idles); // timers heap_init(&loop->timers, timers_compare); heap_init(&loop->realtimers, timers_compare); // ios // NOTE: io_array_init when hio_get -> io_array_resize // io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE); // readbuf // NOTE: alloc readbuf when hio_use_loop_readbuf // loop->readbuf.len = HLOOP_READ_BUFSIZE; // HV_ALLOC(loop->readbuf.base, loop->readbuf.len); // NOTE: iowatcher_init when hio_add -> iowatcher_add_event // iowatcher_init(loop); // custom_events hmutex_init(&loop->custom_events_mutex); // NOTE: hloop_create_eventfds when hloop_post_event or hloop_run loop->eventfds[0] = loop->eventfds[1] = -1; // NOTE: init start_time here, because htimer_add use it. loop->start_ms = gettimeofday_ms(); loop->start_hrtime = loop->cur_hrtime = gethrtime_us(); } static void hloop_cleanup(hloop_t* loop) { // pendings printd("cleanup pendings...\n"); for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) { loop->pendings[i] = NULL; } // ios printd("cleanup ios...\n"); for (int i = 0; i < loop->ios.maxsize; ++i) { hio_t* io = loop->ios.ptr[i]; if (io) { hio_free(io); } } io_array_cleanup(&loop->ios); // idles printd("cleanup idles...\n"); struct list_node* node = loop->idles.next; hidle_t* idle; while (node != &loop->idles) { idle = IDLE_ENTRY(node); node = node->next; HV_FREE(idle); } list_init(&loop->idles); // timers printd("cleanup timers...\n"); htimer_t* timer; while (loop->timers.root) { timer = TIMER_ENTRY(loop->timers.root); heap_dequeue(&loop->timers); HV_FREE(timer); } heap_init(&loop->timers, NULL); while (loop->realtimers.root) { timer = TIMER_ENTRY(loop->realtimers.root); heap_dequeue(&loop->realtimers); HV_FREE(timer); } heap_init(&loop->realtimers, NULL); // signals printd("cleanup signals...\n"); for (int i = 0; i < loop->signals.maxsize; ++i) { hsignal_t* sig = loop->signals.ptr[i]; HV_FREE(sig); } signal_array_cleanup(&loop->signals); // readbuf if (loop->readbuf.base && loop->readbuf.len) { HV_FREE(loop->readbuf.base); loop->readbuf.base = NULL; loop->readbuf.len = 0; } // iowatcher iowatcher_cleanup(loop); // custom_events hmutex_lock(&loop->custom_events_mutex); hloop_destroy_eventfds(loop); event_queue_cleanup(&loop->custom_events); hmutex_unlock(&loop->custom_events_mutex); hmutex_destroy(&loop->custom_events_mutex); } hloop_t* hloop_new(int flags) { hloop_t* loop; HV_ALLOC_SIZEOF(loop); hloop_init(loop); loop->flags |= flags; hlogd("hloop_new tid=%ld", loop->tid); return loop; } void hloop_free(hloop_t** pp) { if (pp == NULL || *pp == NULL) return; hloop_t* loop = *pp; if (loop->status == HLOOP_STATUS_DESTROY) return; loop->status = HLOOP_STATUS_DESTROY; hlogd("hloop_free tid=%ld", hv_gettid()); hloop_cleanup(loop); HV_FREE(loop); *pp = NULL; } // while (loop->status) { hloop_process_events(loop); } int hloop_run(hloop_t* loop) { if (loop == NULL) return -1; if (loop->status == HLOOP_STATUS_RUNNING) return -2; loop->status = HLOOP_STATUS_RUNNING; loop->pid = hv_getpid(); loop->tid = hv_gettid(); hlogd("hloop_run tid=%ld", loop->tid); if (loop->intern_nevents == 0) { hmutex_lock(&loop->custom_events_mutex); if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) { hloop_create_eventfds(loop); } hmutex_unlock(&loop->custom_events_mutex); #ifdef DEBUG htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE); ++loop->intern_nevents; #endif } while (loop->status != HLOOP_STATUS_STOP) { if (loop->status == HLOOP_STATUS_PAUSE) { hv_msleep(HLOOP_PAUSE_TIME); hloop_update_time(loop); continue; } ++loop->loop_cnt; if ((loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) && loop->nactives <= loop->intern_nevents) { break; } hloop_process_events(loop, HLOOP_MAX_BLOCK_TIME); if (loop->flags & HLOOP_FLAG_RUN_ONCE) { break; } } loop->status = HLOOP_STATUS_STOP; loop->end_hrtime = gethrtime_us(); if (loop->flags & HLOOP_FLAG_AUTO_FREE) { hloop_free(&loop); } return 0; } int hloop_wakeup(hloop_t* loop) { hevent_t ev; memset(&ev, 0, sizeof(ev)); hloop_post_event(loop, &ev); return 0; } int hloop_stop(hloop_t* loop) { if (loop == NULL) return -1; if (loop->status == HLOOP_STATUS_STOP) return -2; hlogd("hloop_stop tid=%ld", hv_gettid()); if (hv_gettid() != loop->tid) { hloop_wakeup(loop); } loop->status = HLOOP_STATUS_STOP; return 0; } int hloop_pause(hloop_t* loop) { if (loop->status == HLOOP_STATUS_RUNNING) { loop->status = HLOOP_STATUS_PAUSE; } return 0; } int hloop_resume(hloop_t* loop) { if (loop->status == HLOOP_STATUS_PAUSE) { loop->status = HLOOP_STATUS_RUNNING; } return 0; } hloop_status_e hloop_status(hloop_t* loop) { return loop->status; } void hloop_update_time(hloop_t* loop) { loop->cur_hrtime = gethrtime_us(); if (hloop_now(loop) != time(NULL)) { // systemtime changed, we adjust start_ms loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000; } } uint64_t hloop_now(hloop_t* loop) { return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000; } uint64_t hloop_now_ms(hloop_t* loop) { return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000; } uint64_t hloop_now_us(hloop_t* loop) { return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime); } uint64_t hloop_now_hrtime(hloop_t* loop) { return loop->cur_hrtime; } uint64_t hio_last_read_time(hio_t* io) { hloop_t* loop = io->loop; return loop->start_ms + (io->last_read_hrtime - loop->start_hrtime) / 1000; } uint64_t hio_last_write_time(hio_t* io) { hloop_t* loop = io->loop; return loop->start_ms + (io->last_write_hrtime - loop->start_hrtime) / 1000; } long hloop_pid(hloop_t* loop) { return loop->pid; } long hloop_tid(hloop_t* loop) { return loop->tid; } uint64_t hloop_count(hloop_t* loop) { return loop->loop_cnt; } uint32_t hloop_nios(hloop_t* loop) { return loop->nios; } uint32_t hloop_ntimers(hloop_t* loop) { return loop->ntimers; } uint32_t hloop_nidles(hloop_t* loop) { return loop->nidles; } uint32_t hloop_nactives(hloop_t* loop) { return loop->nactives; } void hloop_set_userdata(hloop_t* loop, void* userdata) { loop->userdata = userdata; } void* hloop_userdata(hloop_t* loop) { return loop->userdata; } static hloop_t* s_signal_loop = NULL; static void signal_handler(int signo) { if (!s_signal_loop) return; if (signo >= s_signal_loop->signals.maxsize) return; hsignal_t* sig = s_signal_loop->signals.ptr[signo]; if (!sig) return; hloop_post_event(s_signal_loop, sig); } hsignal_t* hsignal_add(hloop_t* loop, hsignal_cb cb, int signo) { int max_signo = 64; #ifdef _NSIG max_signo = _NSIG; #endif if (signo <= 0 || signo >= max_signo) { hloge("signo %d over %d!", signo, max_signo); return NULL; } if (loop->signals.maxsize == 0) { signal_array_init(&loop->signals, max_signo); } hsignal_t* sig = loop->signals.ptr[signo]; if (sig == NULL) { HV_ALLOC_SIZEOF(sig); sig->loop = loop; sig->event_type = HEVENT_TYPE_SIGNAL; // NOTE: use event_id as signo sig->event_id = signo; sig->cb = cb; sig->priority = HEVENT_HIGHEST_PRIORITY; loop->signals.ptr[signo] = sig; loop->nsignals++; } EVENT_ACTIVE(sig); s_signal_loop = loop; signal(signo, signal_handler); return sig; } void hsignal_del(hsignal_t* sig) { if (!sig->active) return; hloop_t* loop = sig->loop; int signo = (int)sig->event_id; if (signo >= loop->signals.maxsize) return; loop->signals.ptr[signo] = NULL; loop->nsignals--; EVENT_DEL(sig); } hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) { hidle_t* idle; HV_ALLOC_SIZEOF(idle); idle->event_type = HEVENT_TYPE_IDLE; idle->priority = HEVENT_LOWEST_PRIORITY; idle->repeat = repeat; list_add(&idle->node, &loop->idles); EVENT_ADD(loop, idle, cb); loop->nidles++; return idle; } static void __hidle_del(hidle_t* idle) { if (idle->destroy) return; idle->destroy = 1; list_del(&idle->node); idle->loop->nidles--; } void hidle_del(hidle_t* idle) { if (!idle->active) return; __hidle_del(idle); EVENT_DEL(idle); } htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat) { if (timeout_ms == 0) return NULL; htimeout_t* timer; HV_ALLOC_SIZEOF(timer); timer->event_type = HEVENT_TYPE_TIMEOUT; timer->priority = HEVENT_HIGHEST_PRIORITY; timer->repeat = repeat; timer->timeout = timeout_ms; hloop_update_time(loop); timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout_ms * 1000; // NOTE: Limit granularity to 100ms if (timeout_ms >= 1000 && timeout_ms % 100 == 0) { timer->next_timeout = timer->next_timeout / 100000 * 100000; } heap_insert(&loop->timers, &timer->node); EVENT_ADD(loop, timer, cb); loop->ntimers++; return (htimer_t*)timer; } void htimer_reset(htimer_t* timer, uint32_t timeout_ms) { if (timer->event_type != HEVENT_TYPE_TIMEOUT) { return; } hloop_t* loop = timer->loop; htimeout_t* timeout = (htimeout_t*)timer; if (timer->destroy) { loop->ntimers++; } else { heap_remove(&loop->timers, &timer->node); } if (timer->repeat == 0) { timer->repeat = 1; } if (timeout_ms > 0) { timeout->timeout = timeout_ms; } timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout->timeout * 1000; // NOTE: Limit granularity to 100ms if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) { timer->next_timeout = timer->next_timeout / 100000 * 100000; } heap_insert(&loop->timers, &timer->node); EVENT_RESET(timer); } htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, int8_t minute, int8_t hour, int8_t day, int8_t week, int8_t month, uint32_t repeat) { if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) { return NULL; } hperiod_t* timer; HV_ALLOC_SIZEOF(timer); timer->event_type = HEVENT_TYPE_PERIOD; timer->priority = HEVENT_HIGH_PRIORITY; timer->repeat = repeat; timer->minute = minute; timer->hour = hour; timer->day = day; timer->month = month; timer->week = week; timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000; heap_insert(&loop->realtimers, &timer->node); EVENT_ADD(loop, timer, cb); loop->ntimers++; return (htimer_t*)timer; } static void __htimer_del(htimer_t* timer) { if (timer->destroy) return; if (timer->event_type == HEVENT_TYPE_TIMEOUT) { heap_remove(&timer->loop->timers, &timer->node); } else if (timer->event_type == HEVENT_TYPE_PERIOD) { heap_remove(&timer->loop->realtimers, &timer->node); } timer->loop->ntimers--; timer->destroy = 1; } void htimer_del(htimer_t* timer) { if (!timer->active) return; __htimer_del(timer); EVENT_DEL(timer); } const char* hio_engine() { #ifdef EVENT_SELECT return "select"; #elif defined(EVENT_POLL) return "poll"; #elif defined(EVENT_EPOLL) return "epoll"; #elif defined(EVENT_KQUEUE) return "kqueue"; #elif defined(EVENT_IOCP) return "iocp"; #elif defined(EVENT_PORT) return "evport"; #else return "noevent"; #endif } static inline hio_t* __hio_get(hloop_t* loop, int fd) { if (fd >= loop->ios.maxsize) { int newsize = ceil2e(fd); newsize = MAX(newsize, IO_ARRAY_INIT_SIZE); io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd); } return loop->ios.ptr[fd]; } hio_t* hio_get(hloop_t* loop, int fd) { hio_t* io = __hio_get(loop, fd); if (io == NULL) { HV_ALLOC_SIZEOF(io); hio_init(io); io->event_type = HEVENT_TYPE_IO; io->loop = loop; io->fd = fd; loop->ios.ptr[fd] = io; } if (!io->ready) { hio_ready(io); } return io; } void hio_detach(hio_t* io) { hloop_t* loop = io->loop; int fd = io->fd; assert(loop != NULL && fd < loop->ios.maxsize); loop->ios.ptr[fd] = NULL; } void hio_attach(hloop_t* loop, hio_t* io) { int fd = io->fd; // NOTE: hio was not freed for reused when closed, but attached hio can't be reused, // so we need to free it if fd exists to avoid memory leak. hio_t* preio = __hio_get(loop, fd); if (preio != NULL && preio != io) { hio_free(preio); } io->loop = loop; // NOTE: use new_loop readbuf hio_use_loop_readbuf(io); loop->ios.ptr[fd] = io; } bool hio_exists(hloop_t* loop, int fd) { if (fd >= loop->ios.maxsize) { return false; } return loop->ios.ptr[fd] != NULL; } int hio_add(hio_t* io, hio_cb cb, int events) { printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events); #ifdef OS_WIN // Windows iowatcher not work on stdio if (io->fd < 3) return -1; #endif hloop_t* loop = io->loop; if (!io->active) { EVENT_ADD(loop, io, cb); loop->nios++; } if (!io->ready) { hio_ready(io); } if (cb) { io->cb = (hevent_cb)cb; } if (!(io->events & events)) { iowatcher_add_event(loop, io->fd, events); io->events |= events; } return 0; } int hio_del(hio_t* io, int events) { printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events); #ifdef OS_WIN // Windows iowatcher not work on stdio if (io->fd < 3) return -1; #endif if (!io->active) return -1; if (io->events & events) { iowatcher_del_event(io->loop, io->fd, events); io->events &= ~events; } if (io->events == 0) { io->loop->nios--; // NOTE: not EVENT_DEL, avoid free EVENT_INACTIVE(io); } return 0; } static void hio_close_event_cb(hevent_t* ev) { hio_t* io = (hio_t*)ev->userdata; uint32_t id = (uintptr_t)ev->privdata; if (io->id != id) return; hio_close(io); } int hio_close_async(hio_t* io) { hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.cb = hio_close_event_cb; ev.userdata = io; ev.privdata = (void*)(uintptr_t)io->id; hloop_post_event(io->loop, &ev); return 0; } //------------------high-level apis------------------------------------------- hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) { hio_t* io = hio_get(loop, fd); assert(io != NULL); if (buf && len) { io->readbuf.base = (char*)buf; io->readbuf.len = len; } if (read_cb) { io->read_cb = read_cb; } hio_read(io); return io; } hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) { hio_t* io = hio_get(loop, fd); assert(io != NULL); if (write_cb) { io->write_cb = write_cb; } hio_write(io, buf, len); return io; } hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) { hio_t* io = hio_get(loop, listenfd); assert(io != NULL); if (accept_cb) { io->accept_cb = accept_cb; } if (hio_accept(io) != 0) return NULL; return io; } hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) { hio_t* io = hio_get(loop, connfd); assert(io != NULL); if (connect_cb) { io->connect_cb = connect_cb; } if (hio_connect(io) != 0) return NULL; return io; } void hclose (hloop_t* loop, int fd) { hio_t* io = hio_get(loop, fd); assert(io != NULL); hio_close(io); } hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) { //hio_t* io = hio_get(loop, connfd); //assert(io != NULL); //io->recv = 1; //if (io->io_type != HIO_TYPE_SSL) { //io->io_type = HIO_TYPE_TCP; //} return hread(loop, connfd, buf, len, read_cb); } hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) { //hio_t* io = hio_get(loop, connfd); //assert(io != NULL); //io->send = 1; //if (io->io_type != HIO_TYPE_SSL) { //io->io_type = HIO_TYPE_TCP; //} return hwrite(loop, connfd, buf, len, write_cb); } hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) { //hio_t* io = hio_get(loop, sockfd); //assert(io != NULL); //io->recvfrom = 1; //io->io_type = HIO_TYPE_UDP; return hread(loop, sockfd, buf, len, read_cb); } hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) { //hio_t* io = hio_get(loop, sockfd); //assert(io != NULL); //io->sendto = 1; //io->io_type = HIO_TYPE_UDP; return hwrite(loop, sockfd, buf, len, write_cb); } //-----------------top-level apis--------------------------------------------- hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) { int sock_type = (type & HIO_TYPE_SOCK_STREAM) ? SOCK_STREAM : (type & HIO_TYPE_SOCK_DGRAM) ? SOCK_DGRAM : (type & HIO_TYPE_SOCK_RAW) ? SOCK_RAW : -1; if (sock_type == -1) return NULL; sockaddr_u addr; memset(&addr, 0, sizeof(addr)); int ret = -1; #ifdef ENABLE_UDS if (port < 0) { sockaddr_set_path(&addr, host); ret = 0; } #endif if (port >= 0) { ret = sockaddr_set_ipport(&addr, host, port); } if (ret != 0) { // fprintf(stderr, "unknown host: %s\n", host); return NULL; } int sockfd = socket(addr.sa.sa_family, sock_type, 0); if (sockfd < 0) { perror("socket"); return NULL; } hio_t* io = NULL; if (side == HIO_SERVER_SIDE) { #ifdef OS_UNIX so_reuseaddr(sockfd, 1); // so_reuseport(sockfd, 1); #endif if (addr.sa.sa_family == AF_INET6) { ip_v6only(sockfd, 0); } if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) { perror("bind"); closesocket(sockfd); return NULL; } if (sock_type == SOCK_STREAM) { if (listen(sockfd, SOMAXCONN) < 0) { perror("listen"); closesocket(sockfd); return NULL; } } } io = hio_get(loop, sockfd); assert(io != NULL); io->io_type = type; if (side == HIO_SERVER_SIDE) { hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr)); io->priority = HEVENT_HIGH_PRIORITY; } else { hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr)); } return io; } hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) { hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE); if (io == NULL) return NULL; hio_setcb_accept(io, accept_cb); if (hio_accept(io) != 0) return NULL; return io; } hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) { hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (io == NULL) return NULL; hio_setcb_connect(io, connect_cb); hio_setcb_close(io, close_cb); if (hio_connect(io) != 0) return NULL; return io; } hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) { hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE); if (io == NULL) return NULL; hio_setcb_accept(io, accept_cb); if (hio_accept(io) != 0) return NULL; return io; } hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) { hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE); if (io == NULL) return NULL; hio_setcb_connect(io, connect_cb); hio_setcb_close(io, close_cb); if (hio_connect(io) != 0) return NULL; return io; } hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) { return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE); } hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) { return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE); } int hio_create_pipe(hloop_t* loop, hio_t* pipeio[2]) { int pipefd[2]; hio_type_e type = HIO_TYPE_PIPE; #if defined(OS_UNIX) && HAVE_PIPE if (pipe(pipefd) != 0) { hloge("pipe create failed!"); return -1; } #else if (Socketpair(AF_INET, SOCK_STREAM, 0, pipefd) != 0) { hloge("socketpair create failed!"); return -1; } type = HIO_TYPE_TCP; #endif pipeio[0] = hio_get(loop, pipefd[0]); pipeio[1] = hio_get(loop, pipefd[1]); pipeio[0]->io_type = type; pipeio[1]->io_type = type; return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/hloop.h000066400000000000000000000665551520575453600261010ustar00rootroot00000000000000#ifndef HV_LOOP_H_ #define HV_LOOP_H_ #include "hexport.h" #include "hplatform.h" #include "hdef.h" #include "hssl.h" typedef struct hloop_s hloop_t; typedef struct hevent_s hevent_t; // NOTE: The following structures are subclasses of hevent_t, // inheriting hevent_t data members and function members. typedef struct hio_s hio_t; typedef struct hidle_s hidle_t; typedef struct htimer_s htimer_t; typedef struct htimeout_s htimeout_t; typedef struct hperiod_s hperiod_t; typedef struct hevent_s hsignal_t; typedef void (*hevent_cb) (hevent_t* ev); typedef void (*hio_cb) (hio_t* io); typedef void (*hidle_cb) (hidle_t* idle); typedef void (*htimer_cb) (htimer_t* timer); typedef void (*hsignal_cb) (hsignal_t* sig); typedef void (*haccept_cb) (hio_t* io); typedef void (*hconnect_cb) (hio_t* io); typedef void (*hread_cb) (hio_t* io, void* buf, int readbytes); typedef void (*hwrite_cb) (hio_t* io, const void* buf, int writebytes); typedef void (*hclose_cb) (hio_t* io); typedef enum { HLOOP_STATUS_STOP, HLOOP_STATUS_RUNNING, HLOOP_STATUS_PAUSE, HLOOP_STATUS_DESTROY } hloop_status_e; typedef enum { HEVENT_TYPE_NONE = 0, HEVENT_TYPE_IO = 0x00000001, HEVENT_TYPE_TIMEOUT = 0x00000010, HEVENT_TYPE_PERIOD = 0x00000020, HEVENT_TYPE_TIMER = HEVENT_TYPE_TIMEOUT|HEVENT_TYPE_PERIOD, HEVENT_TYPE_IDLE = 0x00000100, HEVENT_TYPE_SIGNAL = 0x00000200, HEVENT_TYPE_CUSTOM = 0x00000400, // 1024 } hevent_type_e; #define HEVENT_LOWEST_PRIORITY (-5) #define HEVENT_LOW_PRIORITY (-3) #define HEVENT_NORMAL_PRIORITY 0 #define HEVENT_HIGH_PRIORITY 3 #define HEVENT_HIGHEST_PRIORITY 5 #define HEVENT_PRIORITY_SIZE (HEVENT_HIGHEST_PRIORITY-HEVENT_LOWEST_PRIORITY+1) #define HEVENT_PRIORITY_INDEX(priority) (priority-HEVENT_LOWEST_PRIORITY) #define HEVENT_FLAGS \ unsigned destroy :1; \ unsigned active :1; \ unsigned pending :1; #define HEVENT_FIELDS \ hloop_t* loop; \ hevent_type_e event_type; \ uint64_t event_id; \ hevent_cb cb; \ void* userdata; \ void* privdata; \ struct hevent_s* pending_next; \ int priority; \ HEVENT_FLAGS // sizeof(struct hevent_s)=64 on x64 struct hevent_s { HEVENT_FIELDS }; #define hevent_set_id(ev, id) ((hevent_t*)(ev))->event_id = id #define hevent_set_cb(ev, cb) ((hevent_t*)(ev))->cb = cb #define hevent_set_priority(ev, prio) ((hevent_t*)(ev))->priority = prio #define hevent_set_userdata(ev, udata) ((hevent_t*)(ev))->userdata = (void*)udata #define hevent_loop(ev) (((hevent_t*)(ev))->loop) #define hevent_type(ev) (((hevent_t*)(ev))->event_type) #define hevent_id(ev) (((hevent_t*)(ev))->event_id) #define hevent_cb(ev) (((hevent_t*)(ev))->cb) #define hevent_priority(ev) (((hevent_t*)(ev))->priority) #define hevent_userdata(ev) (((hevent_t*)(ev))->userdata) typedef enum { HIO_TYPE_UNKNOWN = 0, HIO_TYPE_STDIN = 0x00000001, HIO_TYPE_STDOUT = 0x00000002, HIO_TYPE_STDERR = 0x00000004, HIO_TYPE_STDIO = 0x0000000F, HIO_TYPE_FILE = 0x00000010, HIO_TYPE_PIPE = 0x00000020, HIO_TYPE_IP = 0x00000100, HIO_TYPE_SOCK_RAW = 0x00000F00, HIO_TYPE_UDP = 0x00001000, HIO_TYPE_KCP = 0x00002000, HIO_TYPE_DTLS = 0x00010000, HIO_TYPE_SOCK_DGRAM = 0x000FF000, HIO_TYPE_TCP = 0x00100000, HIO_TYPE_SSL = 0x01000000, HIO_TYPE_TLS = HIO_TYPE_SSL, HIO_TYPE_SOCK_STREAM= 0x0FF00000, HIO_TYPE_SOCKET = 0x0FFFFF00, } hio_type_e; typedef enum { HIO_SERVER_SIDE = 0, HIO_CLIENT_SIDE = 1, } hio_side_e; #define HIO_DEFAULT_CONNECT_TIMEOUT 10000 // ms #define HIO_DEFAULT_CLOSE_TIMEOUT 60000 // ms #define HIO_DEFAULT_KEEPALIVE_TIMEOUT 75000 // ms #define HIO_DEFAULT_HEARTBEAT_INTERVAL 10000 // ms BEGIN_EXTERN_C // loop #define HLOOP_FLAG_RUN_ONCE 0x00000001 #define HLOOP_FLAG_AUTO_FREE 0x00000002 #define HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS 0x00000004 HV_EXPORT hloop_t* hloop_new(int flags DEFAULT(HLOOP_FLAG_AUTO_FREE)); // WARN: Forbid to call hloop_free if HLOOP_FLAG_AUTO_FREE set. HV_EXPORT void hloop_free(hloop_t** pp); HV_EXPORT int hloop_process_events(hloop_t* loop, int timeout_ms DEFAULT(0)); // NOTE: when no active events, loop will quit if HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS set. HV_EXPORT int hloop_run(hloop_t* loop); // NOTE: hloop_stop called in loop-thread just set flag to quit in next loop, // if called in other thread, it will wakeup loop-thread from blocking poll system call, // then you should join loop thread to safely exit loop thread. HV_EXPORT int hloop_stop(hloop_t* loop); HV_EXPORT int hloop_pause(hloop_t* loop); HV_EXPORT int hloop_resume(hloop_t* loop); HV_EXPORT int hloop_wakeup(hloop_t* loop); HV_EXPORT hloop_status_e hloop_status(hloop_t* loop); HV_EXPORT void hloop_update_time(hloop_t* loop); HV_EXPORT uint64_t hloop_now(hloop_t* loop); // s HV_EXPORT uint64_t hloop_now_ms(hloop_t* loop); // ms HV_EXPORT uint64_t hloop_now_us(hloop_t* loop); // us HV_EXPORT uint64_t hloop_now_hrtime(hloop_t* loop); // us // export some hloop's members // @return pid of hloop_run HV_EXPORT long hloop_pid(hloop_t* loop); // @return tid of hloop_run HV_EXPORT long hloop_tid(hloop_t* loop); // @return count of loop HV_EXPORT uint64_t hloop_count(hloop_t* loop); // @return number of ios HV_EXPORT uint32_t hloop_nios(hloop_t* loop); // @return number of timers HV_EXPORT uint32_t hloop_ntimers(hloop_t* loop); // @return number of idles HV_EXPORT uint32_t hloop_nidles(hloop_t* loop); // @return number of active events HV_EXPORT uint32_t hloop_nactives(hloop_t* loop); // userdata HV_EXPORT void hloop_set_userdata(hloop_t* loop, void* userdata); HV_EXPORT void* hloop_userdata(hloop_t* loop); // custom_event /* * hevent_t ev; * memset(&ev, 0, sizeof(hevent_t)); * ev.event_type = (hevent_type_e)(HEVENT_TYPE_CUSTOM + 1); * ev.cb = custom_event_cb; * ev.userdata = userdata; * hloop_post_event(loop, &ev); */ // NOTE: hloop_post_event is thread-safe, used to post event from other thread to loop thread. HV_EXPORT void hloop_post_event(hloop_t* loop, hevent_t* ev); // signal HV_EXPORT hsignal_t* hsignal_add(hloop_t* loop, hsignal_cb cb, int signo); HV_EXPORT void hsignal_del(hsignal_t* sig); // idle HV_EXPORT hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat DEFAULT(INFINITE)); HV_EXPORT void hidle_del(hidle_t* idle); // timer HV_EXPORT htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat DEFAULT(INFINITE)); /* * minute hour day week month cb * 0~59 0~23 1~31 0~6 1~12 * -1 -1 -1 -1 -1 cron.minutely * 30 -1 -1 -1 -1 cron.hourly * 30 1 -1 -1 -1 cron.daily * 30 1 15 -1 -1 cron.monthly * 30 1 -1 5 -1 cron.weekly * 30 1 1 -1 10 cron.yearly */ HV_EXPORT htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, int8_t minute DEFAULT(0), int8_t hour DEFAULT(-1), int8_t day DEFAULT(-1), int8_t week DEFAULT(-1), int8_t month DEFAULT(-1), uint32_t repeat DEFAULT(INFINITE)); HV_EXPORT void htimer_del(htimer_t* timer); HV_EXPORT void htimer_reset(htimer_t* timer, uint32_t timeout_ms DEFAULT(0)); // io //-----------------------low-level apis--------------------------------------- #define HV_READ 0x0001 #define HV_WRITE 0x0004 #define HV_RDWR (HV_READ|HV_WRITE) /* const char* hio_engine() { #ifdef EVENT_SELECT return "select"; #elif defined(EVENT_POLL) return "poll"; #elif defined(EVENT_EPOLL) return "epoll"; #elif defined(EVENT_KQUEUE) return "kqueue"; #elif defined(EVENT_IOCP) return "iocp"; #elif defined(EVENT_PORT) return "evport"; #else return "noevent"; #endif } */ HV_EXPORT const char* hio_engine(); HV_EXPORT hio_t* hio_get(hloop_t* loop, int fd); HV_EXPORT int hio_add(hio_t* io, hio_cb cb, int events DEFAULT(HV_READ)); HV_EXPORT int hio_del(hio_t* io, int events DEFAULT(HV_RDWR)); // NOTE: io detach from old loop and attach to new loop /* @see examples/multi-thread/one-acceptor-multi-workers.c void new_conn_event(hevent_t* ev) { hloop_t* loop = ev->loop; hio_t* io = (hio_t*)hevent_userdata(ev); hio_attach(loop, io); } void on_accpet(hio_t* io) { hio_detach(io); hloop_t* worker_loop = get_one_loop(); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.loop = worker_loop; ev.cb = new_conn_event; ev.userdata = io; hloop_post_event(worker_loop, &ev); } */ HV_EXPORT void hio_detach(/*hloop_t* loop,*/ hio_t* io); HV_EXPORT void hio_attach(hloop_t* loop, hio_t* io); HV_EXPORT bool hio_exists(hloop_t* loop, int fd); // hio_t fields // NOTE: fd cannot be used as unique identifier, so we provide an id. HV_EXPORT uint32_t hio_id (hio_t* io); HV_EXPORT int hio_fd (hio_t* io); HV_EXPORT int hio_error (hio_t* io); HV_EXPORT int hio_events (hio_t* io); HV_EXPORT int hio_revents (hio_t* io); HV_EXPORT hio_type_e hio_type (hio_t* io); HV_EXPORT struct sockaddr* hio_localaddr(hio_t* io); HV_EXPORT struct sockaddr* hio_peeraddr (hio_t* io); HV_EXPORT void hio_set_context(hio_t* io, void* ctx); HV_EXPORT void* hio_context(hio_t* io); HV_EXPORT bool hio_is_opened(hio_t* io); HV_EXPORT bool hio_is_connected(hio_t* io); HV_EXPORT bool hio_is_closed(hio_t* io); // iobuf // #include "hbuf.h" typedef struct fifo_buf_s hio_readbuf_t; // NOTE: One loop per thread, one readbuf per loop. // But you can pass in your own readbuf instead of the default readbuf to avoid memcopy. HV_EXPORT void hio_set_readbuf(hio_t* io, void* buf, size_t len); HV_EXPORT hio_readbuf_t* hio_get_readbuf(hio_t* io); HV_EXPORT void hio_set_max_read_bufsize (hio_t* io, uint32_t size); HV_EXPORT void hio_set_max_write_bufsize(hio_t* io, uint32_t size); // NOTE: hio_write is non-blocking, so there is a write queue inside hio_t to cache unwritten data and wait for writable. // @return current buffer size of write queue. HV_EXPORT size_t hio_write_bufsize(hio_t* io); #define hio_write_is_complete(io) (hio_write_bufsize(io) == 0) HV_EXPORT uint64_t hio_last_read_time(hio_t* io); // ms HV_EXPORT uint64_t hio_last_write_time(hio_t* io); // ms // set callbacks HV_EXPORT void hio_setcb_accept (hio_t* io, haccept_cb accept_cb); HV_EXPORT void hio_setcb_connect (hio_t* io, hconnect_cb connect_cb); HV_EXPORT void hio_setcb_read (hio_t* io, hread_cb read_cb); HV_EXPORT void hio_setcb_write (hio_t* io, hwrite_cb write_cb); HV_EXPORT void hio_setcb_close (hio_t* io, hclose_cb close_cb); // get callbacks HV_EXPORT haccept_cb hio_getcb_accept(hio_t* io); HV_EXPORT hconnect_cb hio_getcb_connect(hio_t* io); HV_EXPORT hread_cb hio_getcb_read(hio_t* io); HV_EXPORT hwrite_cb hio_getcb_write(hio_t* io); HV_EXPORT hclose_cb hio_getcb_close(hio_t* io); // Enable SSL/TLS is so easy :) HV_EXPORT int hio_enable_ssl(hio_t* io); HV_EXPORT bool hio_is_ssl(hio_t* io); HV_EXPORT int hio_set_ssl (hio_t* io, hssl_t ssl); HV_EXPORT int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx); // hssl_ctx_new(opt) -> hio_set_ssl_ctx HV_EXPORT int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); HV_EXPORT hssl_t hio_get_ssl(hio_t* io); HV_EXPORT hssl_ctx_t hio_get_ssl_ctx(hio_t* io); // for hssl_set_sni_hostname HV_EXPORT int hio_set_hostname(hio_t* io, const char* hostname); HV_EXPORT const char* hio_get_hostname(hio_t* io); // connect timeout => hclose_cb HV_EXPORT void hio_set_connect_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CONNECT_TIMEOUT)); // close timeout => hclose_cb HV_EXPORT void hio_set_close_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CLOSE_TIMEOUT)); // read timeout => hclose_cb HV_EXPORT void hio_set_read_timeout(hio_t* io, int timeout_ms); // write timeout => hclose_cb HV_EXPORT void hio_set_write_timeout(hio_t* io, int timeout_ms); // keepalive timeout => hclose_cb HV_EXPORT void hio_set_keepalive_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_KEEPALIVE_TIMEOUT)); /* void send_heartbeat(hio_t* io) { static char buf[] = "PING\r\n"; hio_write(io, buf, 6); } hio_set_heartbeat(io, 3000, send_heartbeat); */ typedef void (*hio_send_heartbeat_fn)(hio_t* io); // heartbeat interval => hio_send_heartbeat_fn HV_EXPORT void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn); // Nonblocking, poll IO events in the loop to call corresponding callback. // hio_add(io, HV_READ) => accept => haccept_cb HV_EXPORT int hio_accept (hio_t* io); // connect => hio_add(io, HV_WRITE) => hconnect_cb HV_EXPORT int hio_connect(hio_t* io); // hio_add(io, HV_READ) => read => hread_cb HV_EXPORT int hio_read (hio_t* io); #define hio_read_start(io) hio_read(io) #define hio_read_stop(io) hio_del(io, HV_READ) // hio_read_start => hread_cb => hio_read_stop HV_EXPORT int hio_read_once (hio_t* io); // hio_read_once => hread_cb(len) HV_EXPORT int hio_read_until_length(hio_t* io, unsigned int len); // hio_read_once => hread_cb(...delim) HV_EXPORT int hio_read_until_delim (hio_t* io, unsigned char delim); HV_EXPORT int hio_read_remain(hio_t* io); // @see examples/tinyhttpd.c examples/tinyproxyd.c #define hio_readline(io) hio_read_until_delim(io, '\n') #define hio_readstring(io) hio_read_until_delim(io, '\0') #define hio_readbytes(io, len) hio_read_until_length(io, len) #define hio_read_until(io, len) hio_read_until_length(io, len) // NOTE: hio_write is thread-safe, locked by recursive_mutex, allow to be called by other threads. // hio_try_write => hio_add(io, HV_WRITE) => write => hwrite_cb HV_EXPORT int hio_write (hio_t* io, const void* buf, size_t len); // NOTE: hio_close is thread-safe, hio_close_async will be called actually in other thread. // hio_del(io, HV_RDWR) => close => hclose_cb HV_EXPORT int hio_close (hio_t* io); // NOTE: hloop_post_event(hio_close_event) HV_EXPORT int hio_close_async(hio_t* io); //------------------high-level apis------------------------------------------- // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read HV_EXPORT hio_t* hread (hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb); // hio_get -> hio_setcb_write -> hio_write HV_EXPORT hio_t* hwrite (hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); // hio_get -> hio_close HV_EXPORT void hclose (hloop_t* loop, int fd); // tcp // hio_get -> hio_setcb_accept -> hio_accept HV_EXPORT hio_t* haccept (hloop_t* loop, int listenfd, haccept_cb accept_cb); // hio_get -> hio_setcb_connect -> hio_connect HV_EXPORT hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb); // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read HV_EXPORT hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb); // hio_get -> hio_setcb_write -> hio_write HV_EXPORT hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); // udp HV_EXPORT void hio_set_type(hio_t* io, hio_type_e type); HV_EXPORT void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen); HV_EXPORT void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen); // NOTE: must call hio_set_peeraddr before hrecvfrom/hsendto // hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read HV_EXPORT hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb); // hio_get -> hio_setcb_write -> hio_write HV_EXPORT hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); //-----------------top-level apis--------------------------------------------- // @hio_create_socket: socket -> bind -> listen // sockaddr_set_ipport -> socket -> hio_get(loop, sockfd) -> // side == HIO_SERVER_SIDE ? bind -> // type & HIO_TYPE_SOCK_STREAM ? listen -> HV_EXPORT hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type DEFAULT(HIO_TYPE_TCP), hio_side_e side DEFAULT(HIO_SERVER_SIDE)); // @tcp_server: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept // @see examples/tcp_echo_server.c HV_EXPORT hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); // @tcp_client: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect // @see examples/nc.c HV_EXPORT hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); // @ssl_server: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept // @see examples/tcp_echo_server.c => #define TEST_SSL 1 HV_EXPORT hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); // @ssl_client: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect // @see examples/nc.c => #define TEST_SSL 1 HV_EXPORT hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); // @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE) // @see examples/udp_echo_server.c HV_EXPORT hio_t* hloop_create_udp_server (hloop_t* loop, const char* host, int port); // @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE) // @see examples/nc.c HV_EXPORT hio_t* hloop_create_udp_client (hloop_t* loop, const char* host, int port); //-----------------pipe--------------------------------------------- // @see examples/pipe_test.c HV_EXPORT int hio_create_pipe(hloop_t* loop, hio_t* pipeio[2]); //-----------------upstream--------------------------------------------- // hio_read(io) // hio_read(io->upstream_io) HV_EXPORT void hio_read_upstream(hio_t* io); // on_write(io) -> hio_write_is_complete(io) -> hio_read(io->upstream_io) HV_EXPORT void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes); // hio_write(io->upstream_io, buf, bytes) HV_EXPORT void hio_write_upstream(hio_t* io, void* buf, int bytes); // hio_close(io->upstream_io) HV_EXPORT void hio_close_upstream(hio_t* io); // io1->upstream_io = io2; // io2->upstream_io = io1; // @see examples/socks5_proxy_server.c HV_EXPORT void hio_setup_upstream(hio_t* io1, hio_t* io2); // @return io->upstream_io HV_EXPORT hio_t* hio_get_upstream(hio_t* io); // @tcp_upstream: hio_create_socket -> hio_setup_upstream -> hio_connect -> on_connect -> hio_read_upstream // @return upstream_io // @see examples/tcp_proxy_server.c HV_EXPORT hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl DEFAULT(0)); #define hio_setup_ssl_upstream(io, host, port) hio_setup_tcp_upstream(io, host, port, 1) // @udp_upstream: hio_create_socket -> hio_setup_upstream -> hio_read_upstream // @return upstream_io // @see examples/udp_proxy_server.c HV_EXPORT hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port); //-----------------unpack--------------------------------------------- typedef enum { UNPACK_MODE_NONE = 0, UNPACK_BY_FIXED_LENGTH = 1, // Not recommended UNPACK_BY_DELIMITER = 2, // Suitable for text protocol UNPACK_BY_LENGTH_FIELD = 3, // Suitable for binary protocol } unpack_mode_e; #define DEFAULT_PACKAGE_MAX_LENGTH (1 << 21) // 2M // UNPACK_BY_DELIMITER #define PACKAGE_MAX_DELIMITER_BYTES 8 // UNPACK_BY_LENGTH_FIELD typedef enum { ENCODE_BY_VARINT = 17, // 1 MSB + 7 bits ENCODE_BY_LITTEL_ENDIAN = LITTLE_ENDIAN, // 1234 ENCODE_BY_BIG_ENDIAN = BIG_ENDIAN, // 4321 } unpack_coding_e; typedef struct unpack_setting_s { unpack_mode_e mode; unsigned int package_max_length; union { // UNPACK_BY_FIXED_LENGTH struct { unsigned int fixed_length; }; // UNPACK_BY_DELIMITER struct { unsigned char delimiter[PACKAGE_MAX_DELIMITER_BYTES]; unsigned short delimiter_bytes; }; /* * UNPACK_BY_LENGTH_FIELD * * package_len = head_len + body_len + length_adjustment * * if (length_field_coding == ENCODE_BY_VARINT) head_len = body_offset + varint_bytes - length_field_bytes; * else head_len = body_offset; * * length_field stores body length, exclude head length, * if length_field = head_len + body_len, then length_adjustment should be set to -head_len. * */ struct { unsigned short body_offset; // Equal to head length usually unsigned short length_field_offset; unsigned short length_field_bytes; short length_adjustment; unpack_coding_e length_field_coding; }; }; #ifdef __cplusplus unpack_setting_s() { // Recommended setting: // head = flags:1byte + length:4bytes = 5bytes mode = UNPACK_BY_LENGTH_FIELD; package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; fixed_length = 0; delimiter_bytes = 0; body_offset = 5; length_field_offset = 1; length_field_bytes = 4; length_field_coding = ENCODE_BY_BIG_ENDIAN; length_adjustment = 0; } #endif } unpack_setting_t; /* * @see examples/jsonrpc examples/protorpc * * NOTE: unpack_setting_t of multiple IOs of the same function also are same, * so only the pointer of unpack_setting_t is stored in hio_t, * the life time of unpack_setting_t shoud be guaranteed by caller. */ HV_EXPORT void hio_set_unpack(hio_t* io, unpack_setting_t* setting); HV_EXPORT void hio_unset_unpack(hio_t* io); // unpack examples /* unpack_setting_t ftp_unpack_setting; memset(&ftp_unpack_setting, 0, sizeof(unpack_setting_t)); ftp_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; ftp_unpack_setting.mode = UNPACK_BY_DELIMITER; ftp_unpack_setting.delimiter[0] = '\r'; ftp_unpack_setting.delimiter[1] = '\n'; ftp_unpack_setting.delimiter_bytes = 2; unpack_setting_t mqtt_unpack_setting = { .mode = UNPACK_BY_LENGTH_FIELD, .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, .body_offset = 2, .length_field_offset = 1, .length_field_bytes = 1, .length_field_coding = ENCODE_BY_VARINT, }; unpack_setting_t grpc_unpack_setting = { .mode = UNPACK_BY_LENGTH_FIELD, .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, .body_offset = 5, .length_field_offset = 1, .length_field_bytes = 4, .length_field_coding = ENCODE_BY_BIG_ENDIAN, }; */ //-----------------reconnect---------------------------------------- #define DEFAULT_RECONNECT_MIN_DELAY 1000 // ms #define DEFAULT_RECONNECT_MAX_DELAY 60000 // ms #define DEFAULT_RECONNECT_DELAY_POLICY 2 // exponential #define DEFAULT_RECONNECT_MAX_RETRY_CNT INFINITE typedef struct reconn_setting_s { uint32_t min_delay; // ms uint32_t max_delay; // ms uint32_t cur_delay; // ms /* * @delay_policy * 0: fixed * min_delay=3s => 3,3,3... * 1: linear * min_delay=3s max_delay=10s => 3,6,9,10,10... * other: exponential * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60... */ uint32_t delay_policy; uint32_t max_retry_cnt; uint32_t cur_retry_cnt; #ifdef __cplusplus reconn_setting_s() { min_delay = DEFAULT_RECONNECT_MIN_DELAY; max_delay = DEFAULT_RECONNECT_MAX_DELAY; cur_delay = 0; // 1,2,4,8,16,32,60,60... delay_policy = DEFAULT_RECONNECT_DELAY_POLICY; max_retry_cnt = DEFAULT_RECONNECT_MAX_RETRY_CNT; cur_retry_cnt = 0; } #endif } reconn_setting_t; HV_INLINE void reconn_setting_init(reconn_setting_t* reconn) { reconn->min_delay = DEFAULT_RECONNECT_MIN_DELAY; reconn->max_delay = DEFAULT_RECONNECT_MAX_DELAY; reconn->cur_delay = 0; // 1,2,4,8,16,32,60,60... reconn->delay_policy = DEFAULT_RECONNECT_DELAY_POLICY; reconn->max_retry_cnt = DEFAULT_RECONNECT_MAX_RETRY_CNT; reconn->cur_retry_cnt = 0; } HV_INLINE void reconn_setting_reset(reconn_setting_t* reconn) { reconn->cur_delay = 0; reconn->cur_retry_cnt = 0; } HV_INLINE bool reconn_setting_can_retry(reconn_setting_t* reconn) { ++reconn->cur_retry_cnt; return reconn->max_retry_cnt == INFINITE || reconn->cur_retry_cnt < reconn->max_retry_cnt; } HV_INLINE uint32_t reconn_setting_calc_delay(reconn_setting_t* reconn) { if (reconn->delay_policy == 0) { // fixed reconn->cur_delay = reconn->min_delay; } else if (reconn->delay_policy == 1) { // linear reconn->cur_delay += reconn->min_delay; } else { // exponential reconn->cur_delay *= reconn->delay_policy; } reconn->cur_delay = MAX(reconn->cur_delay, reconn->min_delay); reconn->cur_delay = MIN(reconn->cur_delay, reconn->max_delay); return reconn->cur_delay; } //-----------------LoadBalance------------------------------------- typedef enum { LB_RoundRobin, LB_Random, LB_LeastConnections, LB_IpHash, LB_UrlHash, } load_balance_e; //-----------------rudp--------------------------------------------- #if WITH_KCP #define WITH_RUDP 1 #endif #if WITH_RUDP // NOTE: hio_close_rudp is thread-safe. HV_EXPORT int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr DEFAULT(NULL)); #endif #if WITH_KCP typedef struct kcp_setting_s { // ikcp_create(conv, ...) unsigned int conv; // ikcp_nodelay(kcp, nodelay, interval, fastresend, nocwnd) int nodelay; int interval; int fastresend; int nocwnd; // ikcp_wndsize(kcp, sndwnd, rcvwnd) int sndwnd; int rcvwnd; // ikcp_setmtu(kcp, mtu) int mtu; // ikcp_update int update_interval; #ifdef __cplusplus kcp_setting_s() { conv = 0x11223344; // normal mode nodelay = 0; interval = 40; fastresend = 0; nocwnd = 0; // fast mode // nodelay = 1; // interval = 10; // fastresend = 2; // nocwnd = 1; sndwnd = 0; rcvwnd = 0; mtu = 1400; update_interval = 10; // ms } #endif } kcp_setting_t; HV_INLINE void kcp_setting_init_with_normal_mode(kcp_setting_t* setting) { memset(setting, 0, sizeof(kcp_setting_t)); setting->nodelay = 0; setting->interval = 40; setting->fastresend = 0; setting->nocwnd = 0; } HV_INLINE void kcp_setting_init_with_fast_mode(kcp_setting_t* setting) { memset(setting, 0, sizeof(kcp_setting_t)); setting->nodelay = 0; setting->interval = 30; setting->fastresend = 2; setting->nocwnd = 1; } HV_INLINE void kcp_setting_init_with_fast2_mode(kcp_setting_t* setting) { memset(setting, 0, sizeof(kcp_setting_t)); setting->nodelay = 1; setting->interval = 20; setting->fastresend = 2; setting->nocwnd = 1; } HV_INLINE void kcp_setting_init_with_fast3_mode(kcp_setting_t* setting) { memset(setting, 0, sizeof(kcp_setting_t)); setting->nodelay = 1; setting->interval = 10; setting->fastresend = 2; setting->nocwnd = 1; } // @see examples/udp_echo_server.c => #define TEST_KCP 1 HV_EXPORT int hio_set_kcp(hio_t* io, kcp_setting_t* setting DEFAULT(NULL)); #endif END_EXTERN_C #endif // HV_LOOP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/iocp.c000066400000000000000000000042761520575453600256750ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_IOCP #include "hplatform.h" #include "hdef.h" #include "hevent.h" #include "overlapio.h" typedef struct iocp_ctx_s { HANDLE iocp; } iocp_ctx_t; int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; iocp_ctx_t* iocp_ctx; HV_ALLOC_SIZEOF(iocp_ctx); iocp_ctx->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); loop->iowatcher = iocp_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { if (loop->iowatcher == NULL) return 0; iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; CloseHandle(iocp_ctx->iocp); HV_FREE(loop->iowatcher); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; hio_t* io = loop->ios.ptr[fd]; if (io && io->events == 0 && events != 0) { CreateIoCompletionPort((HANDLE)fd, iocp_ctx->iocp, 0, 0); } return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { hio_t* io = loop->ios.ptr[fd]; if ((io->events & ~events) == 0) { CancelIo((HANDLE)fd); } return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { if (loop->iowatcher == NULL) return 0; iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; DWORD bytes = 0; ULONG_PTR key = 0; LPOVERLAPPED povlp = NULL; BOOL bRet = GetQueuedCompletionStatus(iocp_ctx->iocp, &bytes, &key, &povlp, timeout); int err = 0; if (povlp == NULL) { err = WSAGetLastError(); if (err == WAIT_TIMEOUT || ERROR_NETNAME_DELETED || ERROR_OPERATION_ABORTED) { return 0; } return -err; } hoverlapped_t* hovlp = (hoverlapped_t*)povlp; hio_t* io = hovlp->io; if (bRet == FALSE) { err = WSAGetLastError(); printd("iocp ret=%d err=%d bytes=%u\n", bRet, err, bytes); // NOTE: when ConnectEx failed, err != 0 hovlp->error = err; } // NOTE: when WSASend/WSARecv disconnect, bytes = 0 hovlp->bytes = bytes; io->hovlp = hovlp; io->revents |= hovlp->event; EVENT_PENDING(hovlp->io); return 1; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/iowatcher.h000066400000000000000000000016271520575453600267320ustar00rootroot00000000000000#ifndef IO_WATCHER_H_ #define IO_WATCHER_H_ #include "hloop.h" #include "hplatform.h" #if !defined(EVENT_SELECT) && \ !defined(EVENT_POLL) && \ !defined(EVENT_EPOLL) && \ !defined(EVENT_KQUEUE) && \ !defined(EVENT_IOCP) && \ !defined(EVENT_PORT) && \ !defined(EVENT_NOEVENT) #ifdef OS_WIN #if WITH_WEPOLL #define EVENT_EPOLL // wepoll -> iocp #else #define EVENT_POLL // WSAPoll #endif #elif defined(OS_LINUX) #define EVENT_EPOLL #elif defined(OS_MAC) #define EVENT_KQUEUE #elif defined(OS_BSD) #define EVENT_KQUEUE #elif defined(OS_SOLARIS) #define EVENT_PORT #else #define EVENT_SELECT #endif #endif int iowatcher_init(hloop_t* loop); int iowatcher_cleanup(hloop_t* loop); int iowatcher_add_event(hloop_t* loop, int fd, int events); int iowatcher_del_event(hloop_t* loop, int fd, int events); int iowatcher_poll_events(hloop_t* loop, int timeout); #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/000077500000000000000000000000001520575453600253435ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/LICENSE000066400000000000000000000021021520575453600263430ustar00rootroot00000000000000MIT License Copyright (c) 2017 Lin Wei (skywind3000 at gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/hkcp.c000066400000000000000000000111771520575453600264430ustar00rootroot00000000000000#include "hkcp.h" #if WITH_KCP #include "hevent.h" #include "hlog.h" #include "hthread.h" static kcp_setting_t s_kcp_setting; static int __kcp_output(const char* buf, int len, ikcpcb* ikcp, void* userdata) { // printf("ikcp_output len=%d\n", len); rudp_entry_t* rudp = (rudp_entry_t*)userdata; assert(rudp != NULL && rudp->io != NULL); int nsend = sendto(rudp->io->fd, buf, len, 0, &rudp->addr.sa, SOCKADDR_LEN(&rudp->addr)); // printf("sendto nsend=%d\n", nsend); return nsend; } static void __kcp_update_timer_cb(htimer_t* timer) { rudp_entry_t* rudp = (rudp_entry_t*)timer->privdata; assert(rudp != NULL && rudp->io != NULL && rudp->kcp.ikcp != NULL); ikcp_update(rudp->kcp.ikcp, (IUINT32)(rudp->io->loop->cur_hrtime / 1000)); } void kcp_release(kcp_t* kcp) { if (kcp->ikcp == NULL) return; if (kcp->update_timer) { htimer_del(kcp->update_timer); kcp->update_timer = NULL; } HV_FREE(kcp->readbuf.base); kcp->readbuf.len = 0; // printf("ikcp_release ikcp=%p\n", kcp->ikcp); ikcp_release(kcp->ikcp); kcp->ikcp = NULL; } int hio_set_kcp(hio_t* io, kcp_setting_t* setting) { io->io_type = HIO_TYPE_KCP; io->kcp_setting = setting; return 0; } kcp_t* hio_get_kcp(hio_t* io, uint32_t conv) { rudp_entry_t* rudp = hio_get_rudp(io); assert(rudp != NULL); kcp_t* kcp = &rudp->kcp; if (kcp->ikcp != NULL) return kcp; if (io->kcp_setting == NULL) { io->kcp_setting = &s_kcp_setting; } kcp_setting_t* setting = io->kcp_setting; kcp->ikcp = ikcp_create(conv, rudp); // printf("ikcp_create conv=%u ikcp=%p\n", conv, kcp->ikcp); kcp->ikcp->output = __kcp_output; kcp->conv = conv; if (setting->interval > 0) { ikcp_nodelay(kcp->ikcp, setting->nodelay, setting->interval, setting->fastresend, setting->nocwnd); } if (setting->sndwnd > 0 && setting->rcvwnd > 0) { ikcp_wndsize(kcp->ikcp, setting->sndwnd, setting->rcvwnd); } if (setting->mtu > 0) { ikcp_setmtu(kcp->ikcp, setting->mtu); } if (kcp->update_timer == NULL) { int update_interval = setting->update_interval; if (update_interval == 0) { update_interval = DEFAULT_KCP_UPDATE_INTERVAL; } kcp->update_timer = htimer_add(io->loop, __kcp_update_timer_cb, update_interval, INFINITE); kcp->update_timer->privdata = rudp; } // NOTE: alloc kcp->readbuf when hio_read_kcp return kcp; } static void hio_write_kcp_event_cb(hevent_t* ev) { hio_t* io = (hio_t*)ev->userdata; hbuf_t* buf = (hbuf_t*)ev->privdata; hio_write_kcp(io, buf->base, buf->len); HV_FREE(buf); } static int hio_write_kcp_async(hio_t* io, const void* data, size_t len) { hbuf_t* buf = NULL; HV_ALLOC(buf, sizeof(hbuf_t) + len); buf->base = (char*)buf + sizeof(hbuf_t); buf->len = len; memcpy(buf->base, data, len); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.cb = hio_write_kcp_event_cb; ev.userdata = io; ev.privdata = buf; hloop_post_event(io->loop, &ev); return len; } int hio_write_kcp(hio_t* io, const void* buf, size_t len) { if (hv_gettid() != io->loop->tid) { return hio_write_kcp_async(io, buf, len); } IUINT32 conv = io->kcp_setting ? io->kcp_setting->conv : 0; kcp_t* kcp = hio_get_kcp(io, conv); // printf("hio_write_kcp conv=%u=%u\n", conv, kcp->conv); int nsend = ikcp_send(kcp->ikcp, (const char*)buf, len); // printf("ikcp_send len=%d nsend=%d\n", (int)len, nsend); if (nsend < 0) { hloge("ikcp_send error: %d", nsend); return nsend; } ikcp_update(kcp->ikcp, (IUINT32)io->loop->cur_hrtime / 1000); return len; } int hio_read_kcp (hio_t* io, void* buf, int readbytes) { IUINT32 conv = ikcp_getconv(buf); kcp_t* kcp = hio_get_kcp(io, conv); // printf("hio_read_kcp conv=%u=%u\n", conv, kcp->conv); if (kcp->conv != conv) { hloge("recv invalid kcp packet!"); hio_close_rudp(io, io->peeraddr); return -1; } // printf("ikcp_input len=%d\n", readbytes); int ret = ikcp_input(kcp->ikcp, (const char*)buf, readbytes); // printf("ikcp_input ret=%d\n", ret); if (ret != 0) { return 0; } if (kcp->readbuf.base == NULL || kcp->readbuf.len == 0) { kcp->readbuf.len = DEFAULT_KCP_READ_BUFSIZE; HV_ALLOC(kcp->readbuf.base, kcp->readbuf.len); } while (1) { int nrecv = ikcp_recv(kcp->ikcp, kcp->readbuf.base, kcp->readbuf.len); // printf("ikcp_recv nrecv=%d\n", nrecv); if (nrecv < 0) break; hio_read_cb(io, kcp->readbuf.base, nrecv); ret += nrecv; } return ret; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/hkcp.h000066400000000000000000000011371520575453600264430ustar00rootroot00000000000000#ifndef HV_KCP_H_ #define HV_KCP_H_ #include "hloop.h" #if WITH_KCP #include "ikcp.h" #include "hbuf.h" #define DEFAULT_KCP_UPDATE_INTERVAL 10 // ms #define DEFAULT_KCP_READ_BUFSIZE 1400 typedef struct kcp_s { ikcpcb* ikcp; uint32_t conv; htimer_t* update_timer; hbuf_t readbuf; } kcp_t; // NOTE: kcp_create in hio_get_kcp void kcp_release(kcp_t* kcp); kcp_t* hio_get_kcp (hio_t* io, uint32_t conv); int hio_read_kcp (hio_t* io, void* buf, int readbytes); int hio_write_kcp(hio_t* io, const void* buf, size_t len); #endif #endif // HV_KCP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/ikcp.c000066400000000000000000000757221520575453600264520ustar00rootroot00000000000000//===================================================================== // // KCP - A Better ARQ Protocol Implementation // skywind3000 (at) gmail.com, 2010-2011 // // Features: // + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. // + Maximum RTT reduce three times vs tcp. // + Lightweight, distributed as a single source file. // //===================================================================== #include "ikcp.h" #include #include #include #include #include //===================================================================== // KCP BASIC //===================================================================== const IUINT32 IKCP_RTO_NDL = 30; // no delay min rto const IUINT32 IKCP_RTO_MIN = 100; // normal min rto const IUINT32 IKCP_RTO_DEF = 200; const IUINT32 IKCP_RTO_MAX = 60000; const IUINT32 IKCP_CMD_PUSH = 81; // cmd: push data const IUINT32 IKCP_CMD_ACK = 82; // cmd: ack const IUINT32 IKCP_CMD_WASK = 83; // cmd: window probe (ask) const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell) const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS const IUINT32 IKCP_WND_SND = 32; const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size const IUINT32 IKCP_MTU_DEF = 1400; const IUINT32 IKCP_ACK_FAST = 3; const IUINT32 IKCP_INTERVAL = 100; const IUINT32 IKCP_OVERHEAD = 24; const IUINT32 IKCP_DEADLINK = 20; const IUINT32 IKCP_THRESH_INIT = 2; const IUINT32 IKCP_THRESH_MIN = 2; const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack //--------------------------------------------------------------------- // encode / decode //--------------------------------------------------------------------- /* encode 8 bits unsigned int */ static inline char *ikcp_encode8u(char *p, unsigned char c) { *(unsigned char*)p++ = c; return p; } /* decode 8 bits unsigned int */ static inline const char *ikcp_decode8u(const char *p, unsigned char *c) { *c = *(unsigned char*)p++; return p; } /* encode 16 bits unsigned int (lsb) */ static inline char *ikcp_encode16u(char *p, unsigned short w) { #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN *(unsigned char*)(p + 0) = (w & 255); *(unsigned char*)(p + 1) = (w >> 8); #else memcpy(p, &w, 2); #endif p += 2; return p; } /* decode 16 bits unsigned int (lsb) */ static inline const char *ikcp_decode16u(const char *p, unsigned short *w) { #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN *w = *(const unsigned char*)(p + 1); *w = *(const unsigned char*)(p + 0) + (*w << 8); #else memcpy(w, p, 2); #endif p += 2; return p; } /* encode 32 bits unsigned int (lsb) */ static inline char *ikcp_encode32u(char *p, IUINT32 l) { #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN *(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff); *(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff); *(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff); *(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff); #else memcpy(p, &l, 4); #endif p += 4; return p; } /* decode 32 bits unsigned int (lsb) */ static inline const char *ikcp_decode32u(const char *p, IUINT32 *l) { #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN *l = *(const unsigned char*)(p + 3); *l = *(const unsigned char*)(p + 2) + (*l << 8); *l = *(const unsigned char*)(p + 1) + (*l << 8); *l = *(const unsigned char*)(p + 0) + (*l << 8); #else memcpy(l, p, 4); #endif p += 4; return p; } static inline IUINT32 _imin_(IUINT32 a, IUINT32 b) { return a <= b ? a : b; } static inline IUINT32 _imax_(IUINT32 a, IUINT32 b) { return a >= b ? a : b; } static inline IUINT32 _ibound_(IUINT32 lower, IUINT32 middle, IUINT32 upper) { return _imin_(_imax_(lower, middle), upper); } static inline long _itimediff(IUINT32 later, IUINT32 earlier) { return ((IINT32)(later - earlier)); } //--------------------------------------------------------------------- // manage segment //--------------------------------------------------------------------- typedef struct IKCPSEG IKCPSEG; static void* (*ikcp_malloc_hook)(size_t) = NULL; static void (*ikcp_free_hook)(void *) = NULL; // internal malloc static void* ikcp_malloc(size_t size) { if (ikcp_malloc_hook) return ikcp_malloc_hook(size); return malloc(size); } // internal free static void ikcp_free(void *ptr) { if (ikcp_free_hook) { ikcp_free_hook(ptr); } else { free(ptr); } } // redefine allocator void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)) { ikcp_malloc_hook = new_malloc; ikcp_free_hook = new_free; } // allocate a new kcp segment static IKCPSEG* ikcp_segment_new(ikcpcb *kcp, int size) { return (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size); } // delete a segment static void ikcp_segment_delete(ikcpcb *kcp, IKCPSEG *seg) { ikcp_free(seg); } // write log void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...) { char buffer[1024]; va_list argptr; if ((mask & kcp->logmask) == 0 || kcp->writelog == 0) return; va_start(argptr, fmt); vsprintf(buffer, fmt, argptr); va_end(argptr); kcp->writelog(buffer, kcp, kcp->user); } // check log mask static int ikcp_canlog(const ikcpcb *kcp, int mask) { if ((mask & kcp->logmask) == 0 || kcp->writelog == NULL) return 0; return 1; } // output segment static int ikcp_output(ikcpcb *kcp, const void *data, int size) { assert(kcp); assert(kcp->output); if (ikcp_canlog(kcp, IKCP_LOG_OUTPUT)) { ikcp_log(kcp, IKCP_LOG_OUTPUT, "[RO] %ld bytes", (long)size); } if (size == 0) return 0; return kcp->output((const char*)data, size, kcp, kcp->user); } // output queue void ikcp_qprint(const char *name, const struct IQUEUEHEAD *head) { #if 0 const struct IQUEUEHEAD *p; printf("<%s>: [", name); for (p = head->next; p != head; p = p->next) { const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); printf("(%lu %d)", (unsigned long)seg->sn, (int)(seg->ts % 10000)); if (p->next != head) printf(","); } printf("]\n"); #endif } //--------------------------------------------------------------------- // create a new kcpcb //--------------------------------------------------------------------- ikcpcb* ikcp_create(IUINT32 conv, void *user) { ikcpcb *kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB)); if (kcp == NULL) return NULL; kcp->conv = conv; kcp->user = user; kcp->snd_una = 0; kcp->snd_nxt = 0; kcp->rcv_nxt = 0; kcp->ts_recent = 0; kcp->ts_lastack = 0; kcp->ts_probe = 0; kcp->probe_wait = 0; kcp->snd_wnd = IKCP_WND_SND; kcp->rcv_wnd = IKCP_WND_RCV; kcp->rmt_wnd = IKCP_WND_RCV; kcp->cwnd = 0; kcp->incr = 0; kcp->probe = 0; kcp->mtu = IKCP_MTU_DEF; kcp->mss = kcp->mtu - IKCP_OVERHEAD; kcp->stream = 0; kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3); if (kcp->buffer == NULL) { ikcp_free(kcp); return NULL; } iqueue_init(&kcp->snd_queue); iqueue_init(&kcp->rcv_queue); iqueue_init(&kcp->snd_buf); iqueue_init(&kcp->rcv_buf); kcp->nrcv_buf = 0; kcp->nsnd_buf = 0; kcp->nrcv_que = 0; kcp->nsnd_que = 0; kcp->state = 0; kcp->acklist = NULL; kcp->ackblock = 0; kcp->ackcount = 0; kcp->rx_srtt = 0; kcp->rx_rttval = 0; kcp->rx_rto = IKCP_RTO_DEF; kcp->rx_minrto = IKCP_RTO_MIN; kcp->current = 0; kcp->interval = IKCP_INTERVAL; kcp->ts_flush = IKCP_INTERVAL; kcp->nodelay = 0; kcp->updated = 0; kcp->logmask = 0; kcp->ssthresh = IKCP_THRESH_INIT; kcp->fastresend = 0; kcp->fastlimit = IKCP_FASTACK_LIMIT; kcp->nocwnd = 0; kcp->xmit = 0; kcp->dead_link = IKCP_DEADLINK; kcp->output = NULL; kcp->writelog = NULL; return kcp; } //--------------------------------------------------------------------- // release a new kcpcb //--------------------------------------------------------------------- void ikcp_release(ikcpcb *kcp) { assert(kcp); if (kcp) { IKCPSEG *seg; while (!iqueue_is_empty(&kcp->snd_buf)) { seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node); iqueue_del(&seg->node); ikcp_segment_delete(kcp, seg); } while (!iqueue_is_empty(&kcp->rcv_buf)) { seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); iqueue_del(&seg->node); ikcp_segment_delete(kcp, seg); } while (!iqueue_is_empty(&kcp->snd_queue)) { seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); iqueue_del(&seg->node); ikcp_segment_delete(kcp, seg); } while (!iqueue_is_empty(&kcp->rcv_queue)) { seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); iqueue_del(&seg->node); ikcp_segment_delete(kcp, seg); } if (kcp->buffer) { ikcp_free(kcp->buffer); } if (kcp->acklist) { ikcp_free(kcp->acklist); } kcp->nrcv_buf = 0; kcp->nsnd_buf = 0; kcp->nrcv_que = 0; kcp->nsnd_que = 0; kcp->ackcount = 0; kcp->buffer = NULL; kcp->acklist = NULL; ikcp_free(kcp); } } //--------------------------------------------------------------------- // set output callback, which will be invoked by kcp //--------------------------------------------------------------------- void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, ikcpcb *kcp, void *user)) { kcp->output = output; } //--------------------------------------------------------------------- // user/upper level recv: returns size, returns below zero for EAGAIN //--------------------------------------------------------------------- int ikcp_recv(ikcpcb *kcp, char *buffer, int len) { struct IQUEUEHEAD *p; int ispeek = (len < 0)? 1 : 0; int peeksize; int recover = 0; IKCPSEG *seg; assert(kcp); if (iqueue_is_empty(&kcp->rcv_queue)) return -1; if (len < 0) len = -len; peeksize = ikcp_peeksize(kcp); if (peeksize < 0) return -2; if (peeksize > len) return -3; if (kcp->nrcv_que >= kcp->rcv_wnd) recover = 1; // merge fragment for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue; ) { int fragment; seg = iqueue_entry(p, IKCPSEG, node); p = p->next; if (buffer) { memcpy(buffer, seg->data, seg->len); buffer += seg->len; } len += seg->len; fragment = seg->frg; if (ikcp_canlog(kcp, IKCP_LOG_RECV)) { ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn); } if (ispeek == 0) { iqueue_del(&seg->node); ikcp_segment_delete(kcp, seg); kcp->nrcv_que--; } if (fragment == 0) break; } assert(len == peeksize); // move available data from rcv_buf -> rcv_queue while (! iqueue_is_empty(&kcp->rcv_buf)) { seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { iqueue_del(&seg->node); kcp->nrcv_buf--; iqueue_add_tail(&seg->node, &kcp->rcv_queue); kcp->nrcv_que++; kcp->rcv_nxt++; } else { break; } } // fast recover if (kcp->nrcv_que < kcp->rcv_wnd && recover) { // ready to send back IKCP_CMD_WINS in ikcp_flush // tell remote my window size kcp->probe |= IKCP_ASK_TELL; } return len; } //--------------------------------------------------------------------- // peek data size //--------------------------------------------------------------------- int ikcp_peeksize(const ikcpcb *kcp) { struct IQUEUEHEAD *p; IKCPSEG *seg; int length = 0; assert(kcp); if (iqueue_is_empty(&kcp->rcv_queue)) return -1; seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); if (seg->frg == 0) return seg->len; if (kcp->nrcv_que < seg->frg + 1) return -1; for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) { seg = iqueue_entry(p, IKCPSEG, node); length += seg->len; if (seg->frg == 0) break; } return length; } //--------------------------------------------------------------------- // user/upper level send, returns below zero for error //--------------------------------------------------------------------- int ikcp_send(ikcpcb *kcp, const char *buffer, int len) { IKCPSEG *seg; int count, i; assert(kcp->mss > 0); if (len < 0) return -1; // append to previous segment in streaming mode (if possible) if (kcp->stream != 0) { if (!iqueue_is_empty(&kcp->snd_queue)) { IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node); if (old->len < kcp->mss) { int capacity = kcp->mss - old->len; int extend = (len < capacity)? len : capacity; seg = ikcp_segment_new(kcp, old->len + extend); assert(seg); if (seg == NULL) { return -2; } iqueue_add_tail(&seg->node, &kcp->snd_queue); memcpy(seg->data, old->data, old->len); if (buffer) { memcpy(seg->data + old->len, buffer, extend); buffer += extend; } seg->len = old->len + extend; seg->frg = 0; len -= extend; iqueue_del_init(&old->node); ikcp_segment_delete(kcp, old); } } if (len <= 0) { return 0; } } if (len <= (int)kcp->mss) count = 1; else count = (len + kcp->mss - 1) / kcp->mss; if (count >= (int)IKCP_WND_RCV) return -2; if (count == 0) count = 1; // fragment for (i = 0; i < count; i++) { int size = len > (int)kcp->mss ? (int)kcp->mss : len; seg = ikcp_segment_new(kcp, size); assert(seg); if (seg == NULL) { return -2; } if (buffer && len > 0) { memcpy(seg->data, buffer, size); } seg->len = size; seg->frg = (kcp->stream == 0)? (count - i - 1) : 0; iqueue_init(&seg->node); iqueue_add_tail(&seg->node, &kcp->snd_queue); kcp->nsnd_que++; if (buffer) { buffer += size; } len -= size; } return 0; } //--------------------------------------------------------------------- // parse ack //--------------------------------------------------------------------- static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt) { IINT32 rto = 0; if (kcp->rx_srtt == 0) { kcp->rx_srtt = rtt; kcp->rx_rttval = rtt / 2; } else { long delta = rtt - kcp->rx_srtt; if (delta < 0) delta = -delta; kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4; kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8; if (kcp->rx_srtt < 1) kcp->rx_srtt = 1; } rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval); kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX); } static void ikcp_shrink_buf(ikcpcb *kcp) { struct IQUEUEHEAD *p = kcp->snd_buf.next; if (p != &kcp->snd_buf) { IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); kcp->snd_una = seg->sn; } else { kcp->snd_una = kcp->snd_nxt; } } static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn) { struct IQUEUEHEAD *p, *next; if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) return; for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); next = p->next; if (sn == seg->sn) { iqueue_del(p); ikcp_segment_delete(kcp, seg); kcp->nsnd_buf--; break; } if (_itimediff(sn, seg->sn) < 0) { break; } } } static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una) { struct IQUEUEHEAD *p, *next; for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); next = p->next; if (_itimediff(una, seg->sn) > 0) { iqueue_del(p); ikcp_segment_delete(kcp, seg); kcp->nsnd_buf--; } else { break; } } } static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) { struct IQUEUEHEAD *p, *next; if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) return; for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); next = p->next; if (_itimediff(sn, seg->sn) < 0) { break; } else if (sn != seg->sn) { #ifndef IKCP_FASTACK_CONSERVE seg->fastack++; #else if (_itimediff(ts, seg->ts) >= 0) seg->fastack++; #endif } } } //--------------------------------------------------------------------- // ack append //--------------------------------------------------------------------- static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) { IUINT32 newsize = kcp->ackcount + 1; IUINT32 *ptr; if (newsize > kcp->ackblock) { IUINT32 *acklist; IUINT32 newblock; for (newblock = 8; newblock < newsize; newblock <<= 1); acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2); if (acklist == NULL) { assert(acklist != NULL); abort(); } if (kcp->acklist != NULL) { IUINT32 x; for (x = 0; x < kcp->ackcount; x++) { acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0]; acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1]; } ikcp_free(kcp->acklist); } kcp->acklist = acklist; kcp->ackblock = newblock; } ptr = &kcp->acklist[kcp->ackcount * 2]; ptr[0] = sn; ptr[1] = ts; kcp->ackcount++; } static void ikcp_ack_get(const ikcpcb *kcp, int p, IUINT32 *sn, IUINT32 *ts) { if (sn) sn[0] = kcp->acklist[p * 2 + 0]; if (ts) ts[0] = kcp->acklist[p * 2 + 1]; } //--------------------------------------------------------------------- // parse data //--------------------------------------------------------------------- void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg) { struct IQUEUEHEAD *p, *prev; IUINT32 sn = newseg->sn; int repeat = 0; if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 || _itimediff(sn, kcp->rcv_nxt) < 0) { ikcp_segment_delete(kcp, newseg); return; } for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) { IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); prev = p->prev; if (seg->sn == sn) { repeat = 1; break; } if (_itimediff(sn, seg->sn) > 0) { break; } } if (repeat == 0) { iqueue_init(&newseg->node); iqueue_add(&newseg->node, p); kcp->nrcv_buf++; } else { ikcp_segment_delete(kcp, newseg); } #if 0 ikcp_qprint("rcvbuf", &kcp->rcv_buf); printf("rcv_nxt=%lu\n", kcp->rcv_nxt); #endif // move available data from rcv_buf -> rcv_queue while (! iqueue_is_empty(&kcp->rcv_buf)) { IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { iqueue_del(&seg->node); kcp->nrcv_buf--; iqueue_add_tail(&seg->node, &kcp->rcv_queue); kcp->nrcv_que++; kcp->rcv_nxt++; } else { break; } } #if 0 ikcp_qprint("queue", &kcp->rcv_queue); printf("rcv_nxt=%lu\n", kcp->rcv_nxt); #endif #if 1 // printf("snd(buf=%d, queue=%d)\n", kcp->nsnd_buf, kcp->nsnd_que); // printf("rcv(buf=%d, queue=%d)\n", kcp->nrcv_buf, kcp->nrcv_que); #endif } //--------------------------------------------------------------------- // input data //--------------------------------------------------------------------- int ikcp_input(ikcpcb *kcp, const char *data, long size) { IUINT32 prev_una = kcp->snd_una; IUINT32 maxack = 0, latest_ts = 0; int flag = 0; if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) { ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size); } if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1; while (1) { IUINT32 ts, sn, len, una, conv; IUINT16 wnd; IUINT8 cmd, frg; IKCPSEG *seg; if (size < (int)IKCP_OVERHEAD) break; data = ikcp_decode32u(data, &conv); if (conv != kcp->conv) return -1; data = ikcp_decode8u(data, &cmd); data = ikcp_decode8u(data, &frg); data = ikcp_decode16u(data, &wnd); data = ikcp_decode32u(data, &ts); data = ikcp_decode32u(data, &sn); data = ikcp_decode32u(data, &una); data = ikcp_decode32u(data, &len); size -= IKCP_OVERHEAD; if ((long)size < (long)len || (int)len < 0) return -2; if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK && cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS) return -3; kcp->rmt_wnd = wnd; ikcp_parse_una(kcp, una); ikcp_shrink_buf(kcp); if (cmd == IKCP_CMD_ACK) { if (_itimediff(kcp->current, ts) >= 0) { ikcp_update_ack(kcp, _itimediff(kcp->current, ts)); } ikcp_parse_ack(kcp, sn); ikcp_shrink_buf(kcp); if (flag == 0) { flag = 1; maxack = sn; latest_ts = ts; } else { if (_itimediff(sn, maxack) > 0) { #ifndef IKCP_FASTACK_CONSERVE maxack = sn; latest_ts = ts; #else if (_itimediff(ts, latest_ts) > 0) { maxack = sn; latest_ts = ts; } #endif } } if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) { ikcp_log(kcp, IKCP_LOG_IN_ACK, "input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn, (long)_itimediff(kcp->current, ts), (long)kcp->rx_rto); } } else if (cmd == IKCP_CMD_PUSH) { if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) { ikcp_log(kcp, IKCP_LOG_IN_DATA, "input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts); } if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) { ikcp_ack_push(kcp, sn, ts); if (_itimediff(sn, kcp->rcv_nxt) >= 0) { seg = ikcp_segment_new(kcp, len); seg->conv = conv; seg->cmd = cmd; seg->frg = frg; seg->wnd = wnd; seg->ts = ts; seg->sn = sn; seg->una = una; seg->len = len; if (len > 0) { memcpy(seg->data, data, len); } ikcp_parse_data(kcp, seg); } } } else if (cmd == IKCP_CMD_WASK) { // ready to send back IKCP_CMD_WINS in ikcp_flush // tell remote my window size kcp->probe |= IKCP_ASK_TELL; if (ikcp_canlog(kcp, IKCP_LOG_IN_PROBE)) { ikcp_log(kcp, IKCP_LOG_IN_PROBE, "input probe"); } } else if (cmd == IKCP_CMD_WINS) { // do nothing if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) { ikcp_log(kcp, IKCP_LOG_IN_WINS, "input wins: %lu", (unsigned long)(wnd)); } } else { return -3; } data += len; size -= len; } if (flag != 0) { ikcp_parse_fastack(kcp, maxack, latest_ts); } if (_itimediff(kcp->snd_una, prev_una) > 0) { if (kcp->cwnd < kcp->rmt_wnd) { IUINT32 mss = kcp->mss; if (kcp->cwnd < kcp->ssthresh) { kcp->cwnd++; kcp->incr += mss; } else { if (kcp->incr < mss) kcp->incr = mss; kcp->incr += (mss * mss) / kcp->incr + (mss / 16); if ((kcp->cwnd + 1) * mss <= kcp->incr) { #if 1 kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1); #else kcp->cwnd++; #endif } } if (kcp->cwnd > kcp->rmt_wnd) { kcp->cwnd = kcp->rmt_wnd; kcp->incr = kcp->rmt_wnd * mss; } } } return 0; } //--------------------------------------------------------------------- // ikcp_encode_seg //--------------------------------------------------------------------- static char *ikcp_encode_seg(char *ptr, const IKCPSEG *seg) { ptr = ikcp_encode32u(ptr, seg->conv); ptr = ikcp_encode8u(ptr, (IUINT8)seg->cmd); ptr = ikcp_encode8u(ptr, (IUINT8)seg->frg); ptr = ikcp_encode16u(ptr, (IUINT16)seg->wnd); ptr = ikcp_encode32u(ptr, seg->ts); ptr = ikcp_encode32u(ptr, seg->sn); ptr = ikcp_encode32u(ptr, seg->una); ptr = ikcp_encode32u(ptr, seg->len); return ptr; } static int ikcp_wnd_unused(const ikcpcb *kcp) { if (kcp->nrcv_que < kcp->rcv_wnd) { return kcp->rcv_wnd - kcp->nrcv_que; } return 0; } //--------------------------------------------------------------------- // ikcp_flush //--------------------------------------------------------------------- void ikcp_flush(ikcpcb *kcp) { IUINT32 current = kcp->current; char *buffer = kcp->buffer; char *ptr = buffer; int count, size, i; IUINT32 resent, cwnd; IUINT32 rtomin; struct IQUEUEHEAD *p; int change = 0; int lost = 0; IKCPSEG seg; // 'ikcp_update' haven't been called. if (kcp->updated == 0) return; seg.conv = kcp->conv; seg.cmd = IKCP_CMD_ACK; seg.frg = 0; seg.wnd = ikcp_wnd_unused(kcp); seg.una = kcp->rcv_nxt; seg.len = 0; seg.sn = 0; seg.ts = 0; // flush acknowledges count = kcp->ackcount; for (i = 0; i < count; i++) { size = (int)(ptr - buffer); if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { ikcp_output(kcp, buffer, size); ptr = buffer; } ikcp_ack_get(kcp, i, &seg.sn, &seg.ts); ptr = ikcp_encode_seg(ptr, &seg); } kcp->ackcount = 0; // probe window size (if remote window size equals zero) if (kcp->rmt_wnd == 0) { if (kcp->probe_wait == 0) { kcp->probe_wait = IKCP_PROBE_INIT; kcp->ts_probe = kcp->current + kcp->probe_wait; } else { if (_itimediff(kcp->current, kcp->ts_probe) >= 0) { if (kcp->probe_wait < IKCP_PROBE_INIT) kcp->probe_wait = IKCP_PROBE_INIT; kcp->probe_wait += kcp->probe_wait / 2; if (kcp->probe_wait > IKCP_PROBE_LIMIT) kcp->probe_wait = IKCP_PROBE_LIMIT; kcp->ts_probe = kcp->current + kcp->probe_wait; kcp->probe |= IKCP_ASK_SEND; } } } else { kcp->ts_probe = 0; kcp->probe_wait = 0; } // flush window probing commands if (kcp->probe & IKCP_ASK_SEND) { seg.cmd = IKCP_CMD_WASK; size = (int)(ptr - buffer); if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { ikcp_output(kcp, buffer, size); ptr = buffer; } ptr = ikcp_encode_seg(ptr, &seg); } // flush window probing commands if (kcp->probe & IKCP_ASK_TELL) { seg.cmd = IKCP_CMD_WINS; size = (int)(ptr - buffer); if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { ikcp_output(kcp, buffer, size); ptr = buffer; } ptr = ikcp_encode_seg(ptr, &seg); } kcp->probe = 0; // calculate window size cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd); if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd); // move data from snd_queue to snd_buf while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) { IKCPSEG *newseg; if (iqueue_is_empty(&kcp->snd_queue)) break; newseg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); iqueue_del(&newseg->node); iqueue_add_tail(&newseg->node, &kcp->snd_buf); kcp->nsnd_que--; kcp->nsnd_buf++; newseg->conv = kcp->conv; newseg->cmd = IKCP_CMD_PUSH; newseg->wnd = seg.wnd; newseg->ts = current; newseg->sn = kcp->snd_nxt++; newseg->una = kcp->rcv_nxt; newseg->resendts = current; newseg->rto = kcp->rx_rto; newseg->fastack = 0; newseg->xmit = 0; } // calculate resent resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff; rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0; // flush data segments for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { IKCPSEG *segment = iqueue_entry(p, IKCPSEG, node); int needsend = 0; if (segment->xmit == 0) { needsend = 1; segment->xmit++; segment->rto = kcp->rx_rto; segment->resendts = current + segment->rto + rtomin; } else if (_itimediff(current, segment->resendts) >= 0) { needsend = 1; segment->xmit++; kcp->xmit++; if (kcp->nodelay == 0) { segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto); } else { IINT32 step = (kcp->nodelay < 2)? ((IINT32)(segment->rto)) : kcp->rx_rto; segment->rto += step / 2; } segment->resendts = current + segment->rto; lost = 1; } else if (segment->fastack >= resent) { if ((int)segment->xmit <= kcp->fastlimit || kcp->fastlimit <= 0) { needsend = 1; segment->xmit++; segment->fastack = 0; segment->resendts = current + segment->rto; change++; } } if (needsend) { int need; segment->ts = current; segment->wnd = seg.wnd; segment->una = kcp->rcv_nxt; size = (int)(ptr - buffer); need = IKCP_OVERHEAD + segment->len; if (size + need > (int)kcp->mtu) { ikcp_output(kcp, buffer, size); ptr = buffer; } ptr = ikcp_encode_seg(ptr, segment); if (segment->len > 0) { memcpy(ptr, segment->data, segment->len); ptr += segment->len; } if (segment->xmit >= kcp->dead_link) { kcp->state = (IUINT32)-1; } } } // flash remain segments size = (int)(ptr - buffer); if (size > 0) { ikcp_output(kcp, buffer, size); } // update ssthresh if (change) { IUINT32 inflight = kcp->snd_nxt - kcp->snd_una; kcp->ssthresh = inflight / 2; if (kcp->ssthresh < IKCP_THRESH_MIN) kcp->ssthresh = IKCP_THRESH_MIN; kcp->cwnd = kcp->ssthresh + resent; kcp->incr = kcp->cwnd * kcp->mss; } if (lost) { kcp->ssthresh = cwnd / 2; if (kcp->ssthresh < IKCP_THRESH_MIN) kcp->ssthresh = IKCP_THRESH_MIN; kcp->cwnd = 1; kcp->incr = kcp->mss; } if (kcp->cwnd < 1) { kcp->cwnd = 1; kcp->incr = kcp->mss; } } //--------------------------------------------------------------------- // update state (call it repeatedly, every 10ms-100ms), or you can ask // ikcp_check when to call it again (without ikcp_input/_send calling). // 'current' - current timestamp in millisec. //--------------------------------------------------------------------- void ikcp_update(ikcpcb *kcp, IUINT32 current) { IINT32 slap; kcp->current = current; if (kcp->updated == 0) { kcp->updated = 1; kcp->ts_flush = kcp->current; } slap = _itimediff(kcp->current, kcp->ts_flush); if (slap >= 10000 || slap < -10000) { kcp->ts_flush = kcp->current; slap = 0; } if (slap >= 0) { kcp->ts_flush += kcp->interval; if (_itimediff(kcp->current, kcp->ts_flush) >= 0) { kcp->ts_flush = kcp->current + kcp->interval; } ikcp_flush(kcp); } } //--------------------------------------------------------------------- // Determine when should you invoke ikcp_update: // returns when you should invoke ikcp_update in millisec, if there // is no ikcp_input/_send calling. you can call ikcp_update in that // time, instead of call update repeatly. // Important to reduce unnacessary ikcp_update invoking. use it to // schedule ikcp_update (eg. implementing an epoll-like mechanism, // or optimize ikcp_update when handling massive kcp connections) //--------------------------------------------------------------------- IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current) { IUINT32 ts_flush = kcp->ts_flush; IINT32 tm_flush = 0x7fffffff; IINT32 tm_packet = 0x7fffffff; IUINT32 minimal = 0; struct IQUEUEHEAD *p; if (kcp->updated == 0) { return current; } if (_itimediff(current, ts_flush) >= 10000 || _itimediff(current, ts_flush) < -10000) { ts_flush = current; } if (_itimediff(current, ts_flush) >= 0) { return current; } tm_flush = _itimediff(ts_flush, current); for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); IINT32 diff = _itimediff(seg->resendts, current); if (diff <= 0) { return current; } if (diff < tm_packet) tm_packet = diff; } minimal = (IUINT32)(tm_packet < tm_flush ? tm_packet : tm_flush); if (minimal >= kcp->interval) minimal = kcp->interval; return current + minimal; } int ikcp_setmtu(ikcpcb *kcp, int mtu) { char *buffer; if (mtu < 50 || mtu < (int)IKCP_OVERHEAD) return -1; buffer = (char*)ikcp_malloc((mtu + IKCP_OVERHEAD) * 3); if (buffer == NULL) return -2; kcp->mtu = mtu; kcp->mss = kcp->mtu - IKCP_OVERHEAD; ikcp_free(kcp->buffer); kcp->buffer = buffer; return 0; } int ikcp_interval(ikcpcb *kcp, int interval) { if (interval > 5000) interval = 5000; else if (interval < 10) interval = 10; kcp->interval = interval; return 0; } int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc) { if (nodelay >= 0) { kcp->nodelay = nodelay; if (nodelay) { kcp->rx_minrto = IKCP_RTO_NDL; } else { kcp->rx_minrto = IKCP_RTO_MIN; } } if (interval >= 0) { if (interval > 5000) interval = 5000; else if (interval < 10) interval = 10; kcp->interval = interval; } if (resend >= 0) { kcp->fastresend = resend; } if (nc >= 0) { kcp->nocwnd = nc; } return 0; } int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd) { if (kcp) { if (sndwnd > 0) { kcp->snd_wnd = sndwnd; } if (rcvwnd > 0) { // must >= max fragment size kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV); } } return 0; } int ikcp_waitsnd(const ikcpcb *kcp) { return kcp->nsnd_buf + kcp->nsnd_que; } // read conv IUINT32 ikcp_getconv(const void *ptr) { IUINT32 conv; ikcp_decode32u((const char*)ptr, &conv); return conv; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kcp/ikcp.h000066400000000000000000000276061520575453600264550ustar00rootroot00000000000000//===================================================================== // // KCP - A Better ARQ Protocol Implementation // skywind3000 (at) gmail.com, 2010-2011 // // Features: // + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. // + Maximum RTT reduce three times vs tcp. // + Lightweight, distributed as a single source file. // //===================================================================== #ifndef __IKCP_H__ #define __IKCP_H__ #include #include #include //===================================================================== // 32BIT INTEGER DEFINITION //===================================================================== #ifndef __INTEGER_32_BITS__ #define __INTEGER_32_BITS__ #if defined(_WIN64) || defined(WIN64) || defined(__amd64__) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_IA64) || \ defined(_M_AMD64) typedef unsigned int ISTDUINT32; typedef int ISTDINT32; #elif defined(_WIN32) || defined(WIN32) || defined(__i386__) || \ defined(__i386) || defined(_M_X86) typedef unsigned long ISTDUINT32; typedef long ISTDINT32; #elif defined(__MACOS__) typedef UInt32 ISTDUINT32; typedef SInt32 ISTDINT32; #elif defined(__APPLE__) && defined(__MACH__) #include typedef u_int32_t ISTDUINT32; typedef int32_t ISTDINT32; #elif defined(__BEOS__) #include typedef u_int32_t ISTDUINT32; typedef int32_t ISTDINT32; #elif (defined(_MSC_VER) || defined(__BORLANDC__)) && (!defined(__MSDOS__)) typedef unsigned __int32 ISTDUINT32; typedef __int32 ISTDINT32; #elif defined(__GNUC__) #include typedef uint32_t ISTDUINT32; typedef int32_t ISTDINT32; #else typedef unsigned long ISTDUINT32; typedef long ISTDINT32; #endif #endif //===================================================================== // Integer Definition //===================================================================== #ifndef __IINT8_DEFINED #define __IINT8_DEFINED typedef char IINT8; #endif #ifndef __IUINT8_DEFINED #define __IUINT8_DEFINED typedef unsigned char IUINT8; #endif #ifndef __IUINT16_DEFINED #define __IUINT16_DEFINED typedef unsigned short IUINT16; #endif #ifndef __IINT16_DEFINED #define __IINT16_DEFINED typedef short IINT16; #endif #ifndef __IINT32_DEFINED #define __IINT32_DEFINED typedef ISTDINT32 IINT32; #endif #ifndef __IUINT32_DEFINED #define __IUINT32_DEFINED typedef ISTDUINT32 IUINT32; #endif #ifndef __IINT64_DEFINED #define __IINT64_DEFINED #if defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 IINT64; #else typedef long long IINT64; #endif #endif #ifndef __IUINT64_DEFINED #define __IUINT64_DEFINED #if defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 IUINT64; #else typedef unsigned long long IUINT64; #endif #endif #ifndef INLINE #if defined(__GNUC__) #if (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) #define INLINE __inline__ __attribute__((always_inline)) #else #define INLINE __inline__ #endif #elif (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__)) #define INLINE __inline #else #define INLINE #endif #endif #if (!defined(__cplusplus)) && (!defined(inline)) #define inline INLINE #endif //===================================================================== // QUEUE DEFINITION //===================================================================== #ifndef __IQUEUE_DEF__ #define __IQUEUE_DEF__ struct IQUEUEHEAD { struct IQUEUEHEAD *next, *prev; }; typedef struct IQUEUEHEAD iqueue_head; //--------------------------------------------------------------------- // queue init //--------------------------------------------------------------------- #define IQUEUE_HEAD_INIT(name) { &(name), &(name) } #define IQUEUE_HEAD(name) \ struct IQUEUEHEAD name = IQUEUE_HEAD_INIT(name) #define IQUEUE_INIT(ptr) ( \ (ptr)->next = (ptr), (ptr)->prev = (ptr)) #define IOFFSETOF(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #define ICONTAINEROF(ptr, type, member) ( \ (type*)( ((char*)((type*)ptr)) - IOFFSETOF(type, member)) ) #define IQUEUE_ENTRY(ptr, type, member) ICONTAINEROF(ptr, type, member) //--------------------------------------------------------------------- // queue operation //--------------------------------------------------------------------- #define IQUEUE_ADD(node, head) ( \ (node)->prev = (head), (node)->next = (head)->next, \ (head)->next->prev = (node), (head)->next = (node)) #define IQUEUE_ADD_TAIL(node, head) ( \ (node)->prev = (head)->prev, (node)->next = (head), \ (head)->prev->next = (node), (head)->prev = (node)) #define IQUEUE_DEL_BETWEEN(p, n) ((n)->prev = (p), (p)->next = (n)) #define IQUEUE_DEL(entry) (\ (entry)->next->prev = (entry)->prev, \ (entry)->prev->next = (entry)->next, \ (entry)->next = 0, (entry)->prev = 0) #define IQUEUE_DEL_INIT(entry) do { \ IQUEUE_DEL(entry); IQUEUE_INIT(entry); } while (0) #define IQUEUE_IS_EMPTY(entry) ((entry) == (entry)->next) #define iqueue_init IQUEUE_INIT #define iqueue_entry IQUEUE_ENTRY #define iqueue_add IQUEUE_ADD #define iqueue_add_tail IQUEUE_ADD_TAIL #define iqueue_del IQUEUE_DEL #define iqueue_del_init IQUEUE_DEL_INIT #define iqueue_is_empty IQUEUE_IS_EMPTY #define IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) \ for ((iterator) = iqueue_entry((head)->next, TYPE, MEMBER); \ &((iterator)->MEMBER) != (head); \ (iterator) = iqueue_entry((iterator)->MEMBER.next, TYPE, MEMBER)) #define iqueue_foreach(iterator, head, TYPE, MEMBER) \ IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) #define iqueue_foreach_entry(pos, head) \ for( (pos) = (head)->next; (pos) != (head) ; (pos) = (pos)->next ) #define __iqueue_splice(list, head) do { \ iqueue_head *first = (list)->next, *last = (list)->prev; \ iqueue_head *at = (head)->next; \ (first)->prev = (head), (head)->next = (first); \ (last)->next = (at), (at)->prev = (last); } while (0) #define iqueue_splice(list, head) do { \ if (!iqueue_is_empty(list)) __iqueue_splice(list, head); } while (0) #define iqueue_splice_init(list, head) do { \ iqueue_splice(list, head); iqueue_init(list); } while (0) #ifdef _MSC_VER #pragma warning(disable:4311) #pragma warning(disable:4312) #pragma warning(disable:4996) #endif #endif //--------------------------------------------------------------------- // BYTE ORDER & ALIGNMENT //--------------------------------------------------------------------- #ifndef IWORDS_BIG_ENDIAN #ifdef _BIG_ENDIAN_ #if _BIG_ENDIAN_ #define IWORDS_BIG_ENDIAN 1 #endif #endif #ifndef IWORDS_BIG_ENDIAN #if defined(__hppa__) || \ defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ (defined(__MIPS__) && defined(__MIPSEB__)) || \ defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ defined(__sparc__) || defined(__powerpc__) || \ defined(__mc68000__) || defined(__s390x__) || defined(__s390__) #define IWORDS_BIG_ENDIAN 1 #endif #endif #ifndef IWORDS_BIG_ENDIAN #define IWORDS_BIG_ENDIAN 0 #endif #endif #ifndef IWORDS_MUST_ALIGN #if defined(__i386__) || defined(__i386) || defined(_i386_) #define IWORDS_MUST_ALIGN 0 #elif defined(_M_IX86) || defined(_X86_) || defined(__x86_64__) #define IWORDS_MUST_ALIGN 0 #elif defined(__amd64) || defined(__amd64__) #define IWORDS_MUST_ALIGN 0 #else #define IWORDS_MUST_ALIGN 1 #endif #endif //===================================================================== // SEGMENT //===================================================================== struct IKCPSEG { struct IQUEUEHEAD node; IUINT32 conv; IUINT32 cmd; IUINT32 frg; IUINT32 wnd; IUINT32 ts; IUINT32 sn; IUINT32 una; IUINT32 len; IUINT32 resendts; IUINT32 rto; IUINT32 fastack; IUINT32 xmit; char data[1]; }; //--------------------------------------------------------------------- // IKCPCB //--------------------------------------------------------------------- struct IKCPCB { IUINT32 conv, mtu, mss, state; IUINT32 snd_una, snd_nxt, rcv_nxt; IUINT32 ts_recent, ts_lastack, ssthresh; IINT32 rx_rttval, rx_srtt, rx_rto, rx_minrto; IUINT32 snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe; IUINT32 current, interval, ts_flush, xmit; IUINT32 nrcv_buf, nsnd_buf; IUINT32 nrcv_que, nsnd_que; IUINT32 nodelay, updated; IUINT32 ts_probe, probe_wait; IUINT32 dead_link, incr; struct IQUEUEHEAD snd_queue; struct IQUEUEHEAD rcv_queue; struct IQUEUEHEAD snd_buf; struct IQUEUEHEAD rcv_buf; IUINT32 *acklist; IUINT32 ackcount; IUINT32 ackblock; void *user; char *buffer; int fastresend; int fastlimit; int nocwnd, stream; int logmask; int (*output)(const char *buf, int len, struct IKCPCB *kcp, void *user); void (*writelog)(const char *log, struct IKCPCB *kcp, void *user); }; typedef struct IKCPCB ikcpcb; #define IKCP_LOG_OUTPUT 1 #define IKCP_LOG_INPUT 2 #define IKCP_LOG_SEND 4 #define IKCP_LOG_RECV 8 #define IKCP_LOG_IN_DATA 16 #define IKCP_LOG_IN_ACK 32 #define IKCP_LOG_IN_PROBE 64 #define IKCP_LOG_IN_WINS 128 #define IKCP_LOG_OUT_DATA 256 #define IKCP_LOG_OUT_ACK 512 #define IKCP_LOG_OUT_PROBE 1024 #define IKCP_LOG_OUT_WINS 2048 #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------- // interface //--------------------------------------------------------------------- // create a new kcp control object, 'conv' must equal in two endpoint // from the same connection. 'user' will be passed to the output callback // output callback can be setup like this: 'kcp->output = my_udp_output' ikcpcb* ikcp_create(IUINT32 conv, void *user); // release kcp control object void ikcp_release(ikcpcb *kcp); // set output callback, which will be invoked by kcp void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, ikcpcb *kcp, void *user)); // user/upper level recv: returns size, returns below zero for EAGAIN int ikcp_recv(ikcpcb *kcp, char *buffer, int len); // user/upper level send, returns below zero for error int ikcp_send(ikcpcb *kcp, const char *buffer, int len); // update state (call it repeatedly, every 10ms-100ms), or you can ask // ikcp_check when to call it again (without ikcp_input/_send calling). // 'current' - current timestamp in millisec. void ikcp_update(ikcpcb *kcp, IUINT32 current); // Determine when should you invoke ikcp_update: // returns when you should invoke ikcp_update in millisec, if there // is no ikcp_input/_send calling. you can call ikcp_update in that // time, instead of call update repeatly. // Important to reduce unnacessary ikcp_update invoking. use it to // schedule ikcp_update (eg. implementing an epoll-like mechanism, // or optimize ikcp_update when handling massive kcp connections) IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current); // when you received a low level packet (eg. UDP packet), call it int ikcp_input(ikcpcb *kcp, const char *data, long size); // flush pending data void ikcp_flush(ikcpcb *kcp); // check the size of next message in the recv queue int ikcp_peeksize(const ikcpcb *kcp); // change MTU size, default is 1400 int ikcp_setmtu(ikcpcb *kcp, int mtu); // set maximum window size: sndwnd=32, rcvwnd=32 by default int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd); // get how many packet is waiting to be sent int ikcp_waitsnd(const ikcpcb *kcp); // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) // nodelay: 0:disable(default), 1:enable // interval: internal update timer interval in millisec, default is 100ms // resend: 0:disable fast resend(default), 1:enable fast resend // nc: 0:normal congestion control(default), 1:disable congestion control int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc); void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...); // setup allocator void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)); // read conv IUINT32 ikcp_getconv(const void *ptr); #ifdef __cplusplus } #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/kqueue.c000066400000000000000000000123761520575453600262420ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_KQUEUE #include "hplatform.h" #include "hdef.h" #include #include "hevent.h" #define EVENTS_INIT_SIZE 64 #define READ_INDEX 0 #define WRITE_INDEX 1 #define EVENT_INDEX(type) ((type == EVFILT_READ) ? READ_INDEX : WRITE_INDEX) typedef struct kqueue_ctx_s { int kqfd; int capacity; int nchanges; struct kevent* changes; //int nevents; // nevents == nchanges struct kevent* events; } kqueue_ctx_t; static void kqueue_ctx_resize(kqueue_ctx_t* kqueue_ctx, int size) { int bytes = sizeof(struct kevent) * size; int oldbytes = sizeof(struct kevent) * kqueue_ctx->capacity; kqueue_ctx->changes = (struct kevent*)hv_realloc(kqueue_ctx->changes, bytes, oldbytes); kqueue_ctx->events = (struct kevent*)hv_realloc(kqueue_ctx->events, bytes, oldbytes); kqueue_ctx->capacity = size; } int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; kqueue_ctx_t* kqueue_ctx; HV_ALLOC_SIZEOF(kqueue_ctx); kqueue_ctx->kqfd = kqueue(); kqueue_ctx->capacity = EVENTS_INIT_SIZE; kqueue_ctx->nchanges = 0; int bytes = sizeof(struct kevent) * kqueue_ctx->capacity; HV_ALLOC(kqueue_ctx->changes, bytes); HV_ALLOC(kqueue_ctx->events, bytes); loop->iowatcher = kqueue_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { if (loop->iowatcher == NULL) return 0; kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; close(kqueue_ctx->kqfd); HV_FREE(kqueue_ctx->changes); HV_FREE(kqueue_ctx->events); HV_FREE(loop->iowatcher); return 0; } static int __add_event(hloop_t* loop, int fd, int event) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; hio_t* io = loop->ios.ptr[fd]; int idx = io->event_index[EVENT_INDEX(event)]; if (idx < 0) { io->event_index[EVENT_INDEX(event)] = idx = kqueue_ctx->nchanges; kqueue_ctx->nchanges++; if (idx == kqueue_ctx->capacity) { kqueue_ctx_resize(kqueue_ctx, kqueue_ctx->capacity*2); } memset(kqueue_ctx->changes+idx, 0, sizeof(struct kevent)); kqueue_ctx->changes[idx].ident = fd; } assert(kqueue_ctx->changes[idx].ident == fd); kqueue_ctx->changes[idx].filter = event; kqueue_ctx->changes[idx].flags = EV_ADD|EV_ENABLE; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, NULL, 0, &ts); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (events & HV_READ) { __add_event(loop, fd, EVFILT_READ); } if (events & HV_WRITE) { __add_event(loop, fd, EVFILT_WRITE); } return 0; } static int __del_event(hloop_t* loop, int fd, int event) { kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; if (kqueue_ctx == NULL) return 0; hio_t* io = loop->ios.ptr[fd]; int idx = io->event_index[EVENT_INDEX(event)]; if (idx < 0) return 0; assert(kqueue_ctx->changes[idx].ident == fd); kqueue_ctx->changes[idx].flags = EV_DELETE; io->event_index[EVENT_INDEX(event)] = -1; int lastidx = kqueue_ctx->nchanges - 1; if (idx < lastidx) { // swap struct kevent tmp; tmp = kqueue_ctx->changes[idx]; kqueue_ctx->changes[idx] = kqueue_ctx->changes[lastidx]; kqueue_ctx->changes[lastidx] = tmp; hio_t* last = loop->ios.ptr[kqueue_ctx->changes[idx].ident]; if (last) { last->event_index[EVENT_INDEX(kqueue_ctx->changes[idx].filter)] = idx; } } struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, NULL, 0, &ts); kqueue_ctx->nchanges--; return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { if (events & HV_READ) { __del_event(loop, fd, EVFILT_READ); } if (events & HV_WRITE) { __del_event(loop, fd, EVFILT_WRITE); } return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; if (kqueue_ctx == NULL) return 0; if (kqueue_ctx->nchanges == 0) return 0; struct timespec ts, *tp; if (timeout == INFINITE) { tp = NULL; } else { ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; tp = &ts; } int nkqueue = kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, kqueue_ctx->events, kqueue_ctx->nchanges, tp); if (nkqueue < 0) { perror("kevent"); return nkqueue; } if (nkqueue == 0) return 0; int nevents = 0; for (int i = 0; i < nkqueue; ++i) { if (kqueue_ctx->events[i].flags & EV_ERROR) { continue; } ++nevents; int fd = kqueue_ctx->events[i].ident; int revents = kqueue_ctx->events[i].filter; hio_t* io = loop->ios.ptr[fd]; if (io) { if (revents & EVFILT_READ) { io->revents |= HV_READ; } if (revents & EVFILT_WRITE) { io->revents |= HV_WRITE; } EVENT_PENDING(io); } if (nevents == nkqueue) break; } return nevents; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/nio.c000066400000000000000000000426571520575453600255350ustar00rootroot00000000000000#include "iowatcher.h" #ifndef EVENT_IOCP #include "hevent.h" #include "hsocket.h" #include "hssl.h" #include "hlog.h" #include "herr.h" #include "hthread.h" static void __connect_timeout_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; if (io) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("connect timeout [%s] <=> [%s]", SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); io->error = ETIMEDOUT; hio_close(io); } } static void __close_timeout_cb(htimer_t* timer) { hio_t* io = (hio_t*)timer->privdata; if (io) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("close timeout [%s] <=> [%s]", SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); io->error = ETIMEDOUT; hio_close(io); } } static void __accept_cb(hio_t* io) { hio_accept_cb(io); } static void __connect_cb(hio_t* io) { hio_del_connect_timer(io); hio_connect_cb(io); } static void __read_cb(hio_t* io, void* buf, int readbytes) { // printd("> %.*s\n", readbytes, buf); io->last_read_hrtime = io->loop->cur_hrtime; hio_handle_read(io, buf, readbytes); } static void __write_cb(hio_t* io, const void* buf, int writebytes) { // printd("< %.*s\n", writebytes, buf); io->last_write_hrtime = io->loop->cur_hrtime; hio_write_cb(io, buf, writebytes); } static void __close_cb(hio_t* io) { // printd("close fd=%d\n", io->fd); hio_del_connect_timer(io); hio_del_close_timer(io); hio_del_read_timer(io); hio_del_write_timer(io); hio_del_keepalive_timer(io); hio_del_heartbeat_timer(io); hio_close_cb(io); } static void ssl_server_handshake(hio_t* io) { printd("ssl server handshake...\n"); int ret = hssl_accept(io->ssl); if (ret == 0) { // handshake finish hio_del(io, HV_READ); printd("ssl handshake finished.\n"); __accept_cb(io); } else if (ret == HSSL_WANT_READ) { if ((io->events & HV_READ) == 0) { hio_add(io, ssl_server_handshake, HV_READ); } } else { hloge("ssl handshake failed: %d", ret); io->error = ERR_SSL_HANDSHAKE; hio_close(io); } } static void ssl_client_handshake(hio_t* io) { printd("ssl client handshake...\n"); int ret = hssl_connect(io->ssl); if (ret == 0) { // handshake finish hio_del(io, HV_READ); printd("ssl handshake finished.\n"); __connect_cb(io); } else if (ret == HSSL_WANT_READ) { if ((io->events & HV_READ) == 0) { hio_add(io, ssl_client_handshake, HV_READ); } } else { hloge("ssl handshake failed: %d", ret); io->error = ERR_SSL_HANDSHAKE; hio_close(io); } } static void nio_accept(hio_t* io) { // printd("nio_accept listenfd=%d\n", io->fd); int connfd = 0, err = 0, accept_cnt = 0; socklen_t addrlen; hio_t* connio = NULL; while (accept_cnt++ < 3) { addrlen = sizeof(sockaddr_u); connfd = accept(io->fd, io->peeraddr, &addrlen); if (connfd < 0) { err = socket_errno(); if (err == EAGAIN || err == EINTR) { return; } else { perror("accept"); io->error = err; goto accept_error; } } addrlen = sizeof(sockaddr_u); getsockname(connfd, io->localaddr, &addrlen); connio = hio_get(io->loop, connfd); // NOTE: inherit from listenio connio->accept_cb = io->accept_cb; connio->userdata = io->userdata; if (io->unpack_setting) { hio_set_unpack(connio, io->unpack_setting); } if (io->io_type == HIO_TYPE_SSL) { if (connio->ssl == NULL) { // io->ssl_ctx > g_ssl_ctx > hssl_ctx_new hssl_ctx_t ssl_ctx = NULL; if (io->ssl_ctx) { ssl_ctx = io->ssl_ctx; } else if (g_ssl_ctx) { ssl_ctx = g_ssl_ctx; } else { io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); io->alloced_ssl_ctx = 1; } if (ssl_ctx == NULL) { io->error = ERR_NEW_SSL_CTX; goto accept_error; } hssl_t ssl = hssl_new(ssl_ctx, connfd); if (ssl == NULL) { io->error = ERR_NEW_SSL; goto accept_error; } connio->ssl = ssl; } hio_enable_ssl(connio); ssl_server_handshake(connio); } else { // NOTE: SSL call accept_cb after handshake finished __accept_cb(connio); } } return; accept_error: hloge("listenfd=%d accept error: %s:%d", io->fd, socket_strerror(io->error), io->error); // NOTE: Don't close listen fd automatically anyway. // hio_close(io); } static void nio_connect(hio_t* io) { // printd("nio_connect connfd=%d\n", io->fd); socklen_t addrlen = sizeof(sockaddr_u); int ret = getpeername(io->fd, io->peeraddr, &addrlen); if (ret < 0) { io->error = socket_errno(); goto connect_error; } else { addrlen = sizeof(sockaddr_u); getsockname(io->fd, io->localaddr, &addrlen); if (io->io_type == HIO_TYPE_SSL) { if (io->ssl == NULL) { // io->ssl_ctx > g_ssl_ctx > hssl_ctx_new hssl_ctx_t ssl_ctx = NULL; if (io->ssl_ctx) { ssl_ctx = io->ssl_ctx; } else if (g_ssl_ctx) { ssl_ctx = g_ssl_ctx; } else { io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); io->alloced_ssl_ctx = 1; } if (ssl_ctx == NULL) { io->error = ERR_NEW_SSL_CTX; goto connect_error; } hssl_t ssl = hssl_new(ssl_ctx, io->fd); if (ssl == NULL) { io->error = ERR_NEW_SSL; goto connect_error; } io->ssl = ssl; } if (io->hostname) { hssl_set_sni_hostname(io->ssl, io->hostname); } ssl_client_handshake(io); } else { // NOTE: SSL call connect_cb after handshake finished __connect_cb(io); } return; } connect_error: hlogw("connfd=%d connect error: %s:%d", io->fd, socket_strerror(io->error), io->error); hio_close(io); } static void nio_connect_event_cb(hevent_t* ev) { hio_t* io = (hio_t*)ev->userdata; uint32_t id = (uintptr_t)ev->privdata; if (io->id != id) return; nio_connect(io); } static int nio_connect_async(hio_t* io) { hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.cb = nio_connect_event_cb; ev.userdata = io; ev.privdata = (void*)(uintptr_t)io->id; hloop_post_event(io->loop, &ev); return 0; } static int __nio_read(hio_t* io, void* buf, int len) { int nread = 0; switch (io->io_type) { case HIO_TYPE_SSL: nread = hssl_read(io->ssl, buf, len); break; case HIO_TYPE_TCP: nread = recv(io->fd, buf, len, 0); break; case HIO_TYPE_UDP: case HIO_TYPE_KCP: case HIO_TYPE_IP: { socklen_t addrlen = sizeof(sockaddr_u); nread = recvfrom(io->fd, buf, len, 0, io->peeraddr, &addrlen); } break; default: nread = read(io->fd, buf, len); break; } // hlogd("read retval=%d", nread); return nread; } static int __nio_write(hio_t* io, const void* buf, int len) { int nwrite = 0; switch (io->io_type) { case HIO_TYPE_SSL: nwrite = hssl_write(io->ssl, buf, len); break; case HIO_TYPE_TCP: { int flag = 0; #ifdef MSG_NOSIGNAL flag |= MSG_NOSIGNAL; #endif nwrite = send(io->fd, buf, len, flag); } break; case HIO_TYPE_UDP: case HIO_TYPE_KCP: case HIO_TYPE_IP: { nwrite = sendto(io->fd, buf, len, 0, io->peeraddr, SOCKADDR_LEN(io->peeraddr)); if (((sockaddr_u*)io->localaddr)->sin.sin_port == 0) { socklen_t addrlen = sizeof(sockaddr_u); getsockname(io->fd, io->localaddr, &addrlen); } } break; default: nwrite = write(io->fd, buf, len); break; } // hlogd("write retval=%d", nwrite); return nwrite; } static void nio_read(hio_t* io) { // printd("nio_read fd=%d\n", io->fd); void* buf; int len = 0, nread = 0, err = 0; read: buf = io->readbuf.base + io->readbuf.tail; if (io->read_flags & HIO_READ_UNTIL_LENGTH) { len = io->read_until_length - (io->readbuf.tail - io->readbuf.head); } else { len = io->readbuf.len - io->readbuf.tail; } assert(len > 0); nread = __nio_read(io, buf, len); // printd("read retval=%d\n", nread); if (nread < 0) { err = socket_errno(); if (err == EAGAIN || err == EINTR) { // goto read_done; return; } else if (err == EMSGSIZE) { nread = len; } else { // perror("read"); io->error = err; goto read_error; } } if (nread == 0 && (io->io_type & HIO_TYPE_SOCK_STREAM)) { goto disconnect; } if (nread < len) { // NOTE: make string friendly ((char*)buf)[nread] = '\0'; } io->readbuf.tail += nread; __read_cb(io, buf, nread); if (nread == len && !io->closed) { // NOTE: ssl may have own cache if (io->io_type == HIO_TYPE_SSL) { // read continue goto read; } } return; read_error: disconnect: if (io->io_type & HIO_TYPE_SOCK_STREAM) { hio_close(io); } } static void nio_write(hio_t* io) { // printd("nio_write fd=%d\n", io->fd); int nwrite = 0, err = 0; hrecursive_mutex_lock(&io->write_mutex); write: if (write_queue_empty(&io->write_queue)) { hrecursive_mutex_unlock(&io->write_mutex); if (io->close) { io->close = 0; hio_close(io); } return; } offset_buf_t* pbuf = write_queue_front(&io->write_queue); char* base = pbuf->base; char* buf = base + pbuf->offset; int len = pbuf->len - pbuf->offset; nwrite = __nio_write(io, buf, len); // printd("write retval=%d\n", nwrite); if (nwrite < 0) { err = socket_errno(); if (err == EAGAIN || err == EINTR) { hrecursive_mutex_unlock(&io->write_mutex); return; } else { // perror("write"); io->error = err; goto write_error; } } if (nwrite == 0 && (io->io_type & HIO_TYPE_SOCK_STREAM)) { goto disconnect; } pbuf->offset += nwrite; io->write_bufsize -= nwrite; __write_cb(io, buf, nwrite); if (nwrite == len) { // NOTE: after write_cb, pbuf maybe invalid. // HV_FREE(pbuf->base); HV_FREE(base); write_queue_pop_front(&io->write_queue); if (!io->closed) { // write continue goto write; } } hrecursive_mutex_unlock(&io->write_mutex); return; write_error: disconnect: hrecursive_mutex_unlock(&io->write_mutex); if (io->io_type & HIO_TYPE_SOCK_STREAM) { hio_close(io); } } static void hio_handle_events(hio_t* io) { if ((io->events & HV_READ) && (io->revents & HV_READ)) { if (io->accept) { nio_accept(io); } else { nio_read(io); } } if ((io->events & HV_WRITE) && (io->revents & HV_WRITE)) { // NOTE: del HV_WRITE, if write_queue empty hrecursive_mutex_lock(&io->write_mutex); if (write_queue_empty(&io->write_queue)) { hio_del(io, HV_WRITE); } hrecursive_mutex_unlock(&io->write_mutex); if (io->connect) { // NOTE: connect just do once // ONESHOT io->connect = 0; nio_connect(io); } else { nio_write(io); } } io->revents = 0; } int hio_accept(hio_t* io) { io->accept = 1; return hio_add(io, hio_handle_events, HV_READ); } int hio_connect(hio_t* io) { int ret = connect(io->fd, io->peeraddr, SOCKADDR_LEN(io->peeraddr)); #ifdef OS_WIN if (ret < 0 && socket_errno() != WSAEWOULDBLOCK) { #else if (ret < 0 && socket_errno() != EINPROGRESS) { #endif perror("connect"); io->error = socket_errno(); hio_close_async(io); return ret; } if (ret == 0) { // connect ok nio_connect_async(io); return 0; } int timeout = io->connect_timeout ? io->connect_timeout : HIO_DEFAULT_CONNECT_TIMEOUT; io->connect_timer = htimer_add(io->loop, __connect_timeout_cb, timeout, 1); io->connect_timer->privdata = io; io->connect = 1; return hio_add(io, hio_handle_events, HV_WRITE); } int hio_read (hio_t* io) { if (io->closed) { hloge("hio_read called but fd[%d] already closed!", io->fd); return -1; } hio_add(io, hio_handle_events, HV_READ); if (io->readbuf.tail > io->readbuf.head && io->unpack_setting == NULL && io->read_flags == 0) { hio_read_remain(io); } return 0; } int hio_write (hio_t* io, const void* buf, size_t len) { if (io->closed) { hloge("hio_write called but fd[%d] already closed!", io->fd); return -1; } int nwrite = 0, err = 0; hrecursive_mutex_lock(&io->write_mutex); #if WITH_KCP if (io->io_type == HIO_TYPE_KCP) { nwrite = hio_write_kcp(io, buf, len); // if (nwrite < 0) goto write_error; goto write_done; } #endif if (write_queue_empty(&io->write_queue)) { try_write: nwrite = __nio_write(io, buf, len); // printd("write retval=%d\n", nwrite); if (nwrite < 0) { err = socket_errno(); if (err == EAGAIN || err == EINTR) { nwrite = 0; hlogw("try_write failed, enqueue!"); goto enqueue; } else { // perror("write"); io->error = err; goto write_error; } } if (nwrite == len) { goto write_done; } if (nwrite == 0 && (io->io_type & HIO_TYPE_SOCK_STREAM)) { goto disconnect; } enqueue: hio_add(io, hio_handle_events, HV_WRITE); } if (nwrite < len) { if (io->write_bufsize + len - nwrite > io->max_write_bufsize) { hloge("write bufsize > %u, close it!", io->max_write_bufsize); io->error = ERR_OVER_LIMIT; goto write_error; } offset_buf_t remain; remain.len = len - nwrite; remain.offset = 0; // NOTE: free in nio_write HV_ALLOC(remain.base, remain.len); memcpy(remain.base, ((char*)buf) + nwrite, remain.len); if (io->write_queue.maxsize == 0) { write_queue_init(&io->write_queue, 4); } write_queue_push_back(&io->write_queue, &remain); io->write_bufsize += remain.len; if (io->write_bufsize > WRITE_BUFSIZE_HIGH_WATER) { hlogw("write len=%u enqueue %u, bufsize=%u over high water %u", (unsigned int)len, (unsigned int)(remain.len - remain.offset), (unsigned int)io->write_bufsize, (unsigned int)WRITE_BUFSIZE_HIGH_WATER); } } write_done: hrecursive_mutex_unlock(&io->write_mutex); if (nwrite > 0) { __write_cb(io, buf, nwrite); } return nwrite; write_error: disconnect: hrecursive_mutex_unlock(&io->write_mutex); /* NOTE: * We usually free resources in hclose_cb, * if hio_close_sync, we have to be very careful to avoid using freed resources. * But if hio_close_async, we do not have to worry about this. */ if (io->io_type & HIO_TYPE_SOCK_STREAM) { hio_close_async(io); } return nwrite < 0 ? nwrite : -1; } int hio_close (hio_t* io) { if (io->closed) return 0; if (io->destroy == 0 && hv_gettid() != io->loop->tid) { return hio_close_async(io); } hrecursive_mutex_lock(&io->write_mutex); if (io->closed) { hrecursive_mutex_unlock(&io->write_mutex); return 0; } if (!write_queue_empty(&io->write_queue) && io->error == 0 && io->close == 0 && io->destroy == 0) { io->close = 1; hrecursive_mutex_unlock(&io->write_mutex); hlogw("write_queue not empty, close later."); int timeout_ms = io->close_timeout ? io->close_timeout : HIO_DEFAULT_CLOSE_TIMEOUT; io->close_timer = htimer_add(io->loop, __close_timeout_cb, timeout_ms, 1); io->close_timer->privdata = io; return 0; } io->closed = 1; hrecursive_mutex_unlock(&io->write_mutex); hio_done(io); __close_cb(io); if (io->ssl) { hssl_free(io->ssl); io->ssl = NULL; } if (io->ssl_ctx && io->alloced_ssl_ctx) { hssl_ctx_free(io->ssl_ctx); io->ssl_ctx = NULL; } SAFE_FREE(io->hostname); if (io->io_type & HIO_TYPE_SOCKET) { closesocket(io->fd); } else if (io->io_type == HIO_TYPE_PIPE) { close(io->fd); } return 0; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/nlog.c000066400000000000000000000043061520575453600256740ustar00rootroot00000000000000#include "nlog.h" #include "list.h" #include "hdef.h" #include "hbase.h" #include "hsocket.h" #include "hmutex.h" typedef struct network_logger_s { hloop_t* loop; hio_t* listenio; struct list_head clients; } network_logger_t; typedef struct nlog_client { hio_t* io; struct list_node node; } nlog_client; static network_logger_t s_logger = {0}; static hmutex_t s_mutex; static void on_close(hio_t* io) { printd("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); nlog_client* client = (nlog_client*)hevent_userdata(io); if (client) { hevent_set_userdata(io, NULL); hmutex_lock(&s_mutex); list_del(&client->node); hmutex_unlock(&s_mutex); HV_FREE(client); } } static void on_read(hio_t* io, void* buf, int readbytes) { printd("on_read fd=%d readbytes=%d\n", hio_fd(io), readbytes); printd("< %s\n", (char*)buf); // nothing to do } static void on_accept(hio_t* io) { /* printd("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ hio_setcb_read(io, on_read); hio_setcb_close(io, on_close); hio_read(io); // free on_close nlog_client* client; HV_ALLOC_SIZEOF(client); client->io = io; hevent_set_userdata(io, client); hmutex_lock(&s_mutex); list_add(&client->node, &s_logger.clients); hmutex_unlock(&s_mutex); } void network_logger(int loglevel, const char* buf, int len) { struct list_node* node; nlog_client* client; hmutex_lock(&s_mutex); list_for_each (node, &s_logger.clients) { client = list_entry(node, nlog_client, node); hio_write(client->io, buf, len); } hmutex_unlock(&s_mutex); } hio_t* nlog_listen(hloop_t* loop, int port) { s_logger.loop = loop; s_logger.listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); list_init(&s_logger.clients); hmutex_init(&s_mutex); return s_logger.listenio; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/nlog.h000066400000000000000000000014561520575453600257040ustar00rootroot00000000000000#ifndef HV_NLOG_H_ #define HV_NLOG_H_ // nlog: extend hlog use hloop /* you can recv log by: * Windows: telnet ip port * Linux: nc ip port */ /* * @see examples/hloop_test.c #include "hlog.h" #include "nlog.h" void timer_write_log(htimer_t* timer) { static int cnt = 0; hlogi("[%d] Do you recv me?", ++cnt); } int main() { hloop_t* loop = hloop_new(0); hlog_set_handler(network_logger); nlog_listen(loop, DEFAULT_LOG_PORT); htimer_add(loop, timer_write_log, 1000, INFINITE); hloop_run(loop); hloop_free(&loop); } */ #include "hexport.h" #include "hloop.h" #define DEFAULT_LOG_PORT 10514 BEGIN_EXTERN_C HV_EXPORT void network_logger(int loglevel, const char* buf, int len); HV_EXPORT hio_t* nlog_listen(hloop_t* loop, int port); END_EXTERN_C #endif // HV_NLOG_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/noevent.c000066400000000000000000000006351520575453600264140ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_NOEVENT int iowatcher_init(hloop_t* loop) { return 0; } int iowatcher_cleanup(hloop_t* loop) { return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { hv_delay(timeout); return 0; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/overlapio.c000066400000000000000000000311141520575453600267320ustar00rootroot00000000000000// WARN: overlapio maybe need MemoryPool to avoid alloc/free #include "iowatcher.h" #ifdef EVENT_IOCP #include "overlapio.h" #include "hevent.h" #define ACCEPTEX_NUM 10 int post_acceptex(hio_t* listenio, hoverlapped_t* hovlp) { LPFN_ACCEPTEX AcceptEx = NULL; GUID guidAcceptEx = WSAID_ACCEPTEX; DWORD dwbytes = 0; if (WSAIoctl(listenio->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidAcceptEx, sizeof(guidAcceptEx), &AcceptEx, sizeof(AcceptEx), &dwbytes, NULL, NULL) != 0) { return WSAGetLastError(); } int connfd = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); if (connfd < 0) { return WSAGetLastError(); } if (hovlp == NULL) { HV_ALLOC_SIZEOF(hovlp); hovlp->buf.len = 20 + sizeof(struct sockaddr_in6) * 2; HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); } hovlp->fd = connfd; hovlp->event = HV_READ; hovlp->io = listenio; if (AcceptEx(listenio->fd, connfd, hovlp->buf.buf, 0, sizeof(struct sockaddr_in6), sizeof(struct sockaddr_in6), &dwbytes, &hovlp->ovlp) != TRUE) { int err = WSAGetLastError(); if (err != ERROR_IO_PENDING) { fprintf(stderr, "AcceptEx error: %d\n", err); return err; } } return 0; } int post_recv(hio_t* io, hoverlapped_t* hovlp) { if (hovlp == NULL) { HV_ALLOC_SIZEOF(hovlp); } hovlp->fd = io->fd; hovlp->event = HV_READ; hovlp->io = io; hovlp->buf.len = io->readbuf.len; if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); } else { hovlp->buf.buf = io->readbuf.base; } //memset(hovlp->buf.buf, 0, hovlp->buf.len); DWORD dwbytes = 0; DWORD flags = 0; int ret = 0; if (io->io_type == HIO_TYPE_TCP) { ret = WSARecv(io->fd, &hovlp->buf, 1, &dwbytes, &flags, &hovlp->ovlp, NULL); } else if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { if (hovlp->addr == NULL) { hovlp->addrlen = sizeof(struct sockaddr_in6); HV_ALLOC(hovlp->addr, sizeof(struct sockaddr_in6)); } ret = WSARecvFrom(io->fd, &hovlp->buf, 1, &dwbytes, &flags, hovlp->addr, &hovlp->addrlen, &hovlp->ovlp, NULL); } else { ret = -1; } //printd("WSARecv ret=%d bytes=%u\n", ret, dwbytes); if (ret != 0) { int err = WSAGetLastError(); if (err != ERROR_IO_PENDING) { fprintf(stderr, "WSARecv error: %d\n", err); return err; } } return 0; } static void on_acceptex_complete(hio_t* io) { printd("on_acceptex_complete------\n"); hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; int listenfd = io->fd; int connfd = hovlp->fd; LPFN_GETACCEPTEXSOCKADDRS GetAcceptExSockaddrs = NULL; GUID guidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS; DWORD dwbytes = 0; if (WSAIoctl(connfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidGetAcceptExSockaddrs, sizeof(guidGetAcceptExSockaddrs), &GetAcceptExSockaddrs, sizeof(GetAcceptExSockaddrs), &dwbytes, NULL, NULL) != 0) { return; } struct sockaddr* plocaladdr = NULL; struct sockaddr* ppeeraddr = NULL; socklen_t localaddrlen; socklen_t peeraddrlen; GetAcceptExSockaddrs(hovlp->buf.buf, 0, sizeof(struct sockaddr_in6), sizeof(struct sockaddr_in6), &plocaladdr, &localaddrlen, &ppeeraddr, &peeraddrlen); memcpy(io->localaddr, plocaladdr, localaddrlen); memcpy(io->peeraddr, ppeeraddr, peeraddrlen); if (io->accept_cb) { setsockopt(connfd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (const char*)&listenfd, sizeof(int)); hio_t* connio = hio_get(io->loop, connfd); connio->userdata = io->userdata; memcpy(connio->localaddr, io->localaddr, localaddrlen); memcpy(connio->peeraddr, io->peeraddr, peeraddrlen); /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("accept listenfd=%d connfd=%d [%s] <= [%s]\n", listenfd, connfd, SOCKADDR_STR(connio->localaddr, localaddrstr), SOCKADDR_STR(connio->peeraddr, peeraddrstr)); */ //printd("accept_cb------\n"); io->accept_cb(connio); //printd("accept_cb======\n"); } post_acceptex(io, hovlp); } static void on_connectex_complete(hio_t* io) { printd("on_connectex_complete------\n"); hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; io->error = hovlp->error; HV_FREE(io->hovlp); if (io->error != 0) { hio_close(io); return; } if (io->connect_cb) { setsockopt(io->fd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0); socklen_t addrlen = sizeof(struct sockaddr_in6); getsockname(io->fd, io->localaddr, &addrlen); addrlen = sizeof(struct sockaddr_in6); getpeername(io->fd, io->peeraddr, &addrlen); /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("connect connfd=%d [%s] => [%s]\n", io->fd, SOCKADDR_STR(io->localaddr, localaddrstr), SOCKADDR_STR(io->peeraddr, peeraddrstr)); */ //printd("connect_cb------\n"); io->connect_cb(io); //printd("connect_cb======\n"); } } static void on_wsarecv_complete(hio_t* io) { printd("on_recv_complete------\n"); hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; if (hovlp->bytes == 0) { io->error = WSAGetLastError(); hio_close(io); return; } if (io->read_cb) { if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { if (hovlp->addr && hovlp->addrlen) { hio_set_peeraddr(io, hovlp->addr, hovlp->addrlen); } } //printd("read_cb------\n"); io->read_cb(io, hovlp->buf.buf, hovlp->bytes); //printd("read_cb======\n"); } if (io->io_type == HIO_TYPE_TCP) { // reuse hovlp if (!io->closed) { post_recv(io, hovlp); } } else if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { HV_FREE(hovlp->buf.buf); HV_FREE(hovlp->addr); HV_FREE(io->hovlp); } } static void on_wsasend_complete(hio_t* io) { printd("on_send_complete------\n"); hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; if (hovlp->bytes == 0) { io->error = WSAGetLastError(); hio_close(io); goto end; } if (io->write_cb) { if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { if (hovlp->addr) { hio_set_peeraddr(io, hovlp->addr, hovlp->addrlen); } } //printd("write_cb------\n"); io->write_cb(io, hovlp->buf.buf, hovlp->bytes); //printd("write_cb======\n"); } end: if (io->hovlp) { HV_FREE(hovlp->buf.buf); HV_FREE(io->hovlp); } } static void hio_handle_events(hio_t* io) { if ((io->events & HV_READ) && (io->revents & HV_READ)) { if (io->accept) { on_acceptex_complete(io); } else { on_wsarecv_complete(io); } } if ((io->events & HV_WRITE) && (io->revents & HV_WRITE)) { // NOTE: HV_WRITE just do once // ONESHOT iowatcher_del_event(io->loop, io->fd, HV_WRITE); io->events &= ~HV_WRITE; if (io->connect) { io->connect = 0; on_connectex_complete(io); } else { on_wsasend_complete(io); } } io->revents = 0; } int hio_accept (hio_t* io) { for (int i = 0; i < ACCEPTEX_NUM; ++i) { post_acceptex(io, NULL); } io->accept = 1; return hio_add(io, hio_handle_events, HV_READ); } int hio_connect (hio_t* io) { // NOTE: ConnectEx must call bind struct sockaddr_in localaddr; socklen_t addrlen = sizeof(localaddr); memset(&localaddr, 0, addrlen); localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = htonl(INADDR_ANY); localaddr.sin_port = htons(0); if (bind(io->fd, (struct sockaddr*)&localaddr, addrlen) < 0) { perror("bind"); goto error; } // ConnectEx io->connectex = 1; LPFN_CONNECTEX ConnectEx = NULL; GUID guidConnectEx = WSAID_CONNECTEX; DWORD dwbytes; if (WSAIoctl(io->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidConnectEx, sizeof(guidConnectEx), &ConnectEx, sizeof(ConnectEx), &dwbytes, NULL, NULL) != 0) { goto error; } // NOTE: free on_connectex_complete hoverlapped_t* hovlp; HV_ALLOC_SIZEOF(hovlp); hovlp->fd = io->fd; hovlp->event = HV_WRITE; hovlp->io = io; if (ConnectEx(io->fd, io->peeraddr, sizeof(struct sockaddr_in6), NULL, 0, &dwbytes, &hovlp->ovlp) != TRUE) { int err = WSAGetLastError(); if (err != ERROR_IO_PENDING) { fprintf(stderr, "AcceptEx error: %d\n", err); goto error; } } io->connect = 1; return hio_add(io, hio_handle_events, HV_WRITE); error: hio_close(io); return 0; } int hio_read (hio_t* io) { post_recv(io, NULL); return hio_add(io, hio_handle_events, HV_READ); } int hio_write(hio_t* io, const void* buf, size_t len) { int nwrite = 0; try_send: if (io->io_type == HIO_TYPE_TCP) { nwrite = send(io->fd, buf, len, 0); } else if (io->io_type == HIO_TYPE_UDP) { nwrite = sendto(io->fd, buf, len, 0, io->peeraddr, sizeof(struct sockaddr_in6)); } else if (io->io_type == HIO_TYPE_IP) { goto WSASend; } else { nwrite = -1; } //printd("write retval=%d\n", nwrite); if (nwrite < 0) { if (socket_errno() == EAGAIN) { nwrite = 0; goto WSASend; } else { perror("write"); io->error = socket_errno(); goto write_error; } } if (nwrite == 0) { goto disconnect; } if (io->write_cb) { //printd("try_write_cb------\n"); io->write_cb(io, buf, nwrite); //printd("try_write_cb======\n"); } if (nwrite == len) { //goto write_done; return nwrite; } WSASend: { hoverlapped_t* hovlp; HV_ALLOC_SIZEOF(hovlp); hovlp->fd = io->fd; hovlp->event = HV_WRITE; hovlp->buf.len = len - nwrite; // NOTE: free on_send_complete HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); memcpy(hovlp->buf.buf, ((char*)buf) + nwrite, hovlp->buf.len); hovlp->io = io; DWORD dwbytes = 0; DWORD flags = 0; int ret = 0; if (io->io_type == HIO_TYPE_TCP) { ret = WSASend(io->fd, &hovlp->buf, 1, &dwbytes, flags, &hovlp->ovlp, NULL); } else if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { ret = WSASendTo(io->fd, &hovlp->buf, 1, &dwbytes, flags, io->peeraddr, sizeof(struct sockaddr_in6), &hovlp->ovlp, NULL); } else { ret = -1; } //printd("WSASend ret=%d bytes=%u\n", ret, dwbytes); if (ret != 0) { int err = WSAGetLastError(); if (err != ERROR_IO_PENDING) { fprintf(stderr, "WSASend error: %d\n", err); return ret; } } return hio_add(io, hio_handle_events, HV_WRITE); } write_error: disconnect: hio_close(io); return 0; } int hio_close (hio_t* io) { if (io->closed) return 0; io->closed = 1; hio_done(io); if (io->hovlp) { hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; // NOTE: hread buf provided by caller if (hovlp->buf.buf != io->readbuf.base) { HV_FREE(hovlp->buf.buf); } HV_FREE(hovlp->addr); HV_FREE(io->hovlp); } if (io->close_cb) { //printd("close_cb------\n"); io->close_cb(io); //printd("close_cb======\n"); } if (io->io_type & HIO_TYPE_SOCKET) { #ifdef USE_DISCONNECTEX // DisconnectEx reuse socket if (io->connectex) { io->connectex = 0; LPFN_DISCONNECTEX DisconnectEx = NULL; GUID guidDisconnectEx = WSAID_DISCONNECTEX; DWORD dwbytes; if (WSAIoctl(io->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidDisconnectEx, sizeof(guidDisconnectEx), &DisconnectEx, sizeof(DisconnectEx), &dwbytes, NULL, NULL) != 0) { return; } DisconnectEx(io->fd, NULL, 0, 0); } #else closesocket(io->fd); #endif } return 0; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/overlapio.h000066400000000000000000000011651520575453600267420ustar00rootroot00000000000000#ifndef HV_OVERLAPPED_H_ #define HV_OVERLAPPED_H_ #include "iowatcher.h" #ifdef EVENT_IOCP #include "hbuf.h" #include "hsocket.h" #include #ifdef _MSC_VER #pragma comment(lib, "mswsock.lib") #endif typedef struct hoverlapped_s { OVERLAPPED ovlp; int fd; int event; WSABUF buf; int bytes; int error; hio_t* io; // for recvfrom struct sockaddr* addr; int addrlen; } hoverlapped_t; int post_acceptex(hio_t* listenio, hoverlapped_t* hovlp); int post_recv(hio_t* io, hoverlapped_t* hovlp); #endif #endif // HV_OVERLAPPED_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/poll.c000066400000000000000000000067551520575453600257150ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_POLL #include "hplatform.h" #include "hdef.h" #include "hevent.h" #ifdef OS_WIN #define poll WSAPoll #endif #ifdef OS_LINUX #include #endif #include "array.h" #define FDS_INIT_SIZE 64 ARRAY_DECL(struct pollfd, pollfds); typedef struct poll_ctx_s { int capacity; struct pollfds fds; } poll_ctx_t; int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; poll_ctx_t* poll_ctx; HV_ALLOC_SIZEOF(poll_ctx); pollfds_init(&poll_ctx->fds, FDS_INIT_SIZE); loop->iowatcher = poll_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { if (loop->iowatcher == NULL) return 0; poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; pollfds_cleanup(&poll_ctx->fds); HV_FREE(loop->iowatcher); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; hio_t* io = loop->ios.ptr[fd]; int idx = io->event_index[0]; struct pollfd* pfd = NULL; if (idx < 0) { io->event_index[0] = idx = poll_ctx->fds.size; if (idx == poll_ctx->fds.maxsize) { pollfds_double_resize(&poll_ctx->fds); } poll_ctx->fds.size++; pfd = poll_ctx->fds.ptr + idx; pfd->fd = fd; pfd->events = 0; pfd->revents = 0; } else { pfd = poll_ctx->fds.ptr + idx; assert(pfd->fd == fd); } if (events & HV_READ) { pfd->events |= POLLIN; } if (events & HV_WRITE) { pfd->events |= POLLOUT; } return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; if (poll_ctx == NULL) return 0; hio_t* io = loop->ios.ptr[fd]; int idx = io->event_index[0]; if (idx < 0) return 0; struct pollfd* pfd = poll_ctx->fds.ptr + idx; assert(pfd->fd == fd); if (events & HV_READ) { pfd->events &= ~POLLIN; } if (events & HV_WRITE) { pfd->events &= ~POLLOUT; } if (pfd->events == 0) { pollfds_del_nomove(&poll_ctx->fds, idx); // NOTE: correct event_index if (idx < poll_ctx->fds.size) { hio_t* last = loop->ios.ptr[poll_ctx->fds.ptr[idx].fd]; last->event_index[0] = idx; } io->event_index[0] = -1; } return 0; } int iowatcher_poll_events(hloop_t* loop, int timeout) { poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; if (poll_ctx == NULL) return 0; if (poll_ctx->fds.size == 0) return 0; int npoll = poll(poll_ctx->fds.ptr, poll_ctx->fds.size, timeout); if (npoll < 0) { if (errno == EINTR) { return 0; } perror("poll"); return npoll; } if (npoll == 0) return 0; int nevents = 0; for (int i = 0; i < poll_ctx->fds.size; ++i) { int fd = poll_ctx->fds.ptr[i].fd; short revents = poll_ctx->fds.ptr[i].revents; if (revents) { ++nevents; hio_t* io = loop->ios.ptr[fd]; if (io) { if (revents & (POLLIN | POLLHUP | POLLERR)) { io->revents |= HV_READ; } if (revents & (POLLOUT | POLLHUP | POLLERR)) { io->revents |= HV_WRITE; } EVENT_PENDING(io); } } if (nevents == npoll) break; } return nevents; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/rudp.c000066400000000000000000000104731520575453600257110ustar00rootroot00000000000000#include "rudp.h" #if WITH_RUDP #include "hevent.h" void rudp_entry_free(rudp_entry_t* entry) { #if WITH_KCP kcp_release(&entry->kcp); #endif HV_FREE(entry); } void rudp_init(rudp_t* rudp) { // printf("rudp init\n"); rudp->rb_root.rb_node = NULL; hmutex_init(&rudp->mutex); } void rudp_cleanup(rudp_t* rudp) { // printf("rudp cleaup\n"); struct rb_node* n = NULL; rudp_entry_t* e = NULL; while ((n = rudp->rb_root.rb_node)) { e = rb_entry(n, rudp_entry_t, rb_node); rb_erase(n, &rudp->rb_root); rudp_entry_free(e); } hmutex_destroy(&rudp->mutex); } bool rudp_insert(rudp_t* rudp, rudp_entry_t* entry) { struct rb_node** n = &rudp->rb_root.rb_node; struct rb_node* parent = NULL; rudp_entry_t* e = NULL; int cmp = 0; bool exists = false; while (*n) { parent = *n; e = rb_entry(*n, rudp_entry_t, rb_node); cmp = memcmp(&entry->addr, &e->addr, sizeof(sockaddr_u)); if (cmp < 0) { n = &(*n)->rb_left; } else if (cmp > 0) { n = &(*n)->rb_right; } else { exists = true; break; } } if (!exists) { rb_link_node(&entry->rb_node, parent, n); rb_insert_color(&entry->rb_node, &rudp->rb_root); } return !exists; } rudp_entry_t* rudp_search(rudp_t* rudp, struct sockaddr* addr) { struct rb_node* n = rudp->rb_root.rb_node; rudp_entry_t* e = NULL; int cmp = 0; bool exists = false; while (n) { e = rb_entry(n, rudp_entry_t, rb_node); cmp = memcmp(addr, &e->addr, sizeof(sockaddr_u)); if (cmp < 0) { n = n->rb_left; } else if (cmp > 0) { n = n->rb_right; } else { exists = true; break; } } return exists ? e : NULL; } rudp_entry_t* rudp_remove(rudp_t* rudp, struct sockaddr* addr) { hmutex_lock(&rudp->mutex); rudp_entry_t* e = rudp_search(rudp, addr); if (e) { // printf("rudp_remove "); // SOCKADDR_PRINT(addr); rb_erase(&e->rb_node, &rudp->rb_root); } hmutex_unlock(&rudp->mutex); return e; } rudp_entry_t* rudp_get(rudp_t* rudp, struct sockaddr* addr) { hmutex_lock(&rudp->mutex); struct rb_node** n = &rudp->rb_root.rb_node; struct rb_node* parent = NULL; rudp_entry_t* e = NULL; int cmp = 0; bool exists = false; // search while (*n) { parent = *n; e = rb_entry(*n, rudp_entry_t, rb_node); cmp = memcmp(addr, &e->addr, sizeof(sockaddr_u)); if (cmp < 0) { n = &(*n)->rb_left; } else if (cmp > 0) { n = &(*n)->rb_right; } else { exists = true; break; } } if (!exists) { // insert // printf("rudp_insert "); // SOCKADDR_PRINT(addr); HV_ALLOC_SIZEOF(e); memcpy(&e->addr, addr, SOCKADDR_LEN(addr)); rb_link_node(&e->rb_node, parent, n); rb_insert_color(&e->rb_node, &rudp->rb_root); } hmutex_unlock(&rudp->mutex); return e; } void rudp_del(rudp_t* rudp, struct sockaddr* addr) { hmutex_lock(&rudp->mutex); rudp_entry_t* e = rudp_search(rudp, addr); if (e) { // printf("rudp_remove "); // SOCKADDR_PRINT(addr); rb_erase(&e->rb_node, &rudp->rb_root); rudp_entry_free(e); } hmutex_unlock(&rudp->mutex); } rudp_entry_t* hio_get_rudp(hio_t* io) { rudp_entry_t* rudp = rudp_get(&io->rudp, io->peeraddr); rudp->io = io; return rudp; } static void hio_close_rudp_event_cb(hevent_t* ev) { rudp_entry_t* entry = (rudp_entry_t*)ev->userdata; rudp_del(&entry->io->rudp, (struct sockaddr*)&entry->addr); // rudp_entry_free(entry); } int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr) { if (peeraddr == NULL) peeraddr = io->peeraddr; // NOTE: do rudp_del for thread-safe rudp_entry_t* entry = rudp_get(&io->rudp, peeraddr); // NOTE: just rudp_remove first, do rudp_entry_free async for safe. // rudp_entry_t* entry = rudp_remove(&io->rudp, peeraddr); if (entry) { hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.cb = hio_close_rudp_event_cb; ev.userdata = entry; ev.priority = HEVENT_HIGH_PRIORITY; hloop_post_event(io->loop, &ev); } return 0; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/rudp.h000066400000000000000000000022441520575453600257130ustar00rootroot00000000000000#ifndef HV_RUDP_H_ #define HV_RUDP_H_ #include "hloop.h" #if WITH_RUDP #include "rbtree.h" #include "hsocket.h" #include "hmutex.h" #if WITH_KCP #include "kcp/hkcp.h" #endif typedef struct rudp_s { struct rb_root rb_root; hmutex_t mutex; } rudp_t; typedef struct rudp_entry_s { struct rb_node rb_node; sockaddr_u addr; // key // val hio_t* io; #if WITH_KCP kcp_t kcp; #endif } rudp_entry_t; // NOTE: rudp_entry_t alloc when rudp_get void rudp_entry_free(rudp_entry_t* entry); void rudp_init(rudp_t* rudp); void rudp_cleanup(rudp_t* rudp); bool rudp_insert(rudp_t* rudp, rudp_entry_t* entry); // NOTE: just rb_erase, not free rudp_entry_t* rudp_remove(rudp_t* rudp, struct sockaddr* addr); rudp_entry_t* rudp_search(rudp_t* rudp, struct sockaddr* addr); #define rudp_has(rudp, addr) (rudp_search(rudp, addr) != NULL) // rudp_search + malloc + rudp_insert rudp_entry_t* rudp_get(rudp_t* rudp, struct sockaddr* addr); // rudp_remove + free void rudp_del(rudp_t* rudp, struct sockaddr* addr); // rudp_get(&io->rudp, io->peeraddr) rudp_entry_t* hio_get_rudp(hio_t* io); #endif // WITH_RUDP #endif // HV_RUDP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/select.c000066400000000000000000000106411520575453600262130ustar00rootroot00000000000000#include "iowatcher.h" #ifdef EVENT_SELECT #include "hplatform.h" #include "hdef.h" #include "hevent.h" #include "hsocket.h" typedef struct select_ctx_s { int max_fd; fd_set readfds; fd_set writefds; int nread; int nwrite; } select_ctx_t; int iowatcher_init(hloop_t* loop) { if (loop->iowatcher) return 0; select_ctx_t* select_ctx; HV_ALLOC_SIZEOF(select_ctx); select_ctx->max_fd = -1; FD_ZERO(&select_ctx->readfds); FD_ZERO(&select_ctx->writefds); select_ctx->nread = 0; select_ctx->nwrite = 0; loop->iowatcher = select_ctx; return 0; } int iowatcher_cleanup(hloop_t* loop) { HV_FREE(loop->iowatcher); return 0; } int iowatcher_add_event(hloop_t* loop, int fd, int events) { if (loop->iowatcher == NULL) { iowatcher_init(loop); } select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; if (fd > select_ctx->max_fd) { select_ctx->max_fd = fd; } if (events & HV_READ) { if (!FD_ISSET(fd, &select_ctx->readfds)) { FD_SET(fd, &select_ctx->readfds); select_ctx->nread++; } } if (events & HV_WRITE) { if (!FD_ISSET(fd, &select_ctx->writefds)) { FD_SET(fd, &select_ctx->writefds); select_ctx->nwrite++; } } return 0; } int iowatcher_del_event(hloop_t* loop, int fd, int events) { select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; if (select_ctx == NULL) return 0; if (fd == select_ctx->max_fd) { select_ctx->max_fd = -1; } if (events & HV_READ) { if (FD_ISSET(fd, &select_ctx->readfds)) { FD_CLR(fd, &select_ctx->readfds); select_ctx->nread--; } } if (events & HV_WRITE) { if (FD_ISSET(fd, &select_ctx->writefds)) { FD_CLR(fd, &select_ctx->writefds); select_ctx->nwrite--; } } return 0; } static int find_max_active_fd(hloop_t* loop) { hio_t* io = NULL; for (int i = loop->ios.maxsize-1; i >= 0; --i) { io = loop->ios.ptr[i]; if (io && io->active && io->events) return i; } return -1; } static int remove_bad_fds(hloop_t* loop) { select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; if (select_ctx == NULL) return 0; int badfds = 0; int error = 0; socklen_t optlen = sizeof(error); for (int fd = 0; fd <= select_ctx->max_fd; ++fd) { if (FD_ISSET(fd, &select_ctx->readfds) || FD_ISSET(fd, &select_ctx->writefds)) { error = 0; optlen = sizeof(int); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&error, &optlen) < 0 || error != 0) { ++badfds; hio_t* io = loop->ios.ptr[fd]; if (io) { hio_del(io, HV_RDWR); } } } } return badfds; } int iowatcher_poll_events(hloop_t* loop, int timeout) { select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; if (select_ctx == NULL) return 0; if (select_ctx->nread == 0 && select_ctx->nwrite == 0) { return 0; } int max_fd = select_ctx->max_fd; fd_set readfds = select_ctx->readfds; fd_set writefds = select_ctx->writefds; if (max_fd == -1) { select_ctx->max_fd = max_fd = find_max_active_fd(loop); } struct timeval tv, *tp; if (timeout == INFINITE) { tp = NULL; } else { tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; tp = &tv; } int nselect = select(max_fd+1, &readfds, &writefds, NULL, tp); if (nselect < 0) { #ifdef OS_WIN if (WSAGetLastError() == WSAENOTSOCK) { #else if (errno == EBADF) { perror("select"); #endif remove_bad_fds(loop); return -EBADF; } return nselect; } if (nselect == 0) return 0; int nevents = 0; int revents = 0; for (int fd = 0; fd <= max_fd; ++fd) { revents = 0; if (FD_ISSET(fd, &readfds)) { ++nevents; revents |= HV_READ; } if (FD_ISSET(fd, &writefds)) { ++nevents; revents |= HV_WRITE; } if (revents) { hio_t* io = loop->ios.ptr[fd]; if (io) { io->revents = revents; EVENT_PENDING(io); } } if (nevents == nselect) break; } return nevents; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/unpack.c000066400000000000000000000133001520575453600262100ustar00rootroot00000000000000#include "unpack.h" #include "hevent.h" #include "herr.h" #include "hlog.h" #include "hmath.h" int hio_unpack(hio_t* io, void* buf, int readbytes) { unpack_setting_t* setting = io->unpack_setting; switch(setting->mode) { case UNPACK_BY_FIXED_LENGTH: return hio_unpack_by_fixed_length(io, buf, readbytes); case UNPACK_BY_DELIMITER: return hio_unpack_by_delimiter(io, buf, readbytes); case UNPACK_BY_LENGTH_FIELD: return hio_unpack_by_length_field(io, buf, readbytes); default: hio_read_cb(io, buf, readbytes); return readbytes; } } int hio_unpack_by_fixed_length(hio_t* io, void* buf, int readbytes) { const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; const unsigned char* ep = (const unsigned char*)buf + readbytes; unpack_setting_t* setting = io->unpack_setting; int fixed_length = setting->fixed_length; assert(io->readbuf.len >= fixed_length); const unsigned char* p = sp; int remain = ep - p; int handled = 0; while (remain >= fixed_length) { hio_read_cb(io, (void*)p, fixed_length); handled += fixed_length; p += fixed_length; remain -= fixed_length; } io->readbuf.head = 0; io->readbuf.tail = remain; if (remain) { // [p, p+remain] => [base, base+remain] if (p != (unsigned char*)io->readbuf.base) { memmove(io->readbuf.base, p, remain); } } return handled; } int hio_unpack_by_delimiter(hio_t* io, void* buf, int readbytes) { const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; const unsigned char* ep = (const unsigned char*)buf + readbytes; unpack_setting_t* setting = io->unpack_setting; unsigned char* delimiter = setting->delimiter; int delimiter_bytes = setting->delimiter_bytes; const unsigned char* p = (const unsigned char*)buf - delimiter_bytes + 1; if (p < sp) p = sp; int remain = ep - p; int handled = 0; int i = 0; while (remain >= delimiter_bytes) { for (i = 0; i < delimiter_bytes; ++i) { if (p[i] != delimiter[i]) { goto not_match; } } match: p += delimiter_bytes; remain -= delimiter_bytes; hio_read_cb(io, (void*)sp, p - sp); handled += p - sp; sp = p; continue; not_match: ++p; --remain; } remain = ep - sp; io->readbuf.head = 0; io->readbuf.tail = remain; if (remain) { // [sp, sp+remain] => [base, base+remain] if (sp != (unsigned char*)io->readbuf.base) { memmove(io->readbuf.base, sp, remain); } if (io->readbuf.tail == io->readbuf.len) { if (io->readbuf.len >= setting->package_max_length) { hloge("recv package over %d bytes!", (int)setting->package_max_length); io->error = ERR_OVER_LIMIT; hio_close(io); return -1; } int newsize = MIN(io->readbuf.len * 2, setting->package_max_length); hio_alloc_readbuf(io, newsize); } } return handled; } int hio_unpack_by_length_field(hio_t* io, void* buf, int readbytes) { const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; const unsigned char* ep = (const unsigned char*)buf + readbytes; unpack_setting_t* setting = io->unpack_setting; const unsigned char* p = sp; int remain = ep - p; int handled = 0; unsigned int head_len = setting->body_offset; unsigned int body_len = 0; unsigned int package_len = head_len; const unsigned char* lp = NULL; while (remain >= setting->body_offset) { body_len = 0; lp = p + setting->length_field_offset; if (setting->length_field_coding == BIG_ENDIAN) { for (int i = 0; i < setting->length_field_bytes; ++i) { body_len = (body_len << 8) | (unsigned int)*lp++; } } else if (setting->length_field_coding == LITTLE_ENDIAN) { for (int i = 0; i < setting->length_field_bytes; ++i) { body_len |= ((unsigned int)*lp++) << (i * 8); } } else if (setting->length_field_coding == ENCODE_BY_VARINT) { int varint_bytes = ep - lp; body_len = varint_decode(lp, &varint_bytes); if (varint_bytes == 0) break; if (varint_bytes == -1) { hloge("varint is too big!"); io->error = ERR_OVER_LIMIT; hio_close(io); return -1; } head_len = setting->body_offset + varint_bytes - setting->length_field_bytes; } package_len = head_len + body_len + setting->length_adjustment; if (remain >= package_len) { hio_read_cb(io, (void*)p, package_len); handled += package_len; p += package_len; remain -= package_len; } else { break; } } io->readbuf.head = 0; io->readbuf.tail = remain; if (remain) { // [p, p+remain] => [base, base+remain] if (p != (unsigned char*)io->readbuf.base) { memmove(io->readbuf.base, p, remain); } if (package_len > io->readbuf.len) { if (package_len > setting->package_max_length) { hloge("package length over %d bytes!", (int)setting->package_max_length); io->error = ERR_OVER_LIMIT; hio_close(io); return -1; } int newsize = LIMIT(package_len, io->readbuf.len * 2, setting->package_max_length); hio_alloc_readbuf(io, newsize); } } return handled; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/unpack.h000066400000000000000000000005301520575453600262160ustar00rootroot00000000000000#ifndef HV_UNPACK_H_ #define HV_UNPACK_H_ #include "hloop.h" int hio_unpack(hio_t* io, void* buf, int readbytes); int hio_unpack_by_fixed_length(hio_t* io, void* buf, int readbytes); int hio_unpack_by_delimiter(hio_t* io, void* buf, int readbytes); int hio_unpack_by_length_field(hio_t* io, void* buf, int readbytes); #endif // HV_UNPACK_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/wepoll/000077500000000000000000000000001520575453600260705ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/wepoll/LICENSE000066400000000000000000000025621520575453600271020ustar00rootroot00000000000000wepoll - epoll for Windows https://github.com/piscisaureus/wepoll Copyright 2012-2020, Bert Belder 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. kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/wepoll/README.md000066400000000000000000000174101520575453600273520ustar00rootroot00000000000000# wepoll - epoll for windows [![][ci status badge]][ci status link] This library implements the [epoll][man epoll] API for Windows applications. It is fast and scalable, and it closely resembles the API and behavior of Linux' epoll. ## Rationale Unlike Linux, OS X, and many other operating systems, Windows doesn't have a good API for receiving socket state notifications. It only supports the `select` and `WSAPoll` APIs, but they [don't scale][select scale] and suffer from [other issues][wsapoll broken]. Using I/O completion ports isn't always practical when software is designed to be cross-platform. Wepoll offers an alternative that is much closer to a drop-in replacement for software that was designed to run on Linux. ## Features * Can poll 100000s of sockets efficiently. * Fully thread-safe. * Multiple threads can poll the same epoll port. * Sockets can be added to multiple epoll sets. * All epoll events (`EPOLLIN`, `EPOLLOUT`, `EPOLLPRI`, `EPOLLRDHUP`) are supported. * Level-triggered and one-shot (`EPOLLONESTHOT`) modes are supported * Trivial to embed: you need [only two files][dist]. ## Limitations * Only works with sockets. * Edge-triggered (`EPOLLET`) mode isn't supported. ## How to use The library is [distributed][dist] as a single source file ([wepoll.c][wepoll.c]) and a single header file ([wepoll.h][wepoll.h]).
Compile the .c file as part of your project, and include the header wherever needed. ## Compatibility * Requires Windows Vista or higher. * Can be compiled with recent versions of MSVC, Clang, and GCC. ## API ### General remarks * The epoll port is a `HANDLE`, not a file descriptor. * All functions set both `errno` and `GetLastError()` on failure. * For more extensive documentation, see the [epoll(7) man page][man epoll], and the per-function man pages that are linked below. ### epoll_create/epoll_create1 ```c HANDLE epoll_create(int size); HANDLE epoll_create1(int flags); ``` * Create a new epoll instance (port). * `size` is ignored but most be greater than zero. * `flags` must be zero as there are no supported flags. * Returns `NULL` on failure. * [Linux man page][man epoll_create] ### epoll_close ```c int epoll_close(HANDLE ephnd); ``` * Close an epoll port. * Do not attempt to close the epoll port with `close()`, `CloseHandle()` or `closesocket()`. ### epoll_ctl ```c int epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* event); ``` * Control which socket events are monitored by an epoll port. * `ephnd` must be a HANDLE created by [`epoll_create()`](#epoll_createepoll_create1) or [`epoll_create1()`](#epoll_createepoll_create1). * `op` must be one of `EPOLL_CTL_ADD`, `EPOLL_CTL_MOD`, `EPOLL_CTL_DEL`. * `sock` must be a valid socket created by [`socket()`][msdn socket], [`WSASocket()`][msdn wsasocket], or [`accept()`][msdn accept]. * `event` should be a pointer to a [`struct epoll_event`](#struct-epoll_event).
If `op` is `EPOLL_CTL_DEL` then the `event` parameter is ignored, and it may be `NULL`. * Returns 0 on success, -1 on failure. * It is recommended to always explicitly remove a socket from its epoll set using `EPOLL_CTL_DEL` *before* closing it.
As on Linux, closed sockets are automatically removed from the epoll set, but wepoll may not be able to detect that a socket was closed until the next call to [`epoll_wait()`](#epoll_wait). * [Linux man page][man epoll_ctl] ### epoll_wait ```c int epoll_wait(HANDLE ephnd, struct epoll_event* events, int maxevents, int timeout); ``` * Receive socket events from an epoll port. * `events` should point to a caller-allocated array of [`epoll_event`](#struct-epoll_event) structs, which will receive the reported events. * `maxevents` is the maximum number of events that will be written to the `events` array, and must be greater than zero. * `timeout` specifies whether to block when no events are immediately available. - `<0` block indefinitely - `0` report any events that are already waiting, but don't block - `≥1` block for at most N milliseconds * Return value: - `-1` an error occurred - `0` timed out without any events to report - `≥1` the number of events stored in the `events` buffer * [Linux man page][man epoll_wait] ### struct epoll_event ```c typedef union epoll_data { void* ptr; int fd; uint32_t u32; uint64_t u64; SOCKET sock; /* Windows specific */ HANDLE hnd; /* Windows specific */ } epoll_data_t; ``` ```c struct epoll_event { uint32_t events; /* Epoll events and flags */ epoll_data_t data; /* User data variable */ }; ``` * The `events` field is a bit mask containing the events being monitored/reported, and optional flags.
Flags are accepted by [`epoll_ctl()`](#epoll_ctl), but they are not reported back by [`epoll_wait()`](#epoll_wait). * The `data` field can be used to associate application-specific information with a socket; its value will be returned unmodified by [`epoll_wait()`](#epoll_wait). * [Linux man page][man epoll_ctl] | Event | Description | |---------------|----------------------------------------------------------------------| | `EPOLLIN` | incoming data available, or incoming connection ready to be accepted | | `EPOLLOUT` | ready to send data, or outgoing connection successfully established | | `EPOLLRDHUP` | remote peer initiated graceful socket shutdown | | `EPOLLPRI` | out-of-band data available for reading | | `EPOLLERR` | socket error1 | | `EPOLLHUP` | socket hang-up1 | | `EPOLLRDNORM` | same as `EPOLLIN` | | `EPOLLRDBAND` | same as `EPOLLPRI` | | `EPOLLWRNORM` | same as `EPOLLOUT` | | `EPOLLWRBAND` | same as `EPOLLOUT` | | `EPOLLMSG` | never reported | | Flag | Description | |------------------|---------------------------| | `EPOLLONESHOT` | report event(s) only once | | `EPOLLET` | not supported by wepoll | | `EPOLLEXCLUSIVE` | not supported by wepoll | | `EPOLLWAKEUP` | not supported by wepoll | 1: the `EPOLLERR` and `EPOLLHUP` events may always be reported by [`epoll_wait()`](#epoll_wait), regardless of the event mask that was passed to [`epoll_ctl()`](#epoll_ctl). [ci status badge]: https://ci.appveyor.com/api/projects/status/github/piscisaureus/wepoll?branch=master&svg=true [ci status link]: https://ci.appveyor.com/project/piscisaureus/wepoll/branch/master [dist]: https://github.com/piscisaureus/wepoll/tree/dist [man epoll]: http://man7.org/linux/man-pages/man7/epoll.7.html [man epoll_create]: http://man7.org/linux/man-pages/man2/epoll_create.2.html [man epoll_ctl]: http://man7.org/linux/man-pages/man2/epoll_ctl.2.html [man epoll_wait]: http://man7.org/linux/man-pages/man2/epoll_wait.2.html [msdn accept]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx [msdn socket]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms740506(v=vs.85).aspx [msdn wsasocket]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx [select scale]: https://daniel.haxx.se/docs/poll-vs-select.html [wsapoll broken]: https://daniel.haxx.se/blog/2012/10/10/wsapoll-is-broken/ [wepoll.c]: https://github.com/piscisaureus/wepoll/blob/dist/wepoll.c [wepoll.h]: https://github.com/piscisaureus/wepoll/blob/dist/wepoll.h kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/wepoll/wepoll.c000066400000000000000000002105561520575453600275470ustar00rootroot00000000000000/* * wepoll - epoll for Windows * https://github.com/piscisaureus/wepoll * * Copyright 2012-2020, Bert Belder * 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 WEPOLL_EXPORT #define WEPOLL_EXPORT #endif #include enum EPOLL_EVENTS { EPOLLIN = (int) (1U << 0), EPOLLPRI = (int) (1U << 1), EPOLLOUT = (int) (1U << 2), EPOLLERR = (int) (1U << 3), EPOLLHUP = (int) (1U << 4), EPOLLRDNORM = (int) (1U << 6), EPOLLRDBAND = (int) (1U << 7), EPOLLWRNORM = (int) (1U << 8), EPOLLWRBAND = (int) (1U << 9), EPOLLMSG = (int) (1U << 10), /* Never reported. */ EPOLLRDHUP = (int) (1U << 13), EPOLLONESHOT = (int) (1U << 31) }; #define EPOLLIN (1U << 0) #define EPOLLPRI (1U << 1) #define EPOLLOUT (1U << 2) #define EPOLLERR (1U << 3) #define EPOLLHUP (1U << 4) #define EPOLLRDNORM (1U << 6) #define EPOLLRDBAND (1U << 7) #define EPOLLWRNORM (1U << 8) #define EPOLLWRBAND (1U << 9) #define EPOLLMSG (1U << 10) #define EPOLLRDHUP (1U << 13) #define EPOLLONESHOT (1U << 31) #define EPOLL_CTL_ADD 1 #define EPOLL_CTL_MOD 2 #define EPOLL_CTL_DEL 3 typedef void* HANDLE; typedef uintptr_t SOCKET; typedef union epoll_data { void* ptr; int fd; uint32_t u32; uint64_t u64; SOCKET sock; /* Windows specific */ HANDLE hnd; /* Windows specific */ } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events and flags */ epoll_data_t data; /* User data variable */ }; #ifdef __cplusplus extern "C" { #endif WEPOLL_EXPORT HANDLE epoll_create(int size); WEPOLL_EXPORT HANDLE epoll_create1(int flags); WEPOLL_EXPORT int epoll_close(HANDLE ephnd); WEPOLL_EXPORT int epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* event); WEPOLL_EXPORT int epoll_wait(HANDLE ephnd, struct epoll_event* events, int maxevents, int timeout); #ifdef __cplusplus } /* extern "C" */ #endif #include #include #define WEPOLL_INTERNAL static #define WEPOLL_INTERNAL_EXTERN static #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnonportable-system-include-path" #pragma clang diagnostic ignored "-Wreserved-id-macro" #elif defined(_MSC_VER) #pragma warning(push, 1) #endif #undef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #undef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #include #include #include #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif WEPOLL_INTERNAL int nt_global_init(void); typedef LONG NTSTATUS; typedef NTSTATUS* PNTSTATUS; #ifndef NT_SUCCESS #define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0) #endif #ifndef STATUS_SUCCESS #define STATUS_SUCCESS ((NTSTATUS) 0x00000000L) #endif #ifndef STATUS_PENDING #define STATUS_PENDING ((NTSTATUS) 0x00000103L) #endif #ifndef STATUS_CANCELLED #define STATUS_CANCELLED ((NTSTATUS) 0xC0000120L) #endif #ifndef STATUS_NOT_FOUND #define STATUS_NOT_FOUND ((NTSTATUS) 0xC0000225L) #endif typedef struct _IO_STATUS_BLOCK { NTSTATUS Status; ULONG_PTR Information; } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; typedef VOID(NTAPI* PIO_APC_ROUTINE)(PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG Reserved); typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; #define RTL_CONSTANT_STRING(s) \ { sizeof(s) - sizeof((s)[0]), sizeof(s), s } typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; #define RTL_CONSTANT_OBJECT_ATTRIBUTES(ObjectName, Attributes) \ { sizeof(OBJECT_ATTRIBUTES), NULL, ObjectName, Attributes, NULL, NULL } #ifndef FILE_OPEN #define FILE_OPEN 0x00000001UL #endif #define KEYEDEVENT_WAIT 0x00000001UL #define KEYEDEVENT_WAKE 0x00000002UL #define KEYEDEVENT_ALL_ACCESS \ (STANDARD_RIGHTS_REQUIRED | KEYEDEVENT_WAIT | KEYEDEVENT_WAKE) #define NT_NTDLL_IMPORT_LIST(X) \ X(NTSTATUS, \ NTAPI, \ NtCancelIoFileEx, \ (HANDLE FileHandle, \ PIO_STATUS_BLOCK IoRequestToCancel, \ PIO_STATUS_BLOCK IoStatusBlock)) \ \ X(NTSTATUS, \ NTAPI, \ NtCreateFile, \ (PHANDLE FileHandle, \ ACCESS_MASK DesiredAccess, \ POBJECT_ATTRIBUTES ObjectAttributes, \ PIO_STATUS_BLOCK IoStatusBlock, \ PLARGE_INTEGER AllocationSize, \ ULONG FileAttributes, \ ULONG ShareAccess, \ ULONG CreateDisposition, \ ULONG CreateOptions, \ PVOID EaBuffer, \ ULONG EaLength)) \ \ X(NTSTATUS, \ NTAPI, \ NtCreateKeyedEvent, \ (PHANDLE KeyedEventHandle, \ ACCESS_MASK DesiredAccess, \ POBJECT_ATTRIBUTES ObjectAttributes, \ ULONG Flags)) \ \ X(NTSTATUS, \ NTAPI, \ NtDeviceIoControlFile, \ (HANDLE FileHandle, \ HANDLE Event, \ PIO_APC_ROUTINE ApcRoutine, \ PVOID ApcContext, \ PIO_STATUS_BLOCK IoStatusBlock, \ ULONG IoControlCode, \ PVOID InputBuffer, \ ULONG InputBufferLength, \ PVOID OutputBuffer, \ ULONG OutputBufferLength)) \ \ X(NTSTATUS, \ NTAPI, \ NtReleaseKeyedEvent, \ (HANDLE KeyedEventHandle, \ PVOID KeyValue, \ BOOLEAN Alertable, \ PLARGE_INTEGER Timeout)) \ \ X(NTSTATUS, \ NTAPI, \ NtWaitForKeyedEvent, \ (HANDLE KeyedEventHandle, \ PVOID KeyValue, \ BOOLEAN Alertable, \ PLARGE_INTEGER Timeout)) \ \ X(ULONG, WINAPI, RtlNtStatusToDosError, (NTSTATUS Status)) #define X(return_type, attributes, name, parameters) \ WEPOLL_INTERNAL_EXTERN return_type(attributes* name) parameters; NT_NTDLL_IMPORT_LIST(X) #undef X #define AFD_POLL_RECEIVE 0x0001 #define AFD_POLL_RECEIVE_EXPEDITED 0x0002 #define AFD_POLL_SEND 0x0004 #define AFD_POLL_DISCONNECT 0x0008 #define AFD_POLL_ABORT 0x0010 #define AFD_POLL_LOCAL_CLOSE 0x0020 #define AFD_POLL_ACCEPT 0x0080 #define AFD_POLL_CONNECT_FAIL 0x0100 typedef struct _AFD_POLL_HANDLE_INFO { HANDLE Handle; ULONG Events; NTSTATUS Status; } AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO; typedef struct _AFD_POLL_INFO { LARGE_INTEGER Timeout; ULONG NumberOfHandles; ULONG Exclusive; AFD_POLL_HANDLE_INFO Handles[1]; } AFD_POLL_INFO, *PAFD_POLL_INFO; WEPOLL_INTERNAL int afd_create_device_handle(HANDLE iocp_handle, HANDLE* afd_device_handle_out); WEPOLL_INTERNAL int afd_poll(HANDLE afd_device_handle, AFD_POLL_INFO* poll_info, IO_STATUS_BLOCK* io_status_block); WEPOLL_INTERNAL int afd_cancel_poll(HANDLE afd_device_handle, IO_STATUS_BLOCK* io_status_block); #define return_map_error(value) \ do { \ err_map_win_error(); \ return (value); \ } while (0) #define return_set_error(value, error) \ do { \ err_set_win_error(error); \ return (value); \ } while (0) WEPOLL_INTERNAL void err_map_win_error(void); WEPOLL_INTERNAL void err_set_win_error(DWORD error); WEPOLL_INTERNAL int err_check_handle(HANDLE handle); #define IOCTL_AFD_POLL 0x00012024 static UNICODE_STRING afd__device_name = RTL_CONSTANT_STRING(L"\\Device\\Afd\\Wepoll"); static OBJECT_ATTRIBUTES afd__device_attributes = RTL_CONSTANT_OBJECT_ATTRIBUTES(&afd__device_name, 0); int afd_create_device_handle(HANDLE iocp_handle, HANDLE* afd_device_handle_out) { HANDLE afd_device_handle; IO_STATUS_BLOCK iosb; NTSTATUS status; /* By opening \Device\Afd without specifying any extended attributes, we'll * get a handle that lets us talk to the AFD driver, but that doesn't have an * associated endpoint (so it's not a socket). */ status = NtCreateFile(&afd_device_handle, SYNCHRONIZE, &afd__device_attributes, &iosb, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, 0, NULL, 0); if (status != STATUS_SUCCESS) return_set_error(-1, RtlNtStatusToDosError(status)); if (CreateIoCompletionPort(afd_device_handle, iocp_handle, 0, 0) == NULL) goto error; if (!SetFileCompletionNotificationModes(afd_device_handle, FILE_SKIP_SET_EVENT_ON_HANDLE)) goto error; *afd_device_handle_out = afd_device_handle; return 0; error: CloseHandle(afd_device_handle); return_map_error(-1); } int afd_poll(HANDLE afd_device_handle, AFD_POLL_INFO* poll_info, IO_STATUS_BLOCK* io_status_block) { NTSTATUS status; /* Blocking operation is not supported. */ assert(io_status_block != NULL); io_status_block->Status = STATUS_PENDING; status = NtDeviceIoControlFile(afd_device_handle, NULL, NULL, io_status_block, io_status_block, IOCTL_AFD_POLL, poll_info, sizeof *poll_info, poll_info, sizeof *poll_info); if (status == STATUS_SUCCESS) return 0; else if (status == STATUS_PENDING) return_set_error(-1, ERROR_IO_PENDING); else return_set_error(-1, RtlNtStatusToDosError(status)); } int afd_cancel_poll(HANDLE afd_device_handle, IO_STATUS_BLOCK* io_status_block) { NTSTATUS cancel_status; IO_STATUS_BLOCK cancel_iosb; /* If the poll operation has already completed or has been cancelled earlier, * there's nothing left for us to do. */ if (io_status_block->Status != STATUS_PENDING) return 0; cancel_status = NtCancelIoFileEx(afd_device_handle, io_status_block, &cancel_iosb); /* NtCancelIoFileEx() may return STATUS_NOT_FOUND if the operation completed * just before calling NtCancelIoFileEx(). This is not an error. */ if (cancel_status == STATUS_SUCCESS || cancel_status == STATUS_NOT_FOUND) return 0; else return_set_error(-1, RtlNtStatusToDosError(cancel_status)); } WEPOLL_INTERNAL int epoll_global_init(void); WEPOLL_INTERNAL int init(void); typedef struct port_state port_state_t; typedef struct queue queue_t; typedef struct sock_state sock_state_t; typedef struct ts_tree_node ts_tree_node_t; WEPOLL_INTERNAL port_state_t* port_new(HANDLE* iocp_handle_out); WEPOLL_INTERNAL int port_close(port_state_t* port_state); WEPOLL_INTERNAL int port_delete(port_state_t* port_state); WEPOLL_INTERNAL int port_wait(port_state_t* port_state, struct epoll_event* events, int maxevents, int timeout); WEPOLL_INTERNAL int port_ctl(port_state_t* port_state, int op, SOCKET sock, struct epoll_event* ev); WEPOLL_INTERNAL int port_register_socket(port_state_t* port_state, sock_state_t* sock_state, SOCKET socket); WEPOLL_INTERNAL void port_unregister_socket(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL sock_state_t* port_find_socket(port_state_t* port_state, SOCKET socket); WEPOLL_INTERNAL void port_request_socket_update(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL void port_cancel_socket_update(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL void port_add_deleted_socket(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL void port_remove_deleted_socket(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL HANDLE port_get_iocp_handle(port_state_t* port_state); WEPOLL_INTERNAL queue_t* port_get_poll_group_queue(port_state_t* port_state); WEPOLL_INTERNAL port_state_t* port_state_from_handle_tree_node( ts_tree_node_t* tree_node); WEPOLL_INTERNAL ts_tree_node_t* port_state_to_handle_tree_node( port_state_t* port_state); /* The reflock is a special kind of lock that normally prevents a chunk of * memory from being freed, but does allow the chunk of memory to eventually be * released in a coordinated fashion. * * Under normal operation, threads increase and decrease the reference count, * which are wait-free operations. * * Exactly once during the reflock's lifecycle, a thread holding a reference to * the lock may "destroy" the lock; this operation blocks until all other * threads holding a reference to the lock have dereferenced it. After * "destroy" returns, the calling thread may assume that no other threads have * a reference to the lock. * * Attemmpting to lock or destroy a lock after reflock_unref_and_destroy() has * been called is invalid and results in undefined behavior. Therefore the user * should use another lock to guarantee that this can't happen. */ typedef struct reflock { volatile long state; /* 32-bit Interlocked APIs operate on `long` values. */ } reflock_t; WEPOLL_INTERNAL int reflock_global_init(void); WEPOLL_INTERNAL void reflock_init(reflock_t* reflock); WEPOLL_INTERNAL void reflock_ref(reflock_t* reflock); WEPOLL_INTERNAL void reflock_unref(reflock_t* reflock); WEPOLL_INTERNAL void reflock_unref_and_destroy(reflock_t* reflock); #include /* N.b.: the tree functions do not set errno or LastError when they fail. Each * of the API functions has at most one failure mode. It is up to the caller to * set an appropriate error code when necessary. */ typedef struct tree tree_t; typedef struct tree_node tree_node_t; typedef struct tree { tree_node_t* root; } tree_t; typedef struct tree_node { tree_node_t* left; tree_node_t* right; tree_node_t* parent; uintptr_t key; bool red; } tree_node_t; WEPOLL_INTERNAL void tree_init(tree_t* tree); WEPOLL_INTERNAL void tree_node_init(tree_node_t* node); WEPOLL_INTERNAL int tree_add(tree_t* tree, tree_node_t* node, uintptr_t key); WEPOLL_INTERNAL void tree_del(tree_t* tree, tree_node_t* node); WEPOLL_INTERNAL tree_node_t* tree_find(const tree_t* tree, uintptr_t key); WEPOLL_INTERNAL tree_node_t* tree_root(const tree_t* tree); typedef struct ts_tree { tree_t tree; SRWLOCK lock; } ts_tree_t; typedef struct ts_tree_node { tree_node_t tree_node; reflock_t reflock; } ts_tree_node_t; WEPOLL_INTERNAL void ts_tree_init(ts_tree_t* rtl); WEPOLL_INTERNAL void ts_tree_node_init(ts_tree_node_t* node); WEPOLL_INTERNAL int ts_tree_add(ts_tree_t* ts_tree, ts_tree_node_t* node, uintptr_t key); WEPOLL_INTERNAL ts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree, uintptr_t key); WEPOLL_INTERNAL ts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree, uintptr_t key); WEPOLL_INTERNAL void ts_tree_node_unref(ts_tree_node_t* node); WEPOLL_INTERNAL void ts_tree_node_unref_and_destroy(ts_tree_node_t* node); static ts_tree_t epoll__handle_tree; int epoll_global_init(void) { ts_tree_init(&epoll__handle_tree); return 0; } static HANDLE epoll__create(void) { port_state_t* port_state; HANDLE ephnd; ts_tree_node_t* tree_node; if (init() < 0) return NULL; port_state = port_new(&ephnd); if (port_state == NULL) return NULL; tree_node = port_state_to_handle_tree_node(port_state); if (ts_tree_add(&epoll__handle_tree, tree_node, (uintptr_t) ephnd) < 0) { /* This should never happen. */ port_delete(port_state); return_set_error(NULL, ERROR_ALREADY_EXISTS); } return ephnd; } HANDLE epoll_create(int size) { if (size <= 0) return_set_error(NULL, ERROR_INVALID_PARAMETER); return epoll__create(); } HANDLE epoll_create1(int flags) { if (flags != 0) return_set_error(NULL, ERROR_INVALID_PARAMETER); return epoll__create(); } int epoll_close(HANDLE ephnd) { ts_tree_node_t* tree_node; port_state_t* port_state; if (init() < 0) return -1; tree_node = ts_tree_del_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); if (tree_node == NULL) { err_set_win_error(ERROR_INVALID_PARAMETER); goto err; } port_state = port_state_from_handle_tree_node(tree_node); port_close(port_state); ts_tree_node_unref_and_destroy(tree_node); return port_delete(port_state); err: err_check_handle(ephnd); return -1; } int epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* ev) { ts_tree_node_t* tree_node; port_state_t* port_state; int r; if (init() < 0) return -1; tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); if (tree_node == NULL) { err_set_win_error(ERROR_INVALID_PARAMETER); goto err; } port_state = port_state_from_handle_tree_node(tree_node); r = port_ctl(port_state, op, sock, ev); ts_tree_node_unref(tree_node); if (r < 0) goto err; return 0; err: /* On Linux, in the case of epoll_ctl(), EBADF takes priority over other * errors. Wepoll mimics this behavior. */ err_check_handle(ephnd); err_check_handle((HANDLE) sock); return -1; } int epoll_wait(HANDLE ephnd, struct epoll_event* events, int maxevents, int timeout) { ts_tree_node_t* tree_node; port_state_t* port_state; int num_events; if (maxevents <= 0) return_set_error(-1, ERROR_INVALID_PARAMETER); if (init() < 0) return -1; tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); if (tree_node == NULL) { err_set_win_error(ERROR_INVALID_PARAMETER); goto err; } port_state = port_state_from_handle_tree_node(tree_node); num_events = port_wait(port_state, events, maxevents, timeout); ts_tree_node_unref(tree_node); if (num_events < 0) goto err; return num_events; err: err_check_handle(ephnd); return -1; } #include #define ERR__ERRNO_MAPPINGS(X) \ X(ERROR_ACCESS_DENIED, EACCES) \ X(ERROR_ALREADY_EXISTS, EEXIST) \ X(ERROR_BAD_COMMAND, EACCES) \ X(ERROR_BAD_EXE_FORMAT, ENOEXEC) \ X(ERROR_BAD_LENGTH, EACCES) \ X(ERROR_BAD_NETPATH, ENOENT) \ X(ERROR_BAD_NET_NAME, ENOENT) \ X(ERROR_BAD_NET_RESP, ENETDOWN) \ X(ERROR_BAD_PATHNAME, ENOENT) \ X(ERROR_BROKEN_PIPE, EPIPE) \ X(ERROR_CANNOT_MAKE, EACCES) \ X(ERROR_COMMITMENT_LIMIT, ENOMEM) \ X(ERROR_CONNECTION_ABORTED, ECONNABORTED) \ X(ERROR_CONNECTION_ACTIVE, EISCONN) \ X(ERROR_CONNECTION_REFUSED, ECONNREFUSED) \ X(ERROR_CRC, EACCES) \ X(ERROR_DIR_NOT_EMPTY, ENOTEMPTY) \ X(ERROR_DISK_FULL, ENOSPC) \ X(ERROR_DUP_NAME, EADDRINUSE) \ X(ERROR_FILENAME_EXCED_RANGE, ENOENT) \ X(ERROR_FILE_NOT_FOUND, ENOENT) \ X(ERROR_GEN_FAILURE, EACCES) \ X(ERROR_GRACEFUL_DISCONNECT, EPIPE) \ X(ERROR_HOST_DOWN, EHOSTUNREACH) \ X(ERROR_HOST_UNREACHABLE, EHOSTUNREACH) \ X(ERROR_INSUFFICIENT_BUFFER, EFAULT) \ X(ERROR_INVALID_ADDRESS, EADDRNOTAVAIL) \ X(ERROR_INVALID_FUNCTION, EINVAL) \ X(ERROR_INVALID_HANDLE, EBADF) \ X(ERROR_INVALID_NETNAME, EADDRNOTAVAIL) \ X(ERROR_INVALID_PARAMETER, EINVAL) \ X(ERROR_INVALID_USER_BUFFER, EMSGSIZE) \ X(ERROR_IO_PENDING, EINPROGRESS) \ X(ERROR_LOCK_VIOLATION, EACCES) \ X(ERROR_MORE_DATA, EMSGSIZE) \ X(ERROR_NETNAME_DELETED, ECONNABORTED) \ X(ERROR_NETWORK_ACCESS_DENIED, EACCES) \ X(ERROR_NETWORK_BUSY, ENETDOWN) \ X(ERROR_NETWORK_UNREACHABLE, ENETUNREACH) \ X(ERROR_NOACCESS, EFAULT) \ X(ERROR_NONPAGED_SYSTEM_RESOURCES, ENOMEM) \ X(ERROR_NOT_ENOUGH_MEMORY, ENOMEM) \ X(ERROR_NOT_ENOUGH_QUOTA, ENOMEM) \ X(ERROR_NOT_FOUND, ENOENT) \ X(ERROR_NOT_LOCKED, EACCES) \ X(ERROR_NOT_READY, EACCES) \ X(ERROR_NOT_SAME_DEVICE, EXDEV) \ X(ERROR_NOT_SUPPORTED, ENOTSUP) \ X(ERROR_NO_MORE_FILES, ENOENT) \ X(ERROR_NO_SYSTEM_RESOURCES, ENOMEM) \ X(ERROR_OPERATION_ABORTED, EINTR) \ X(ERROR_OUT_OF_PAPER, EACCES) \ X(ERROR_PAGED_SYSTEM_RESOURCES, ENOMEM) \ X(ERROR_PAGEFILE_QUOTA, ENOMEM) \ X(ERROR_PATH_NOT_FOUND, ENOENT) \ X(ERROR_PIPE_NOT_CONNECTED, EPIPE) \ X(ERROR_PORT_UNREACHABLE, ECONNRESET) \ X(ERROR_PROTOCOL_UNREACHABLE, ENETUNREACH) \ X(ERROR_REM_NOT_LIST, ECONNREFUSED) \ X(ERROR_REQUEST_ABORTED, EINTR) \ X(ERROR_REQ_NOT_ACCEP, EWOULDBLOCK) \ X(ERROR_SECTOR_NOT_FOUND, EACCES) \ X(ERROR_SEM_TIMEOUT, ETIMEDOUT) \ X(ERROR_SHARING_VIOLATION, EACCES) \ X(ERROR_TOO_MANY_NAMES, ENOMEM) \ X(ERROR_TOO_MANY_OPEN_FILES, EMFILE) \ X(ERROR_UNEXP_NET_ERR, ECONNABORTED) \ X(ERROR_WAIT_NO_CHILDREN, ECHILD) \ X(ERROR_WORKING_SET_QUOTA, ENOMEM) \ X(ERROR_WRITE_PROTECT, EACCES) \ X(ERROR_WRONG_DISK, EACCES) \ X(WSAEACCES, EACCES) \ X(WSAEADDRINUSE, EADDRINUSE) \ X(WSAEADDRNOTAVAIL, EADDRNOTAVAIL) \ X(WSAEAFNOSUPPORT, EAFNOSUPPORT) \ X(WSAECONNABORTED, ECONNABORTED) \ X(WSAECONNREFUSED, ECONNREFUSED) \ X(WSAECONNRESET, ECONNRESET) \ X(WSAEDISCON, EPIPE) \ X(WSAEFAULT, EFAULT) \ X(WSAEHOSTDOWN, EHOSTUNREACH) \ X(WSAEHOSTUNREACH, EHOSTUNREACH) \ X(WSAEINPROGRESS, EBUSY) \ X(WSAEINTR, EINTR) \ X(WSAEINVAL, EINVAL) \ X(WSAEISCONN, EISCONN) \ X(WSAEMSGSIZE, EMSGSIZE) \ X(WSAENETDOWN, ENETDOWN) \ X(WSAENETRESET, EHOSTUNREACH) \ X(WSAENETUNREACH, ENETUNREACH) \ X(WSAENOBUFS, ENOMEM) \ X(WSAENOTCONN, ENOTCONN) \ X(WSAENOTSOCK, ENOTSOCK) \ X(WSAEOPNOTSUPP, EOPNOTSUPP) \ X(WSAEPROCLIM, ENOMEM) \ X(WSAESHUTDOWN, EPIPE) \ X(WSAETIMEDOUT, ETIMEDOUT) \ X(WSAEWOULDBLOCK, EWOULDBLOCK) \ X(WSANOTINITIALISED, ENETDOWN) \ X(WSASYSNOTREADY, ENETDOWN) \ X(WSAVERNOTSUPPORTED, ENOSYS) static errno_t err__map_win_error_to_errno(DWORD error) { switch (error) { #define X(error_sym, errno_sym) \ case error_sym: \ return errno_sym; ERR__ERRNO_MAPPINGS(X) #undef X } return EINVAL; } void err_map_win_error(void) { errno = err__map_win_error_to_errno(GetLastError()); } void err_set_win_error(DWORD error) { SetLastError(error); errno = err__map_win_error_to_errno(error); } int err_check_handle(HANDLE handle) { DWORD flags; /* GetHandleInformation() succeeds when passed INVALID_HANDLE_VALUE, so check * for this condition explicitly. */ if (handle == INVALID_HANDLE_VALUE) return_set_error(-1, ERROR_INVALID_HANDLE); if (!GetHandleInformation(handle, &flags)) return_map_error(-1); return 0; } #include #define array_count(a) (sizeof(a) / (sizeof((a)[0]))) #define container_of(ptr, type, member) \ ((type*) ((uintptr_t) (ptr) - offsetof(type, member))) #define unused_var(v) ((void) (v)) /* Polyfill `inline` for older versions of msvc (up to Visual Studio 2013) */ #if defined(_MSC_VER) && _MSC_VER < 1900 #define inline __inline #endif WEPOLL_INTERNAL int ws_global_init(void); WEPOLL_INTERNAL SOCKET ws_get_base_socket(SOCKET socket); static bool init__done = false; static INIT_ONCE init__once = INIT_ONCE_STATIC_INIT; static BOOL CALLBACK init__once_callback(INIT_ONCE* once, void* parameter, void** context) { unused_var(once); unused_var(parameter); unused_var(context); /* N.b. that initialization order matters here. */ if (ws_global_init() < 0 || nt_global_init() < 0 || reflock_global_init() < 0 || epoll_global_init() < 0) return FALSE; init__done = true; return TRUE; } int init(void) { if (!init__done && !InitOnceExecuteOnce(&init__once, init__once_callback, NULL, NULL)) /* `InitOnceExecuteOnce()` itself is infallible, and it doesn't set any * error code when the once-callback returns FALSE. We return -1 here to * indicate that global initialization failed; the failing init function is * resposible for setting `errno` and calling `SetLastError()`. */ return -1; return 0; } /* Set up a workaround for the following problem: * FARPROC addr = GetProcAddress(...); * MY_FUNC func = (MY_FUNC) addr; <-- GCC 8 warning/error. * MY_FUNC func = (MY_FUNC) (void*) addr; <-- MSVC warning/error. * To compile cleanly with either compiler, do casts with this "bridge" type: * MY_FUNC func = (MY_FUNC) (nt__fn_ptr_cast_t) addr; */ #ifdef __GNUC__ typedef void* nt__fn_ptr_cast_t; #else typedef FARPROC nt__fn_ptr_cast_t; #endif #define X(return_type, attributes, name, parameters) \ WEPOLL_INTERNAL return_type(attributes* name) parameters = NULL; NT_NTDLL_IMPORT_LIST(X) #undef X int nt_global_init(void) { HMODULE ntdll; FARPROC fn_ptr; ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll == NULL) return -1; #define X(return_type, attributes, name, parameters) \ fn_ptr = GetProcAddress(ntdll, #name); \ if (fn_ptr == NULL) \ return -1; \ name = (return_type(attributes*) parameters)(nt__fn_ptr_cast_t) fn_ptr; NT_NTDLL_IMPORT_LIST(X) #undef X return 0; } #include typedef struct poll_group poll_group_t; typedef struct queue_node queue_node_t; WEPOLL_INTERNAL poll_group_t* poll_group_acquire(port_state_t* port); WEPOLL_INTERNAL void poll_group_release(poll_group_t* poll_group); WEPOLL_INTERNAL void poll_group_delete(poll_group_t* poll_group); WEPOLL_INTERNAL poll_group_t* poll_group_from_queue_node( queue_node_t* queue_node); WEPOLL_INTERNAL HANDLE poll_group_get_afd_device_handle(poll_group_t* poll_group); typedef struct queue_node { queue_node_t* prev; queue_node_t* next; } queue_node_t; typedef struct queue { queue_node_t head; } queue_t; WEPOLL_INTERNAL void queue_init(queue_t* queue); WEPOLL_INTERNAL void queue_node_init(queue_node_t* node); WEPOLL_INTERNAL queue_node_t* queue_first(const queue_t* queue); WEPOLL_INTERNAL queue_node_t* queue_last(const queue_t* queue); WEPOLL_INTERNAL void queue_prepend(queue_t* queue, queue_node_t* node); WEPOLL_INTERNAL void queue_append(queue_t* queue, queue_node_t* node); WEPOLL_INTERNAL void queue_move_to_start(queue_t* queue, queue_node_t* node); WEPOLL_INTERNAL void queue_move_to_end(queue_t* queue, queue_node_t* node); WEPOLL_INTERNAL void queue_remove(queue_node_t* node); WEPOLL_INTERNAL bool queue_is_empty(const queue_t* queue); WEPOLL_INTERNAL bool queue_is_enqueued(const queue_node_t* node); #define POLL_GROUP__MAX_GROUP_SIZE 32 typedef struct poll_group { port_state_t* port_state; queue_node_t queue_node; HANDLE afd_device_handle; size_t group_size; } poll_group_t; static poll_group_t* poll_group__new(port_state_t* port_state) { HANDLE iocp_handle = port_get_iocp_handle(port_state); queue_t* poll_group_queue = port_get_poll_group_queue(port_state); poll_group_t* poll_group = malloc(sizeof *poll_group); if (poll_group == NULL) return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); memset(poll_group, 0, sizeof *poll_group); queue_node_init(&poll_group->queue_node); poll_group->port_state = port_state; if (afd_create_device_handle(iocp_handle, &poll_group->afd_device_handle) < 0) { free(poll_group); return NULL; } queue_append(poll_group_queue, &poll_group->queue_node); return poll_group; } void poll_group_delete(poll_group_t* poll_group) { assert(poll_group->group_size == 0); CloseHandle(poll_group->afd_device_handle); queue_remove(&poll_group->queue_node); free(poll_group); } poll_group_t* poll_group_from_queue_node(queue_node_t* queue_node) { return container_of(queue_node, poll_group_t, queue_node); } HANDLE poll_group_get_afd_device_handle(poll_group_t* poll_group) { return poll_group->afd_device_handle; } poll_group_t* poll_group_acquire(port_state_t* port_state) { queue_t* poll_group_queue = port_get_poll_group_queue(port_state); poll_group_t* poll_group = !queue_is_empty(poll_group_queue) ? container_of( queue_last(poll_group_queue), poll_group_t, queue_node) : NULL; if (poll_group == NULL || poll_group->group_size >= POLL_GROUP__MAX_GROUP_SIZE) poll_group = poll_group__new(port_state); if (poll_group == NULL) return NULL; if (++poll_group->group_size == POLL_GROUP__MAX_GROUP_SIZE) queue_move_to_start(poll_group_queue, &poll_group->queue_node); return poll_group; } void poll_group_release(poll_group_t* poll_group) { port_state_t* port_state = poll_group->port_state; queue_t* poll_group_queue = port_get_poll_group_queue(port_state); poll_group->group_size--; assert(poll_group->group_size < POLL_GROUP__MAX_GROUP_SIZE); queue_move_to_end(poll_group_queue, &poll_group->queue_node); /* Poll groups are currently only freed when the epoll port is closed. */ } WEPOLL_INTERNAL sock_state_t* sock_new(port_state_t* port_state, SOCKET socket); WEPOLL_INTERNAL void sock_delete(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL void sock_force_delete(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL int sock_set_event(port_state_t* port_state, sock_state_t* sock_state, const struct epoll_event* ev); WEPOLL_INTERNAL int sock_update(port_state_t* port_state, sock_state_t* sock_state); WEPOLL_INTERNAL int sock_feed_event(port_state_t* port_state, IO_STATUS_BLOCK* io_status_block, struct epoll_event* ev); WEPOLL_INTERNAL sock_state_t* sock_state_from_queue_node( queue_node_t* queue_node); WEPOLL_INTERNAL queue_node_t* sock_state_to_queue_node( sock_state_t* sock_state); WEPOLL_INTERNAL sock_state_t* sock_state_from_tree_node( tree_node_t* tree_node); WEPOLL_INTERNAL tree_node_t* sock_state_to_tree_node(sock_state_t* sock_state); #define PORT__MAX_ON_STACK_COMPLETIONS 256 typedef struct port_state { HANDLE iocp_handle; tree_t sock_tree; queue_t sock_update_queue; queue_t sock_deleted_queue; queue_t poll_group_queue; ts_tree_node_t handle_tree_node; CRITICAL_SECTION lock; size_t active_poll_count; } port_state_t; static inline port_state_t* port__alloc(void) { port_state_t* port_state = malloc(sizeof *port_state); if (port_state == NULL) return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); return port_state; } static inline void port__free(port_state_t* port) { assert(port != NULL); free(port); } static inline HANDLE port__create_iocp(void) { HANDLE iocp_handle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); if (iocp_handle == NULL) return_map_error(NULL); return iocp_handle; } port_state_t* port_new(HANDLE* iocp_handle_out) { port_state_t* port_state; HANDLE iocp_handle; port_state = port__alloc(); if (port_state == NULL) goto err1; iocp_handle = port__create_iocp(); if (iocp_handle == NULL) goto err2; memset(port_state, 0, sizeof *port_state); port_state->iocp_handle = iocp_handle; tree_init(&port_state->sock_tree); queue_init(&port_state->sock_update_queue); queue_init(&port_state->sock_deleted_queue); queue_init(&port_state->poll_group_queue); ts_tree_node_init(&port_state->handle_tree_node); InitializeCriticalSection(&port_state->lock); *iocp_handle_out = iocp_handle; return port_state; err2: port__free(port_state); err1: return NULL; } static inline int port__close_iocp(port_state_t* port_state) { HANDLE iocp_handle = port_state->iocp_handle; port_state->iocp_handle = NULL; if (!CloseHandle(iocp_handle)) return_map_error(-1); return 0; } int port_close(port_state_t* port_state) { int result; EnterCriticalSection(&port_state->lock); result = port__close_iocp(port_state); LeaveCriticalSection(&port_state->lock); return result; } int port_delete(port_state_t* port_state) { tree_node_t* tree_node; queue_node_t* queue_node; /* At this point the IOCP port should have been closed. */ assert(port_state->iocp_handle == NULL); while ((tree_node = tree_root(&port_state->sock_tree)) != NULL) { sock_state_t* sock_state = sock_state_from_tree_node(tree_node); sock_force_delete(port_state, sock_state); } while ((queue_node = queue_first(&port_state->sock_deleted_queue)) != NULL) { sock_state_t* sock_state = sock_state_from_queue_node(queue_node); sock_force_delete(port_state, sock_state); } while ((queue_node = queue_first(&port_state->poll_group_queue)) != NULL) { poll_group_t* poll_group = poll_group_from_queue_node(queue_node); poll_group_delete(poll_group); } assert(queue_is_empty(&port_state->sock_update_queue)); DeleteCriticalSection(&port_state->lock); port__free(port_state); return 0; } static int port__update_events(port_state_t* port_state) { queue_t* sock_update_queue = &port_state->sock_update_queue; /* Walk the queue, submitting new poll requests for every socket that needs * it. */ while (!queue_is_empty(sock_update_queue)) { queue_node_t* queue_node = queue_first(sock_update_queue); sock_state_t* sock_state = sock_state_from_queue_node(queue_node); if (sock_update(port_state, sock_state) < 0) return -1; /* sock_update() removes the socket from the update queue. */ } return 0; } static inline void port__update_events_if_polling(port_state_t* port_state) { if (port_state->active_poll_count > 0) port__update_events(port_state); } static inline int port__feed_events(port_state_t* port_state, struct epoll_event* epoll_events, OVERLAPPED_ENTRY* iocp_events, DWORD iocp_event_count) { int epoll_event_count = 0; DWORD i; for (i = 0; i < iocp_event_count; i++) { IO_STATUS_BLOCK* io_status_block = (IO_STATUS_BLOCK*) iocp_events[i].lpOverlapped; struct epoll_event* ev = &epoll_events[epoll_event_count]; epoll_event_count += sock_feed_event(port_state, io_status_block, ev); } return epoll_event_count; } static inline int port__poll(port_state_t* port_state, struct epoll_event* epoll_events, OVERLAPPED_ENTRY* iocp_events, DWORD maxevents, DWORD timeout) { DWORD completion_count; if (port__update_events(port_state) < 0) return -1; port_state->active_poll_count++; LeaveCriticalSection(&port_state->lock); BOOL r = GetQueuedCompletionStatusEx(port_state->iocp_handle, iocp_events, maxevents, &completion_count, timeout, FALSE); EnterCriticalSection(&port_state->lock); port_state->active_poll_count--; if (!r) return_map_error(-1); return port__feed_events( port_state, epoll_events, iocp_events, completion_count); } int port_wait(port_state_t* port_state, struct epoll_event* events, int maxevents, int timeout) { OVERLAPPED_ENTRY stack_iocp_events[PORT__MAX_ON_STACK_COMPLETIONS]; OVERLAPPED_ENTRY* iocp_events; uint64_t due = 0; DWORD gqcs_timeout; int result; /* Check whether `maxevents` is in range. */ if (maxevents <= 0) return_set_error(-1, ERROR_INVALID_PARAMETER); /* Decide whether the IOCP completion list can live on the stack, or allocate * memory for it on the heap. */ if ((size_t) maxevents <= array_count(stack_iocp_events)) { iocp_events = stack_iocp_events; } else if ((iocp_events = malloc((size_t) maxevents * sizeof *iocp_events)) == NULL) { iocp_events = stack_iocp_events; maxevents = array_count(stack_iocp_events); } /* Compute the timeout for GetQueuedCompletionStatus, and the wait end * time, if the user specified a timeout other than zero or infinite. */ if (timeout > 0) { due = GetTickCount64() + (uint64_t) timeout; gqcs_timeout = (DWORD) timeout; } else if (timeout == 0) { gqcs_timeout = 0; } else { gqcs_timeout = INFINITE; } EnterCriticalSection(&port_state->lock); /* Dequeue completion packets until either at least one interesting event * has been discovered, or the timeout is reached. */ for (;;) { uint64_t now; result = port__poll( port_state, events, iocp_events, (DWORD) maxevents, gqcs_timeout); if (result < 0 || result > 0) break; /* Result, error, or time-out. */ if (timeout < 0) continue; /* When timeout is negative, never time out. */ /* Update time. */ now = GetTickCount64(); /* Do not allow the due time to be in the past. */ if (now >= due) { SetLastError(WAIT_TIMEOUT); break; } /* Recompute time-out argument for GetQueuedCompletionStatus. */ gqcs_timeout = (DWORD)(due - now); } port__update_events_if_polling(port_state); LeaveCriticalSection(&port_state->lock); if (iocp_events != stack_iocp_events) free(iocp_events); if (result >= 0) return result; else if (GetLastError() == WAIT_TIMEOUT) return 0; else return -1; } static inline int port__ctl_add(port_state_t* port_state, SOCKET sock, struct epoll_event* ev) { sock_state_t* sock_state = sock_new(port_state, sock); if (sock_state == NULL) return -1; if (sock_set_event(port_state, sock_state, ev) < 0) { sock_delete(port_state, sock_state); return -1; } port__update_events_if_polling(port_state); return 0; } static inline int port__ctl_mod(port_state_t* port_state, SOCKET sock, struct epoll_event* ev) { sock_state_t* sock_state = port_find_socket(port_state, sock); if (sock_state == NULL) return -1; if (sock_set_event(port_state, sock_state, ev) < 0) return -1; port__update_events_if_polling(port_state); return 0; } static inline int port__ctl_del(port_state_t* port_state, SOCKET sock) { sock_state_t* sock_state = port_find_socket(port_state, sock); if (sock_state == NULL) return -1; sock_delete(port_state, sock_state); return 0; } static inline int port__ctl_op(port_state_t* port_state, int op, SOCKET sock, struct epoll_event* ev) { switch (op) { case EPOLL_CTL_ADD: return port__ctl_add(port_state, sock, ev); case EPOLL_CTL_MOD: return port__ctl_mod(port_state, sock, ev); case EPOLL_CTL_DEL: return port__ctl_del(port_state, sock); default: return_set_error(-1, ERROR_INVALID_PARAMETER); } } int port_ctl(port_state_t* port_state, int op, SOCKET sock, struct epoll_event* ev) { int result; EnterCriticalSection(&port_state->lock); result = port__ctl_op(port_state, op, sock, ev); LeaveCriticalSection(&port_state->lock); return result; } int port_register_socket(port_state_t* port_state, sock_state_t* sock_state, SOCKET socket) { if (tree_add(&port_state->sock_tree, sock_state_to_tree_node(sock_state), socket) < 0) return_set_error(-1, ERROR_ALREADY_EXISTS); return 0; } void port_unregister_socket(port_state_t* port_state, sock_state_t* sock_state) { tree_del(&port_state->sock_tree, sock_state_to_tree_node(sock_state)); } sock_state_t* port_find_socket(port_state_t* port_state, SOCKET socket) { tree_node_t* tree_node = tree_find(&port_state->sock_tree, socket); if (tree_node == NULL) return_set_error(NULL, ERROR_NOT_FOUND); return sock_state_from_tree_node(tree_node); } void port_request_socket_update(port_state_t* port_state, sock_state_t* sock_state) { if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) return; queue_append(&port_state->sock_update_queue, sock_state_to_queue_node(sock_state)); } void port_cancel_socket_update(port_state_t* port_state, sock_state_t* sock_state) { unused_var(port_state); if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) return; queue_remove(sock_state_to_queue_node(sock_state)); } void port_add_deleted_socket(port_state_t* port_state, sock_state_t* sock_state) { if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) return; queue_append(&port_state->sock_deleted_queue, sock_state_to_queue_node(sock_state)); } void port_remove_deleted_socket(port_state_t* port_state, sock_state_t* sock_state) { unused_var(port_state); if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) return; queue_remove(sock_state_to_queue_node(sock_state)); } HANDLE port_get_iocp_handle(port_state_t* port_state) { assert(port_state->iocp_handle != NULL); return port_state->iocp_handle; } queue_t* port_get_poll_group_queue(port_state_t* port_state) { return &port_state->poll_group_queue; } port_state_t* port_state_from_handle_tree_node(ts_tree_node_t* tree_node) { return container_of(tree_node, port_state_t, handle_tree_node); } ts_tree_node_t* port_state_to_handle_tree_node(port_state_t* port_state) { return &port_state->handle_tree_node; } void queue_init(queue_t* queue) { queue_node_init(&queue->head); } void queue_node_init(queue_node_t* node) { node->prev = node; node->next = node; } static inline void queue__detach_node(queue_node_t* node) { node->prev->next = node->next; node->next->prev = node->prev; } queue_node_t* queue_first(const queue_t* queue) { return !queue_is_empty(queue) ? queue->head.next : NULL; } queue_node_t* queue_last(const queue_t* queue) { return !queue_is_empty(queue) ? queue->head.prev : NULL; } void queue_prepend(queue_t* queue, queue_node_t* node) { node->next = queue->head.next; node->prev = &queue->head; node->next->prev = node; queue->head.next = node; } void queue_append(queue_t* queue, queue_node_t* node) { node->next = &queue->head; node->prev = queue->head.prev; node->prev->next = node; queue->head.prev = node; } void queue_move_to_start(queue_t* queue, queue_node_t* node) { queue__detach_node(node); queue_prepend(queue, node); } void queue_move_to_end(queue_t* queue, queue_node_t* node) { queue__detach_node(node); queue_append(queue, node); } void queue_remove(queue_node_t* node) { queue__detach_node(node); queue_node_init(node); } bool queue_is_empty(const queue_t* queue) { return !queue_is_enqueued(&queue->head); } bool queue_is_enqueued(const queue_node_t* node) { return node->prev != node; } #define REFLOCK__REF ((long) 0x00000001UL) #define REFLOCK__REF_MASK ((long) 0x0fffffffUL) #define REFLOCK__DESTROY ((long) 0x10000000UL) #define REFLOCK__DESTROY_MASK ((long) 0xf0000000UL) #define REFLOCK__POISON ((long) 0x300dead0UL) static HANDLE reflock__keyed_event = NULL; int reflock_global_init(void) { NTSTATUS status = NtCreateKeyedEvent( &reflock__keyed_event, KEYEDEVENT_ALL_ACCESS, NULL, 0); if (status != STATUS_SUCCESS) return_set_error(-1, RtlNtStatusToDosError(status)); return 0; } void reflock_init(reflock_t* reflock) { reflock->state = 0; } static void reflock__signal_event(void* address) { NTSTATUS status = NtReleaseKeyedEvent(reflock__keyed_event, address, FALSE, NULL); if (status != STATUS_SUCCESS) abort(); } static void reflock__await_event(void* address) { NTSTATUS status = NtWaitForKeyedEvent(reflock__keyed_event, address, FALSE, NULL); if (status != STATUS_SUCCESS) abort(); } void reflock_ref(reflock_t* reflock) { long state = InterlockedAdd(&reflock->state, REFLOCK__REF); /* Verify that the counter didn't overflow and the lock isn't destroyed. */ assert((state & REFLOCK__DESTROY_MASK) == 0); unused_var(state); } void reflock_unref(reflock_t* reflock) { long state = InterlockedAdd(&reflock->state, -REFLOCK__REF); /* Verify that the lock was referenced and not already destroyed. */ assert((state & REFLOCK__DESTROY_MASK & ~REFLOCK__DESTROY) == 0); if (state == REFLOCK__DESTROY) reflock__signal_event(reflock); } void reflock_unref_and_destroy(reflock_t* reflock) { long state = InterlockedAdd(&reflock->state, REFLOCK__DESTROY - REFLOCK__REF); long ref_count = state & REFLOCK__REF_MASK; /* Verify that the lock was referenced and not already destroyed. */ assert((state & REFLOCK__DESTROY_MASK) == REFLOCK__DESTROY); if (ref_count != 0) reflock__await_event(reflock); state = InterlockedExchange(&reflock->state, REFLOCK__POISON); assert(state == REFLOCK__DESTROY); } #define SOCK__KNOWN_EPOLL_EVENTS \ (EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | \ EPOLLRDBAND | EPOLLWRNORM | EPOLLWRBAND | EPOLLMSG | EPOLLRDHUP) typedef enum sock__poll_status { SOCK__POLL_IDLE = 0, SOCK__POLL_PENDING, SOCK__POLL_CANCELLED } sock__poll_status_t; typedef struct sock_state { IO_STATUS_BLOCK io_status_block; AFD_POLL_INFO poll_info; queue_node_t queue_node; tree_node_t tree_node; poll_group_t* poll_group; SOCKET base_socket; epoll_data_t user_data; uint32_t user_events; uint32_t pending_events; sock__poll_status_t poll_status; bool delete_pending; } sock_state_t; static inline sock_state_t* sock__alloc(void) { sock_state_t* sock_state = malloc(sizeof *sock_state); if (sock_state == NULL) return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); return sock_state; } static inline void sock__free(sock_state_t* sock_state) { assert(sock_state != NULL); free(sock_state); } static inline int sock__cancel_poll(sock_state_t* sock_state) { assert(sock_state->poll_status == SOCK__POLL_PENDING); if (afd_cancel_poll(poll_group_get_afd_device_handle(sock_state->poll_group), &sock_state->io_status_block) < 0) return -1; sock_state->poll_status = SOCK__POLL_CANCELLED; sock_state->pending_events = 0; return 0; } sock_state_t* sock_new(port_state_t* port_state, SOCKET socket) { SOCKET base_socket; poll_group_t* poll_group; sock_state_t* sock_state; if (socket == 0 || socket == INVALID_SOCKET) return_set_error(NULL, ERROR_INVALID_HANDLE); base_socket = ws_get_base_socket(socket); if (base_socket == INVALID_SOCKET) return NULL; poll_group = poll_group_acquire(port_state); if (poll_group == NULL) return NULL; sock_state = sock__alloc(); if (sock_state == NULL) goto err1; memset(sock_state, 0, sizeof *sock_state); sock_state->base_socket = base_socket; sock_state->poll_group = poll_group; tree_node_init(&sock_state->tree_node); queue_node_init(&sock_state->queue_node); if (port_register_socket(port_state, sock_state, socket) < 0) goto err2; return sock_state; err2: sock__free(sock_state); err1: poll_group_release(poll_group); return NULL; } static int sock__delete(port_state_t* port_state, sock_state_t* sock_state, bool force) { if (!sock_state->delete_pending) { if (sock_state->poll_status == SOCK__POLL_PENDING) sock__cancel_poll(sock_state); port_cancel_socket_update(port_state, sock_state); port_unregister_socket(port_state, sock_state); sock_state->delete_pending = true; } /* If the poll request still needs to complete, the sock_state object can't * be free()d yet. `sock_feed_event()` or `port_close()` will take care * of this later. */ if (force || sock_state->poll_status == SOCK__POLL_IDLE) { /* Free the sock_state now. */ port_remove_deleted_socket(port_state, sock_state); poll_group_release(sock_state->poll_group); sock__free(sock_state); } else { /* Free the socket later. */ port_add_deleted_socket(port_state, sock_state); } return 0; } void sock_delete(port_state_t* port_state, sock_state_t* sock_state) { sock__delete(port_state, sock_state, false); } void sock_force_delete(port_state_t* port_state, sock_state_t* sock_state) { sock__delete(port_state, sock_state, true); } int sock_set_event(port_state_t* port_state, sock_state_t* sock_state, const struct epoll_event* ev) { /* EPOLLERR and EPOLLHUP are always reported, even when not requested by the * caller. However they are disabled after a event has been reported for a * socket for which the EPOLLONESHOT flag was set. */ uint32_t events = ev->events | EPOLLERR | EPOLLHUP; sock_state->user_events = events; sock_state->user_data = ev->data; if ((events & SOCK__KNOWN_EPOLL_EVENTS & ~sock_state->pending_events) != 0) port_request_socket_update(port_state, sock_state); return 0; } static inline DWORD sock__epoll_events_to_afd_events(uint32_t epoll_events) { /* Always monitor for AFD_POLL_LOCAL_CLOSE, which is triggered when the * socket is closed with closesocket() or CloseHandle(). */ DWORD afd_events = AFD_POLL_LOCAL_CLOSE; if (epoll_events & (EPOLLIN | EPOLLRDNORM)) afd_events |= AFD_POLL_RECEIVE | AFD_POLL_ACCEPT; if (epoll_events & (EPOLLPRI | EPOLLRDBAND)) afd_events |= AFD_POLL_RECEIVE_EXPEDITED; if (epoll_events & (EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND)) afd_events |= AFD_POLL_SEND; if (epoll_events & (EPOLLIN | EPOLLRDNORM | EPOLLRDHUP)) afd_events |= AFD_POLL_DISCONNECT; if (epoll_events & EPOLLHUP) afd_events |= AFD_POLL_ABORT; if (epoll_events & EPOLLERR) afd_events |= AFD_POLL_CONNECT_FAIL; return afd_events; } static inline uint32_t sock__afd_events_to_epoll_events(DWORD afd_events) { uint32_t epoll_events = 0; if (afd_events & (AFD_POLL_RECEIVE | AFD_POLL_ACCEPT)) epoll_events |= EPOLLIN | EPOLLRDNORM; if (afd_events & AFD_POLL_RECEIVE_EXPEDITED) epoll_events |= EPOLLPRI | EPOLLRDBAND; if (afd_events & AFD_POLL_SEND) epoll_events |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND; if (afd_events & AFD_POLL_DISCONNECT) epoll_events |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP; if (afd_events & AFD_POLL_ABORT) epoll_events |= EPOLLHUP; if (afd_events & AFD_POLL_CONNECT_FAIL) /* Linux reports all these events after connect() has failed. */ epoll_events |= EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLRDNORM | EPOLLWRNORM | EPOLLRDHUP; return epoll_events; } int sock_update(port_state_t* port_state, sock_state_t* sock_state) { assert(!sock_state->delete_pending); if ((sock_state->poll_status == SOCK__POLL_PENDING) && (sock_state->user_events & SOCK__KNOWN_EPOLL_EVENTS & ~sock_state->pending_events) == 0) { /* All the events the user is interested in are already being monitored by * the pending poll operation. It might spuriously complete because of an * event that we're no longer interested in; when that happens we'll submit * a new poll operation with the updated event mask. */ } else if (sock_state->poll_status == SOCK__POLL_PENDING) { /* A poll operation is already pending, but it's not monitoring for all the * events that the user is interested in. Therefore, cancel the pending * poll operation; when we receive it's completion package, a new poll * operation will be submitted with the correct event mask. */ if (sock__cancel_poll(sock_state) < 0) return -1; } else if (sock_state->poll_status == SOCK__POLL_CANCELLED) { /* The poll operation has already been cancelled, we're still waiting for * it to return. For now, there's nothing that needs to be done. */ } else if (sock_state->poll_status == SOCK__POLL_IDLE) { /* No poll operation is pending; start one. */ sock_state->poll_info.Exclusive = FALSE; sock_state->poll_info.NumberOfHandles = 1; sock_state->poll_info.Timeout.QuadPart = INT64_MAX; sock_state->poll_info.Handles[0].Handle = (HANDLE) sock_state->base_socket; sock_state->poll_info.Handles[0].Status = 0; sock_state->poll_info.Handles[0].Events = sock__epoll_events_to_afd_events(sock_state->user_events); if (afd_poll(poll_group_get_afd_device_handle(sock_state->poll_group), &sock_state->poll_info, &sock_state->io_status_block) < 0) { switch (GetLastError()) { case ERROR_IO_PENDING: /* Overlapped poll operation in progress; this is expected. */ break; case ERROR_INVALID_HANDLE: /* Socket closed; it'll be dropped from the epoll set. */ return sock__delete(port_state, sock_state, false); default: /* Other errors are propagated to the caller. */ return_map_error(-1); } } /* The poll request was successfully submitted. */ sock_state->poll_status = SOCK__POLL_PENDING; sock_state->pending_events = sock_state->user_events; } else { /* Unreachable. */ assert(false); } port_cancel_socket_update(port_state, sock_state); return 0; } int sock_feed_event(port_state_t* port_state, IO_STATUS_BLOCK* io_status_block, struct epoll_event* ev) { sock_state_t* sock_state = container_of(io_status_block, sock_state_t, io_status_block); AFD_POLL_INFO* poll_info = &sock_state->poll_info; uint32_t epoll_events = 0; sock_state->poll_status = SOCK__POLL_IDLE; sock_state->pending_events = 0; if (sock_state->delete_pending) { /* Socket has been deleted earlier and can now be freed. */ return sock__delete(port_state, sock_state, false); } else if (io_status_block->Status == STATUS_CANCELLED) { /* The poll request was cancelled by CancelIoEx. */ } else if (!NT_SUCCESS(io_status_block->Status)) { /* The overlapped request itself failed in an unexpected way. */ epoll_events = EPOLLERR; } else if (poll_info->NumberOfHandles < 1) { /* This poll operation succeeded but didn't report any socket events. */ } else if (poll_info->Handles[0].Events & AFD_POLL_LOCAL_CLOSE) { /* The poll operation reported that the socket was closed. */ return sock__delete(port_state, sock_state, false); } else { /* Events related to our socket were reported. */ epoll_events = sock__afd_events_to_epoll_events(poll_info->Handles[0].Events); } /* Requeue the socket so a new poll request will be submitted. */ port_request_socket_update(port_state, sock_state); /* Filter out events that the user didn't ask for. */ epoll_events &= sock_state->user_events; /* Return if there are no epoll events to report. */ if (epoll_events == 0) return 0; /* If the the socket has the EPOLLONESHOT flag set, unmonitor all events, * even EPOLLERR and EPOLLHUP. But always keep looking for closed sockets. */ if (sock_state->user_events & EPOLLONESHOT) sock_state->user_events = 0; ev->data = sock_state->user_data; ev->events = epoll_events; return 1; } sock_state_t* sock_state_from_queue_node(queue_node_t* queue_node) { return container_of(queue_node, sock_state_t, queue_node); } queue_node_t* sock_state_to_queue_node(sock_state_t* sock_state) { return &sock_state->queue_node; } sock_state_t* sock_state_from_tree_node(tree_node_t* tree_node) { return container_of(tree_node, sock_state_t, tree_node); } tree_node_t* sock_state_to_tree_node(sock_state_t* sock_state) { return &sock_state->tree_node; } void ts_tree_init(ts_tree_t* ts_tree) { tree_init(&ts_tree->tree); InitializeSRWLock(&ts_tree->lock); } void ts_tree_node_init(ts_tree_node_t* node) { tree_node_init(&node->tree_node); reflock_init(&node->reflock); } int ts_tree_add(ts_tree_t* ts_tree, ts_tree_node_t* node, uintptr_t key) { int r; AcquireSRWLockExclusive(&ts_tree->lock); r = tree_add(&ts_tree->tree, &node->tree_node, key); ReleaseSRWLockExclusive(&ts_tree->lock); return r; } static inline ts_tree_node_t* ts_tree__find_node(ts_tree_t* ts_tree, uintptr_t key) { tree_node_t* tree_node = tree_find(&ts_tree->tree, key); if (tree_node == NULL) return NULL; return container_of(tree_node, ts_tree_node_t, tree_node); } ts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree, uintptr_t key) { ts_tree_node_t* ts_tree_node; AcquireSRWLockExclusive(&ts_tree->lock); ts_tree_node = ts_tree__find_node(ts_tree, key); if (ts_tree_node != NULL) { tree_del(&ts_tree->tree, &ts_tree_node->tree_node); reflock_ref(&ts_tree_node->reflock); } ReleaseSRWLockExclusive(&ts_tree->lock); return ts_tree_node; } ts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree, uintptr_t key) { ts_tree_node_t* ts_tree_node; AcquireSRWLockShared(&ts_tree->lock); ts_tree_node = ts_tree__find_node(ts_tree, key); if (ts_tree_node != NULL) reflock_ref(&ts_tree_node->reflock); ReleaseSRWLockShared(&ts_tree->lock); return ts_tree_node; } void ts_tree_node_unref(ts_tree_node_t* node) { reflock_unref(&node->reflock); } void ts_tree_node_unref_and_destroy(ts_tree_node_t* node) { reflock_unref_and_destroy(&node->reflock); } void tree_init(tree_t* tree) { memset(tree, 0, sizeof *tree); } void tree_node_init(tree_node_t* node) { memset(node, 0, sizeof *node); } #define TREE__ROTATE(cis, trans) \ tree_node_t* p = node; \ tree_node_t* q = node->trans; \ tree_node_t* parent = p->parent; \ \ if (parent) { \ if (parent->left == p) \ parent->left = q; \ else \ parent->right = q; \ } else { \ tree->root = q; \ } \ \ q->parent = parent; \ p->parent = q; \ p->trans = q->cis; \ if (p->trans) \ p->trans->parent = p; \ q->cis = p; static inline void tree__rotate_left(tree_t* tree, tree_node_t* node) { TREE__ROTATE(left, right) } static inline void tree__rotate_right(tree_t* tree, tree_node_t* node) { TREE__ROTATE(right, left) } #define TREE__INSERT_OR_DESCEND(side) \ if (parent->side) { \ parent = parent->side; \ } else { \ parent->side = node; \ break; \ } #define TREE__REBALANCE_AFTER_INSERT(cis, trans) \ tree_node_t* grandparent = parent->parent; \ tree_node_t* uncle = grandparent->trans; \ \ if (uncle && uncle->red) { \ parent->red = uncle->red = false; \ grandparent->red = true; \ node = grandparent; \ } else { \ if (node == parent->trans) { \ tree__rotate_##cis(tree, parent); \ node = parent; \ parent = node->parent; \ } \ parent->red = false; \ grandparent->red = true; \ tree__rotate_##trans(tree, grandparent); \ } int tree_add(tree_t* tree, tree_node_t* node, uintptr_t key) { tree_node_t* parent; parent = tree->root; if (parent) { for (;;) { if (key < parent->key) { TREE__INSERT_OR_DESCEND(left) } else if (key > parent->key) { TREE__INSERT_OR_DESCEND(right) } else { return -1; } } } else { tree->root = node; } node->key = key; node->left = node->right = NULL; node->parent = parent; node->red = true; for (; parent && parent->red; parent = node->parent) { if (parent == parent->parent->left) { TREE__REBALANCE_AFTER_INSERT(left, right) } else { TREE__REBALANCE_AFTER_INSERT(right, left) } } tree->root->red = false; return 0; } #define TREE__REBALANCE_AFTER_REMOVE(cis, trans) \ tree_node_t* sibling = parent->trans; \ \ if (sibling->red) { \ sibling->red = false; \ parent->red = true; \ tree__rotate_##cis(tree, parent); \ sibling = parent->trans; \ } \ if ((sibling->left && sibling->left->red) || \ (sibling->right && sibling->right->red)) { \ if (!sibling->trans || !sibling->trans->red) { \ sibling->cis->red = false; \ sibling->red = true; \ tree__rotate_##trans(tree, sibling); \ sibling = parent->trans; \ } \ sibling->red = parent->red; \ parent->red = sibling->trans->red = false; \ tree__rotate_##cis(tree, parent); \ node = tree->root; \ break; \ } \ sibling->red = true; void tree_del(tree_t* tree, tree_node_t* node) { tree_node_t* parent = node->parent; tree_node_t* left = node->left; tree_node_t* right = node->right; tree_node_t* next; bool red; if (!left) { next = right; } else if (!right) { next = left; } else { next = right; while (next->left) next = next->left; } if (parent) { if (parent->left == node) parent->left = next; else parent->right = next; } else { tree->root = next; } if (left && right) { red = next->red; next->red = node->red; next->left = left; left->parent = next; if (next != right) { parent = next->parent; next->parent = node->parent; node = next->right; parent->left = node; next->right = right; right->parent = next; } else { next->parent = parent; parent = next; node = next->right; } } else { red = node->red; node = next; } if (node) node->parent = parent; if (red) return; if (node && node->red) { node->red = false; return; } do { if (node == tree->root) break; if (node == parent->left) { TREE__REBALANCE_AFTER_REMOVE(left, right) } else { TREE__REBALANCE_AFTER_REMOVE(right, left) } node = parent; parent = parent->parent; } while (!node->red); if (node) node->red = false; } tree_node_t* tree_find(const tree_t* tree, uintptr_t key) { tree_node_t* node = tree->root; while (node) { if (key < node->key) node = node->left; else if (key > node->key) node = node->right; else return node; } return NULL; } tree_node_t* tree_root(const tree_t* tree) { return tree->root; } #ifndef SIO_BSP_HANDLE_POLL #define SIO_BSP_HANDLE_POLL 0x4800001D #endif #ifndef SIO_BASE_HANDLE #define SIO_BASE_HANDLE 0x48000022 #endif int ws_global_init(void) { int r; WSADATA wsa_data; r = WSAStartup(MAKEWORD(2, 2), &wsa_data); if (r != 0) return_set_error(-1, (DWORD) r); return 0; } static inline SOCKET ws__ioctl_get_bsp_socket(SOCKET socket, DWORD ioctl) { SOCKET bsp_socket; DWORD bytes; if (WSAIoctl(socket, ioctl, NULL, 0, &bsp_socket, sizeof bsp_socket, &bytes, NULL, NULL) != SOCKET_ERROR) return bsp_socket; else return INVALID_SOCKET; } SOCKET ws_get_base_socket(SOCKET socket) { SOCKET base_socket; DWORD error; for (;;) { base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BASE_HANDLE); if (base_socket != INVALID_SOCKET) return base_socket; error = GetLastError(); if (error == WSAENOTSOCK) return_set_error(INVALID_SOCKET, error); /* Even though Microsoft documentation clearly states that LSPs should * never intercept the `SIO_BASE_HANDLE` ioctl [1], Komodia based LSPs do * so anyway, breaking it, with the apparent intention of preventing LSP * bypass [2]. Fortunately they don't handle `SIO_BSP_HANDLE_POLL`, which * will at least let us obtain the socket associated with the next winsock * protocol chain entry. If this succeeds, loop around and call * `SIO_BASE_HANDLE` again with the returned BSP socket, to make sure that * we unwrap all layers and retrieve the actual base socket. * [1] https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls * [2] https://www.komodia.com/newwiki/index.php?title=Komodia%27s_Redirector_bug_fixes#Version_2.2.2.6 */ base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BSP_HANDLE_POLL); if (base_socket != INVALID_SOCKET && base_socket != socket) socket = base_socket; else return_set_error(INVALID_SOCKET, error); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/event/wepoll/wepoll.h000066400000000000000000000066171520575453600275550ustar00rootroot00000000000000/* * wepoll - epoll for Windows * https://github.com/piscisaureus/wepoll * * Copyright 2012-2020, Bert Belder * 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 WEPOLL_H_ #define WEPOLL_H_ #ifndef WEPOLL_EXPORT #define WEPOLL_EXPORT #endif #include enum EPOLL_EVENTS { EPOLLIN = (int) (1U << 0), EPOLLPRI = (int) (1U << 1), EPOLLOUT = (int) (1U << 2), EPOLLERR = (int) (1U << 3), EPOLLHUP = (int) (1U << 4), EPOLLRDNORM = (int) (1U << 6), EPOLLRDBAND = (int) (1U << 7), EPOLLWRNORM = (int) (1U << 8), EPOLLWRBAND = (int) (1U << 9), EPOLLMSG = (int) (1U << 10), /* Never reported. */ EPOLLRDHUP = (int) (1U << 13), EPOLLONESHOT = (int) (1U << 31) }; #define EPOLLIN (1U << 0) #define EPOLLPRI (1U << 1) #define EPOLLOUT (1U << 2) #define EPOLLERR (1U << 3) #define EPOLLHUP (1U << 4) #define EPOLLRDNORM (1U << 6) #define EPOLLRDBAND (1U << 7) #define EPOLLWRNORM (1U << 8) #define EPOLLWRBAND (1U << 9) #define EPOLLMSG (1U << 10) #define EPOLLRDHUP (1U << 13) #define EPOLLONESHOT (1U << 31) #define EPOLL_CTL_ADD 1 #define EPOLL_CTL_MOD 2 #define EPOLL_CTL_DEL 3 typedef void* HANDLE; typedef uintptr_t SOCKET; typedef union epoll_data { void* ptr; int fd; uint32_t u32; uint64_t u64; SOCKET sock; /* Windows specific */ HANDLE hnd; /* Windows specific */ } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events and flags */ epoll_data_t data; /* User data variable */ }; #ifdef __cplusplus extern "C" { #endif WEPOLL_EXPORT HANDLE epoll_create(int size); WEPOLL_EXPORT HANDLE epoll_create1(int flags); WEPOLL_EXPORT int epoll_close(HANDLE ephnd); WEPOLL_EXPORT int epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* event); WEPOLL_EXPORT int epoll_wait(HANDLE ephnd, struct epoll_event* events, int maxevents, int timeout); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* WEPOLL_H_ */ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/000077500000000000000000000000001520575453600244175ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/Buffer.h000066400000000000000000000003061520575453600260000ustar00rootroot00000000000000#ifndef HV_BUFFER_HPP_ #define HV_BUFFER_HPP_ #include #include "hbuf.h" namespace hv { typedef HBuf Buffer; typedef std::shared_ptr BufferPtr; } #endif // HV_BUFFER_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/Channel.h000066400000000000000000000233031520575453600261410ustar00rootroot00000000000000#ifndef HV_CHANNEL_HPP_ #define HV_CHANNEL_HPP_ #include #include #include #include #include "hloop.h" #include "hsocket.h" #include "Buffer.h" namespace hv { class Channel { public: Channel(hio_t* io = NULL) { io_ = io; fd_ = -1; id_ = 0; ctx_ = NULL; status = CLOSED; if (io) { fd_ = hio_fd(io); id_ = hio_id(io); ctx_ = hio_context(io); hio_set_context(io, this); if (hio_is_opened(io)) { status = OPENED; } if (hio_getcb_read(io) == NULL) { hio_setcb_read(io_, on_read); } if (hio_getcb_write(io) == NULL) { hio_setcb_write(io_, on_write); } if (hio_getcb_close(io) == NULL) { hio_setcb_close(io_, on_close); } } } virtual ~Channel() { if (isOpened()) { close(); // NOTE: Detach after destructor to avoid triggering onclose if (io_ && id_ == hio_id(io_)) { hio_set_context(io_, NULL); } } } hio_t* io() { return io_; } int fd() { return fd_; } uint32_t id() { return id_; } int error() { return hio_error(io_); } // context void* context() { return ctx_; } void setContext(void* ctx) { ctx_ = ctx; } template T* newContext() { ctx_ = new T; return (T*)ctx_; } template T* getContext() { return (T*)ctx_; } template void deleteContext() { if (ctx_) { delete (T*)ctx_; ctx_ = NULL; } } // contextPtr std::shared_ptr contextPtr() { return contextPtr_; } void setContextPtr(const std::shared_ptr& ctx) { contextPtr_ = ctx; } void setContextPtr(std::shared_ptr&& ctx) { contextPtr_ = std::move(ctx); } template std::shared_ptr newContextPtr() { contextPtr_ = std::make_shared(); return std::static_pointer_cast(contextPtr_); } template std::shared_ptr getContextPtr() { return std::static_pointer_cast(contextPtr_); } void deleteContextPtr() { contextPtr_.reset(); } bool isOpened() { if (io_ == NULL || status >= DISCONNECTED) return false; return id_ == hio_id(io_) && hio_is_opened(io_); } bool isClosed() { return !isOpened(); } int startRead() { if (!isOpened()) return -1; return hio_read_start(io_); } int stopRead() { if (!isOpened()) return -1; return hio_read_stop(io_); } int readOnce() { if (!isOpened()) return -1; return hio_read_once(io_); } int readString() { if (!isOpened()) return -1; return hio_readstring(io_); } int readLine() { if (!isOpened()) return -1; return hio_readline(io_); } int readBytes(int len) { if (!isOpened() || len <= 0) return -1; return hio_readbytes(io_, len); } // write thread-safe int write(const void* data, int size) { if (!isOpened()) return -1; return hio_write(io_, data, size); } int write(Buffer* buf) { return write(buf->data(), buf->size()); } int write(const std::string& str) { return write(str.data(), str.size()); } // iobuf setting void setReadBuf(void* buf, size_t len) { if (io_ == NULL) return; hio_set_readbuf(io_, buf, len); } void setMaxReadBufsize(uint32_t size) { if (io_ == NULL) return; hio_set_max_read_bufsize(io_, size); } void setMaxWriteBufsize(uint32_t size) { if (io_ == NULL) return; hio_set_max_write_bufsize(io_, size); } size_t writeBufsize() { if (io_ == NULL) return 0; return hio_write_bufsize(io_); } bool isWriteComplete() { return writeBufsize() == 0; } // close thread-safe int close(bool async = false) { if (isClosed()) return -1; status = CLOSED; return async ? hio_close_async(io_) : hio_close(io_); } public: hio_t* io_; int fd_; uint32_t id_; void* ctx_; enum Status { OPENED, CONNECTING, CONNECTED, DISCONNECTED, CLOSED, }; std::atomic status; std::function onread; // NOTE: Use Channel::isWriteComplete in onwrite callback to determine whether all data has been written. std::function onwrite; std::function onclose; std::shared_ptr contextPtr_; private: static void on_read(hio_t* io, void* data, int readbytes) { Channel* channel = (Channel*)hio_context(io); if (channel && channel->onread) { Buffer buf(data, readbytes); channel->onread(&buf); } } static void on_write(hio_t* io, const void* data, int writebytes) { Channel* channel = (Channel*)hio_context(io); if (channel && channel->onwrite) { Buffer buf((void*)data, writebytes); channel->onwrite(&buf); } } static void on_close(hio_t* io) { Channel* channel = (Channel*)hio_context(io); if (channel) { channel->status = CLOSED; if (channel->onclose) { channel->onclose(); } } } }; class SocketChannel : public Channel { public: std::function onconnect; // only for TcpClient std::function heartbeat; SocketChannel(hio_t* io) : Channel(io) { } virtual ~SocketChannel() {} // SSL/TLS int enableSSL() { if (io_ == NULL) return -1; return hio_enable_ssl(io_); } bool isSSL() { if (io_ == NULL) return false; return hio_is_ssl(io_); } int setSSL(hssl_t ssl) { if (io_ == NULL) return -1; return hio_set_ssl(io_, ssl); } int setSslCtx(hssl_ctx_t ssl_ctx) { if (io_ == NULL) return -1; return hio_set_ssl_ctx(io_, ssl_ctx); } int newSslCtx(hssl_ctx_opt_t* opt) { if (io_ == NULL) return -1; return hio_new_ssl_ctx(io_, opt); } // for hssl_set_sni_hostname int setHostname(const std::string& hostname) { if (io_ == NULL) return -1; return hio_set_hostname(io_, hostname.c_str()); } // timeout void setConnectTimeout(int timeout_ms) { if (io_ == NULL) return; hio_set_connect_timeout(io_, timeout_ms); } void setCloseTimeout(int timeout_ms) { if (io_ == NULL) return; hio_set_close_timeout(io_, timeout_ms); } void setReadTimeout(int timeout_ms) { if (io_ == NULL) return; hio_set_read_timeout(io_, timeout_ms); } void setWriteTimeout(int timeout_ms) { if (io_ == NULL) return; hio_set_write_timeout(io_, timeout_ms); } void setKeepaliveTimeout(int timeout_ms) { if (io_ == NULL) return; hio_set_keepalive_timeout(io_, timeout_ms); } // heartbeat // NOTE: Beware of circular reference problems caused by passing SocketChannelPtr by value. void setHeartbeat(int interval_ms, std::function fn) { if (io_ == NULL) return; heartbeat = std::move(fn); hio_set_heartbeat(io_, interval_ms, send_heartbeat); } /* * unpack * * NOTE: unpack_setting_t of multiple IOs of the same function also are same, * so only the pointer of unpack_setting_t is stored in hio_t, * the life time of unpack_setting_t shoud be guaranteed by caller. */ void setUnpack(unpack_setting_t* setting) { if (io_ == NULL) return; hio_set_unpack(io_, setting); } int startConnect(int port, const char* host = "127.0.0.1") { sockaddr_u peeraddr; memset(&peeraddr, 0, sizeof(peeraddr)); int ret = sockaddr_set_ipport(&peeraddr, host, port); if (ret != 0) { // hloge("unknown host %s", host); return ret; } return startConnect(&peeraddr.sa); } int startConnect(struct sockaddr* peeraddr) { if (io_ == NULL) return -1; hio_set_peeraddr(io_, peeraddr, SOCKADDR_LEN(peeraddr)); return startConnect(); } int startConnect() { if (io_ == NULL) return -1; status = CONNECTING; hio_setcb_connect(io_, on_connect); return hio_connect(io_); } bool isConnected() { return status == CONNECTED && isOpened(); } std::string localaddr() { if (io_ == NULL) return ""; struct sockaddr* addr = hio_localaddr(io_); char buf[SOCKADDR_STRLEN] = {0}; return SOCKADDR_STR(addr, buf); } std::string peeraddr() { if (io_ == NULL) return ""; struct sockaddr* addr = hio_peeraddr(io_); char buf[SOCKADDR_STRLEN] = {0}; return SOCKADDR_STR(addr, buf); } private: static void on_connect(hio_t* io) { SocketChannel* channel = (SocketChannel*)hio_context(io); if (channel) { channel->status = CONNECTED; if (channel->onconnect) { channel->onconnect(); } } } static void send_heartbeat(hio_t* io) { SocketChannel* channel = (SocketChannel*)hio_context(io); if (channel && channel->heartbeat) { channel->heartbeat(); } } }; typedef std::shared_ptr ChannelPtr; typedef std::shared_ptr SocketChannelPtr; } #endif // HV_CHANNEL_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/Event.h000066400000000000000000000016511520575453600256540ustar00rootroot00000000000000#ifndef HV_EVENT_HPP_ #define HV_EVENT_HPP_ #include #include #include "hloop.h" namespace hv { struct Event; struct Timer; typedef uint64_t TimerID; #define INVALID_TIMER_ID ((hv::TimerID)-1) typedef std::function EventCallback; typedef std::function TimerCallback; struct Event { hevent_t event; EventCallback cb; Event(EventCallback cb = NULL) { memset(&event, 0, sizeof(hevent_t)); this->cb = std::move(cb); } }; struct Timer { htimer_t* timer; TimerCallback cb; uint32_t repeat; Timer(htimer_t* timer = NULL, TimerCallback cb = NULL, uint32_t repeat = INFINITE) { this->timer = timer; this->cb = std::move(cb); this->repeat = repeat; } }; typedef std::shared_ptr EventPtr; typedef std::shared_ptr TimerPtr; } #endif // HV_EVENT_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoop.h000066400000000000000000000166711520575453600265160ustar00rootroot00000000000000#ifndef HV_EVENT_LOOP_HPP_ #define HV_EVENT_LOOP_HPP_ #include #include #include #include #include "hloop.h" #include "hthread.h" #include "Status.h" #include "Event.h" #include "ThreadLocalStorage.h" namespace hv { class EventLoop : public Status { public: typedef std::function Functor; // New an EventLoop using an existing hloop_t object, // so we can embed an EventLoop object into the old application based on hloop. // NOTE: Be careful to deal with destroy of hloop_t. EventLoop(hloop_t* loop = NULL) { setStatus(kInitializing); if (loop) { loop_ = loop; is_loop_owner = false; } else { loop_ = hloop_new(HLOOP_FLAG_AUTO_FREE); is_loop_owner = true; } connectionNum = 0; nextTimerID = 0; setStatus(kInitialized); } ~EventLoop() { stop(); } hloop_t* loop() { return loop_; } // @brief Run loop forever void run() { if (loop_ == NULL) return; if (status() == kRunning) return; ThreadLocalStorage::set(ThreadLocalStorage::EVENT_LOOP, this); setStatus(kRunning); hloop_run(loop_); setStatus(kStopped); } // stop thread-safe void stop() { if (loop_ == NULL) return; if (status() < kRunning) { if (is_loop_owner) { hloop_free(&loop_); } loop_ = NULL; return; } setStatus(kStopping); hloop_stop(loop_); loop_ = NULL; } void pause() { if (loop_ == NULL) return; if (isRunning()) { hloop_pause(loop_); setStatus(kPause); } } void resume() { if (loop_ == NULL) return; if (isPause()) { hloop_resume(loop_); setStatus(kRunning); } } // Timer interfaces: setTimer, killTimer, resetTimer TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) { if (loop_ == NULL) return INVALID_TIMER_ID; assertInLoopThread(); htimer_t* htimer = htimer_add(loop_, onTimer, timeout_ms, repeat); assert(htimer != NULL); if (timerID == INVALID_TIMER_ID) { timerID = generateTimerID(); } hevent_set_id(htimer, timerID); hevent_set_userdata(htimer, this); timers[timerID] = std::make_shared(htimer, cb, repeat); return timerID; } // setTimerInLoop thread-safe TimerID setTimerInLoop(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) { if (timerID == INVALID_TIMER_ID) { timerID = generateTimerID(); } runInLoop(std::bind(&EventLoop::setTimer, this, timeout_ms, cb, repeat, timerID)); return timerID; } // alias javascript setTimeout, setInterval // setTimeout thread-safe TimerID setTimeout(int timeout_ms, TimerCallback cb) { return setTimerInLoop(timeout_ms, cb, 1); } // setInterval thread-safe TimerID setInterval(int interval_ms, TimerCallback cb) { return setTimerInLoop(interval_ms, cb, INFINITE); } // killTimer thread-safe void killTimer(TimerID timerID) { runInLoop([timerID, this](){ auto iter = timers.find(timerID); if (iter != timers.end()) { htimer_del(iter->second->timer); timers.erase(iter); } }); } // resetTimer thread-safe void resetTimer(TimerID timerID, int timeout_ms = 0) { runInLoop([timerID, timeout_ms, this](){ auto iter = timers.find(timerID); if (iter != timers.end()) { htimer_reset(iter->second->timer, timeout_ms); if (iter->second->repeat == 0) { iter->second->repeat = 1; } } }); } long tid() { if (loop_ == NULL) return hv_gettid(); return hloop_tid(loop_); } bool isInLoopThread() { if (loop_ == NULL) return false; return hv_gettid() == hloop_tid(loop_); } void assertInLoopThread() { assert(isInLoopThread()); } void runInLoop(Functor fn) { if (isRunning() && isInLoopThread()) { if (fn) fn(); } else { queueInLoop(std::move(fn)); } } void queueInLoop(Functor fn) { postEvent([fn](Event* ev) { if (fn) fn(); }); } void postEvent(EventCallback cb) { if (loop_ == NULL) return; EventPtr ev = std::make_shared(cb); hevent_set_userdata(&ev->event, this); ev->event.cb = onCustomEvent; mutex_.lock(); customEvents.push(ev); mutex_.unlock(); hloop_post_event(loop_, &ev->event); } private: TimerID generateTimerID() { return (((TimerID)tid() & 0xFFFFFFFF) << 32) | ++nextTimerID; } static void onTimer(htimer_t* htimer) { EventLoop* loop = (EventLoop*)hevent_userdata(htimer); TimerID timerID = hevent_id(htimer); TimerPtr timer = NULL; auto iter = loop->timers.find(timerID); if (iter != loop->timers.end()) { timer = iter->second; if (timer->repeat != INFINITE) --timer->repeat; } if (timer) { if (timer->cb) timer->cb(timerID); if (timer->repeat == 0) { // htimer_t alloc and free by hloop, but timers[timerID] managed by EventLoop. loop->timers.erase(timerID); } } } static void onCustomEvent(hevent_t* hev) { EventLoop* loop = (EventLoop*)hevent_userdata(hev); loop->mutex_.lock(); EventPtr ev = loop->customEvents.front(); loop->customEvents.pop(); loop->mutex_.unlock(); if (ev && ev->cb) ev->cb(ev.get()); } public: std::atomic connectionNum; // for LB_LeastConnections private: hloop_t* loop_; bool is_loop_owner; std::mutex mutex_; std::queue customEvents; // GUAREDE_BY(mutex_) std::map timers; std::atomic nextTimerID; }; typedef std::shared_ptr EventLoopPtr; // ThreadLocalStorage static inline EventLoop* tlsEventLoop() { return (EventLoop*)ThreadLocalStorage::get(ThreadLocalStorage::EVENT_LOOP); } #define currentThreadEventLoop ::hv::tlsEventLoop() static inline TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) { EventLoop* loop = tlsEventLoop(); assert(loop != NULL); if (loop == NULL) return INVALID_TIMER_ID; return loop->setTimer(timeout_ms, cb, repeat); } static inline void killTimer(TimerID timerID) { EventLoop* loop = tlsEventLoop(); assert(loop != NULL); if (loop == NULL) return; loop->killTimer(timerID); } static inline void resetTimer(TimerID timerID, int timeout_ms) { EventLoop* loop = tlsEventLoop(); assert(loop != NULL); if (loop == NULL) return; loop->resetTimer(timerID, timeout_ms); } static inline TimerID setTimeout(int timeout_ms, TimerCallback cb) { return setTimer(timeout_ms, cb, 1); } static inline TimerID setInterval(int interval_ms, TimerCallback cb) { return setTimer(interval_ms, cb, INFINITE); } } #endif // HV_EVENT_LOOP_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoopThread.h000066400000000000000000000055331520575453600276410ustar00rootroot00000000000000#ifndef HV_EVENT_LOOP_THREAD_HPP_ #define HV_EVENT_LOOP_THREAD_HPP_ #include #include "hlog.h" #include "EventLoop.h" namespace hv { class EventLoopThread : public Status { public: // Return 0 means OK, other failed. typedef std::function Functor; EventLoopThread(EventLoopPtr loop = NULL) { setStatus(kInitializing); loop_ = loop ? loop : std::make_shared(); setStatus(kInitialized); } ~EventLoopThread() { stop(); join(); } const EventLoopPtr& loop() { return loop_; } hloop_t* hloop() { return loop_->loop(); } bool isRunning() { return loop_->isRunning(); } // @param wait_thread_started: if ture this method will block until loop_thread started. // @param pre: This functor will be executed when loop_thread started. // @param post:This Functor will be executed when loop_thread stopped. void start(bool wait_thread_started = true, Functor pre = Functor(), Functor post = Functor()) { if (status() >= kStarting && status() < kStopped) return; if (isRunning()) return; setStatus(kStarting); thread_ = std::make_shared(&EventLoopThread::loop_thread, this, pre, post); if (wait_thread_started) { while (loop_->status() < kRunning) { hv_delay(1); } } } // @param wait_thread_started: if ture this method will block until loop_thread stopped. // stop thread-safe void stop(bool wait_thread_stopped = false) { if (status() < kStarting || status() >= kStopping) return; setStatus(kStopping); long loop_tid = loop_->tid(); loop_->stop(); if (wait_thread_stopped) { if (hv_gettid() == loop_tid) return; join(); } } // @brief join loop_thread // @note destructor will join loop_thread if you forget to call this method. void join() { if (thread_ && thread_->joinable()) { thread_->join(); thread_ = NULL; } } private: void loop_thread(const Functor& pre, const Functor& post) { hlogi("EventLoopThread started, tid=%ld", hv_gettid()); setStatus(kStarted); if (pre) { loop_->queueInLoop([this, pre]{ if (pre() != 0) { loop_->stop(); } }); } loop_->run(); assert(loop_->isStopped()); if (post) { post(); } setStatus(kStopped); hlogi("EventLoopThread stopped, tid=%ld", hv_gettid()); } private: EventLoopPtr loop_; std::shared_ptr thread_; }; typedef std::shared_ptr EventLoopThreadPtr; } #endif // HV_EVENT_LOOP_THREAD_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoopThreadPool.h000066400000000000000000000103351520575453600304670ustar00rootroot00000000000000#ifndef HV_EVENT_LOOP_THREAD_POOL_HPP_ #define HV_EVENT_LOOP_THREAD_POOL_HPP_ #include "EventLoopThread.h" #include "hbase.h" namespace hv { class EventLoopThreadPool : public Status { public: EventLoopThreadPool(int thread_num = std::thread::hardware_concurrency()) { setStatus(kInitializing); thread_num_ = thread_num; next_loop_idx_ = 0; setStatus(kInitialized); } ~EventLoopThreadPool() { stop(); join(); } int threadNum() { return thread_num_; } void setThreadNum(int num) { thread_num_ = num; } EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin) { size_t numLoops = loop_threads_.size(); if (numLoops == 0) return NULL; size_t idx = 0; if (lb == LB_RoundRobin) { if (++next_loop_idx_ >= numLoops) next_loop_idx_ = 0; idx = next_loop_idx_ % numLoops; } else if (lb == LB_Random) { idx = hv_rand(0, numLoops - 1); } else if (lb == LB_LeastConnections) { for (size_t i = 1; i < numLoops; ++i) { if (loop_threads_[i]->loop()->connectionNum < loop_threads_[idx]->loop()->connectionNum) { idx = i; } } } else { // Not Implemented } return loop_threads_[idx]->loop(); } EventLoopPtr loop(int idx = -1) { if (idx >= 0 && idx < (int)loop_threads_.size()) { return loop_threads_[idx]->loop(); } return nextLoop(); } hloop_t* hloop(int idx = -1) { EventLoopPtr ptr = loop(idx); return ptr ? ptr->loop() : NULL; } // @param wait_threads_started: if ture this method will block until all loop_threads started. // @param pre: This functor will be executed when loop_thread started. // @param post:This Functor will be executed when loop_thread stopped. void start(bool wait_threads_started = false, std::function pre = NULL, std::function post = NULL) { if (thread_num_ == 0) return; if (status() >= kStarting && status() < kStopped) return; setStatus(kStarting); auto started_cnt = std::make_shared>(0); auto exited_cnt = std::make_shared>(0); loop_threads_.clear(); for (int i = 0; i < thread_num_; ++i) { auto loop_thread = std::make_shared(); const EventLoopPtr& loop = loop_thread->loop(); loop_thread->start(false, [this, started_cnt, pre, &loop]() { if (++(*started_cnt) == thread_num_) { setStatus(kRunning); } if (pre) pre(loop); return 0; }, [this, exited_cnt, post, &loop]() { if (post) post(loop); if (++(*exited_cnt) == thread_num_) { setStatus(kStopped); } return 0; } ); loop_threads_.push_back(loop_thread); } if (wait_threads_started) { while (status() < kRunning) { hv_delay(1); } } } // @param wait_threads_started: if ture this method will block until all loop_threads stopped. // stop thread-safe void stop(bool wait_threads_stopped = false) { if (status() < kStarting || status() >= kStopping) return; setStatus(kStopping); for (auto& loop_thread : loop_threads_) { loop_thread->stop(false); } if (wait_threads_stopped) { join(); } } // @brief join all loop_threads // @note destructor will join loop_threads if you forget to call this method. void join() { for (auto& loop_thread : loop_threads_) { loop_thread->join(); } } private: int thread_num_; std::vector loop_threads_; std::atomic next_loop_idx_; }; } #endif // HV_EVENT_LOOP_THREAD_POOL_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoopThreadPool_test.cpp000066400000000000000000000024141520575453600320600ustar00rootroot00000000000000/* * EventLoopThreadPool_test.cpp * * @build: make evpp * */ #include "hv.h" #include "EventLoopThreadPool.h" using namespace hv; static void onTimer(TimerID timerID, int n) { printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); } int main(int argc, char* argv[]) { HV_MEMCHECK; hlog_set_level(LOG_LEVEL_DEBUG); printf("main tid=%ld\n", hv_gettid()); EventLoopThreadPool loop_threads(4); loop_threads.start(true); int thread_num = loop_threads.threadNum(); for (int i = 0; i < thread_num; ++i) { EventLoopPtr loop = loop_threads.nextLoop(); printf("worker[%d] tid=%ld\n", i, loop->tid()); loop->runInLoop([loop](){ // runEvery 1s loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); }); loop->queueInLoop([](){ printf("queueInLoop tid=%ld\n", hv_gettid()); }); loop->runInLoop([](){ printf("runInLoop tid=%ld\n", hv_gettid()); }); } // runAfter 10s loop_threads.loop()->setTimeout(10000, [&loop_threads](TimerID timerID){ loop_threads.stop(false); }); // wait loop_threads exit loop_threads.join(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoopThread_test.cpp000066400000000000000000000016751520575453600312360ustar00rootroot00000000000000/* * EventLoopThread_test.cpp * * @build: make evpp * */ #include "hv.h" #include "EventLoopThread.h" using namespace hv; static void onTimer(TimerID timerID, int n) { printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); } int main(int argc, char* argv[]) { HV_MEMCHECK; printf("main tid=%ld\n", hv_gettid()); EventLoopThread loop_thread; const EventLoopPtr& loop = loop_thread.loop(); // runEvery 1s loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); // runAfter 10s loop->setTimeout(10000, [&loop](TimerID timerID){ loop->stop(); }); loop_thread.start(); loop->queueInLoop([](){ printf("queueInLoop tid=%ld\n", hv_gettid()); }); loop->runInLoop([](){ printf("runInLoop tid=%ld\n", hv_gettid()); }); // wait loop_thread exit loop_thread.join(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/EventLoop_test.cpp000066400000000000000000000015541520575453600301020ustar00rootroot00000000000000/* * EventLoop_test.cpp * * @build: make evpp * */ #include "hv.h" #include "EventLoop.h" using namespace hv; static void onTimer(TimerID timerID, int n) { printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); } int main(int argc, char* argv[]) { HV_MEMCHECK; printf("main tid=%ld\n", hv_gettid()); auto loop = std::make_shared(); // runEvery 1s loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); // runAfter 10s loop->setTimeout(10000, [&loop](TimerID timerID){ loop->stop(); }); loop->queueInLoop([](){ printf("queueInLoop tid=%ld\n", hv_gettid()); }); loop->runInLoop([](){ printf("runInLoop tid=%ld\n", hv_gettid()); }); // run until loop stopped loop->run(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/README.md000066400000000000000000000020641520575453600257000ustar00rootroot00000000000000The evpp module is designed to be header-only and does not participate in compilation. hloop.h is encapsulated into c++ classes, referring to muduo and evpp. You can modify and use evpp classes according to your own business. evpp模块被设计成只包含头文件,不参与编译。 hloop.h中的c接口被封装成了c++的类,参考了muduo和evpp。 你能修改和使用这些类根据你自己的业务。 ## 目录结构 ``` . ├── Buffer.h 缓存类 ├── Channel.h 通道类,封装了hio_t ├── Event.h 事件类,封装了hevent_t、htimer_t ├── EventLoop.h 事件循环类,封装了hloop_t ├── EventLoopThread.h 事件循环线程类,组合了EventLoop和thread ├── EventLoopThreadPool.h 事件循环线程池类,组合了EventLoop和ThreadPool ├── TcpClient.h TCP客户端类 ├── TcpServer.h TCP服务端类 ├── UdpClient.h UDP客户端类 └── UdpServer.h UDP服务端类 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/Status.h000066400000000000000000000016221520575453600260540ustar00rootroot00000000000000#ifndef HV_STATUS_HPP_ #define HV_STATUS_HPP_ #include namespace hv { class Status { public: enum KStatus { kNull = 0, kInitializing = 1, kInitialized = 2, kStarting = 3, kStarted = 4, kRunning = 5, kPause = 6, kStopping = 7, kStopped = 8, kDestroyed = 9, }; Status() { status_ = kNull; } ~Status() { status_ = kDestroyed; } KStatus status() { return status_; } void setStatus(KStatus status) { status_ = status; } bool isRunning() { return status_ == kRunning; } bool isPause() { return status_ == kPause; } bool isStopped() { return status_ == kStopped; } private: std::atomic status_; }; } #endif // HV_STATUS_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TcpClient.h000066400000000000000000000213771520575453600264670ustar00rootroot00000000000000#ifndef HV_TCP_CLIENT_HPP_ #define HV_TCP_CLIENT_HPP_ #include "hsocket.h" #include "hssl.h" #include "hlog.h" #include "EventLoopThread.h" #include "Channel.h" namespace hv { template class TcpClientEventLoopTmpl { public: typedef std::shared_ptr TSocketChannelPtr; TcpClientEventLoopTmpl(EventLoopPtr loop = NULL) { loop_ = loop ? loop : std::make_shared(); remote_port = 0; connect_timeout = HIO_DEFAULT_CONNECT_TIMEOUT; tls = false; tls_setting = NULL; reconn_setting = NULL; unpack_setting = NULL; } virtual ~TcpClientEventLoopTmpl() { HV_FREE(tls_setting); HV_FREE(reconn_setting); HV_FREE(unpack_setting); } const EventLoopPtr& loop() { return loop_; } // delete thread-safe void deleteInLoop() { loop_->runInLoop([this](){ delete this; }); } // NOTE: By default, not bind local port. If necessary, you can call bind() after createsocket(). // @retval >=0 connfd, <0 error int createsocket(int remote_port, const char* remote_host = "127.0.0.1") { memset(&remote_addr, 0, sizeof(remote_addr)); int ret = sockaddr_set_ipport(&remote_addr, remote_host, remote_port); if (ret != 0) { return NABS(ret); } this->remote_host = remote_host; this->remote_port = remote_port; return createsocket(&remote_addr.sa); } int createsocket(struct sockaddr* remote_addr) { int connfd = ::socket(remote_addr->sa_family, SOCK_STREAM, 0); // SOCKADDR_PRINT(remote_addr); if (connfd < 0) { perror("socket"); return -2; } hio_t* io = hio_get(loop_->loop(), connfd); assert(io != NULL); hio_set_peeraddr(io, remote_addr, SOCKADDR_LEN(remote_addr)); channel = std::make_shared(io); return connfd; } int bind(int local_port, const char* local_host = "0.0.0.0") { sockaddr_u local_addr; memset(&local_addr, 0, sizeof(local_addr)); int ret = sockaddr_set_ipport(&local_addr, local_host, local_port); if (ret != 0) { return NABS(ret); } return bind(&local_addr.sa); } int bind(struct sockaddr* local_addr) { if (channel == NULL || channel->isClosed()) { return -1; } int ret = ::bind(channel->fd(), local_addr, SOCKADDR_LEN(local_addr)); if (ret != 0) { perror("bind"); } return ret; } // closesocket thread-safe void closesocket() { if (channel && channel->status != SocketChannel::CLOSED) { loop_->runInLoop([this](){ if (channel) { setReconnect(NULL); channel->close(); } }); } } int startConnect() { if (channel == NULL || channel->isClosed()) { int connfd = createsocket(&remote_addr.sa); if (connfd < 0) { hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, connfd); return connfd; } } if (channel == NULL || channel->status >= SocketChannel::CONNECTING) { return -1; } if (connect_timeout) { channel->setConnectTimeout(connect_timeout); } if (tls) { channel->enableSSL(); if (tls_setting) { int ret = channel->newSslCtx(tls_setting); if (ret != 0) { hloge("new SSL_CTX failed: %d", ret); closesocket(); return ret; } } if (!is_ipaddr(remote_host.c_str())) { channel->setHostname(remote_host); } } channel->onconnect = [this]() { if (unpack_setting) { channel->setUnpack(unpack_setting); } channel->startRead(); if (onConnection) { onConnection(channel); } if (reconn_setting) { reconn_setting_reset(reconn_setting); } }; channel->onread = [this](Buffer* buf) { if (onMessage) { onMessage(channel, buf); } }; channel->onwrite = [this](Buffer* buf) { if (onWriteComplete) { onWriteComplete(channel, buf); } }; channel->onclose = [this]() { bool reconnect = reconn_setting != NULL; if (onConnection) { onConnection(channel); } if (reconnect) { startReconnect(); } }; return channel->startConnect(); } int startReconnect() { if (!reconn_setting) return -1; if (!reconn_setting_can_retry(reconn_setting)) return -2; uint32_t delay = reconn_setting_calc_delay(reconn_setting); hlogi("reconnect... cnt=%d, delay=%d", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay); loop_->setTimeout(delay, [this](TimerID timerID){ startConnect(); }); return 0; } // start thread-safe void start() { loop_->runInLoop(std::bind(&TcpClientEventLoopTmpl::startConnect, this)); } bool isConnected() { if (channel == NULL) return false; return channel->isConnected(); } // send thread-safe int send(const void* data, int size) { if (!isConnected()) return -1; return channel->write(data, size); } int send(Buffer* buf) { return send(buf->data(), buf->size()); } int send(const std::string& str) { return send(str.data(), str.size()); } int withTLS(hssl_ctx_opt_t* opt = NULL) { tls = true; if (opt) { if (tls_setting == NULL) { HV_ALLOC_SIZEOF(tls_setting); } opt->endpoint = HSSL_CLIENT; *tls_setting = *opt; } return 0; } void setConnectTimeout(int ms) { connect_timeout = ms; } void setReconnect(reconn_setting_t* setting) { if (setting == NULL) { HV_FREE(reconn_setting); return; } if (reconn_setting == NULL) { HV_ALLOC_SIZEOF(reconn_setting); } *reconn_setting = *setting; } bool isReconnect() { return reconn_setting && reconn_setting->cur_retry_cnt > 0; } void setUnpack(unpack_setting_t* setting) { if (setting == NULL) { HV_FREE(unpack_setting); return; } if (unpack_setting == NULL) { HV_ALLOC_SIZEOF(unpack_setting); } *unpack_setting = *setting; } public: TSocketChannelPtr channel; std::string remote_host; int remote_port; sockaddr_u remote_addr; int connect_timeout; bool tls; hssl_ctx_opt_t* tls_setting; reconn_setting_t* reconn_setting; unpack_setting_t* unpack_setting; // Callback std::function onConnection; std::function onMessage; // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. std::function onWriteComplete; private: EventLoopPtr loop_; }; template class TcpClientTmpl : private EventLoopThread, public TcpClientEventLoopTmpl { public: TcpClientTmpl(EventLoopPtr loop = NULL) : EventLoopThread(loop) , TcpClientEventLoopTmpl(EventLoopThread::loop()) , is_loop_owner(loop == NULL) {} virtual ~TcpClientTmpl() { stop(true); } const EventLoopPtr& loop() { return EventLoopThread::loop(); } // start thread-safe void start(bool wait_threads_started = true) { if (isRunning()) { TcpClientEventLoopTmpl::start(); } else { EventLoopThread::start(wait_threads_started, [this]() { TcpClientTmpl::startConnect(); return 0; }); } } // stop thread-safe void stop(bool wait_threads_stopped = true) { TcpClientEventLoopTmpl::closesocket(); if (is_loop_owner) { EventLoopThread::stop(wait_threads_stopped); } } private: bool is_loop_owner; }; typedef TcpClientTmpl TcpClient; } #endif // HV_TCP_CLIENT_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TcpClientEventLoop_test.cpp000066400000000000000000000072461520575453600317140ustar00rootroot00000000000000/* * TcpClientEventLoop_test.cpp * * @build make evpp * @server bin/TcpServer_test 1234 * @client bin/TcpClientEventLoop_test 1234 * */ #include #include "TcpClient.h" #include "htime.h" #define TEST_RECONNECT 1 #define TEST_TLS 0 using namespace hv; class MyTcpClient : public TcpClient { public: MyTcpClient(EventLoopPtr loop = NULL) : TcpClient(loop) { onConnection = [this](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); // send(time) every 3s setInterval(3000, [channel](TimerID timerID){ if (channel->isConnected()) { if (channel->isWriteComplete()) { char str[DATETIME_FMT_BUFLEN] = {0}; datetime_t dt = datetime_now(); datetime_fmt(&dt, str); channel->write(str); } } else { killTimer(timerID); } }); } else { printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } if (isReconnect()) { printf("reconnect cnt=%d, delay=%d\n", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay); } }; onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); }; } int connect(int port) { int connfd = createsocket(port); if (connfd < 0) { return connfd; } #if TEST_RECONNECT // reconnect: 1,2,4,8,10,10,10... reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; setReconnect(&reconn); #endif #if TEST_TLS withTLS(); #endif printf("client connect to port %d, connfd=%d ...\n", port, connfd); start(); return connfd; } }; typedef std::shared_ptr MyTcpClientPtr; int TestMultiClientsRunInOneEventLoop(int port, int nclients) { auto loop_thread = std::make_shared(); loop_thread->start(); std::map clients; for (int i = 0; i < nclients; ++i) { MyTcpClient* client = new MyTcpClient(loop_thread->loop()); client->connect(port); clients[i] = client; } std::string str; while (std::getline(std::cin, str)) { if (str == "close") { for (auto& pair : clients) { MyTcpClient* client = pair.second; client->closesocket(); } } else if (str == "delete") { for (auto& pair : clients) { MyTcpClient* client = pair.second; client->deleteInLoop(); } break; } else { for (auto& pair : clients) { MyTcpClient* client = pair.second; client->send(str); } } } printf("Press Enter key to exit loop.\n"); while (getchar() != '\n'); loop_thread->stop(); loop_thread->join(); return 0; } int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s port [nclients]\n", argv[0]); return -10; } int port = atoi(argv[1]); int nclients = 100; if (argc > 2) { nclients = atoi(argv[2]); } return TestMultiClientsRunInOneEventLoop(port, nclients); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TcpClient_test.cpp000066400000000000000000000051221520575453600300470ustar00rootroot00000000000000/* * TcpClient_test.cpp * * @build make evpp * @server bin/TcpServer_test 1234 * @client bin/TcpClient_test 1234 * */ #include #include "TcpClient.h" #include "htime.h" #define TEST_RECONNECT 1 #define TEST_TLS 0 using namespace hv; int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s remote_port [remote_host]\n", argv[0]); return -10; } int remote_port = atoi(argv[1]); const char* remote_host = "127.0.0.1"; if (argc > 2) { remote_host = argv[2]; } TcpClient cli; int connfd = cli.createsocket(remote_port, remote_host); if (connfd < 0) { return -20; } printf("client connect to port %d, connfd=%d ...\n", remote_port, connfd); cli.onConnection = [&cli](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); // send(time) every 3s setInterval(3000, [channel](TimerID timerID){ if (channel->isConnected()) { if (channel->isWriteComplete()) { char str[DATETIME_FMT_BUFLEN] = {0}; datetime_t dt = datetime_now(); datetime_fmt(&dt, str); channel->write(str); } } else { killTimer(timerID); } }); } else { printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } if (cli.isReconnect()) { printf("reconnect cnt=%d, delay=%d\n", cli.reconn_setting->cur_retry_cnt, cli.reconn_setting->cur_delay); } }; cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); }; #if TEST_RECONNECT // reconnect: 1,2,4,8,10,10,10... reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; cli.setReconnect(&reconn); #endif #if TEST_TLS cli.withTLS(); #endif cli.start(); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { cli.closesocket(); } else if (str == "start") { cli.start(); } else if (str == "stop") { cli.stop(); break; } else { if (!cli.isConnected()) break; cli.send(str); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TcpServer.h000066400000000000000000000232621520575453600265120ustar00rootroot00000000000000#ifndef HV_TCP_SERVER_HPP_ #define HV_TCP_SERVER_HPP_ #include "hsocket.h" #include "hssl.h" #include "hlog.h" #include "EventLoopThreadPool.h" #include "Channel.h" namespace hv { template class TcpServerEventLoopTmpl { public: typedef std::shared_ptr TSocketChannelPtr; TcpServerEventLoopTmpl(EventLoopPtr loop = NULL) { acceptor_loop = loop ? loop : std::make_shared(); port = 0; listenfd = -1; tls = false; tls_setting = NULL; unpack_setting = NULL; max_connections = 0xFFFFFFFF; load_balance = LB_RoundRobin; } virtual ~TcpServerEventLoopTmpl() { HV_FREE(tls_setting); HV_FREE(unpack_setting); } EventLoopPtr loop(int idx = -1) { EventLoopPtr worker_loop = worker_threads.loop(idx); if (worker_loop == NULL) { worker_loop = acceptor_loop; } return worker_loop; } //@retval >=0 listenfd, <0 error int createsocket(int port, const char* host = "0.0.0.0") { listenfd = Listen(port, host); if (listenfd < 0) return listenfd; this->host = host; this->port = port; return listenfd; } // closesocket thread-safe void closesocket() { if (listenfd >= 0) { hloop_t* loop = acceptor_loop->loop(); if (loop) { hio_t* listenio = hio_get(loop, listenfd); assert(listenio != NULL); hio_close_async(listenio); } listenfd = -1; } } void setMaxConnectionNum(uint32_t num) { max_connections = num; } void setLoadBalance(load_balance_e lb) { load_balance = lb; } // NOTE: totalThreadNum = 1 acceptor_thread + N worker_threads (N can be 0) void setThreadNum(int num) { worker_threads.setThreadNum(num); } int startAccept() { if (listenfd < 0) { listenfd = createsocket(port, host.c_str()); if (listenfd < 0) { hloge("createsocket %s:%d return %d!\n", host.c_str(), port, listenfd); return listenfd; } } hloop_t* loop = acceptor_loop->loop(); if (loop == NULL) return -2; hio_t* listenio = haccept(loop, listenfd, onAccept); assert(listenio != NULL); hevent_set_userdata(listenio, this); if (tls) { hio_enable_ssl(listenio); if (tls_setting) { int ret = hio_new_ssl_ctx(listenio, tls_setting); if (ret != 0) { hloge("new SSL_CTX failed: %d", ret); closesocket(); return ret; } } } return 0; } int stopAccept() { if (listenfd < 0) return -1; hloop_t* loop = acceptor_loop->loop(); if (loop == NULL) return -2; hio_t* listenio = hio_get(loop, listenfd); assert(listenio != NULL); return hio_del(listenio, HV_READ); } // start thread-safe void start(bool wait_threads_started = true) { if (worker_threads.threadNum() > 0) { worker_threads.start(wait_threads_started); } acceptor_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::startAccept, this)); } // stop thread-safe void stop(bool wait_threads_stopped = true) { closesocket(); if (worker_threads.threadNum() > 0) { worker_threads.stop(wait_threads_stopped); } } int withTLS(hssl_ctx_opt_t* opt = NULL) { tls = true; if (opt) { if (tls_setting == NULL) { HV_ALLOC_SIZEOF(tls_setting); } opt->endpoint = HSSL_SERVER; *tls_setting = *opt; } return 0; } void setUnpack(unpack_setting_t* setting) { if (setting == NULL) { HV_FREE(unpack_setting); return; } if (unpack_setting == NULL) { HV_ALLOC_SIZEOF(unpack_setting); } *unpack_setting = *setting; } // channel const TSocketChannelPtr& addChannel(hio_t* io) { uint32_t id = hio_id(io); auto channel = std::make_shared(io); std::lock_guard locker(mutex_); channels[id] = channel; return channels[id]; } TSocketChannelPtr getChannelById(uint32_t id) { std::lock_guard locker(mutex_); auto iter = channels.find(id); return iter != channels.end() ? iter->second : NULL; } void removeChannel(const TSocketChannelPtr& channel) { uint32_t id = channel->id(); std::lock_guard locker(mutex_); channels.erase(id); } size_t connectionNum() { std::lock_guard locker(mutex_); return channels.size(); } int foreachChannel(std::function fn) { std::lock_guard locker(mutex_); for (auto& pair : channels) { fn(pair.second); } return channels.size(); } // broadcast thread-safe int broadcast(const void* data, int size) { return foreachChannel([data, size](const TSocketChannelPtr& channel) { channel->write(data, size); }); } int broadcast(const std::string& str) { return broadcast(str.data(), str.size()); } private: static void newConnEvent(hio_t* connio) { TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio); if (server->connectionNum() >= server->max_connections) { hlogw("over max_connections"); hio_close(connio); return; } // NOTE: attach to worker loop EventLoop* worker_loop = currentThreadEventLoop; assert(worker_loop != NULL); hio_attach(worker_loop->loop(), connio); const TSocketChannelPtr& channel = server->addChannel(connio); channel->status = SocketChannel::CONNECTED; channel->onread = [server, &channel](Buffer* buf) { if (server->onMessage) { server->onMessage(channel, buf); } }; channel->onwrite = [server, &channel](Buffer* buf) { if (server->onWriteComplete) { server->onWriteComplete(channel, buf); } }; channel->onclose = [server, &channel]() { EventLoop* worker_loop = currentThreadEventLoop; assert(worker_loop != NULL); --worker_loop->connectionNum; channel->status = SocketChannel::CLOSED; if (server->onConnection) { server->onConnection(channel); } server->removeChannel(channel); // NOTE: After removeChannel, channel may be destroyed, // so in this lambda function, no code should be added below. }; if (server->unpack_setting) { channel->setUnpack(server->unpack_setting); } channel->startRead(); if (server->onConnection) { server->onConnection(channel); } } static void onAccept(hio_t* connio) { TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio); // NOTE: detach from acceptor loop hio_detach(connio); EventLoopPtr worker_loop = server->worker_threads.nextLoop(server->load_balance); if (worker_loop == NULL) { worker_loop = server->acceptor_loop; } ++worker_loop->connectionNum; worker_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::newConnEvent, connio)); } public: std::string host; int port; int listenfd; bool tls; hssl_ctx_opt_t* tls_setting; unpack_setting_t* unpack_setting; // Callback std::function onConnection; std::function onMessage; // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. std::function onWriteComplete; uint32_t max_connections; load_balance_e load_balance; private: // id => TSocketChannelPtr std::map channels; // GUAREDE_BY(mutex_) std::mutex mutex_; EventLoopPtr acceptor_loop; EventLoopThreadPool worker_threads; }; template class TcpServerTmpl : private EventLoopThread, public TcpServerEventLoopTmpl { public: TcpServerTmpl(EventLoopPtr loop = NULL) : EventLoopThread(loop) , TcpServerEventLoopTmpl(EventLoopThread::loop()) , is_loop_owner(loop == NULL) {} virtual ~TcpServerTmpl() { stop(true); } EventLoopPtr loop(int idx = -1) { return TcpServerEventLoopTmpl::loop(idx); } // start thread-safe void start(bool wait_threads_started = true) { TcpServerEventLoopTmpl::start(wait_threads_started); if (!isRunning()) { EventLoopThread::start(wait_threads_started); } } // stop thread-safe void stop(bool wait_threads_stopped = true) { if (is_loop_owner) { EventLoopThread::stop(wait_threads_stopped); } TcpServerEventLoopTmpl::stop(wait_threads_stopped); } private: bool is_loop_owner; }; typedef TcpServerTmpl TcpServer; } #endif // HV_TCP_SERVER_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TcpServer_test.cpp000066400000000000000000000036471520575453600301110ustar00rootroot00000000000000/* * TcpServer_test.cpp * * @build make evpp * @server bin/TcpServer_test 1234 * @client bin/TcpClient_test 1234 * */ #include #include "TcpServer.h" using namespace hv; #define TEST_TLS 0 int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); hlog_set_level(LOG_LEVEL_DEBUG); TcpServer srv; int listenfd = srv.createsocket(port); if (listenfd < 0) { return -20; } printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); srv.onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid()); } else { printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid()); } }; srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { // echo printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); channel->write(buf); }; srv.setThreadNum(4); srv.setLoadBalance(LB_LeastConnections); #if TEST_TLS hssl_ctx_opt_t ssl_opt; memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t)); ssl_opt.crt_file = "cert/server.crt"; ssl_opt.key_file = "cert/server.key"; ssl_opt.verify_peer = 0; srv.withTLS(&ssl_opt); #endif srv.start(); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { srv.closesocket(); } else if (str == "start") { srv.start(); } else if (str == "stop") { srv.stop(); break; } else { srv.broadcast(str.data(), str.size()); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TimerThread.h000066400000000000000000000022271520575453600270030ustar00rootroot00000000000000#ifndef HV_TIMER_THREAD_HPP_ #define HV_TIMER_THREAD_HPP_ #include "EventLoopThread.h" namespace hv { class TimerThread : public EventLoopThread { public: std::atomic nextTimerID; TimerThread() : EventLoopThread() { nextTimerID = 0; start(); } virtual ~TimerThread() { stop(); join(); } public: // setTimer, setTimeout, killTimer, resetTimer thread-safe TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) { TimerID timerID = ++nextTimerID; loop()->setTimerInLoop(timeout_ms, cb, repeat, timerID); return timerID; } // alias javascript setTimeout, setInterval TimerID setTimeout(int timeout_ms, TimerCallback cb) { return setTimer(timeout_ms, cb, 1); } TimerID setInterval(int interval_ms, TimerCallback cb) { return setTimer(interval_ms, cb, INFINITE); } void killTimer(TimerID timerID) { loop()->killTimer(timerID); } void resetTimer(TimerID timerID, int timeout_ms = 0) { loop()->resetTimer(timerID, timeout_ms); } }; } // end namespace hv #endif // HV_TIMER_THREAD_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/TimerThread_test.cpp000066400000000000000000000026131520575453600303740ustar00rootroot00000000000000/* * TimerThread_test.cpp * * @build: make evpp * */ #include "TimerThread.h" #include "singleton.h" namespace hv { class GlobalTimerThread : public TimerThread { SINGLETON_DECL(GlobalTimerThread) protected: GlobalTimerThread() : TimerThread() {} ~GlobalTimerThread() {} public: static TimerID setTimeout(int timeout_ms, TimerCallback cb) { return GlobalTimerThread::instance()->setTimer(timeout_ms, cb, 1); } static void clearTimeout(TimerID timerID) { GlobalTimerThread::instance()->killTimer(timerID); } static TimerID setInterval(int interval_ms, TimerCallback cb) { return GlobalTimerThread::instance()->setTimer(interval_ms, cb, INFINITE); } static void clearInterval(TimerID timerID) { GlobalTimerThread::instance()->killTimer(timerID); } }; SINGLETON_IMPL(GlobalTimerThread) } // end namespace hv int main(int argc, char* argv[]) { hv::GlobalTimerThread::setTimeout(3000, [](hv::TimerID timerID) { printf("setTimeout timerID=%lu time=%lus\n", (unsigned long)timerID, (unsigned long)time(NULL)); }); hv::GlobalTimerThread::setInterval(1000, [](hv::TimerID timerID) { printf("setInterval timerID=%lu time=%lus\n", (unsigned long)timerID, (unsigned long)time(NULL)); }); // press Enter to stop while (getchar() != '\n'); hv::GlobalTimerThread::exitInstance(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/UdpClient.h000066400000000000000000000131741520575453600264650ustar00rootroot00000000000000#ifndef HV_UDP_CLIENT_HPP_ #define HV_UDP_CLIENT_HPP_ #include "hsocket.h" #include "EventLoopThread.h" #include "Channel.h" namespace hv { template class UdpClientEventLoopTmpl { public: typedef std::shared_ptr TSocketChannelPtr; UdpClientEventLoopTmpl(EventLoopPtr loop = NULL) { loop_ = loop ? loop : std::make_shared(); remote_port = 0; #if WITH_KCP kcp_setting = NULL; #endif } virtual ~UdpClientEventLoopTmpl() { #if WITH_KCP HV_FREE(kcp_setting); #endif } const EventLoopPtr& loop() { return loop_; } // NOTE: By default, not bind local port. If necessary, you can call bind() after createsocket(). // @retval >=0 sockfd, <0 error int createsocket(int remote_port, const char* remote_host = "127.0.0.1") { hio_t* io = hloop_create_udp_client(loop_->loop(), remote_host, remote_port); if (io == NULL) return -1; this->remote_host = remote_host; this->remote_port = remote_port; channel = std::make_shared(io); int sockfd = channel->fd(); if (hv_strendswith(remote_host, ".255")) { udp_broadcast(sockfd, 1); } return sockfd; } int bind(int local_port, const char* local_host = "0.0.0.0") { if (channel == NULL || channel->isClosed()) { return -1; } sockaddr_u local_addr; memset(&local_addr, 0, sizeof(local_addr)); int ret = sockaddr_set_ipport(&local_addr, local_host, local_port); if (ret != 0) { return NABS(ret); } ret = ::bind(channel->fd(), &local_addr.sa, SOCKADDR_LEN(&local_addr)); if (ret != 0) { perror("bind"); } hio_set_localaddr(channel->io(), &local_addr.sa, SOCKADDR_LEN(&local_addr)); return ret; } // closesocket thread-safe void closesocket() { if (channel) { channel->close(true); } } int startRecv() { if (channel == NULL || channel->isClosed()) { int sockfd = createsocket(remote_port, remote_host.c_str()); if (sockfd < 0) { hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, sockfd); return sockfd; } } if (channel == NULL || channel->isClosed()) { return -1; } channel->onread = [this](Buffer* buf) { if (onMessage) { onMessage(channel, buf); } }; channel->onwrite = [this](Buffer* buf) { if (onWriteComplete) { onWriteComplete(channel, buf); } }; #if WITH_KCP if (kcp_setting) { hio_set_kcp(channel->io(), kcp_setting); } #endif return channel->startRead(); } int stopRecv() { if (channel == NULL) return -1; return channel->stopRead(); } // start thread-safe void start() { loop_->runInLoop(std::bind(&UdpClientEventLoopTmpl::startRecv, this)); } // sendto thread-safe int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) { if (channel == NULL) return -1; std::lock_guard locker(sendto_mutex); if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr)); return channel->write(data, size); } int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) { return sendto(buf->data(), buf->size(), peeraddr); } int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) { return sendto(str.data(), str.size(), peeraddr); } #if WITH_KCP void setKcp(kcp_setting_t* setting) { if (setting == NULL) { HV_FREE(kcp_setting); return; } if (kcp_setting == NULL) { HV_ALLOC_SIZEOF(kcp_setting); } *kcp_setting = *setting; } #endif public: TSocketChannelPtr channel; std::string remote_host; int remote_port; #if WITH_KCP kcp_setting_t* kcp_setting; #endif // Callback std::function onMessage; // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. std::function onWriteComplete; private: std::mutex sendto_mutex; EventLoopPtr loop_; }; template class UdpClientTmpl : private EventLoopThread, public UdpClientEventLoopTmpl { public: UdpClientTmpl(EventLoopPtr loop = NULL) : EventLoopThread(loop) , UdpClientEventLoopTmpl(EventLoopThread::loop()) , is_loop_owner(loop == NULL) {} virtual ~UdpClientTmpl() { stop(true); } const EventLoopPtr& loop() { return EventLoopThread::loop(); } // start thread-safe void start(bool wait_threads_started = true) { if (isRunning()) { UdpClientEventLoopTmpl::start(); } else { EventLoopThread::start(wait_threads_started, std::bind(&UdpClientTmpl::startRecv, this)); } } // stop thread-safe void stop(bool wait_threads_stopped = true) { UdpClientEventLoopTmpl::closesocket(); if (is_loop_owner) { EventLoopThread::stop(wait_threads_stopped); } } private: bool is_loop_owner; }; typedef UdpClientTmpl UdpClient; } #endif // HV_UDP_CLIENT_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/UdpClient_test.cpp000066400000000000000000000026511520575453600300550ustar00rootroot00000000000000/* * UdpClient_test.cpp * * @build make evpp * @server bin/UdpServer_test 1234 * @client bin/UdpClient_test 1234 * */ #include #include "UdpClient.h" #include "htime.h" using namespace hv; int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s remote_port [remote_host]\n", argv[0]); return -10; } int remote_port = atoi(argv[1]); const char* remote_host = "127.0.0.1"; if (argc > 2) { remote_host = argv[2]; } UdpClient cli; int sockfd = cli.createsocket(remote_port, remote_host); if (sockfd < 0) { return -20; } printf("client sendto port %d, sockfd=%d ...\n", remote_port, sockfd); cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); }; cli.start(); // sendto(time) every 3s cli.loop()->setInterval(3000, [&cli](TimerID timerID) { char str[DATETIME_FMT_BUFLEN] = {0}; datetime_t dt = datetime_now(); datetime_fmt(&dt, str); cli.sendto(str); }); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { cli.closesocket(); } else if (str == "start") { cli.start(); } else if (str == "stop") { cli.stop(); break; } else { cli.sendto(str); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/UdpServer.h000066400000000000000000000112641520575453600265130ustar00rootroot00000000000000#ifndef HV_UDP_SERVER_HPP_ #define HV_UDP_SERVER_HPP_ #include "hsocket.h" #include "EventLoopThreadPool.h" #include "Channel.h" namespace hv { template class UdpServerEventLoopTmpl { public: typedef std::shared_ptr TSocketChannelPtr; UdpServerEventLoopTmpl(EventLoopPtr loop = NULL) { loop_ = loop ? loop : std::make_shared(); port = 0; #if WITH_KCP kcp_setting = NULL; #endif } virtual ~UdpServerEventLoopTmpl() { #if WITH_KCP HV_FREE(kcp_setting); #endif } const EventLoopPtr& loop() { return loop_; } //@retval >=0 bindfd, <0 error int createsocket(int port, const char* host = "0.0.0.0") { hio_t* io = hloop_create_udp_server(loop_->loop(), host, port); if (io == NULL) return -1; this->host = host; this->port = port; channel = std::make_shared(io); return channel->fd(); } // closesocket thread-safe void closesocket() { if (channel) { channel->close(true); } } int startRecv() { if (channel == NULL || channel->isClosed()) { int bindfd = createsocket(port, host.c_str()); if (bindfd < 0) { hloge("createsocket %s:%d return %d!\n", host.c_str(), port, bindfd); return bindfd; } } if (channel == NULL || channel->isClosed()) { return -1; } channel->onread = [this](Buffer* buf) { if (onMessage) { onMessage(channel, buf); } }; channel->onwrite = [this](Buffer* buf) { if (onWriteComplete) { onWriteComplete(channel, buf); } }; #if WITH_KCP if (kcp_setting) { hio_set_kcp(channel->io(), kcp_setting); } #endif return channel->startRead(); } int stopRecv() { if (channel == NULL) return -1; return channel->stopRead(); } // start thread-safe void start() { loop_->runInLoop(std::bind(&UdpServerEventLoopTmpl::startRecv, this)); } // sendto thread-safe int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) { if (channel == NULL) return -1; std::lock_guard locker(sendto_mutex); if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr)); return channel->write(data, size); } int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) { return sendto(buf->data(), buf->size(), peeraddr); } int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) { return sendto(str.data(), str.size(), peeraddr); } #if WITH_KCP void setKcp(kcp_setting_t* setting) { if (setting == NULL) { HV_FREE(kcp_setting); return; } if (kcp_setting == NULL) { HV_ALLOC_SIZEOF(kcp_setting); } *kcp_setting = *setting; } #endif public: std::string host; int port; TSocketChannelPtr channel; #if WITH_KCP kcp_setting_t* kcp_setting; #endif // Callback std::function onMessage; // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. std::function onWriteComplete; private: std::mutex sendto_mutex; EventLoopPtr loop_; }; template class UdpServerTmpl : private EventLoopThread, public UdpServerEventLoopTmpl { public: UdpServerTmpl(EventLoopPtr loop = NULL) : EventLoopThread(loop) , UdpServerEventLoopTmpl(EventLoopThread::loop()) , is_loop_owner(loop == NULL) {} virtual ~UdpServerTmpl() { stop(true); } const EventLoopPtr& loop() { return EventLoopThread::loop(); } // start thread-safe void start(bool wait_threads_started = true) { if (isRunning()) { UdpServerEventLoopTmpl::start(); } else { EventLoopThread::start(wait_threads_started, std::bind(&UdpServerTmpl::startRecv, this)); } } // stop thread-safe void stop(bool wait_threads_stopped = true) { UdpServerEventLoopTmpl::closesocket(); if (is_loop_owner) { EventLoopThread::stop(wait_threads_stopped); } } private: bool is_loop_owner; }; typedef UdpServerTmpl UdpServer; } #endif // HV_UDP_SERVER_HPP_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/UdpServer_test.cpp000066400000000000000000000020711520575453600301010ustar00rootroot00000000000000/* * UdpServer_test.cpp * * @build make evpp * @server bin/UdpServer_test 1234 * @client bin/UdpClient_test 1234 * */ #include #include "UdpServer.h" using namespace hv; int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); UdpServer srv; int bindfd = srv.createsocket(port); if (bindfd < 0) { return -20; } printf("server bind on port %d, bindfd=%d ...\n", port, bindfd); srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { // echo printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); channel->write(buf); }; srv.start(); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { srv.closesocket(); } else if (str == "start") { srv.start(); } else if (str == "stop") { srv.stop(); break; } else { srv.sendto(str); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/evpp/build_test.sh000077500000000000000000000001441520575453600271130ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. cd ${ROOT_DIR} make evpp kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/000077500000000000000000000000001520575453600252635ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/BUILD.bazel000066400000000000000000000103571520575453600271470ustar00rootroot00000000000000load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") cc_binary( name = "hloop_test", srcs = ["hloop_test.c"], deps = ["//:hv"] ) cc_binary( name = "htimer_test", srcs = ["htimer_test.c"], deps = ["//:hv"] ) cc_binary( name = "nc", srcs = ["nc.c"], deps = ["//:hv"] ) cc_binary( name = "tinyhttpd", srcs = ["tinyhttpd.c"], deps = ["//:hv"] ) cc_binary( name = "tinyproxyd", srcs = ["tinyproxyd.c"], deps = ["//:hv"] ) cc_binary( name = "tcp_client_test", srcs = ["tcp_client_test.c"], deps = ["//:hv"] ) cc_binary( name = "tcp_echo_server", srcs = ["tcp_echo_server.c"], deps = ["//:hv"] ) cc_binary( name = "tcp_chat_server", srcs = ["tcp_chat_server.c"], deps = ["//:hv"] ) cc_binary( name = "tcp_proxy_server", srcs = ["tcp_proxy_server.c"], deps = ["//:hv"] ) cc_binary( name = "udp_echo_server", srcs = ["udp_echo_server.c"], deps = ["//:hv"] ) cc_binary( name = "udp_proxy_server", srcs = ["udp_proxy_server.c"], deps = ["//:hv"] ) cc_binary( name = "socks5_proxy_server", srcs = ["socks5_proxy_server.c"], deps = ["//:hv"] ) cc_binary( name = "jsonrpc_client", srcs = ["jsonrpc/jsonrpc_client.c", "jsonrpc/cJSON.c"] + glob(["jsonrpc/*.h"]), copts = ["-DCJSON_HIDE_SYMBOLS"], deps = ["//:hv"] ) cc_binary( name = "jsonrpc_server", srcs = ["jsonrpc/jsonrpc_server.c", "jsonrpc/cJSON.c"] + glob(["jsonrpc/*.h"]), copts = ["-DCJSON_HIDE_SYMBOLS"], deps = ["//:hv"] ) cc_binary( name = "hmain_test", srcs = ["hmain_test.cpp"], deps = ["//:hv"] ) cc_binary( name = "nmap", srcs = glob(["nmap/*"]), copts = ["-DPRINT_DEBUG"], deps = ["//:hv"] ) cc_binary( name = "wrk", srcs = ["wrk.cpp"], deps = ["//:hv"] ) cc_binary( name = "http_server_test", srcs = ["http_server_test.cpp"], deps = ["//:hv"] ) cc_binary( name = "websocket_server_test", srcs = ["websocket_server_test.cpp"], deps = ["//:hv"] ) cc_binary( name = "curl", srcs = ["curl.cpp"], deps = ["//:hv"] ) cc_binary( name = "wget", srcs = ["wget.cpp"], deps = ["//:hv"] ) cc_binary( name = "consul", srcs = glob(["consul/*"]), copts = ["-DPRINT_DEBUG"], deps = ["//:hv"] ) cc_binary( name = "http_client_test", srcs = ["http_client_test.cpp"], deps = ["//:hv"] ) cc_binary( name = "websocket_client_test", srcs = ["websocket_client_test.cpp"], deps = ["//:hv"] ) cc_binary( name = "httpd", srcs = glob(["httpd/*"]), copts = ["-DPRINT_DEBUG"], deps = ["//:hv"] ) cc_binary( name = "mqtt_sub", srcs = ["mqtt/mqtt_sub.c"], deps = ["//:hv"] ) cc_binary( name = "mqtt_pub", srcs = ["mqtt/mqtt_pub.c"], deps = ["//:hv"] ) cc_binary( name = "mqtt_client_test", srcs = ["mqtt/mqtt_client_test.cpp"], deps = ["//:hv"] ) config_setting( name = "with_http_server_client", define_values = { "WITH_EVPP": "ON", "WITH_HTTP": "ON", "WITH_HTTP_SERVER": "ON", "WITH_HTTP_CLIENT": "ON", }, ) filegroup( name = "examples", srcs = [ ":hloop_test", ":htimer_test", ":nc", ":tinyhttpd", ":tinyproxyd", ":tcp_client_test", ":tcp_echo_server", ":tcp_chat_server", ":tcp_proxy_server", ":udp_echo_server", ":udp_proxy_server", ":socks5_proxy_server", ":jsonrpc_client", ":jsonrpc_server", ] + select({ "//:with_evpp": [":hmain_test", ":nmap"], "//conditions:default": [], }) + select({ "//:with_http": [":wrk"], "//conditions:default": [], }) + select({ "//:with_http_server": [":http_server_test", ":websocket_server_test"], "//conditions:default": [], }) + select({ "//:with_http_client": [":curl", ":wget", ":consul", ":http_client_test", ":websocket_client_test"], "//conditions:default": [], }) + select({ "with_http_server_client": [":httpd"], "//conditions:default": [], }) + select({ "//:with_mqtt": ["mqtt_sub", "mqtt_pub", "mqtt_client_test"], "//conditions:default": [], }), visibility = ["//:__pkg__"] ) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/CMakeLists.txt000066400000000000000000000125541520575453600300320ustar00rootroot00000000000000list(APPEND EXAMPLES hloop_test htimer_test pipe_test nc tinyhttpd tinyproxyd tcp_client_test tcp_echo_server tcp_chat_server tcp_proxy_server udp_echo_server udp_proxy_server socks5_proxy_server jsonrpc_client jsonrpc_server ) include_directories(.. ../base ../ssl ../event ../util) add_executable(hloop_test hloop_test.c) target_link_libraries(hloop_test ${HV_LIBRARIES}) add_executable(htimer_test htimer_test.c) target_link_libraries(htimer_test ${HV_LIBRARIES}) add_executable(pipe_test pipe_test.c) target_link_libraries(pipe_test ${HV_LIBRARIES}) add_executable(nc nc.c) target_link_libraries(nc ${HV_LIBRARIES}) add_executable(tinyhttpd tinyhttpd.c) target_link_libraries(tinyhttpd ${HV_LIBRARIES}) add_executable(tinyproxyd tinyproxyd.c) target_link_libraries(tinyproxyd ${HV_LIBRARIES}) add_executable(tcp_client_test tcp_client_test.c) target_link_libraries(tcp_client_test ${HV_LIBRARIES}) add_executable(tcp_echo_server tcp_echo_server.c) target_link_libraries(tcp_echo_server ${HV_LIBRARIES}) add_executable(tcp_chat_server tcp_chat_server.c) target_link_libraries(tcp_chat_server ${HV_LIBRARIES}) add_executable(tcp_proxy_server tcp_proxy_server.c) target_link_libraries(tcp_proxy_server ${HV_LIBRARIES}) add_executable(udp_echo_server udp_echo_server.c) target_link_libraries(udp_echo_server ${HV_LIBRARIES}) add_executable(udp_proxy_server udp_proxy_server.c) target_link_libraries(udp_proxy_server ${HV_LIBRARIES}) add_executable(socks5_proxy_server socks5_proxy_server.c) target_link_libraries(socks5_proxy_server ${HV_LIBRARIES}) add_executable(jsonrpc_client jsonrpc/jsonrpc_client.c jsonrpc/cJSON.c) target_compile_definitions(jsonrpc_client PRIVATE CJSON_HIDE_SYMBOLS) target_link_libraries(jsonrpc_client ${HV_LIBRARIES}) add_executable(jsonrpc_server jsonrpc/jsonrpc_server.c jsonrpc/cJSON.c) target_compile_definitions(jsonrpc_server PRIVATE CJSON_HIDE_SYMBOLS) target_link_libraries(jsonrpc_server ${HV_LIBRARIES}) if(WITH_KCP) glob_headers_and_sources(KCPTUN_SMUX_FILES kcptun/smux) glob_headers_and_sources(KCPTUN_CLIENT_FILES kcptun/client) glob_headers_and_sources(KCPTUN_SERVER_FILES kcptun/server) # kcptun_client add_executable(kcptun_client ${KCPTUN_SMUX_FILES} ${KCPTUN_CLIENT_FILES}) target_link_libraries(kcptun_client ${HV_LIBRARIES}) # kcptun_server add_executable(kcptun_server ${KCPTUN_SMUX_FILES} ${KCPTUN_SERVER_FILES}) target_link_libraries(kcptun_server ${HV_LIBRARIES}) list(APPEND EXAMPLES kcptun_client kcptun_server) endif() if(WITH_EVPP) include_directories(../cpputil ../evpp) # hmain_test add_executable(hmain_test hmain_test.cpp) target_link_libraries(hmain_test ${HV_LIBRARIES}) # nmap glob_headers_and_sources(NMAP_FILES nmap) add_executable(nmap ${NMAP_FILES}) target_compile_definitions(nmap PRIVATE PRINT_DEBUG) target_link_libraries(nmap ${HV_LIBRARIES}) list(APPEND EXAMPLES hmain_test nmap) if(WITH_HTTP) include_directories(../http) # wrk add_executable(wrk wrk.cpp) target_link_libraries(wrk ${HV_LIBRARIES}) list(APPEND EXAMPLES wrk) if(WITH_HTTP_SERVER) include_directories(../http/server) # http_server_test add_executable(http_server_test http_server_test.cpp) target_link_libraries(http_server_test ${HV_LIBRARIES}) # websocket_server_test add_executable(websocket_server_test websocket_server_test.cpp) target_link_libraries(websocket_server_test ${HV_LIBRARIES}) list(APPEND EXAMPLES http_server_test websocket_server_test) endif() if(WITH_HTTP_CLIENT) include_directories(../http/client) # curl set(CURL_TARGET_NAME curl) if(WITH_CURL) set(CURL_TARGET_NAME hv_curl) endif() add_executable(${CURL_TARGET_NAME} curl.cpp) if(WITH_CURL) set_target_properties(${CURL_TARGET_NAME} PROPERTIES OUTPUT_NAME curl) endif() target_link_libraries(${CURL_TARGET_NAME} ${HV_LIBRARIES}) # wget add_executable(wget wget.cpp) target_link_libraries(wget ${HV_LIBRARIES}) # consul glob_headers_and_sources(CONSUL_FILES consul) add_executable(consul ${CONSUL_FILES}) target_compile_definitions(consul PRIVATE PRINT_DEBUG) target_link_libraries(consul ${HV_LIBRARIES}) # http_client_test add_executable(http_client_test http_client_test.cpp) target_link_libraries(http_client_test ${HV_LIBRARIES}) # websocket_client_test add_executable(websocket_client_test websocket_client_test.cpp) target_link_libraries(websocket_client_test ${HV_LIBRARIES}) list(APPEND EXAMPLES ${CURL_TARGET_NAME} wget consul http_client_test websocket_client_test) if(WITH_HTTP_SERVER) # httpd glob_headers_and_sources(HTTPD_FILES httpd) add_executable(httpd ${HTTPD_FILES}) target_link_libraries(httpd ${HV_LIBRARIES}) list(APPEND EXAMPLES httpd) endif() endif() endif() endif() if(WITH_MQTT) include_directories(../mqtt) add_executable(mqtt_sub mqtt/mqtt_sub.c) target_link_libraries(mqtt_sub ${HV_LIBRARIES}) add_executable(mqtt_pub mqtt/mqtt_pub.c) target_link_libraries(mqtt_pub ${HV_LIBRARIES}) add_executable(mqtt_client_test mqtt/mqtt_client_test.cpp) target_link_libraries(mqtt_client_test ${HV_LIBRARIES}) list(APPEND EXAMPLES mqtt_sub mqtt_pub mqtt_client_test) endif() add_custom_target(examples DEPENDS ${EXAMPLES}) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/README.md000066400000000000000000000030251520575453600265420ustar00rootroot00000000000000## 目录结构 ``` . ├── consul/ consul服务注册与发现 ├── httpd/ HTTP服务端 ├── jsonrpc/ json RPC示例 ├── kcptun/ kcp隧道 ├── mqtt/ MQTT发布订阅示例 ├── multi-thread/ 多线程网络编程示例 ├── nmap/ 网络扫描工具 ├── protorpc/ protobuf RPC示例 ├── curl.cpp HTTP请求工具 ├── hloop_test.c 事件循环测试代码 ├── hmain_test.cpp 命令行程序示例代码 ├── htimer_test.c 定时器测试代码 ├── http_client_test.c HTTP客户端测试代码 ├── http_server_test.c HTTP服务端测试代码 ├── nc.c 网络连接工具 ├── pipe_test.c pipe示例代码 ├── socks5_proxy_server.c SOCKS5代理服务 ├── tcp_chat_server.c TCP聊天服务 ├── tcp_echo_server.c TCP回显服务 ├── tcp_proxy_server.c TCP代理服务 ├── tinyhttpd.c 微型HTTP服务 ├── tinyproxyd.c 微型HTTP代理服务 ├── udp_echo_server.c UDP回显服务 ├── udp_proxy_server.c UDP代理服务 ├── websocket_client_test.c WebSocket客户端测试代码 ├── websocket_server_test.c WebSocket服务端测试代码 ├── wget.cpp HTTP文件下载工具 └── wrk.cpp HTTP压测工具 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/consul/000077500000000000000000000000001520575453600265665ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/consul/consul.cpp000066400000000000000000000076641520575453600306120ustar00rootroot00000000000000#include "consul.h" #include "HttpClient.h" using namespace hv; #include "json.hpp" using json = nlohmann::json; #define PROTOCOL "http://" #define API_VERSION "v1" static const char url_register[] = "/agent/service/register"; static const char url_deregister[] = "/agent/service/deregister"; static const char url_discover[] = "/catalog/service"; static std::string make_url(const char* ip, int port, const char* url) { return asprintf(PROTOCOL "%s:%d/" API_VERSION "%s", ip, port, url); } static std::string make_ServiceID(consul_service_t* service) { return asprintf("%s-%s:%d", service->name, service->ip, service->port); } /* { "ID": "redis1", "Name": "redis", "Tags": [ "primary", "v1" ], "Address": "127.0.0.1", "Port": 8000, "Meta": { "redis_version": "4.0" }, "EnableTagOverride": false, "Check": { "DeregisterCriticalServiceAfter": "90m", "Args": ["/usr/local/bin/check_redis.py"], "HTTP": "http://localhost:5000/health", "Interval": "10s", "TTL": "15s" }, "Weights": { "Passing": 10, "Warning": 1 } } */ int register_service(consul_node_t* node, consul_service_t* service, consul_health_t* health) { HttpRequest req; req.method = HTTP_PUT; req.url = make_url(node->ip, node->port, url_register); req.content_type = APPLICATION_JSON; json jservice; jservice["Name"] = service->name; if (*service->ip) { jservice["Address"] = service->ip; } jservice["Port"] = service->port; jservice["ID"] = make_ServiceID(service); json jcheck; if (*health->url == '\0') { snprintf(health->url, sizeof(health->url), "%s:%d", service->ip, service->port); } jcheck[health->protocol] = health->url; jcheck["Interval"] = asprintf("%dms", health->interval); jcheck["DeregisterCriticalServiceAfter"] = asprintf("%dms", health->interval * 3); jservice["Check"] = jcheck; req.body = jservice.dump(); printd("PUT %s\n", req.url.c_str()); printd("%s\n", req.body.c_str()); HttpResponse res; int ret = http_client_send(&req, &res); printd("%s\n", res.body.c_str()); return ret; } int deregister_service(consul_node_t* node, consul_service_t* service) { std::string url = make_url(node->ip, node->port, url_deregister); url += '/'; url += make_ServiceID(service); HttpRequest req; req.method = HTTP_PUT; req.url = url; req.content_type = APPLICATION_JSON; printd("PUT %s\n", req.url.c_str()); HttpResponse res; int ret = http_client_send(&req, &res); printd("%s\n", res.body.c_str()); return ret; } int discover_services(consul_node_t* node, const char* service_name, std::vector& services) { std::string url = make_url(node->ip, node->port, url_discover); url += '/'; url += service_name; HttpRequest req; req.method = HTTP_GET; req.url = url; HttpResponse res; printd("GET %s\n", req.url.c_str()); int ret = http_client_send(&req, &res); if (ret != 0) return ret; printd("%s\n", res.body.c_str()); json jroot = json::parse(res.body); if (!jroot.is_array()) return -1; if (jroot.size() == 0) return 0; consul_service_t service; std::string name, ip; services.clear(); for (size_t i = 0; i < jroot.size(); ++i) { auto jservice = jroot[i]; name = jservice["ServiceName"]; if (jservice.contains("Address")) { ip = jservice["Address"]; } else if (jservice.contains("ServiceAddress")) { ip = jservice["ServiceAddress"]; } else if (jservice.contains("ServiceAddress6")) { ip = jservice["ServiceAddress6"]; } else { continue; } int port = jservice["ServicePort"]; strncpy(service.name, name.c_str(), sizeof(service.name)); strncpy(service.ip, ip.c_str(), sizeof(service.ip)); service.port = port; services.emplace_back(service); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/consul/consul.h000066400000000000000000000022251520575453600302430ustar00rootroot00000000000000#ifndef CONSUL_H_ #define CONSUL_H_ #include #include typedef struct consul_node_s { // node char ip[64]; int port; consul_node_s() { strcpy(ip, "127.0.0.1"); port = 8500; } } consul_node_t; typedef struct consul_service_s { // service char name[64]; char ip[64]; int port; consul_service_s() { name[0] = '\0'; strcpy(ip, "127.0.0.1"); port = 0; } } consul_service_t; typedef struct consul_health_s { // check char protocol[32]; // TCP,HTTP char url[256]; char status[32]; // any,passing,warning,critical int interval; // ms int timeout; // ms consul_health_s() { strcpy(protocol, "TCP"); url[0] = '\0'; strcpy(status, "passing"); interval = 10000; timeout = 3000; } } consul_health_t; int register_service(consul_node_t* node, consul_service_t* service, consul_health_t* health); int deregister_service(consul_node_t* node, consul_service_t* service); int discover_services(consul_node_t* node, const char* service_name, std::vector& services); #endif // CONSUL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/consul/main.cpp000066400000000000000000000034761520575453600302300ustar00rootroot00000000000000#include #include #include #include "consul.h" int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: consul_cli subcmd ServiceName [ServiceAddress ServicePort] [NodeIP NodePort]\n"); printf("subcmd=[register,deregister,discover]\n"); return -10; } const char* subcmd = argv[1]; const char* ServiceName = argv[2]; const char* ServiceAddress = "127.0.0.1"; int ServicePort = 0; const char* NodeIP = "127.0.0.1"; int NodePort = 8500; if (argc > 3) { ServiceAddress = argv[3]; } if (argc > 4) { ServicePort = atoi(argv[4]); } if (argc > 5) { NodeIP = argv[5]; } if (argc > 6) { NodePort = atoi(argv[6]); } consul_node_t node; strncpy(node.ip, NodeIP, sizeof(node.ip)); node.port = NodePort; consul_service_t service; strncpy(service.name, ServiceName, sizeof(service.name)); strncpy(service.ip, ServiceAddress, sizeof(service.ip)); service.port = ServicePort; consul_health_t health; if (strcmp(subcmd, "register") == 0) { int ret = register_service(&node, &service, &health); printf("register_service retval=%d\n", ret); goto discover; } else if (strcmp(subcmd, "deregister") == 0) { int ret = deregister_service(&node, &service); printf("deregister_service retval=%d\n", ret); goto discover; } else if (strcmp(subcmd, "discover") == 0) { discover: std::vector services; discover_services(&node, ServiceName, services); for (auto& service : services) { printf("name=%s ip=%s port=%d\n", service.name, service.ip, service.port); } } else { printf("subcmd error!\n"); return -20; } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/curl.cpp000066400000000000000000000234521520575453600267420ustar00rootroot00000000000000/* * @build: make examples * @server bin/httpd -s restart -d * @usage: bin/curl -v www.baidu.com * bin/curl -v 127.0.0.1:8080 * bin/curl -v 127.0.0.1:8080/ping * bin/curl -v 127.0.0.1:8080/echo -d 'hello,world!' */ #include "HttpClient.h" #include "hurl.h" #ifdef _MSC_VER #include "misc/win32_getopt.h" #else #include #endif static bool verbose = false; static const char* method = NULL; static const char* url = "/"; static int http_version = 1; static int grpc = 0; static int send_count = 1; static int retry_count = 0; static int retry_delay = 3; static int timeout = 0; static int lopt = 0; static const char* http_proxy = NULL; static const char* https_proxy = NULL; static const char* no_proxy = NULL; static const char* options = "hVvX:H:r:d:F:n:"; static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"verion", no_argument, NULL, 'V'}, {"verbose", no_argument, NULL, 'v'}, {"method", required_argument, NULL, 'X'}, {"header", required_argument, NULL, 'H'}, {"range", required_argument, NULL, 'r'}, {"data", required_argument, NULL, 'd'}, {"form", required_argument, NULL, 'F'}, {"count", required_argument, NULL, 'n'}, {"http2", no_argument, &http_version, 2}, {"grpc", no_argument, &grpc, 1}, \ {"http-proxy", required_argument, &lopt, 1}, {"https-proxy", required_argument, &lopt, 2}, {"no-proxy", required_argument, &lopt, 3}, {"retry", required_argument, &lopt, 4}, {"delay", required_argument, &lopt, 5}, {"timeout", required_argument, &lopt, 6}, \ {NULL, 0, NULL, 0} }; static const char* help = R"(Options: -h|--help Print this message. -V|--version Print version. -v|--verbose Show verbose infomation. -X|--method Set http method. -H|--header Add http header, -H "Content-Type: application/json" -r|--range Add http header Range:bytes=0-1023 -d|--data Set http body. -F|--form Set http form, -F "name=value" -F "file=@filename" -n|--count Send request count, used for test keep-alive --http2 Use http2 --grpc Use grpc over http2 --http-proxy Set http proxy --https-proxy Set https proxy --no-proxy Set no proxy --retry Set fail retry count --timeout Set timeout, unit(s) Examples: curl -v GET httpbin.org/get curl -v POST httpbin.org/post user=admin pswd=123456 curl -v PUT httpbin.org/put user=admin pswd=123456 curl -v localhost:8080 curl -v localhost:8080 -r 0-9 curl -v localhost:8080/ping curl -v localhost:8080/query?page_no=1\&page_size=10 curl -v localhost:8080/echo hello,world! curl -v localhost:8080/kv user=admin\&pswd=123456 curl -v localhost:8080/json user=admin pswd=123456 curl -v localhost:8080/form -F file=@filename curl -v localhost:8080/upload @filename )"; static void print_usage() { fprintf(stderr, "Usage: curl [%s] [METHOD] url [header_field:header_value] [body_key=body_value]\n", options); } static void print_version() { fprintf(stderr, "curl version 1.0.0\n"); } static void print_help() { print_usage(); puts(help); print_version(); } static bool is_upper_string(const char* str) { const char* p = str; while (*p >= 'A' && *p <= 'Z') ++p; return *p == '\0'; } static int parse_data(char* arg, HttpRequest* req) { char* pos = NULL; // @filename if (arg[0] == '@') { req->File(arg + 1); return 0; } // k1=v1&k2=v2 hv::KeyValue kvs = hv::splitKV(arg, '&', '='); if (kvs.size() >= 2) { if (req->ContentType() == CONTENT_TYPE_NONE) { req->content_type = X_WWW_FORM_URLENCODED; } for (auto& kv : kvs) { req->Set(kv.first.c_str(), kv.second); } return 0; } // k=v if ((pos = strchr(arg, '=')) != NULL) { *pos = '\0'; if (pos[1] == '@') { // file=@filename req->content_type = MULTIPART_FORM_DATA; req->SetFormFile(optarg, pos + 2); } else { if (req->ContentType() == CONTENT_TYPE_NONE) { req->content_type = APPLICATION_JSON; } req->Set(arg, pos + 1); } return 0; } if (req->ContentType() == CONTENT_TYPE_NONE) { req->content_type = TEXT_PLAIN; } req->body = arg; return 0; } static int parse_cmdline(int argc, char* argv[], HttpRequest* req) { int opt; int opt_idx; char* pos = NULL; while ((opt = getopt_long(argc, argv, options, long_options, &opt_idx)) != EOF) { switch(opt) { case 'h': print_help(); exit(0); case 'V': print_version(); exit(0); case 'v': verbose = true; break; case 'X': method = optarg; break; case 'H': // -H "Content-Type: application/json" pos = strchr(optarg, ':'); if (pos) { *pos = '\0'; req->headers[optarg] = hv::trim(pos + 1); *pos = ':'; } break; case 'r': req->headers["Range"] = std::string("bytes=").append(optarg); break; case 'd': parse_data(optarg, req); break; case 'F': pos = strchr(optarg, '='); if (pos) { req->content_type = MULTIPART_FORM_DATA; *pos = '\0'; if (pos[1] == '@') { // -F file=@filename req->SetFormFile(optarg, pos + 2); } else { // -F name=value req->SetFormData(optarg, pos + 1); } *pos = '='; } break; case 'n': send_count = atoi(optarg); break; case 0 : { switch (lopt) { case 1: http_proxy = optarg; break; case 2: https_proxy = optarg; break; case 3: no_proxy = optarg; break; case 4: retry_count = atoi(optarg);break; case 5: retry_delay = atoi(optarg);break; case 6: timeout = atoi(optarg);break; default: break; } } default: break; } } if (optind == argc) { fprintf(stderr, "Missing url\n"); print_usage(); exit(-1); } if (is_upper_string(argv[optind])) { method = argv[optind++]; } url = argv[optind++]; for (int d = optind; d < argc; ++d) { char* arg = argv[d]; if ((pos = strchr(arg, ':')) != NULL) { *pos = '\0'; req->headers[arg] = pos + 1; } else { parse_data(arg, req); } } // --grpc if (grpc) { http_version = 2; req->content_type = APPLICATION_GRPC; } // --http2 if (http_version == 2) { req->http_major = 2; req->http_minor = 0; } // --timeout if (timeout > 0) { req->timeout = timeout; } return 0; } int main(int argc, char* argv[]) { if (argc < 2) { print_usage(); return 0; } int ret = 0; HttpRequest req; parse_cmdline(argc, argv, &req); if (method) { req.method = http_method_enum(method); } else { req.DumpBody(); if (req.body.empty()) { req.method = HTTP_GET; } else { req.method = HTTP_POST; } } req.url = hv::escapeURL(url); req.http_cb = [](HttpMessage* res, http_parser_state state, const char* data, size_t size) { if (state == HP_HEADERS_COMPLETE) { if (verbose) { fprintf(stderr, "%s", res->Dump(true, false).c_str()); } } else if (state == HP_BODY) { if (data && size) { printf("%.*s", (int)size, data); // This program no need to save data to body. // res->body.append(data, size); } } }; hv::HttpClient cli; // http_proxy if (http_proxy) { hv::StringList ss = hv::split(http_proxy, ':'); const char* host = ss[0].c_str(); int port = ss.size() == 2 ? hv::from_string(ss[1]) : DEFAULT_HTTP_PORT; fprintf(stderr, "* http_proxy=%s:%d\n", host, port); cli.setHttpProxy(host, port); } // https_proxy if (https_proxy) { hv::StringList ss = hv::split(https_proxy, ':'); const char* host = ss[0].c_str(); int port = ss.size() == 2 ? hv::from_string(ss[1]) : DEFAULT_HTTPS_PORT; fprintf(stderr, "* https_proxy=%s:%d\n", host, port); cli.setHttpsProxy(host, port); } // no_proxy if (no_proxy) { hv::StringList ss = hv::split(no_proxy, ','); fprintf(stderr, "* no_proxy="); for (const auto& s : ss) { fprintf(stderr, "%s,", s.c_str()); cli.addNoProxy(s.c_str()); } fprintf(stderr, "\n"); } send: if (verbose) { fprintf(stderr, "%s\n", req.Dump(true, true).c_str()); } HttpResponse res; ret = cli.send(&req, &res); if (ret != 0) { fprintf(stderr, "* Failed:%s:%d\n", http_client_strerror(ret), ret); if (retry_count > 0) { fprintf(stderr, "\nretry again later...%d\n", retry_count); --retry_count; hv_sleep(retry_delay); goto send; } } if (--send_count > 0) { fprintf(stderr, "\nsend again later...%d\n", send_count); hv_sleep(retry_delay); goto send; } return ret; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/hloop_test.c000066400000000000000000000067071520575453600276210ustar00rootroot00000000000000/* * @build: make examples * @usage: bin/hloop_test * bin/nc 127.0.0.1 10514 * nc 127.0.0.1 10514 * */ #include "hloop.h" #include "hbase.h" #include "hlog.h" #include "nlog.h" void mylogger(int loglevel, const char* buf, int len) { if (loglevel >= LOG_LEVEL_ERROR) { stderr_logger(loglevel, buf, len); } if (loglevel >= LOG_LEVEL_INFO) { file_logger(loglevel, buf, len); } network_logger(loglevel, buf, len); } void on_idle(hidle_t* idle) { printf("on_idle: event_id=%llu\tpriority=%d\tuserdata=%ld\n", LLU(hevent_id(idle)), hevent_priority(idle), (long)(intptr_t)(hevent_userdata(idle))); } void on_timer(htimer_t* timer) { hloop_t* loop = hevent_loop(timer); printf("on_timer: event_id=%llu\tpriority=%d\tuserdata=%ld\ttime=%llus\thrtime=%lluus\n", LLU(hevent_id(timer)), hevent_priority(timer), (long)(intptr_t)(hevent_userdata(timer)), LLU(hloop_now(loop)), LLU(hloop_now_hrtime(loop))); } void cron_minutely(htimer_t* timer) { time_t now = time(NULL); printf("cron_minutely: %s\n", ctime(&now)); } void cron_hourly(htimer_t* timer) { time_t now = time(NULL); printf("cron_hourly: %s\n", ctime(&now)); } void timer_write_log(htimer_t* timer) { static int cnt = 0; hlogd("[%d] Do you recv me?", ++cnt); hlogi("[%d] Do you recv me?", ++cnt); hloge("[%d] Do you recv me?", ++cnt); } void on_stdin(hio_t* io, void* buf, int readbytes) { printf("on_stdin fd=%d readbytes=%d\n", hio_fd(io), readbytes); printf("> %s\n", (char*)buf); if (strncmp((char*)buf, "quit", 4) == 0) { hloop_stop(hevent_loop(io)); } } void on_custom_events(hevent_t* ev) { printf("on_custom_events event_type=%d userdata=%ld\n", (int)ev->event_type, (long)(intptr_t)ev->userdata); } void on_signal(hsignal_t* sig) { printf("on_signal signo=%d\n", (int)hevent_id(sig)); hloop_stop(hevent_loop(sig)); } int main() { // memcheck atexit HV_MEMCHECK; hloop_t* loop = hloop_new(0); // test idle and priority for (int i = HEVENT_LOWEST_PRIORITY; i <= HEVENT_HIGHEST_PRIORITY; ++i) { hidle_t* idle = hidle_add(loop, on_idle, 10); hevent_set_priority(idle, i); } // test timer timeout for (int i = 1; i <= 10; ++i) { htimer_t* timer = htimer_add(loop, on_timer, i*1000, 3); hevent_set_userdata(timer, (void*)(intptr_t)i); } // test timer period int minute = time(NULL)%3600/60; htimer_add_period(loop, cron_minutely, -1, -1, -1, -1, -1, INFINITE); htimer_add_period(loop, cron_hourly, minute+1, -1, -1, -1, -1, INFINITE); // test signal: enter Ctrl-C to trigger hsignal_add(loop, on_signal, SIGINT); // test network_logger htimer_add(loop, timer_write_log, 1000, INFINITE); hlog_set_handler(mylogger); hlog_set_file("loop.log"); hlog_set_format(DEFAULT_LOG_FORMAT); #ifndef _MSC_VER logger_enable_color(hlog, 1); #endif nlog_listen(loop, DEFAULT_LOG_PORT); // test nonblock stdin printf("input 'quit' to quit loop\n"); char buf[64]; hread(loop, 0, buf, sizeof(buf), on_stdin); // test custom_events for (int i = 0; i < 10; ++i) { hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.event_type = (hevent_type_e)(HEVENT_TYPE_CUSTOM + i); ev.cb = on_custom_events; ev.userdata = (void*)(intptr_t)i; hloop_post_event(loop, &ev); } hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/hmain_test.cpp000066400000000000000000000147671520575453600301410ustar00rootroot00000000000000#include "hv.h" #include "hmain.h" #include "iniparser.h" /* * @build: make examples * @usage: bin/hmain_test -h * bin/hmain_test -v * * bin/hmain_test -c etc/hmain_test.conf -d * ps aux | grep hmain_test * * bin/hmain_test -s stop * ps aux | grep hmain_test * */ typedef struct conf_ctx_s { IniParser* parser; int loglevel; int worker_processes; int worker_threads; int port; } conf_ctx_t; conf_ctx_t g_conf_ctx; inline void conf_ctx_init(conf_ctx_t* ctx) { ctx->parser = new IniParser; ctx->loglevel = LOG_LEVEL_DEBUG; ctx->worker_processes = 0; ctx->worker_threads = 0; ctx->port = 0; } static void print_version(); static void print_help(); static int parse_confile(const char* confile); static void worker_fn(void* userdata); // long options static const option_t long_options[] = { {'h', "help", NO_ARGUMENT, "Print this information"}, {'v', "version", NO_ARGUMENT, "Print version"}, {'c', "confile", REQUIRED_ARGUMENT, "Set configure file, default etc/{program}.conf"}, {'t', "test", NO_ARGUMENT, "Test configure file and exit"}, {'s', "signal", REQUIRED_ARGUMENT, "send signal to process, signal=[start,stop,restart,status,reload]"}, {'d', "daemon", NO_ARGUMENT, "Daemonize"}, {'p', "port", REQUIRED_ARGUMENT, "Set listen port"} }; void print_version() { printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); } void print_help() { char detail_options[1024] = {0}; dump_opt_long(long_options, ARRAY_SIZE(long_options), detail_options, sizeof(detail_options)); printf("%s\n", detail_options); } int parse_confile(const char* confile) { int ret = g_conf_ctx.parser->LoadFromFile(confile); if (ret != 0) { printf("Load confile [%s] failed: %d\n", confile, ret); exit(-40); } // logfile std::string str = g_conf_ctx.parser->GetValue("logfile"); if (!str.empty()) { strncpy(g_main_ctx.logfile, str.c_str(), sizeof(g_main_ctx.logfile)); } hlog_set_file(g_main_ctx.logfile); // loglevel str = g_conf_ctx.parser->GetValue("loglevel"); if (!str.empty()) { hlog_set_level_by_str(str.c_str()); } // log_filesize str = g_conf_ctx.parser->GetValue("log_filesize"); if (!str.empty()) { hlog_set_max_filesize_by_str(str.c_str()); } // log_remain_days str = g_conf_ctx.parser->GetValue("log_remain_days"); if (!str.empty()) { hlog_set_remain_days(atoi(str.c_str())); } // log_fsync str = g_conf_ctx.parser->GetValue("log_fsync"); if (!str.empty()) { logger_enable_fsync(hlog, hv_getboolean(str.c_str())); } // first log here hlogi("%s version: %s", g_main_ctx.program_name, hv_compile_version()); hlog_fsync(); // worker_processes int worker_processes = 0; #ifdef DEBUG // Disable multi-processes mode for debugging worker_processes = 0; #else str = g_conf_ctx.parser->GetValue("worker_processes"); if (str.size() != 0) { if (strcmp(str.c_str(), "auto") == 0) { worker_processes = get_ncpu(); hlogd("worker_processes=ncpu=%d", worker_processes); } else { worker_processes = atoi(str.c_str()); } } #endif g_conf_ctx.worker_processes = LIMIT(0, worker_processes, MAXNUM_WORKER_PROCESSES); // worker_threads int worker_threads = 0; str = g_conf_ctx.parser->GetValue("worker_threads"); if (str.size() != 0) { if (strcmp(str.c_str(), "auto") == 0) { worker_threads = get_ncpu(); hlogd("worker_threads=ncpu=%d", worker_threads); } else { worker_threads = atoi(str.c_str()); } } g_conf_ctx.worker_threads = LIMIT(0, worker_threads, 64); // port int port = 0; const char* szPort = get_arg("p"); if (szPort) { port = atoi(szPort); } if (port == 0) { port = g_conf_ctx.parser->Get("port"); } if (port == 0) { printf("Please config listen port!\n"); exit(-10); } g_conf_ctx.port = port; hlogi("parse_confile('%s') OK", confile); return 0; } static void on_reload(void* userdata) { hlogi("reload confile [%s]", g_main_ctx.confile); parse_confile(g_main_ctx.confile); } int main(int argc, char** argv) { // g_main_ctx main_ctx_init(argc, argv); if (argc == 1) { print_help(); exit(10); } int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); if (ret != 0) { print_help(); exit(ret); } /* printf("---------------arg------------------------------\n"); printf("%s\n", g_main_ctx.cmdline); for (int i = 0; i < g_main_ctx.arg_kv_size; ++i) { printf("%s\n", g_main_ctx.arg_kv[i]); } for (int i = 0; i < g_main_ctx.arg_list_size; ++i) { printf("%s\n", g_main_ctx.arg_list[i]); } printf("================================================\n"); printf("---------------env------------------------------\n"); for (int i = 0; i < g_main_ctx.envc; ++i) { printf("%s\n", g_main_ctx.save_envp[i]); } printf("================================================\n"); */ // help if (get_arg("h")) { print_help(); exit(0); } // version if (get_arg("v")) { print_version(); exit(0); } // g_conf_ctx conf_ctx_init(&g_conf_ctx); const char* confile = get_arg("c"); if (confile) { strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile)); } parse_confile(g_main_ctx.confile); // test if (get_arg("t")) { printf("Test confile [%s] OK!\n", g_main_ctx.confile); exit(0); } // signal signal_init(on_reload); const char* signal = get_arg("s"); if (signal) { signal_handle(signal); } #ifdef OS_UNIX // daemon if (get_arg("d")) { // nochdir, noclose int ret = daemon(1, 1); if (ret != 0) { printf("daemon error: %d\n", ret); exit(-10); } } #endif // pidfile create_pidfile(); master_workers_run(worker_fn, (void*)(intptr_t)g_conf_ctx.port, g_conf_ctx.worker_processes, g_conf_ctx.worker_threads); return 0; } void worker_fn(void* userdata) { long port = (long)(intptr_t)(userdata); while (1) { printf("port=%ld pid=%ld tid=%ld\n", port, hv_getpid(), hv_gettid()); hv_delay(60000); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/htimer_test.c000066400000000000000000000033751520575453600277660ustar00rootroot00000000000000#include "hloop.h" #include "hbase.h" void on_timer(htimer_t* timer) { printf("time=%llus on_timer\n", LLU(hloop_now(hevent_loop(timer)))); } // test htimer_add void on_timer_add(htimer_t* timer) { printf("time=%llus on_timer_add\n", LLU(hloop_now(hevent_loop(timer)))); htimer_add(hevent_loop(timer), on_timer_add, 1000, 1); } // test htimer_del void on_timer_del(htimer_t* timer) { printf("time=%llus on_timer_del\n", LLU(hloop_now(hevent_loop(timer)))); htimer_del(timer); } // test htimer_reset void on_timer_reset(htimer_t* timer) { printf("time=%llus on_timer_reset\n", LLU(hloop_now(hevent_loop(timer)))); htimer_reset((htimer_t*)hevent_userdata(timer), 0); } // test hloop_stop void on_timer_quit(htimer_t* timer) { printf("time=%llus on_timer_quit\n", LLU(hloop_now(hevent_loop(timer)))); hloop_stop(hevent_loop(timer)); } // test cron void cron_hourly(htimer_t* timer) { time_t tt = time(NULL); printf("time=%llus cron_hourly: %s\n", LLU(hloop_now(hevent_loop(timer))), ctime(&tt)); } int main() { HV_MEMCHECK; hloop_t* loop = hloop_new(0); htimer_add(loop, on_timer_add, 1000, 1); htimer_add(loop, on_timer_del, 1000, 10); htimer_t* reseted = htimer_add(loop, on_timer, 5000, 1); htimer_t* reset = htimer_add(loop, on_timer_reset, 1000, 5); hevent_set_userdata(reset, reseted); // cron_hourly next triggered in one minute int minute = time(NULL)%3600/60; htimer_add_period(loop, cron_hourly, minute+1, -1, -1, -1, -1, INFINITE); // quit application after 1 min htimer_add(loop, on_timer_quit, 60000, 1); printf("time=%llus begin\n", LLU(hloop_now(loop))); hloop_run(loop); printf("time=%llus stop\n", LLU(hloop_now(loop))); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/http_client_test.cpp000066400000000000000000000122001520575453600313360ustar00rootroot00000000000000/* * @build make examples * * @server bin/http_server_test 8080 * * @client bin/http_client_test * */ #include "requests.h" #include "axios.h" using namespace hv; #include "hthread.h" // import hv_gettid static void test_http_async_client(HttpClient* cli, int* resp_cnt) { printf("test_http_async_client request thread tid=%ld\n", hv_gettid()); auto req = std::make_shared(); req->method = HTTP_POST; req->url = "http://127.0.0.1:8080/echo"; req->headers["Connection"] = "keep-alive"; req->body = "This is an async request."; req->timeout = 10; cli->sendAsync(req, [resp_cnt](const HttpResponsePtr& resp) { printf("test_http_async_client response thread tid=%ld\n", hv_gettid()); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } *resp_cnt += 1; }); } static void test_http_sync_client(HttpClient* cli) { HttpRequest req; req.method = HTTP_POST; req.url = "http://127.0.0.1:8080/echo"; req.headers["Connection"] = "keep-alive"; req.body = "This is a sync request."; req.timeout = 10; HttpResponse resp; int ret = cli->send(&req, &resp); if (ret != 0) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp.status_code, resp.status_message()); printf("%s\n", resp.body.c_str()); } } static void test_requests() { // auto resp = requests::get("http://www.example.com"); // // make clean && make WITH_OPENSSL=yes // auto resp = requests::get("https://www.baidu.com"); auto resp = requests::get("http://127.0.0.1:8080/ping"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } // Content-Type: application/json hv::Json jroot; jroot["user"] = "admin"; jroot["pswd"] = "123456"; http_headers headers; headers["Content-Type"] = "application/json"; resp = requests::post("http://127.0.0.1:8080/echo", jroot.dump(), headers); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } // Content-Type: multipart/form-data std::map params; params["user"] = "admin"; params["pswd"] = "123456"; resp = requests::uploadFormFile("http://127.0.0.1:8080/echo", "avatar", "avatar.jpg", params); if (resp == NULL) { printf("uploadFormFile failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } /* size_t filesize = requests::downloadFile("http://www.example.com/index.html", "index.html"); if (filesize == 0) { printf("downloadFile failed!\n"); } else { printf("downloadFile success!\n"); } */ // async /* // auto req = std::make_shared(); req->url = "http://127.0.0.1:8080/echo"; req->method = HTTP_POST; req->body = "This is an async request."; req->timeout = 10; requests::async(req, [](const HttpResponsePtr& resp) { if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } }); */ } static void test_axios() { const char* strReq = R"( { "method": "POST", "url": "http://127.0.0.1:8080/echo", "timeout": 10, "params": { "page_no": "1", "page_size": "10" }, "headers": { "Content-Type": "application/json" }, "body": { "app_id": "123456", "app_secret": "abcdefg" } } )"; // sync auto resp = axios::axios(strReq); // auto resp = axios::post("http://127.0.0.1:8080/echo", strReq); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } // async /* axios::axios(strReq, [](const HttpResponsePtr& resp) { if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } }); */ } int main(int argc, char* argv[]) { int req_cnt = 0; if (argc > 1) req_cnt = atoi(argv[1]); if (req_cnt == 0) req_cnt = 1; HttpClient sync_client; HttpClient async_client; int resp_cnt = 0; for (int i = 0; i < req_cnt; ++i) { test_http_async_client(&async_client, &resp_cnt); test_http_sync_client(&sync_client); test_requests(); test_axios(); } // demo wait async finished while (resp_cnt < req_cnt) hv_delay(100); printf("finished!\n"); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/http_server_test.cpp000066400000000000000000000071171520575453600314010ustar00rootroot00000000000000/* * sample http server * more detail see examples/httpd * */ #include "HttpServer.h" #include "hthread.h" // import hv_gettid #include "hasync.h" // import hv::async using namespace hv; /* * #define TEST_HTTPS 1 * * @build ./configure --with-openssl && make clean && make * * @server bin/http_server_test 8080 * * @client curl -v http://127.0.0.1:8080/ping * curl -v https://127.0.0.1:8443/ping --insecure * bin/curl -v http://127.0.0.1:8080/ping * bin/curl -v https://127.0.0.1:8443/ping * */ #define TEST_HTTPS 0 int main(int argc, char** argv) { HV_MEMCHECK; int port = 0; if (argc > 1) { port = atoi(argv[1]); } if (port == 0) port = 8080; HttpService router; /* Static file service */ // curl -v http://ip:port/ router.Static("/", "./html"); /* Forward proxy service */ router.EnableForwardProxy(); // curl -v http://httpbin.org/get --proxy http://127.0.0.1:8080 router.AddTrustProxy("*httpbin.org"); /* Reverse proxy service */ // curl -v http://ip:port/httpbin/get router.Proxy("/httpbin/", "http://httpbin.org/"); /* API handlers */ // curl -v http://ip:port/ping router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { return resp->String("pong"); }); // curl -v http://ip:port/data router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { static char data[] = "0123456789"; return resp->Data(data, 10 /*, false */); }); // curl -v http://ip:port/paths router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { return resp->Json(router.Paths()); }); // curl -v http://ip:port/get?env=1 router.GET("/get", [](const HttpContextPtr& ctx) { hv::Json resp; resp["origin"] = ctx->ip(); resp["url"] = ctx->url(); resp["args"] = ctx->params(); resp["headers"] = ctx->headers(); return ctx->send(resp.dump(2)); }); // curl -v http://ip:port/echo -d "hello,world!" router.POST("/echo", [](const HttpContextPtr& ctx) { return ctx->send(ctx->body(), ctx->type()); }); // curl -v http://ip:port/user/123 router.GET("/user/{id}", [](const HttpContextPtr& ctx) { hv::Json resp; resp["id"] = ctx->param("id"); return ctx->send(resp.dump(2)); }); // curl -v http://ip:port/async router.GET("/async", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { writer->Begin(); writer->WriteHeader("X-Response-tid", hv_gettid()); writer->WriteHeader("Content-Type", "text/plain"); writer->WriteBody("This is an async response.\n"); writer->End(); }); // middleware router.AllowCORS(); router.Use([](HttpRequest* req, HttpResponse* resp) { resp->SetHeader("X-Request-tid", hv::to_string(hv_gettid())); return HTTP_STATUS_NEXT; }); HttpServer server; server.service = &router; server.port = port; #if TEST_HTTPS server.https_port = 8443; hssl_ctx_opt_t param; memset(¶m, 0, sizeof(param)); param.crt_file = "cert/server.crt"; param.key_file = "cert/server.key"; param.endpoint = HSSL_SERVER; if (server.newSslCtx(¶m) != 0) { fprintf(stderr, "new SSL_CTX failed!\n"); return -20; } #endif // uncomment to test multi-processes // server.setProcessNum(4); // uncomment to test multi-threads // server.setThreadNum(4); server.start(); // press Enter to stop while (getchar() != '\n'); hv::async::cleanup(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/000077500000000000000000000000001520575453600264065ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/handler.cpp000066400000000000000000000305511520575453600305330ustar00rootroot00000000000000#include "handler.h" #include // import std::thread #include // import std::chrono #include "hbase.h" #include "htime.h" #include "hfile.h" #include "hstring.h" #include "EventLoop.h" // import setTimeout, setInterval int Handler::preprocessor(HttpRequest* req, HttpResponse* resp) { // printf("%s:%d\n", req->client_addr.ip.c_str(), req->client_addr.port); // printf("%s\n", req->Dump(true, true).c_str()); #if REDIRECT_HTTP_TO_HTTPS // 301 if (req->scheme == "http") { std::string location = hv::asprintf("https://%s:%d%s", req->host.c_str(), 8443, req->path.c_str()); return resp->Redirect(location, HTTP_STATUS_MOVED_PERMANENTLY); } #endif // Unified verification request Content-Type? // if (req->content_type != APPLICATION_JSON) { // return response_status(resp, HTTP_STATUS_BAD_REQUEST); // } // Deserialize request body to json, form, etc. req->ParseBody(); // Unified setting response Content-Type? resp->content_type = APPLICATION_JSON; return HTTP_STATUS_NEXT; } int Handler::postprocessor(HttpRequest* req, HttpResponse* resp) { // printf("%s\n", resp->Dump(true, true).c_str()); return resp->status_code; } int Handler::errorHandler(const HttpContextPtr& ctx) { int error_code = ctx->response->status_code; return response_status(ctx, error_code); } int Handler::Authorization(HttpRequest* req, HttpResponse* resp) { // authentication sample code if (strcmp(req->path.c_str(), "/login") == 0) { return HTTP_STATUS_NEXT; } std::string token = req->GetHeader("Authorization"); if (token.empty()) { response_status(resp, 10011, "Miss Authorization header!"); return HTTP_STATUS_UNAUTHORIZED; } else if (strcmp(token.c_str(), "abcdefg") != 0) { response_status(resp, 10012, "Authorization failed!"); return HTTP_STATUS_UNAUTHORIZED; } return HTTP_STATUS_NEXT; } int Handler::sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { writer->WriteHeader("X-Response-tid", hv_gettid()); unsigned long long start_ms = gettimeofday_ms(); writer->response->Set("start_ms", start_ms); std::string strTime = req->GetParam("t", "1000"); if (!strTime.empty()) { int ms = atoi(strTime.c_str()); if (ms > 0) { hv_delay(ms); } } unsigned long long end_ms = gettimeofday_ms(); writer->response->Set("end_ms", end_ms); writer->response->Set("cost_ms", end_ms - start_ms); response_status(writer, 0, "OK"); return 200; } int Handler::setTimeout(const HttpContextPtr& ctx) { unsigned long long start_ms = gettimeofday_ms(); ctx->set("start_ms", start_ms); std::string strTime = ctx->param("t", "1000"); if (!strTime.empty()) { int ms = atoi(strTime.c_str()); if (ms > 0) { hv::setTimeout(ms, [ctx, start_ms](hv::TimerID timerID){ unsigned long long end_ms = gettimeofday_ms(); ctx->set("end_ms", end_ms); ctx->set("cost_ms", end_ms - start_ms); response_status(ctx, 0, "OK"); }); } } return HTTP_STATUS_UNFINISHED; } int Handler::query(const HttpContextPtr& ctx) { // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] // ?query => HttpRequest::query_params for (auto& param : ctx->params()) { ctx->set(param.first.c_str(), param.second); } response_status(ctx, 0, "OK"); return 200; } int Handler::kv(HttpRequest* req, HttpResponse* resp) { if (req->content_type != APPLICATION_URLENCODED) { return response_status(resp, HTTP_STATUS_BAD_REQUEST); } resp->content_type = APPLICATION_URLENCODED; resp->kv = req->GetUrlEncoded(); resp->SetUrlEncoded("int", 123); resp->SetUrlEncoded("float", 3.14); resp->SetUrlEncoded("string", "hello"); return 200; } int Handler::json(HttpRequest* req, HttpResponse* resp) { if (req->content_type != APPLICATION_JSON) { return response_status(resp, HTTP_STATUS_BAD_REQUEST); } resp->content_type = APPLICATION_JSON; resp->json = req->GetJson(); resp->json["int"] = 123; resp->json["float"] = 3.14; resp->json["string"] = "hello"; return 200; } int Handler::form(HttpRequest* req, HttpResponse* resp) { if (req->content_type != MULTIPART_FORM_DATA) { return response_status(resp, HTTP_STATUS_BAD_REQUEST); } resp->content_type = MULTIPART_FORM_DATA; resp->form = req->GetForm(); resp->SetFormData("int", 123); resp->SetFormData("float", 3.14); resp->SetFormData("string", "hello"); // resp->SetFormFile("file", "test.jpg"); return 200; } int Handler::grpc(HttpRequest* req, HttpResponse* resp) { if (req->content_type != APPLICATION_GRPC) { return response_status(resp, HTTP_STATUS_BAD_REQUEST); } // parse protobuf // ParseFromString(req->body); // resp->content_type = APPLICATION_GRPC; // serailize protobuf // resp->body = SerializeAsString(xxx); response_status(resp, 0, "OK"); return 200; } int Handler::test(const HttpContextPtr& ctx) { ctx->setContentType(ctx->type()); ctx->set("bool", ctx->get("bool")); ctx->set("int", ctx->get("int")); ctx->set("float", ctx->get("float")); ctx->set("string", ctx->get("string")); response_status(ctx, 0, "OK"); return 200; } int Handler::restful(const HttpContextPtr& ctx) { // RESTful /:field/ => HttpRequest::query_params // path=/group/:group_name/user/:user_id std::string group_name = ctx->param("group_name"); std::string user_id = ctx->param("user_id"); ctx->set("group_name", group_name); ctx->set("user_id", user_id); response_status(ctx, 0, "OK"); return 200; } int Handler::login(const HttpContextPtr& ctx) { std::string username = ctx->get("username"); std::string password = ctx->get("password"); if (username.empty() || password.empty()) { response_status(ctx, 10001, "Miss username or password"); return HTTP_STATUS_BAD_REQUEST; } else if (strcmp(username.c_str(), "admin") != 0) { response_status(ctx, 10002, "Username not exist"); return HTTP_STATUS_BAD_REQUEST; } else if (strcmp(password.c_str(), "123456") != 0) { response_status(ctx, 10003, "Password wrong"); return HTTP_STATUS_BAD_REQUEST; } else { ctx->set("token", "abcdefg"); response_status(ctx, 0, "OK"); return HTTP_STATUS_OK; } } int Handler::upload(const HttpContextPtr& ctx) { int status_code = 200; std::string save_path = "html/uploads/"; if (ctx->is(MULTIPART_FORM_DATA)) { status_code = ctx->request->SaveFormFile("file", save_path.c_str()); } else { std::string filename = ctx->param("filename", "unnamed.txt"); std::string filepath = save_path + filename; status_code = ctx->request->SaveFile(filepath.c_str()); } return response_status(ctx, status_code); } int Handler::recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size) { // printf("recvLargeFile state=%d\n", (int)state); int status_code = HTTP_STATUS_UNFINISHED; HFile* file = (HFile*)ctx->userdata; switch (state) { case HP_HEADERS_COMPLETE: { if (ctx->is(MULTIPART_FORM_DATA)) { // NOTE: You can use multipart_parser if you want to use multipart/form-data. ctx->close(); return HTTP_STATUS_BAD_REQUEST; } std::string save_path = "html/uploads/"; std::string filename = ctx->param("filename", "unnamed.txt"); std::string filepath = save_path + filename; file = new HFile; if (file->open(filepath.c_str(), "wb") != 0) { ctx->close(); return HTTP_STATUS_INTERNAL_SERVER_ERROR; } ctx->userdata = file; } break; case HP_BODY: { if (file && data && size) { if (file->write(data, size) != size) { ctx->close(); return HTTP_STATUS_INTERNAL_SERVER_ERROR; } } } break; case HP_MESSAGE_COMPLETE: { status_code = HTTP_STATUS_OK; ctx->setContentType(APPLICATION_JSON); response_status(ctx, status_code); if (file) { delete file; ctx->userdata = NULL; } } break; case HP_ERROR: { if (file) { file->remove(); delete file; ctx->userdata = NULL; } } break; default: break; } return status_code; } int Handler::sendLargeFile(const HttpContextPtr& ctx) { std::thread([ctx](){ ctx->writer->Begin(); std::string filepath = ctx->service->document_root + ctx->request->Path(); HFile file; if (file.open(filepath.c_str(), "rb") != 0) { ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND); ctx->writer->WriteHeader("Content-Type", "text/html"); ctx->writer->WriteBody("

404 Not Found

"); ctx->writer->End(); return; } http_content_type content_type = CONTENT_TYPE_NONE; const char* suffix = hv_suffixname(filepath.c_str()); if (suffix) { content_type = http_content_type_enum_by_suffix(suffix); } if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) { content_type = APPLICATION_OCTET_STREAM; } size_t filesize = file.size(); ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type)); #if USE_TRANSFER_ENCODING_CHUNKED ctx->writer->WriteHeader("Transfer-Encoding", "chunked"); #else ctx->writer->WriteHeader("Content-Length", filesize); #endif ctx->writer->EndHeaders(); char* buf = NULL; int len = 40960; // 40K SAFE_ALLOC(buf, len); size_t total_readbytes = 0; int last_progress = 0; int sleep_ms_per_send = 0; if (ctx->service->limit_rate <= 0) { // unlimited } else { sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate; } if (sleep_ms_per_send == 0) sleep_ms_per_send = 1; int sleep_ms = sleep_ms_per_send; auto start_time = std::chrono::steady_clock::now(); auto end_time = start_time; while (total_readbytes < filesize) { if (!ctx->writer->isConnected()) { break; } if (!ctx->writer->isWriteComplete()) { hv_delay(1); continue; } size_t readbytes = file.read(buf, len); if (readbytes <= 0) { // read file error! ctx->writer->close(); break; } int nwrite = ctx->writer->WriteBody(buf, readbytes); if (nwrite < 0) { // disconnected! break; } total_readbytes += readbytes; int cur_progress = total_readbytes * 100 / filesize; if (cur_progress > last_progress) { // printf("<< %s progress: %ld/%ld = %d%%\n", // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress); last_progress = cur_progress; } end_time += std::chrono::milliseconds(sleep_ms); std::this_thread::sleep_until(end_time); } ctx->writer->End(); SAFE_FREE(buf); // auto elapsed_time = std::chrono::duration_cast(end_time - start_time); // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count()); }).detach(); return HTTP_STATUS_UNFINISHED; } int Handler::sse(const HttpContextPtr& ctx) { // SSEvent(message) every 1s hv::setInterval(1000, [ctx](hv::TimerID timerID) { if (ctx->writer->isConnected()) { char szTime[DATETIME_FMT_BUFLEN] = {0}; datetime_t now = datetime_now(); datetime_fmt(&now, szTime); ctx->writer->SSEvent(szTime); } else { hv::killTimer(timerID); } }); return HTTP_STATUS_UNFINISHED; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/handler.h000066400000000000000000000040611520575453600301750ustar00rootroot00000000000000#ifndef HV_HTTPD_HANDLER_H #define HV_HTTPD_HANDLER_H #include "HttpService.h" class Handler { public: // preprocessor => middleware -> handlers => postprocessor static int preprocessor(HttpRequest* req, HttpResponse* resp); static int postprocessor(HttpRequest* req, HttpResponse* resp); static int errorHandler(const HttpContextPtr& ctx); // middleware static int Authorization(HttpRequest* req, HttpResponse* resp); static int sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer); static int setTimeout(const HttpContextPtr& ctx); static int query(const HttpContextPtr& ctx); static int kv(HttpRequest* req, HttpResponse* resp); static int json(HttpRequest* req, HttpResponse* resp); static int form(HttpRequest* req, HttpResponse* resp); static int grpc(HttpRequest* req, HttpResponse* resp); static int test(const HttpContextPtr& ctx); static int restful(const HttpContextPtr& ctx); static int login(const HttpContextPtr& ctx); static int upload(const HttpContextPtr& ctx); // SSE: Server Send Events static int sse(const HttpContextPtr& ctx); // LargeFile static int sendLargeFile(const HttpContextPtr& ctx); static int recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size); private: static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) { if (message == NULL) message = http_status_str((enum http_status)code); resp->Set("code", code); resp->Set("message", message); return code; } static int response_status(const HttpResponseWriterPtr& writer, int code = 200, const char* message = NULL) { response_status(writer->response.get(), code, message); writer->End(); return code; } static int response_status(const HttpContextPtr& ctx, int code = 200, const char* message = NULL) { response_status(ctx->response.get(), code, message); ctx->send(); return code; } }; #endif // HV_HTTPD_HANDLER_H kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/httpd.cpp000066400000000000000000000235251520575453600302440ustar00rootroot00000000000000#include "hv.h" #include "hssl.h" #include "hmain.h" #include "iniparser.h" #include "HttpServer.h" #include "hasync.h" // import hv::async #include "router.h" hv::HttpServer g_http_server; hv::HttpService g_http_service; static void print_version(); static void print_help(); static int parse_confile(const char* confile); // long options static const option_t long_options[] = { {'h', "help", NO_ARGUMENT, "Print this information"}, {'v', "version", NO_ARGUMENT, "Print version"}, {'c', "confile", REQUIRED_ARGUMENT, "Set configure file, default etc/{program}.conf"}, {'t', "test", NO_ARGUMENT, "Test configure file and exit"}, {'s', "signal", REQUIRED_ARGUMENT, "send signal to process, signal=[start,stop,restart,status,reload]"}, {'d', "daemon", NO_ARGUMENT, "Daemonize"}, {'p', "port", REQUIRED_ARGUMENT, "Set listen port"} }; void print_version() { printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); } void print_help() { char detail_options[1024] = {0}; dump_opt_long(long_options, ARRAY_SIZE(long_options), detail_options, sizeof(detail_options)); printf("%s\n", detail_options); } int parse_confile(const char* confile) { IniParser ini; int ret = ini.LoadFromFile(confile); if (ret != 0) { printf("Load confile [%s] failed: %d\n", confile, ret); exit(-40); } // logfile std::string str = ini.GetValue("logfile"); if (!str.empty()) { strncpy(g_main_ctx.logfile, str.c_str(), sizeof(g_main_ctx.logfile)); } hlog_set_file(g_main_ctx.logfile); // loglevel str = ini.GetValue("loglevel"); if (!str.empty()) { hlog_set_level_by_str(str.c_str()); } // log_filesize str = ini.GetValue("log_filesize"); if (!str.empty()) { hlog_set_max_filesize_by_str(str.c_str()); } // log_remain_days str = ini.GetValue("log_remain_days"); if (!str.empty()) { hlog_set_remain_days(atoi(str.c_str())); } // log_fsync str = ini.GetValue("log_fsync"); if (!str.empty()) { logger_enable_fsync(hlog, hv_getboolean(str.c_str())); } hlogi("%s version: %s", g_main_ctx.program_name, hv_compile_version()); hlog_fsync(); // worker_processes int worker_processes = 0; #ifdef DEBUG // Disable multi-processes mode for debugging worker_processes = 0; #else str = ini.GetValue("worker_processes"); if (str.size() != 0) { if (strcmp(str.c_str(), "auto") == 0) { worker_processes = get_ncpu(); hlogd("worker_processes=ncpu=%d", worker_processes); } else { worker_processes = atoi(str.c_str()); } } #endif g_http_server.worker_processes = LIMIT(0, worker_processes, MAXNUM_WORKER_PROCESSES); // worker_threads int worker_threads = 0; str = ini.GetValue("worker_threads"); if (str.size() != 0) { if (strcmp(str.c_str(), "auto") == 0) { worker_threads = get_ncpu(); hlogd("worker_threads=ncpu=%d", worker_threads); } else { worker_threads = atoi(str.c_str()); } } g_http_server.worker_threads = LIMIT(0, worker_threads, 64); // worker_connections str = ini.GetValue("worker_connections"); if (str.size() != 0) { g_http_server.worker_connections = atoi(str.c_str()); } // http_port int port = 0; const char* szPort = get_arg("p"); if (szPort) { port = atoi(szPort); } if (port == 0) { port = ini.Get("port"); } if (port == 0) { port = ini.Get("http_port"); } g_http_server.port = port; // https_port if (HV_WITH_SSL) { g_http_server.https_port = ini.Get("https_port"); } if (g_http_server.port == 0 && g_http_server.https_port == 0) { printf("Please config listen port!\n"); exit(-10); } // base_url str = ini.GetValue("base_url"); if (str.size() != 0) { g_http_service.base_url = str; } // document_root str = ini.GetValue("document_root"); if (str.size() != 0) { g_http_service.document_root = str; } // home_page str = ini.GetValue("home_page"); if (str.size() != 0) { g_http_service.home_page = str; } // error_page str = ini.GetValue("error_page"); if (str.size() != 0) { g_http_service.error_page = str; } // index_of str = ini.GetValue("index_of"); if (str.size() != 0) { g_http_service.index_of = str; } // keepalive_timeout str = ini.GetValue("keepalive_timeout"); if (str.size() != 0) { g_http_service.keepalive_timeout = atoi(str.c_str()); } // limit_rate str = ini.GetValue("limit_rate"); if (str.size() != 0) { g_http_service.limit_rate = atoi(str.c_str()); } // access_log str = ini.GetValue("access_log"); if (str.size() != 0) { g_http_service.enable_access_log = hv_getboolean(str.c_str()); } // cors if (ini.Get("cors")) { g_http_service.AllowCORS(); } // ssl if (g_http_server.https_port > 0) { std::string crt_file = ini.GetValue("ssl_certificate"); std::string key_file = ini.GetValue("ssl_privatekey"); std::string ca_file = ini.GetValue("ssl_ca_certificate"); hlogi("SSL backend is %s", hssl_backend()); hssl_ctx_opt_t param; memset(¶m, 0, sizeof(param)); param.crt_file = crt_file.c_str(); param.key_file = key_file.c_str(); param.ca_file = ca_file.c_str(); param.endpoint = HSSL_SERVER; if (g_http_server.newSslCtx(¶m) != 0) { #ifdef OS_WIN if (strcmp(hssl_backend(), "schannel") == 0) { hlogw("schannel needs pkcs12 formatted certificate file."); g_http_server.https_port = 0; } #else hloge("SSL certificate verify failed!"); exit(0); #endif } else { hlogi("SSL certificate verify ok!"); } } // proxy auto proxy_keys = ini.GetKeys("proxy"); for (const auto& proxy_key : proxy_keys) { str = ini.GetValue(proxy_key, "proxy"); if (str.empty()) continue; if (proxy_key[0] == '/') { // reverse proxy const std::string& path = proxy_key; std::string proxy_url = hv::ltrim(str, "> "); hlogi("reverse_proxy %s => %s", path.c_str(), proxy_url.c_str()); g_http_service.Proxy(path.c_str(), proxy_url.c_str()); } else if (strcmp(proxy_key.c_str(), "proxy_connect_timeout") == 0) { g_http_service.proxy_connect_timeout = atoi(str.c_str()); } else if (strcmp(proxy_key.c_str(), "proxy_read_timeout") == 0) { g_http_service.proxy_read_timeout = atoi(str.c_str()); } else if (strcmp(proxy_key.c_str(), "proxy_write_timeout") == 0) { g_http_service.proxy_write_timeout = atoi(str.c_str()); } else if (strcmp(proxy_key.c_str(), "forward_proxy") == 0) { hlogi("forward_proxy = %s", str.c_str()); if (hv_getboolean(str.c_str())) { g_http_service.EnableForwardProxy(); } } else if (strcmp(proxy_key.c_str(), "trust_proxies") == 0) { auto trust_proxies = hv::split(str, ';'); for (auto trust_proxy : trust_proxies) { trust_proxy = hv::trim(trust_proxy); if (trust_proxy.empty()) continue; hlogi("trust_proxy %s", trust_proxy.c_str()); g_http_service.AddTrustProxy(trust_proxy.c_str()); } } else if (strcmp(proxy_key.c_str(), "no_proxies") == 0) { auto no_proxies = hv::split(str, ';'); for (auto no_proxy : no_proxies) { no_proxy = hv::trim(no_proxy); if (no_proxy.empty()) continue; hlogi("no_proxy %s", no_proxy.c_str()); g_http_service.AddNoProxy(no_proxy.c_str()); } } } hlogi("parse_confile('%s') OK", confile); return 0; } static void on_reload(void* userdata) { hlogi("reload confile [%s]", g_main_ctx.confile); parse_confile(g_main_ctx.confile); } int main(int argc, char** argv) { // g_main_ctx main_ctx_init(argc, argv); int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); if (ret != 0) { print_help(); exit(ret); } // help if (get_arg("h")) { print_help(); exit(0); } // version if (get_arg("v")) { print_version(); exit(0); } // parse_confile const char* confile = get_arg("c"); if (confile) { strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile)); } parse_confile(g_main_ctx.confile); // test if (get_arg("t")) { printf("Test confile [%s] OK!\n", g_main_ctx.confile); exit(0); } // signal signal_init(on_reload); const char* signal = get_arg("s"); if (signal) { signal_handle(signal); } #ifdef OS_UNIX // daemon if (get_arg("d")) { // nochdir, noclose int ret = daemon(1, 1); if (ret != 0) { printf("daemon error: %d\n", ret); exit(-10); } } #endif // pidfile create_pidfile(); // http_server Router::Register(g_http_service); g_http_server.registerHttpService(&g_http_service); #if 0 std::atomic_flag init_flag = ATOMIC_FLAG_INIT; g_http_server.onWorkerStart = [&init_flag](){ if (!init_flag.test_and_set()) { hv::async::startup(); } }; g_http_server.onWorkerStop = [&init_flag](){ if (init_flag.test_and_set()) { hv::async::cleanup(); } }; #endif g_http_server.run(); return ret; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/router.cpp000066400000000000000000000134171520575453600304400ustar00rootroot00000000000000#include "router.h" #include "handler.h" #include "hthread.h" // import hv_gettid #include "hasync.h" // import hv::async #include "requests.h" // import requests::async void Router::Register(hv::HttpService& router) { /* handler chain */ // preprocessor -> middleware -> processor -> postprocessor // processor: pathHandlers -> staticHandler -> errorHandler router.preprocessor = Handler::preprocessor; router.postprocessor = Handler::postprocessor; // router.errorHandler = Handler::errorHandler; // router.largeFileHandler = Handler::sendLargeFile; // middleware // router.Use(Handler::Authorization); // curl -v http://ip:port/ping router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { return resp->String("pong"); }); // curl -v http://ip:port/data router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { static char data[] = "0123456789"; return resp->Data(data, 10 /*, false */); }); // curl -v http://ip:port/html/index.html router.GET("/html/index.html", [](HttpRequest* req, HttpResponse* resp) { return resp->File("html/index.html"); }); // curl -v http://ip:port/paths router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { return resp->Json(router.Paths()); }); // curl -v http://ip:port/service router.GET("/service", [](const HttpContextPtr& ctx) { ctx->setContentType("application/json"); ctx->set("base_url", ctx->service->base_url); ctx->set("document_root", ctx->service->document_root); ctx->set("home_page", ctx->service->home_page); ctx->set("error_page", ctx->service->error_page); ctx->set("index_of", ctx->service->index_of); return 200; }); // curl -v http://ip:port/get?env=1 router.GET("/get", [](const HttpContextPtr& ctx) { hv::Json resp; resp["origin"] = ctx->ip(); resp["url"] = ctx->url(); resp["args"] = ctx->params(); resp["headers"] = ctx->headers(); return ctx->send(resp.dump(2)); }); // curl -v http://ip:port/echo -d "hello,world!" router.POST("/echo", [](const HttpContextPtr& ctx) { return ctx->send(ctx->body(), ctx->type()); }); // wildcard * // curl -v http://ip:port/wildcard/any router.GET("/wildcard*", [](HttpRequest* req, HttpResponse* resp) { std::string str = req->path + " match /wildcard*"; return resp->String(str); }); // curl -v http://ip:port/async router.GET("/async", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { writer->Begin(); writer->WriteHeader("X-Response-tid", hv_gettid()); writer->WriteHeader("Content-Type", "text/plain"); writer->WriteBody("This is an async response.\n"); writer->End(); }); // curl -v http://ip:port/www.* // curl -v http://ip:port/www.example.com router.GET("/www.*", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { auto req2 = std::make_shared(); req2->url = req->path.substr(1); requests::async(req2, [writer](const HttpResponsePtr& resp2){ writer->Begin(); if (resp2 == NULL) { writer->WriteStatus(HTTP_STATUS_NOT_FOUND); writer->WriteHeader("Content-Type", "text/html"); writer->WriteBody("

404 Not Found

"); } else { writer->WriteResponse(resp2.get()); } writer->End(); }); }); // curl -v http://ip:port/sleep?t=1000 router.GET("/sleep", Handler::sleep); // curl -v http://ip:port/setTimeout?t=1000 router.GET("/setTimeout", Handler::setTimeout); // curl -v http://ip:port/query?page_no=1\&page_size=10 router.GET("/query", Handler::query); // Content-Type: application/x-www-form-urlencoded // curl -v http://ip:port/kv -H "content-type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' router.POST("/kv", Handler::kv); // Content-Type: application/json // curl -v http://ip:port/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' router.POST("/json", Handler::json); // Content-Type: multipart/form-data // bin/curl -v http://ip:port/form -F 'user=admin' -F 'pswd=123456' router.POST("/form", Handler::form); // curl -v http://ip:port/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' // curl -v http://ip:port/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' // bin/curl -v http://ip:port/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' router.POST("/test", Handler::test); // Content-Type: application/grpc // bin/curl -v --http2 http://ip:port/grpc -H "content-type:application/grpc" -d 'protobuf' router.POST("/grpc", Handler::grpc); // RESTful API: /group/:group_name/user/:user_id // curl -v -X DELETE http://ip:port/group/test/user/123 router.Delete("/group/:group_name/user/:user_id", Handler::restful); // router.Delete("/group/{group_name}/user/{user_id}", Handler::restful); // curl -v http://ip:port/login -H "Content-Type:application/json" -d '{"username":"admin","password":"123456"}' router.POST("/login", Handler::login); // curl -v http://ip:port/upload?filename=LICENSE -d '@LICENSE' // curl -v http://ip:port/upload -F 'file=@LICENSE' router.POST("/upload", Handler::upload); // curl -v http://ip:port/upload/README.md -d '@README.md' router.POST("/upload/{filename}", Handler::recvLargeFile); // SSE: Server Send Events // @test html/EventSource.html EventSource.onmessage router.GET("/sse", Handler::sse); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/httpd/router.h000066400000000000000000000002711520575453600300770ustar00rootroot00000000000000#ifndef HV_HTTPD_ROUTER_H #define HV_HTTPD_ROUTER_H #include "HttpService.h" class Router { public: static void Register(hv::HttpService& router); }; #endif // HV_HTTPD_ROUTER_H kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/000077500000000000000000000000001520575453600267415ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/cJSON.c000066400000000000000000002277371520575453600300430ustar00rootroot00000000000000/* Copyright (c) 2009-2017 Dave Gamble and cJSON contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* cJSON */ /* JSON parser in C. */ /* disable warnings about old C89 functions in MSVC */ #if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) #define _CRT_SECURE_NO_DEPRECATE #endif #ifdef __GNUC__ #pragma GCC visibility push(default) #endif #if defined(_MSC_VER) #pragma warning (push) /* disable warning about single line comments in system headers */ #pragma warning (disable : 4001) #endif #include #include #include #include #include #include #include #ifdef ENABLE_LOCALES #include #endif #if defined(_MSC_VER) #pragma warning (pop) #endif #ifdef __GNUC__ #pragma GCC visibility pop #endif #include "cJSON.h" /* define our own boolean type */ #ifdef true #undef true #endif #define true ((cJSON_bool)1) #ifdef false #undef false #endif #define false ((cJSON_bool)0) /* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ #ifndef isinf #define isinf(d) (isnan((d - d)) && !isnan(d)) #endif #ifndef isnan #define isnan(d) (d != d) #endif #ifndef NAN #ifdef _WIN32 #define NAN sqrt(-1.0) #else #define NAN 0.0/0.0 #endif #endif typedef struct { const unsigned char *json; size_t position; } error; static error global_error = { NULL, 0 }; CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) { return (const char*) (global_error.json + global_error.position); } CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) { if (!cJSON_IsString(item)) { return NULL; } return item->valuestring; } CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) { if (!cJSON_IsNumber(item)) { return (double) NAN; } return item->valuedouble; } /* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ #if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 14) #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. #endif CJSON_PUBLIC(const char*) cJSON_Version(void) { static char version[15]; sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); return version; } /* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) { if ((string1 == NULL) || (string2 == NULL)) { return 1; } if (string1 == string2) { return 0; } for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { if (*string1 == '\0') { return 0; } } return tolower(*string1) - tolower(*string2); } typedef struct internal_hooks { void *(CJSON_CDECL *allocate)(size_t size); void (CJSON_CDECL *deallocate)(void *pointer); void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); } internal_hooks; #if defined(_MSC_VER) /* work around MSVC error C2322: '...' address of dllimport '...' is not static */ static void * CJSON_CDECL internal_malloc(size_t size) { return malloc(size); } static void CJSON_CDECL internal_free(void *pointer) { free(pointer); } static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) { return realloc(pointer, size); } #else #define internal_malloc malloc #define internal_free free #define internal_realloc realloc #endif /* strlen of character literals resolved at compile time */ #define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) { size_t length = 0; unsigned char *copy = NULL; if (string == NULL) { return NULL; } length = strlen((const char*)string) + sizeof(""); copy = (unsigned char*)hooks->allocate(length); if (copy == NULL) { return NULL; } memcpy(copy, string, length); return copy; } CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) { if (hooks == NULL) { /* Reset hooks */ global_hooks.allocate = malloc; global_hooks.deallocate = free; global_hooks.reallocate = realloc; return; } global_hooks.allocate = malloc; if (hooks->malloc_fn != NULL) { global_hooks.allocate = hooks->malloc_fn; } global_hooks.deallocate = free; if (hooks->free_fn != NULL) { global_hooks.deallocate = hooks->free_fn; } /* use realloc only if both free and malloc are used */ global_hooks.reallocate = NULL; if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) { global_hooks.reallocate = realloc; } } /* Internal constructor. */ static cJSON *cJSON_New_Item(const internal_hooks * const hooks) { cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); if (node) { memset(node, '\0', sizeof(cJSON)); } return node; } /* Delete a cJSON structure. */ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) { cJSON *next = NULL; while (item != NULL) { next = item->next; if (!(item->type & cJSON_IsReference) && (item->child != NULL)) { cJSON_Delete(item->child); } if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) { global_hooks.deallocate(item->valuestring); } if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { global_hooks.deallocate(item->string); } global_hooks.deallocate(item); item = next; } } /* get the decimal point character of the current locale */ static unsigned char get_decimal_point(void) { #ifdef ENABLE_LOCALES struct lconv *lconv = localeconv(); return (unsigned char) lconv->decimal_point[0]; #else return '.'; #endif } typedef struct { const unsigned char *content; size_t length; size_t offset; size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ internal_hooks hooks; } parse_buffer; /* check if the given size is left to read in a given parse buffer (starting with 1) */ #define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) /* check if the buffer can be accessed at the given index (starting with 0) */ #define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) #define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) /* get a pointer to the buffer at the position */ #define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) /* Parse the input text to generate a number, and populate the result into item. */ static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) { double number = 0; unsigned char *after_end = NULL; unsigned char number_c_string[64]; unsigned char decimal_point = get_decimal_point(); size_t i = 0; if ((input_buffer == NULL) || (input_buffer->content == NULL)) { return false; } /* copy the number into a temporary buffer and replace '.' with the decimal point * of the current locale (for strtod) * This also takes care of '\0' not necessarily being available for marking the end of the input */ for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) { switch (buffer_at_offset(input_buffer)[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case 'e': case 'E': number_c_string[i] = buffer_at_offset(input_buffer)[i]; break; case '.': number_c_string[i] = decimal_point; break; default: goto loop_end; } } loop_end: number_c_string[i] = '\0'; number = strtod((const char*)number_c_string, (char**)&after_end); if (number_c_string == after_end) { return false; /* parse_error */ } item->valuedouble = number; /* use saturation in case of overflow */ if (number >= INT_MAX) { item->valueint = INT_MAX; } else if (number <= (double)INT_MIN) { item->valueint = INT_MIN; } else { item->valueint = (int)number; } item->type = cJSON_Number; input_buffer->offset += (size_t)(after_end - number_c_string); return true; } /* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) { if (number >= INT_MAX) { object->valueint = INT_MAX; } else if (number <= (double)INT_MIN) { object->valueint = INT_MIN; } else { object->valueint = (int)number; } return object->valuedouble = number; } CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) { char *copy = NULL; /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ if (!(object->type & cJSON_String) || (object->type & cJSON_IsReference)) { return NULL; } if (strlen(valuestring) <= strlen(object->valuestring)) { strcpy(object->valuestring, valuestring); return object->valuestring; } copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); if (copy == NULL) { return NULL; } if (object->valuestring != NULL) { cJSON_free(object->valuestring); } object->valuestring = copy; return copy; } typedef struct { unsigned char *buffer; size_t length; size_t offset; size_t depth; /* current nesting depth (for formatted printing) */ cJSON_bool noalloc; cJSON_bool format; /* is this print a formatted print */ internal_hooks hooks; } printbuffer; /* realloc printbuffer if necessary to have at least "needed" bytes more */ static unsigned char* ensure(printbuffer * const p, size_t needed) { unsigned char *newbuffer = NULL; size_t newsize = 0; if ((p == NULL) || (p->buffer == NULL)) { return NULL; } if ((p->length > 0) && (p->offset >= p->length)) { /* make sure that offset is valid */ return NULL; } if (needed > INT_MAX) { /* sizes bigger than INT_MAX are currently not supported */ return NULL; } needed += p->offset + 1; if (needed <= p->length) { return p->buffer + p->offset; } if (p->noalloc) { return NULL; } /* calculate new buffer size */ if (needed > (INT_MAX / 2)) { /* overflow of int, use INT_MAX if possible */ if (needed <= INT_MAX) { newsize = INT_MAX; } else { return NULL; } } else { newsize = needed * 2; } if (p->hooks.reallocate != NULL) { /* reallocate with realloc if available */ newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); if (newbuffer == NULL) { p->hooks.deallocate(p->buffer); p->length = 0; p->buffer = NULL; return NULL; } } else { /* otherwise reallocate manually */ newbuffer = (unsigned char*)p->hooks.allocate(newsize); if (!newbuffer) { p->hooks.deallocate(p->buffer); p->length = 0; p->buffer = NULL; return NULL; } memcpy(newbuffer, p->buffer, p->offset + 1); p->hooks.deallocate(p->buffer); } p->length = newsize; p->buffer = newbuffer; return newbuffer + p->offset; } /* calculate the new length of the string in a printbuffer and update the offset */ static void update_offset(printbuffer * const buffer) { const unsigned char *buffer_pointer = NULL; if ((buffer == NULL) || (buffer->buffer == NULL)) { return; } buffer_pointer = buffer->buffer + buffer->offset; buffer->offset += strlen((const char*)buffer_pointer); } /* securely comparison of floating-point variables */ static cJSON_bool compare_double(double a, double b) { double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); return (fabs(a - b) <= maxVal * DBL_EPSILON); } /* Render the number nicely from the given item into a string. */ static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output_pointer = NULL; double d = item->valuedouble; int length = 0; size_t i = 0; unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ unsigned char decimal_point = get_decimal_point(); double test = 0.0; if (output_buffer == NULL) { return false; } /* This checks for NaN and Infinity */ if (isnan(d) || isinf(d)) { length = sprintf((char*)number_buffer, "null"); } else { /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ length = sprintf((char*)number_buffer, "%1.15g", d); /* Check whether the original double can be recovered */ if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) { /* If not, print with 17 decimal places of precision */ length = sprintf((char*)number_buffer, "%1.17g", d); } } /* sprintf failed or buffer overrun occurred */ if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { return false; } /* reserve appropriate space in the output */ output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); if (output_pointer == NULL) { return false; } /* copy the printed number to the output and replace locale * dependent decimal point with '.' */ for (i = 0; i < ((size_t)length); i++) { if (number_buffer[i] == decimal_point) { output_pointer[i] = '.'; continue; } output_pointer[i] = number_buffer[i]; } output_pointer[i] = '\0'; output_buffer->offset += (size_t)length; return true; } /* parse 4 digit hexadecimal number */ static unsigned parse_hex4(const unsigned char * const input) { unsigned int h = 0; size_t i = 0; for (i = 0; i < 4; i++) { /* parse digit */ if ((input[i] >= '0') && (input[i] <= '9')) { h += (unsigned int) input[i] - '0'; } else if ((input[i] >= 'A') && (input[i] <= 'F')) { h += (unsigned int) 10 + input[i] - 'A'; } else if ((input[i] >= 'a') && (input[i] <= 'f')) { h += (unsigned int) 10 + input[i] - 'a'; } else /* invalid */ { return 0; } if (i < 3) { /* shift left to make place for the next nibble */ h = h << 4; } } return h; } /* converts a UTF-16 literal to UTF-8 * A literal can be one or two sequences of the form \uXXXX */ static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) { long unsigned int codepoint = 0; unsigned int first_code = 0; const unsigned char *first_sequence = input_pointer; unsigned char utf8_length = 0; unsigned char utf8_position = 0; unsigned char sequence_length = 0; unsigned char first_byte_mark = 0; if ((input_end - first_sequence) < 6) { /* input ends unexpectedly */ goto fail; } /* get the first utf16 sequence */ first_code = parse_hex4(first_sequence + 2); /* check that the code is valid */ if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) { goto fail; } /* UTF16 surrogate pair */ if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) { const unsigned char *second_sequence = first_sequence + 6; unsigned int second_code = 0; sequence_length = 12; /* \uXXXX\uXXXX */ if ((input_end - second_sequence) < 6) { /* input ends unexpectedly */ goto fail; } if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) { /* missing second half of the surrogate pair */ goto fail; } /* get the second utf16 sequence */ second_code = parse_hex4(second_sequence + 2); /* check that the code is valid */ if ((second_code < 0xDC00) || (second_code > 0xDFFF)) { /* invalid second half of the surrogate pair */ goto fail; } /* calculate the unicode codepoint from the surrogate pair */ codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); } else { sequence_length = 6; /* \uXXXX */ codepoint = first_code; } /* encode as UTF-8 * takes at maximum 4 bytes to encode: * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ if (codepoint < 0x80) { /* normal ascii, encoding 0xxxxxxx */ utf8_length = 1; } else if (codepoint < 0x800) { /* two bytes, encoding 110xxxxx 10xxxxxx */ utf8_length = 2; first_byte_mark = 0xC0; /* 11000000 */ } else if (codepoint < 0x10000) { /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ utf8_length = 3; first_byte_mark = 0xE0; /* 11100000 */ } else if (codepoint <= 0x10FFFF) { /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ utf8_length = 4; first_byte_mark = 0xF0; /* 11110000 */ } else { /* invalid unicode codepoint */ goto fail; } /* encode as utf8 */ for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) { /* 10xxxxxx */ (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); codepoint >>= 6; } /* encode first byte */ if (utf8_length > 1) { (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); } else { (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); } *output_pointer += utf8_length; return sequence_length; fail: return 0; } /* Parse the input text into an unescaped cinput, and populate item. */ static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) { const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; unsigned char *output_pointer = NULL; unsigned char *output = NULL; /* not a string */ if (buffer_at_offset(input_buffer)[0] != '\"') { goto fail; } { /* calculate approximate size of the output (overestimate) */ size_t allocation_length = 0; size_t skipped_bytes = 0; while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) { /* is escape sequence */ if (input_end[0] == '\\') { if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) { /* prevent buffer overflow when last input character is a backslash */ goto fail; } skipped_bytes++; input_end++; } input_end++; } if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) { goto fail; /* string ended unexpectedly */ } /* This is at most how much we need for the output */ allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); if (output == NULL) { goto fail; /* allocation failure */ } } output_pointer = output; /* loop through the string literal */ while (input_pointer < input_end) { if (*input_pointer != '\\') { *output_pointer++ = *input_pointer++; } /* escape sequence */ else { unsigned char sequence_length = 2; if ((input_end - input_pointer) < 1) { goto fail; } switch (input_pointer[1]) { case 'b': *output_pointer++ = '\b'; break; case 'f': *output_pointer++ = '\f'; break; case 'n': *output_pointer++ = '\n'; break; case 'r': *output_pointer++ = '\r'; break; case 't': *output_pointer++ = '\t'; break; case '\"': case '\\': case '/': *output_pointer++ = input_pointer[1]; break; /* UTF-16 literal */ case 'u': sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); if (sequence_length == 0) { /* failed to convert UTF16-literal to UTF-8 */ goto fail; } break; default: goto fail; } input_pointer += sequence_length; } } /* zero terminate the output */ *output_pointer = '\0'; item->type = cJSON_String; item->valuestring = (char*)output; input_buffer->offset = (size_t) (input_end - input_buffer->content); input_buffer->offset++; return true; fail: if (output != NULL) { input_buffer->hooks.deallocate(output); } if (input_pointer != NULL) { input_buffer->offset = (size_t)(input_pointer - input_buffer->content); } return false; } /* Render the cstring provided to an escaped version that can be printed. */ static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) { const unsigned char *input_pointer = NULL; unsigned char *output = NULL; unsigned char *output_pointer = NULL; size_t output_length = 0; /* numbers of additional characters needed for escaping */ size_t escape_characters = 0; if (output_buffer == NULL) { return false; } /* empty string */ if (input == NULL) { output = ensure(output_buffer, sizeof("\"\"")); if (output == NULL) { return false; } strcpy((char*)output, "\"\""); return true; } /* set "flag" to 1 if something needs to be escaped */ for (input_pointer = input; *input_pointer; input_pointer++) { switch (*input_pointer) { case '\"': case '\\': case '\b': case '\f': case '\n': case '\r': case '\t': /* one character escape sequence */ escape_characters++; break; default: if (*input_pointer < 32) { /* UTF-16 escape sequence uXXXX */ escape_characters += 5; } break; } } output_length = (size_t)(input_pointer - input) + escape_characters; output = ensure(output_buffer, output_length + sizeof("\"\"")); if (output == NULL) { return false; } /* no characters have to be escaped */ if (escape_characters == 0) { output[0] = '\"'; memcpy(output + 1, input, output_length); output[output_length + 1] = '\"'; output[output_length + 2] = '\0'; return true; } output[0] = '\"'; output_pointer = output + 1; /* copy the string */ for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) { if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) { /* normal character, copy */ *output_pointer = *input_pointer; } else { /* character needs to be escaped */ *output_pointer++ = '\\'; switch (*input_pointer) { case '\\': *output_pointer = '\\'; break; case '\"': *output_pointer = '\"'; break; case '\b': *output_pointer = 'b'; break; case '\f': *output_pointer = 'f'; break; case '\n': *output_pointer = 'n'; break; case '\r': *output_pointer = 'r'; break; case '\t': *output_pointer = 't'; break; default: /* escape and print as unicode codepoint */ sprintf((char*)output_pointer, "u%04x", *input_pointer); output_pointer += 4; break; } } } output[output_length + 1] = '\"'; output[output_length + 2] = '\0'; return true; } /* Invoke print_string_ptr (which is useful) on an item. */ static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) { return print_string_ptr((unsigned char*)item->valuestring, p); } /* Predeclare these prototypes. */ static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); /* Utility to jump whitespace and cr/lf */ static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) { if ((buffer == NULL) || (buffer->content == NULL)) { return NULL; } if (cannot_access_at_index(buffer, 0)) { return buffer; } while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) { buffer->offset++; } if (buffer->offset == buffer->length) { buffer->offset--; } return buffer; } /* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) { if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) { return NULL; } if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) { buffer->offset += 3; } return buffer; } CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) { size_t buffer_length; if (NULL == value) { return NULL; } /* Adding null character size due to require_null_terminated. */ buffer_length = strlen(value) + sizeof(""); return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); } /* Parse an object - create a new root, and populate. */ CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) { parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; cJSON *item = NULL; /* reset error position */ global_error.json = NULL; global_error.position = 0; if (value == NULL || 0 == buffer_length) { goto fail; } buffer.content = (const unsigned char*)value; buffer.length = buffer_length; buffer.offset = 0; buffer.hooks = global_hooks; item = cJSON_New_Item(&global_hooks); if (item == NULL) /* memory fail */ { goto fail; } if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { /* parse failure. ep is set. */ goto fail; } /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ if (require_null_terminated) { buffer_skip_whitespace(&buffer); if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') { goto fail; } } if (return_parse_end) { *return_parse_end = (const char*)buffer_at_offset(&buffer); } return item; fail: if (item != NULL) { cJSON_Delete(item); } if (value != NULL) { error local_error; local_error.json = (const unsigned char*)value; local_error.position = 0; if (buffer.offset < buffer.length) { local_error.position = buffer.offset; } else if (buffer.length > 0) { local_error.position = buffer.length - 1; } if (return_parse_end != NULL) { *return_parse_end = (const char*)local_error.json + local_error.position; } global_error = local_error; } return NULL; } /* Default options for cJSON_Parse */ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) { return cJSON_ParseWithOpts(value, 0, 0); } CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) { return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); } #define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) { static const size_t default_buffer_size = 256; printbuffer buffer[1]; unsigned char *printed = NULL; memset(buffer, 0, sizeof(buffer)); /* create buffer */ buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); buffer->length = default_buffer_size; buffer->format = format; buffer->hooks = *hooks; if (buffer->buffer == NULL) { goto fail; } /* print the value */ if (!print_value(item, buffer)) { goto fail; } update_offset(buffer); /* check if reallocate is available */ if (hooks->reallocate != NULL) { printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); if (printed == NULL) { goto fail; } buffer->buffer = NULL; } else /* otherwise copy the JSON over to a new buffer */ { printed = (unsigned char*) hooks->allocate(buffer->offset + 1); if (printed == NULL) { goto fail; } memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); printed[buffer->offset] = '\0'; /* just to be sure */ /* free the buffer */ hooks->deallocate(buffer->buffer); } return printed; fail: if (buffer->buffer != NULL) { hooks->deallocate(buffer->buffer); } if (printed != NULL) { hooks->deallocate(printed); } return NULL; } /* Render a cJSON item/entity/structure to text. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) { return (char*)print(item, true, &global_hooks); } CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) { return (char*)print(item, false, &global_hooks); } CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) { printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; if (prebuffer < 0) { return NULL; } p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); if (!p.buffer) { return NULL; } p.length = (size_t)prebuffer; p.offset = 0; p.noalloc = false; p.format = fmt; p.hooks = global_hooks; if (!print_value(item, &p)) { global_hooks.deallocate(p.buffer); return NULL; } return (char*)p.buffer; } CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) { printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; if ((length < 0) || (buffer == NULL)) { return false; } p.buffer = (unsigned char*)buffer; p.length = (size_t)length; p.offset = 0; p.noalloc = true; p.format = format; p.hooks = global_hooks; return print_value(item, &p); } /* Parser core - when encountering text, process appropriately. */ static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) { if ((input_buffer == NULL) || (input_buffer->content == NULL)) { return false; /* no input */ } /* parse the different types of values */ /* null */ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) { item->type = cJSON_NULL; input_buffer->offset += 4; return true; } /* false */ if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) { item->type = cJSON_False; input_buffer->offset += 5; return true; } /* true */ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) { item->type = cJSON_True; item->valueint = 1; input_buffer->offset += 4; return true; } /* string */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) { return parse_string(item, input_buffer); } /* number */ if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) { return parse_number(item, input_buffer); } /* array */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) { return parse_array(item, input_buffer); } /* object */ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) { return parse_object(item, input_buffer); } return false; } /* Render a value to text. */ static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output = NULL; if ((item == NULL) || (output_buffer == NULL)) { return false; } switch ((item->type) & 0xFF) { case cJSON_NULL: output = ensure(output_buffer, 5); if (output == NULL) { return false; } strcpy((char*)output, "null"); return true; case cJSON_False: output = ensure(output_buffer, 6); if (output == NULL) { return false; } strcpy((char*)output, "false"); return true; case cJSON_True: output = ensure(output_buffer, 5); if (output == NULL) { return false; } strcpy((char*)output, "true"); return true; case cJSON_Number: return print_number(item, output_buffer); case cJSON_Raw: { size_t raw_length = 0; if (item->valuestring == NULL) { return false; } raw_length = strlen(item->valuestring) + sizeof(""); output = ensure(output_buffer, raw_length); if (output == NULL) { return false; } memcpy(output, item->valuestring, raw_length); return true; } case cJSON_String: return print_string(item, output_buffer); case cJSON_Array: return print_array(item, output_buffer); case cJSON_Object: return print_object(item, output_buffer); default: return false; } } /* Build an array from input text. */ static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) { cJSON *head = NULL; /* head of the linked list */ cJSON *current_item = NULL; if (input_buffer->depth >= CJSON_NESTING_LIMIT) { return false; /* to deeply nested */ } input_buffer->depth++; if (buffer_at_offset(input_buffer)[0] != '[') { /* not an array */ goto fail; } input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) { /* empty array */ goto success; } /* check if we skipped to the end of the buffer */ if (cannot_access_at_index(input_buffer, 0)) { input_buffer->offset--; goto fail; } /* step back to character in front of the first element */ input_buffer->offset--; /* loop through the comma separated array elements */ do { /* allocate next item */ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); if (new_item == NULL) { goto fail; /* allocation failure */ } /* attach next item to list */ if (head == NULL) { /* start the linked list */ current_item = head = new_item; } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; current_item = new_item; } /* parse next value */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_value(current_item, input_buffer)) { goto fail; /* failed to parse value */ } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') { goto fail; /* expected end of array */ } success: input_buffer->depth--; if (head != NULL) { head->prev = current_item; } item->type = cJSON_Array; item->child = head; input_buffer->offset++; return true; fail: if (head != NULL) { cJSON_Delete(head); } return false; } /* Render an array to text */ static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output_pointer = NULL; size_t length = 0; cJSON *current_element = item->child; if (output_buffer == NULL) { return false; } /* Compose the output array. */ /* opening square bracket */ output_pointer = ensure(output_buffer, 1); if (output_pointer == NULL) { return false; } *output_pointer = '['; output_buffer->offset++; output_buffer->depth++; while (current_element != NULL) { if (!print_value(current_element, output_buffer)) { return false; } update_offset(output_buffer); if (current_element->next) { length = (size_t) (output_buffer->format ? 2 : 1); output_pointer = ensure(output_buffer, length + 1); if (output_pointer == NULL) { return false; } *output_pointer++ = ','; if(output_buffer->format) { *output_pointer++ = ' '; } *output_pointer = '\0'; output_buffer->offset += length; } current_element = current_element->next; } output_pointer = ensure(output_buffer, 2); if (output_pointer == NULL) { return false; } *output_pointer++ = ']'; *output_pointer = '\0'; output_buffer->depth--; return true; } /* Build an object from the text. */ static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) { cJSON *head = NULL; /* linked list head */ cJSON *current_item = NULL; if (input_buffer->depth >= CJSON_NESTING_LIMIT) { return false; /* to deeply nested */ } input_buffer->depth++; if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) { goto fail; /* not an object */ } input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) { goto success; /* empty object */ } /* check if we skipped to the end of the buffer */ if (cannot_access_at_index(input_buffer, 0)) { input_buffer->offset--; goto fail; } /* step back to character in front of the first element */ input_buffer->offset--; /* loop through the comma separated array elements */ do { /* allocate next item */ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); if (new_item == NULL) { goto fail; /* allocation failure */ } /* attach next item to list */ if (head == NULL) { /* start the linked list */ current_item = head = new_item; } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; current_item = new_item; } /* parse the name of the child */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_string(current_item, input_buffer)) { goto fail; /* failed to parse name */ } buffer_skip_whitespace(input_buffer); /* swap valuestring and string, because we parsed the name */ current_item->string = current_item->valuestring; current_item->valuestring = NULL; if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) { goto fail; /* invalid object */ } /* parse the value */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); if (!parse_value(current_item, input_buffer)) { goto fail; /* failed to parse value */ } buffer_skip_whitespace(input_buffer); } while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) { goto fail; /* expected end of object */ } success: input_buffer->depth--; if (head != NULL) { head->prev = current_item; } item->type = cJSON_Object; item->child = head; input_buffer->offset++; return true; fail: if (head != NULL) { cJSON_Delete(head); } return false; } /* Render an object to text. */ static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) { unsigned char *output_pointer = NULL; size_t length = 0; cJSON *current_item = item->child; if (output_buffer == NULL) { return false; } /* Compose the output: */ length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ output_pointer = ensure(output_buffer, length + 1); if (output_pointer == NULL) { return false; } *output_pointer++ = '{'; output_buffer->depth++; if (output_buffer->format) { *output_pointer++ = '\n'; } output_buffer->offset += length; while (current_item) { if (output_buffer->format) { size_t i; output_pointer = ensure(output_buffer, output_buffer->depth); if (output_pointer == NULL) { return false; } for (i = 0; i < output_buffer->depth; i++) { *output_pointer++ = '\t'; } output_buffer->offset += output_buffer->depth; } /* print key */ if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) { return false; } update_offset(output_buffer); length = (size_t) (output_buffer->format ? 2 : 1); output_pointer = ensure(output_buffer, length); if (output_pointer == NULL) { return false; } *output_pointer++ = ':'; if (output_buffer->format) { *output_pointer++ = '\t'; } output_buffer->offset += length; /* print value */ if (!print_value(current_item, output_buffer)) { return false; } update_offset(output_buffer); /* print comma if not last */ length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); output_pointer = ensure(output_buffer, length + 1); if (output_pointer == NULL) { return false; } if (current_item->next) { *output_pointer++ = ','; } if (output_buffer->format) { *output_pointer++ = '\n'; } *output_pointer = '\0'; output_buffer->offset += length; current_item = current_item->next; } output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); if (output_pointer == NULL) { return false; } if (output_buffer->format) { size_t i; for (i = 0; i < (output_buffer->depth - 1); i++) { *output_pointer++ = '\t'; } } *output_pointer++ = '}'; *output_pointer = '\0'; output_buffer->depth--; return true; } /* Get Array size/item / object item. */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) { cJSON *child = NULL; size_t size = 0; if (array == NULL) { return 0; } child = array->child; while(child != NULL) { size++; child = child->next; } /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ return (int)size; } static cJSON* get_array_item(const cJSON *array, size_t index) { cJSON *current_child = NULL; if (array == NULL) { return NULL; } current_child = array->child; while ((current_child != NULL) && (index > 0)) { index--; current_child = current_child->next; } return current_child; } CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) { if (index < 0) { return NULL; } return get_array_item(array, (size_t)index); } static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) { cJSON *current_element = NULL; if ((object == NULL) || (name == NULL)) { return NULL; } current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } } else { while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) { current_element = current_element->next; } } if ((current_element == NULL) || (current_element->string == NULL)) { return NULL; } return current_element; } CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) { return get_object_item(object, string, false); } CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) { return get_object_item(object, string, true); } CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) { return cJSON_GetObjectItem(object, string) ? 1 : 0; } /* Utility for array list handling. */ static void suffix_object(cJSON *prev, cJSON *item) { prev->next = item; item->prev = prev; } /* Utility for handling references. */ static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) { cJSON *reference = NULL; if (item == NULL) { return NULL; } reference = cJSON_New_Item(hooks); if (reference == NULL) { return NULL; } memcpy(reference, item, sizeof(cJSON)); reference->string = NULL; reference->type |= cJSON_IsReference; reference->next = reference->prev = NULL; return reference; } static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) { cJSON *child = NULL; if ((item == NULL) || (array == NULL) || (array == item)) { return false; } child = array->child; /* * To find the last item in array quickly, we use prev in array */ if (child == NULL) { /* list is empty, start new one */ array->child = item; item->prev = item; item->next = NULL; } else { /* append to the end */ if (child->prev) { suffix_object(child->prev, item); array->child->prev = item; } } return true; } /* Add item to array/object. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) { return add_item_to_array(array, item); } #if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) #pragma GCC diagnostic push #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wcast-qual" #endif /* helper function to cast away const */ static void* cast_away_const(const void* string) { return (void*)string; } #if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) #pragma GCC diagnostic pop #endif static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) { char *new_key = NULL; int new_type = cJSON_Invalid; if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) { return false; } if (constant_key) { new_key = (char*)cast_away_const(string); new_type = item->type | cJSON_StringIsConst; } else { new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); if (new_key == NULL) { return false; } new_type = item->type & ~cJSON_StringIsConst; } if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { hooks->deallocate(item->string); } item->string = new_key; item->type = new_type; return add_item_to_array(object, item); } CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) { return add_item_to_object(object, string, item, &global_hooks, false); } /* Add an item to an object with constant string as key */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) { return add_item_to_object(object, string, item, &global_hooks, true); } CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) { if (array == NULL) { return false; } return add_item_to_array(array, create_reference(item, &global_hooks)); } CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) { if ((object == NULL) || (string == NULL)) { return false; } return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); } CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) { cJSON *null = cJSON_CreateNull(); if (add_item_to_object(object, name, null, &global_hooks, false)) { return null; } cJSON_Delete(null); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) { cJSON *true_item = cJSON_CreateTrue(); if (add_item_to_object(object, name, true_item, &global_hooks, false)) { return true_item; } cJSON_Delete(true_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) { cJSON *false_item = cJSON_CreateFalse(); if (add_item_to_object(object, name, false_item, &global_hooks, false)) { return false_item; } cJSON_Delete(false_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) { cJSON *bool_item = cJSON_CreateBool(boolean); if (add_item_to_object(object, name, bool_item, &global_hooks, false)) { return bool_item; } cJSON_Delete(bool_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) { cJSON *number_item = cJSON_CreateNumber(number); if (add_item_to_object(object, name, number_item, &global_hooks, false)) { return number_item; } cJSON_Delete(number_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) { cJSON *string_item = cJSON_CreateString(string); if (add_item_to_object(object, name, string_item, &global_hooks, false)) { return string_item; } cJSON_Delete(string_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) { cJSON *raw_item = cJSON_CreateRaw(raw); if (add_item_to_object(object, name, raw_item, &global_hooks, false)) { return raw_item; } cJSON_Delete(raw_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) { cJSON *object_item = cJSON_CreateObject(); if (add_item_to_object(object, name, object_item, &global_hooks, false)) { return object_item; } cJSON_Delete(object_item); return NULL; } CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) { cJSON *array = cJSON_CreateArray(); if (add_item_to_object(object, name, array, &global_hooks, false)) { return array; } cJSON_Delete(array); return NULL; } CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) { if ((parent == NULL) || (item == NULL)) { return NULL; } if (item != parent->child) { /* not the first element */ item->prev->next = item->next; } if (item->next != NULL) { /* not the last element */ item->next->prev = item->prev; } if (item == parent->child) { /* first element */ parent->child = item->next; } else if (item->next == NULL) { /* last element */ parent->child->prev = item->prev; } /* make sure the detached item doesn't point anywhere anymore */ item->prev = NULL; item->next = NULL; return item; } CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) { if (which < 0) { return NULL; } return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); } CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) { cJSON_Delete(cJSON_DetachItemFromArray(array, which)); } CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) { cJSON *to_detach = cJSON_GetObjectItem(object, string); return cJSON_DetachItemViaPointer(object, to_detach); } CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) { cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); return cJSON_DetachItemViaPointer(object, to_detach); } CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) { cJSON_Delete(cJSON_DetachItemFromObject(object, string)); } CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) { cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); } /* Replace array/object items with new ones. */ CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) { cJSON *after_inserted = NULL; if (which < 0) { return false; } after_inserted = get_array_item(array, (size_t)which); if (after_inserted == NULL) { return add_item_to_array(array, newitem); } newitem->next = after_inserted; newitem->prev = after_inserted->prev; after_inserted->prev = newitem; if (after_inserted == array->child) { array->child = newitem; } else { newitem->prev->next = newitem; } return true; } CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) { if ((parent == NULL) || (replacement == NULL) || (item == NULL)) { return false; } if (replacement == item) { return true; } replacement->next = item->next; replacement->prev = item->prev; if (replacement->next != NULL) { replacement->next->prev = replacement; } if (parent->child == item) { if (parent->child->prev == parent->child) { replacement->prev = replacement; } parent->child = replacement; } else { /* * To find the last item in array quickly, we use prev in array. * We can't modify the last item's next pointer where this item was the parent's child */ if (replacement->prev != NULL) { replacement->prev->next = replacement; } if (replacement->next == NULL) { parent->child->prev = replacement; } } item->next = NULL; item->prev = NULL; cJSON_Delete(item); return true; } CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) { if (which < 0) { return false; } return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); } static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) { if ((replacement == NULL) || (string == NULL)) { return false; } /* replace the name in the replacement */ if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) { cJSON_free(replacement->string); } replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); replacement->type &= ~cJSON_StringIsConst; return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); } CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) { return replace_item_in_object(object, string, newitem, false); } CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) { return replace_item_in_object(object, string, newitem, true); } /* Create basic types: */ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_NULL; } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_True; } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_False; } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = boolean ? cJSON_True : cJSON_False; } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_Number; item->valuedouble = num; /* use saturation in case of overflow */ if (num >= INT_MAX) { item->valueint = INT_MAX; } else if (num <= (double)INT_MIN) { item->valueint = INT_MIN; } else { item->valueint = (int)num; } } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_String; item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); if(!item->valuestring) { cJSON_Delete(item); return NULL; } } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) { cJSON *item = cJSON_New_Item(&global_hooks); if (item != NULL) { item->type = cJSON_String | cJSON_IsReference; item->valuestring = (char*)cast_away_const(string); } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) { cJSON *item = cJSON_New_Item(&global_hooks); if (item != NULL) { item->type = cJSON_Object | cJSON_IsReference; item->child = (cJSON*)cast_away_const(child); } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { cJSON *item = cJSON_New_Item(&global_hooks); if (item != NULL) { item->type = cJSON_Array | cJSON_IsReference; item->child = (cJSON*)cast_away_const(child); } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type = cJSON_Raw; item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); if(!item->valuestring) { cJSON_Delete(item); return NULL; } } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) { cJSON *item = cJSON_New_Item(&global_hooks); if(item) { item->type=cJSON_Array; } return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) { cJSON *item = cJSON_New_Item(&global_hooks); if (item) { item->type = cJSON_Object; } return item; } /* Create Arrays: */ CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) { size_t i = 0; cJSON *n = NULL; cJSON *p = NULL; cJSON *a = NULL; if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); for(i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber(numbers[i]); if (!n) { cJSON_Delete(a); return NULL; } if(!i) { a->child = n; } else { suffix_object(p, n); } p = n; } if (a && a->child) { a->child->prev = n; } return a; } CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) { size_t i = 0; cJSON *n = NULL; cJSON *p = NULL; cJSON *a = NULL; if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); for(i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber((double)numbers[i]); if(!n) { cJSON_Delete(a); return NULL; } if(!i) { a->child = n; } else { suffix_object(p, n); } p = n; } if (a && a->child) { a->child->prev = n; } return a; } CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) { size_t i = 0; cJSON *n = NULL; cJSON *p = NULL; cJSON *a = NULL; if ((count < 0) || (numbers == NULL)) { return NULL; } a = cJSON_CreateArray(); for(i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateNumber(numbers[i]); if(!n) { cJSON_Delete(a); return NULL; } if(!i) { a->child = n; } else { suffix_object(p, n); } p = n; } if (a && a->child) { a->child->prev = n; } return a; } CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) { size_t i = 0; cJSON *n = NULL; cJSON *p = NULL; cJSON *a = NULL; if ((count < 0) || (strings == NULL)) { return NULL; } a = cJSON_CreateArray(); for (i = 0; a && (i < (size_t)count); i++) { n = cJSON_CreateString(strings[i]); if(!n) { cJSON_Delete(a); return NULL; } if(!i) { a->child = n; } else { suffix_object(p,n); } p = n; } if (a && a->child) { a->child->prev = n; } return a; } /* Duplication */ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) { cJSON *newitem = NULL; cJSON *child = NULL; cJSON *next = NULL; cJSON *newchild = NULL; /* Bail on bad ptr */ if (!item) { goto fail; } /* Create new item */ newitem = cJSON_New_Item(&global_hooks); if (!newitem) { goto fail; } /* Copy over all vars */ newitem->type = item->type & (~cJSON_IsReference); newitem->valueint = item->valueint; newitem->valuedouble = item->valuedouble; if (item->valuestring) { newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); if (!newitem->valuestring) { goto fail; } } if (item->string) { newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); if (!newitem->string) { goto fail; } } /* If non-recursive, then we're done! */ if (!recurse) { return newitem; } /* Walk the ->next chain for the child. */ child = item->child; while (child != NULL) { newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ if (!newchild) { goto fail; } if (next != NULL) { /* If newitem->child already set, then crosswire ->prev and ->next and move on */ next->next = newchild; newchild->prev = next; next = newchild; } else { /* Set newitem->child and move to it */ newitem->child = newchild; next = newchild; } child = child->next; } if (newitem && newitem->child) { newitem->child->prev = newchild; } return newitem; fail: if (newitem != NULL) { cJSON_Delete(newitem); } return NULL; } static void skip_oneline_comment(char **input) { *input += static_strlen("//"); for (; (*input)[0] != '\0'; ++(*input)) { if ((*input)[0] == '\n') { *input += static_strlen("\n"); return; } } } static void skip_multiline_comment(char **input) { *input += static_strlen("/*"); for (; (*input)[0] != '\0'; ++(*input)) { if (((*input)[0] == '*') && ((*input)[1] == '/')) { *input += static_strlen("*/"); return; } } } static void minify_string(char **input, char **output) { (*output)[0] = (*input)[0]; *input += static_strlen("\""); *output += static_strlen("\""); for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { (*output)[0] = (*input)[0]; if ((*input)[0] == '\"') { (*output)[0] = '\"'; *input += static_strlen("\""); *output += static_strlen("\""); return; } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { (*output)[1] = (*input)[1]; *input += static_strlen("\""); *output += static_strlen("\""); } } } CJSON_PUBLIC(void) cJSON_Minify(char *json) { char *into = json; if (json == NULL) { return; } while (json[0] != '\0') { switch (json[0]) { case ' ': case '\t': case '\r': case '\n': json++; break; case '/': if (json[1] == '/') { skip_oneline_comment(&json); } else if (json[1] == '*') { skip_multiline_comment(&json); } else { json++; } break; case '\"': minify_string(&json, (char**)&into); break; default: into[0] = json[0]; json++; into++; } } /* and null-terminate. */ *into = '\0'; } CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_Invalid; } CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_False; } CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xff) == cJSON_True; } CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & (cJSON_True | cJSON_False)) != 0; } CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_NULL; } CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_Number; } CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_String; } CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_Array; } CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_Object; } CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) { if (item == NULL) { return false; } return (item->type & 0xFF) == cJSON_Raw; } CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) { if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a)) { return false; } /* check if type is valid */ switch (a->type & 0xFF) { case cJSON_False: case cJSON_True: case cJSON_NULL: case cJSON_Number: case cJSON_String: case cJSON_Raw: case cJSON_Array: case cJSON_Object: break; default: return false; } /* identical objects are equal */ if (a == b) { return true; } switch (a->type & 0xFF) { /* in these cases and equal type is enough */ case cJSON_False: case cJSON_True: case cJSON_NULL: return true; case cJSON_Number: if (compare_double(a->valuedouble, b->valuedouble)) { return true; } return false; case cJSON_String: case cJSON_Raw: if ((a->valuestring == NULL) || (b->valuestring == NULL)) { return false; } if (strcmp(a->valuestring, b->valuestring) == 0) { return true; } return false; case cJSON_Array: { cJSON *a_element = a->child; cJSON *b_element = b->child; for (; (a_element != NULL) && (b_element != NULL);) { if (!cJSON_Compare(a_element, b_element, case_sensitive)) { return false; } a_element = a_element->next; b_element = b_element->next; } /* one of the arrays is longer than the other */ if (a_element != b_element) { return false; } return true; } case cJSON_Object: { cJSON *a_element = NULL; cJSON *b_element = NULL; cJSON_ArrayForEach(a_element, a) { /* TODO This has O(n^2) runtime, which is horrible! */ b_element = get_object_item(b, a_element->string, case_sensitive); if (b_element == NULL) { return false; } if (!cJSON_Compare(a_element, b_element, case_sensitive)) { return false; } } /* doing this twice, once on a and b to prevent true comparison if a subset of b * TODO: Do this the proper way, this is just a fix for now */ cJSON_ArrayForEach(b_element, b) { a_element = get_object_item(a, b_element->string, case_sensitive); if (a_element == NULL) { return false; } if (!cJSON_Compare(b_element, a_element, case_sensitive)) { return false; } } return true; } default: return false; } } CJSON_PUBLIC(void *) cJSON_malloc(size_t size) { return global_hooks.allocate(size); } CJSON_PUBLIC(void) cJSON_free(void *object) { global_hooks.deallocate(object); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/cJSON.h000066400000000000000000000367241520575453600300420ustar00rootroot00000000000000/* Copyright (c) 2009-2017 Dave Gamble and cJSON contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef cJSON__h #define cJSON__h #ifdef __cplusplus extern "C" { #endif #if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) #define __WINDOWS__ #endif #ifdef __WINDOWS__ /* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol For *nix builds that support visibility attribute, you can define similar behavior by setting default visibility to hidden by adding -fvisibility=hidden (for gcc) or -xldscope=hidden (for sun cc) to CFLAGS then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does */ #define CJSON_CDECL __cdecl #define CJSON_STDCALL __stdcall /* export symbols by default, this is necessary for copy pasting the C and header file */ #if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) #define CJSON_EXPORT_SYMBOLS #endif #if defined(CJSON_HIDE_SYMBOLS) #define CJSON_PUBLIC(type) type CJSON_STDCALL #elif defined(CJSON_EXPORT_SYMBOLS) #define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL #elif defined(CJSON_IMPORT_SYMBOLS) #define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL #endif #else /* !__WINDOWS__ */ #define CJSON_CDECL #define CJSON_STDCALL #if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) #define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type #else #define CJSON_PUBLIC(type) type #endif #endif /* project version */ #define CJSON_VERSION_MAJOR 1 #define CJSON_VERSION_MINOR 7 #define CJSON_VERSION_PATCH 14 #include /* cJSON Types: */ #define cJSON_Invalid (0) #define cJSON_False (1 << 0) #define cJSON_True (1 << 1) #define cJSON_NULL (1 << 2) #define cJSON_Number (1 << 3) #define cJSON_String (1 << 4) #define cJSON_Array (1 << 5) #define cJSON_Object (1 << 6) #define cJSON_Raw (1 << 7) /* raw json */ #define cJSON_IsReference 256 #define cJSON_StringIsConst 512 /* The cJSON structure: */ typedef struct cJSON { /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ struct cJSON *next; struct cJSON *prev; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ struct cJSON *child; /* The type of the item, as above. */ int type; /* The item's string, if type==cJSON_String and type == cJSON_Raw */ char *valuestring; /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ int valueint; /* The item's number, if type==cJSON_Number */ double valuedouble; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ char *string; } cJSON; typedef struct cJSON_Hooks { /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ void *(CJSON_CDECL *malloc_fn)(size_t sz); void (CJSON_CDECL *free_fn)(void *ptr); } cJSON_Hooks; typedef int cJSON_bool; /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. * This is to prevent stack overflows. */ #ifndef CJSON_NESTING_LIMIT #define CJSON_NESTING_LIMIT 1000 #endif /* returns the version of cJSON as a string */ CJSON_PUBLIC(const char*) cJSON_Version(void); /* Supply malloc, realloc and free functions to cJSON */ CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); /* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ /* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ /* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); /* Render a cJSON entity to text for transfer/storage. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); /* Render a cJSON entity to text for transfer/storage without any formatting. */ CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); /* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ /* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); /* Delete a cJSON entity and all subentities. */ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); /* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); /* Check item type and return its value */ CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); /* These functions check the type of an item */ CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); /* These calls create a cJSON item of the appropriate type. */ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); /* raw json */ CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); /* Create a string where valuestring references a string so * it will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); /* Create an object/array that only references it's elements so * they will not be freed by cJSON_Delete */ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); /* These utilities create an Array of count items. * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); /* Append item to the specified array/object. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before * writing to `item->string` */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); /* Remove/Detach items from Arrays/Objects. */ CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); /* Update array items. */ CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); /* Duplicate a cJSON item */ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); /* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will * need to be released. With recurse!=0, it will duplicate any children connected to the item. * The item->next and ->prev pointers are always zero on return from Duplicate. */ /* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); /* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. * The input pointer json cannot point to a read-only address area, such as a string constant, * but should point to a readable and writable adress area. */ CJSON_PUBLIC(void) cJSON_Minify(char *json); /* Helper functions for creating and adding items to an object at the same time. * They return the added item or NULL on failure. */ CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); /* When assigning an integer value, it needs to be propagated to valuedouble too. */ #define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) /* helper for the cJSON_SetNumberValue macro */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); #define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) /* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); /* Macro for iterating over an array or object */ #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) /* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void) cJSON_free(void *object); #ifdef __cplusplus } #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/handler.h000066400000000000000000000051621520575453600305330ustar00rootroot00000000000000#ifndef HV_JSON_RPC_HANDLER_H_ #define HV_JSON_RPC_HANDLER_H_ #include "router.h" void error_response(cJSON* jres, int code, const char* message) { cJSON* jerror = cJSON_CreateObject(); cJSON_AddItemToObject(jerror, "code", cJSON_CreateNumber(code)); cJSON_AddItemToObject(jerror, "message", cJSON_CreateString(message)); cJSON_AddItemToObject(jres, "error", jerror); } void not_found(cJSON* jreq, cJSON* jres) { error_response(jres, 404, "Not Found"); } void bad_request(cJSON* jreq, cJSON* jres) { error_response(jres, 400, "Bad Request"); } void calc_add(cJSON* jreq, cJSON* jres) { cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); if (cJSON_GetArraySize(jparams) != 2) { bad_request(jreq, jres); return; } cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); int num1 = cJSON_GetNumberValue(jnum1); cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); int num2 = cJSON_GetNumberValue(jnum2); int result = num1 + num2; cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); } void calc_sub(cJSON* jreq, cJSON* jres) { cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); if (cJSON_GetArraySize(jparams) != 2) { bad_request(jreq, jres); return; } cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); int num1 = cJSON_GetNumberValue(jnum1); cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); int num2 = cJSON_GetNumberValue(jnum2); int result = num1 - num2; cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); } void calc_mul(cJSON* jreq, cJSON* jres) { cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); if (cJSON_GetArraySize(jparams) != 2) { bad_request(jreq, jres); return; } cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); int num1 = cJSON_GetNumberValue(jnum1); cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); int num2 = cJSON_GetNumberValue(jnum2); int result = num1 * num2; cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); } void calc_div(cJSON* jreq, cJSON* jres) { cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); if (cJSON_GetArraySize(jparams) != 2) { bad_request(jreq, jres); return; } cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); int num1 = cJSON_GetNumberValue(jnum1); cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); int num2 = cJSON_GetNumberValue(jnum2); if (num2 == 0) { bad_request(jreq, jres); return; } else { int result = num1 / num2; cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); } } #endif // HV_JSON_RPC_ROUTER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/jsonrpc_client.c000066400000000000000000000101421520575453600321170ustar00rootroot00000000000000/* * json rpc client * * @build make jsonrpc * @server bin/jsonrpc_server 1234 * @client bin/jsonrpc_client 127.0.0.1 1234 add 1 2 * */ #include "hloop.h" #include "hatomic.h" #include "hbase.h" #include "hsocket.h" #include "cJSON.h" // hloop_create_tcp_client -> on_connect -> hio_write -> hio_read -> on_recv static int verbose = 0; static unpack_setting_t jsonrpc_unpack_setting; static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); cJSON* jreq = (cJSON*)(hevent_userdata(io)); if (jreq) { cJSON_Delete(jreq); hevent_set_userdata(io, NULL); } hloop_stop(hevent_loop(io)); } static void on_recv(hio_t* io, void* readbuf, int readbytes) { // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } char* resp_str = (char*)readbuf; printf("< %s\n", resp_str); // cJSON_Parse cJSON* jres = cJSON_Parse(resp_str); cJSON* jerror = cJSON_GetObjectItem(jres, "error"); cJSON* jresult = cJSON_GetObjectItem(jres, "result"); // ... cJSON_Delete(jres); hio_close(io); } static void on_connect(hio_t* io) { printf("on_connect fd=%d\n", hio_fd(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("connect connfd=%d [%s] => [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } hio_setcb_read(io, on_recv); hio_set_unpack(io, &jsonrpc_unpack_setting); hio_read(io); cJSON* jreq = (cJSON*)(hevent_userdata(io)); hevent_set_userdata(io, NULL); assert(jreq != NULL); // cJSON_Print -> hio_write char* req_str = cJSON_PrintUnformatted(jreq); printf("> %s\n", req_str); // NOTE: +1 for \0 hio_write(io, req_str, strlen(req_str) + 1); cJSON_Delete(jreq); cJSON_free(req_str); } static int jsonrpc_call(hloop_t* loop, const char* host, int port, const char* method, const char* param1, const char* param2) { hio_t* connio = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (connio == NULL) { return -1; } // printf("connfd=%d\n", hio_fd(connio)); // construct request cJSON* jreq = cJSON_CreateObject(); static hatomic_t s_id = HATOMIC_VAR_INIT(0); cJSON_AddItemToObject(jreq, "id", cJSON_CreateNumber(++s_id)); cJSON_AddItemToObject(jreq, "method", cJSON_CreateString(method)); cJSON* jparams = cJSON_CreateArray(); cJSON_AddItemToArray(jparams, cJSON_CreateNumber(atoi(param1))); cJSON_AddItemToArray(jparams, cJSON_CreateNumber(atoi(param2))); cJSON_AddItemToObject(jreq, "params", jparams); hevent_set_userdata(connio, jreq); hio_setcb_connect(connio, on_connect); hio_setcb_close(connio, on_close); hio_connect(connio); return 0; } int main(int argc, char** argv) { if (argc < 6) { printf("Usage: %s host port method param1 param2\n", argv[0]); printf("method = [add, sub, mul, div]\n"); printf("Examples:\n"); printf(" %s 127.0.0.1 1234 add 1 2\n", argv[0]); printf(" %s 127.0.0.1 1234 div 1 0\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); const char* method = argv[3]; const char* param1 = argv[4]; const char* param2 = argv[5]; // init jsonrpc_unpack_setting memset(&jsonrpc_unpack_setting, 0, sizeof(unpack_setting_t)); jsonrpc_unpack_setting.mode = UNPACK_BY_DELIMITER; jsonrpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; jsonrpc_unpack_setting.delimiter[0] = '\0'; jsonrpc_unpack_setting.delimiter_bytes = 1; hloop_t* loop = hloop_new(0); jsonrpc_call(loop, host, port, method, param1, param2); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/jsonrpc_server.c000066400000000000000000000070321520575453600321530ustar00rootroot00000000000000/* * json rpc server * * @build make jsonrpc * @server bin/jsonrpc_server 1234 * @client bin/jsonrpc_client 127.0.0.1 1234 add 1 2 * */ #include "hloop.h" #include "hbase.h" #include "hsocket.h" #include "cJSON.h" #include "router.h" #include "handler.h" // hloop_create_tcp_server -> on_accept -> hio_read -> on_recv -> hio_write static int verbose = 0; static unpack_setting_t jsonrpc_unpack_setting; jsonrpc_router router[] = { {"add", calc_add}, {"sub", calc_sub}, {"mul", calc_mul}, {"div", calc_div}, }; #define JSONRPC_ROUTER_NUM (sizeof(router)/sizeof(router[0])) static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); } static void on_recv(hio_t* io, void* readbuf, int readbytes) { // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } // cJSON_Parse -> router -> cJSON_Print -> hio_write char* req_str = (char*)readbuf; printf("> %s\n", req_str); cJSON* jreq = cJSON_Parse(req_str); cJSON* jres = cJSON_CreateObject(); cJSON* jid = cJSON_GetObjectItem(jreq, "id"); cJSON* jmethod = cJSON_GetObjectItem(jreq, "method"); if (cJSON_IsNumber(jid)) { long id = cJSON_GetNumberValue(jid); cJSON_AddItemToObject(jres, "id", cJSON_CreateNumber(id)); } if (cJSON_IsString(jmethod)) { // router char* method = cJSON_GetStringValue(jmethod); bool found = false; for (int i = 0; i < JSONRPC_ROUTER_NUM; ++i) { if (strcmp(method, router[i].method) == 0) { found = true; router[i].handler(jreq, jres); break; } } if (!found) { not_found(jreq, jres); } } else { bad_request(jreq, jres); } char* resp_str = cJSON_PrintUnformatted(jres); printf("< %s\n", resp_str); // NOTE: +1 for \0 hio_write(io, resp_str, strlen(resp_str) + 1); cJSON_Delete(jreq); cJSON_Delete(jres); cJSON_free(resp_str); } static void on_accept(hio_t* io) { printf("on_accept connfd=%d\n", hio_fd(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_set_unpack(io, &jsonrpc_unpack_setting); hio_read(io); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); // init jsonrpc_unpack_setting memset(&jsonrpc_unpack_setting, 0, sizeof(unpack_setting_t)); jsonrpc_unpack_setting.mode = UNPACK_BY_DELIMITER; jsonrpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; jsonrpc_unpack_setting.delimiter[0] = '\0'; jsonrpc_unpack_setting.delimiter_bytes = 1; hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); if (listenio == NULL) { return -20; } printf("listenfd=%d\n", hio_fd(listenio)); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/jsonrpc/router.h000066400000000000000000000011071520575453600304310ustar00rootroot00000000000000#ifndef HV_JSON_RPC_ROUTER_H_ #define HV_JSON_RPC_ROUTER_H_ #include "cJSON.h" typedef void (*jsonrpc_handler)(cJSON* jreq, cJSON* jres); typedef struct { const char* method; jsonrpc_handler handler; } jsonrpc_router; void error_response(cJSON* jres, int code, const char* message); void not_found(cJSON* jreq, cJSON* jres); void bad_request(cJSON* jreq, cJSON* jres); void calc_add(cJSON* jreq, cJSON* jres); void calc_sub(cJSON* jreq, cJSON* jres); void calc_mul(cJSON* jreq, cJSON* jres); void calc_div(cJSON* jreq, cJSON* jres); #endif // HV_JSON_RPC_ROUTER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/000077500000000000000000000000001520575453600265675ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/README.md000066400000000000000000000044611520575453600300530ustar00rootroot00000000000000# Intro kcptun > *Disclaimer: The picture comes from [github.com/xtaci/kcptun](https://github.com/xtaci/kcptun). Thanks so much.* # Build ```shell ./configure --with-kcp make clean make examples make kcptun ``` # Usage ```shell $ bin/kcptun_server -h Usage: kcptun_server [hvdl:t:m:] Options: -h|--help Print this information -v|--version Print version -d|--daemon Daemonize -l|--listen value kcp server listen address (default: ":4000") -t|--target value target server address (default: "127.0.0.1:8080") -m|--mode value profiles: fast3, fast2, fast, normal (default: "fast") --mtu value set maximum transmission unit for UDP packets (default: 1350) --sndwnd value set send window size(num of packets) (default: 1024) --rcvwnd value set receive window size(num of packets) (default: 1024) ``` ```shell $ bin/kcptun_client -h Usage: kcptun_client [hvdl:r:m:] Options: -h|--help Print this information -v|--version Print version -d|--daemon Daemonize -l|--localaddr value local listen address (default: ":8388") -r|--remoteaddr value kcp server address (default: "127.0.0.1:4000") -m|--mode value profiles: fast3, fast2, fast, normal (default: "fast") --mtu value set maximum transmission unit for UDP packets (default: 1350) --sndwnd value set send window size(num of packets) (default: 128) --rcvwnd value set receive window size(num of packets) (default: 512) ``` # Test `tcp_client -> kcptun_client -> kcptun_server -> tcp_server` ```shell tcp_server: bin/tcp_echo_server 1234 kcptun_server: bin/kcptun_server -l :4000 -t 127.0.0.1:1234 --mode fast3 kcptun_client: bin/kcptun_client -l :8388 -r 127.0.0.1:4000 --mode fast3 tcp_client: bin/nc 127.0.0.1 8388 > hello < hello ``` This kcptun examples does not implement encryption, compression, and fec.
if you want to use [github.com/xtaci/kcptun](https://github.com/xtaci/kcptun), please add `--crypt null --nocomp --ds 0 --ps 0`.
For example: ```shell golang_kcptun_server -l :4000 -t 127.0.0.1:1234 --mode fast3 --crypt null --nocomp --ds 0 --ps 0 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/client/000077500000000000000000000000001520575453600300455ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/client/main.cpp000066400000000000000000000263451520575453600315070ustar00rootroot00000000000000/* * kcptun client * * @build: ./configure --with-kcp && make clean && make kcptun examples * @tcp_server: bin/tcp_echo_server 1234 * @kcptun_server: bin/kcptun_server -l :4000 -t 127.0.0.1:1234 * @kcptun_client: bin/kcptun_client -l :8388 -r 127.0.0.1:4000 * @tcp_client: bin/nc 127.0.0.1 8388 * > hello * < hello */ #define WITH_KCP 1 #include "hversion.h" #include "hmain.h" #include "hsocket.h" #include "hloop.h" #include "hthread.h" #include "../smux/smux.h" // config static const char* localaddr = ":8388"; static const char* remoteaddr = "127.0.0.1:4000"; static const char* mode = "fast"; static int mtu = 1350; static int sndwnd = 128; static int rcvwnd = 512; // long options static const option_t long_options[] = { {'h', "help", NO_ARGUMENT, "Print this information"}, {'v', "version", NO_ARGUMENT, "Print version"}, {'d', "daemon", NO_ARGUMENT, "Daemonize"}, {'l', "localaddr", REQUIRED_ARGUMENT, "local listen address (default: \":8388\")"}, {'r', "remoteaddr", REQUIRED_ARGUMENT, "kcp server address (default: \"127.0.0.1:4000\")"}, {'m', "mode", REQUIRED_ARGUMENT, "profiles: fast3, fast2, fast, normal, (default: \"fast\")"}, { 0, "mtu", REQUIRED_ARGUMENT, "set maxinum transmission unit for UDP packets (default: 1350)"}, { 0, "sndwnd", REQUIRED_ARGUMENT, "set send window size(num of packets) (default: 128)"}, { 0, "rcvwnd", REQUIRED_ARGUMENT, "set receive window size(num of packets) (default: 512)"}, }; static void print_version() { printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); } static void print_help() { char detail_options[1024] = {0}; dump_opt_long(long_options, ARRAY_SIZE(long_options), detail_options, sizeof(detail_options)); printf("%s\n", detail_options); } static char listen_host[64] = "0.0.0.0"; static int listen_port = 8388; static hio_t* listen_io = NULL; static kcp_setting_t s_kcp_setting; static char kcp_host[64] = "127.0.0.1"; static int kcp_port = 4000; static hio_t* kcp_io = NULL; static smux_config_t smux_config; static smux_session_t smux_session; static smux_stream_t smux_stream0; static int verbose = 1; typedef struct kcp_ctx_s { smux_frame_t frame; uint16_t want_readbytes; } kcp_ctx_t; /* workflow: * * hloop_create_tcp_server -> * on_accept -> smux_session_open_stream -> * on_recv -> hio_write(kcp_io) -> * on_close -> smux_session_close_stream * * hloop_create_udp_client -> hio_set_kcp -> * on_recvfrom -> smux_session_get_stream -> hio_write(stream_io) * */ static void send_hearbeat(htimer_t* timer) { smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(timer); if (smux_stream == NULL) return; // NOP int packlen = smux_stream_output(smux_stream, SMUX_CMD_NOP); if (packlen > 0) { // printf("NOP %d\n", packlen); hio_write(kcp_io, smux_stream->wbuf.base, packlen); } } static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("disconnected connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(io); if (smux_stream == NULL) return; // FIN int packlen = smux_stream_output(smux_stream, SMUX_CMD_FIN); if (packlen > 0) { // printf("FIN %d\n", packlen); hio_write(kcp_io, smux_stream->wbuf.base, packlen); } // kill timer if (smux_stream->timer) { htimer_del(smux_stream->timer); smux_stream->timer = NULL; } // free buffer HV_FREE(smux_stream->rbuf.base); HV_FREE(smux_stream->wbuf.base); smux_session_close_stream(&smux_session, smux_stream->stream_id); hevent_set_userdata(io, NULL); } static void on_recv(hio_t* io, void* buf, int readbytes) { // printf("on_recv %.*s \n", readbytes, (char*)buf); smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(io); if (smux_stream == NULL) return; // PSH smux_frame_t frame; smux_frame_init(&frame); frame.head.sid = smux_stream->stream_id; frame.head.cmd = SMUX_CMD_PSH; frame.head.length = readbytes; frame.data = (const char*)buf; int packlen = smux_frame_pack(&frame, smux_stream->wbuf.base, smux_stream->wbuf.len); if (packlen > 0) { // printf("PSH %d\n", packlen); int nwrite = hio_write(kcp_io, smux_stream->wbuf.base, packlen); // printf("PSH ret=%d\n", nwrite); } } static void on_accept(hio_t* io) { // printf("on_accept connfd=%d\n", hio_fd(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } hio_setcb_close(io, on_close); smux_stream_t* smux_stream = smux_session_open_stream(&smux_session, 0, io); // alloc buffer smux_stream->rbuf.len = mtu; smux_stream->wbuf.len = mtu; HV_ALLOC(smux_stream->rbuf.base, smux_stream->rbuf.len); HV_ALLOC(smux_stream->wbuf.base, smux_stream->wbuf.len); hio_set_readbuf(io, smux_stream->rbuf.base, smux_config.max_frame_size); /* // set heartbeat timer if (smux_config.keepalive_interval > 0) { smux_stream->timer = htimer_add(hevent_loop(io), send_hearbeat, smux_config.keepalive_interval, INFINITE); hevent_set_userdata(smux_stream->timer, smux_stream); } */ hevent_set_userdata(io, smux_stream); // SYN int packlen = smux_stream_output(smux_stream, SMUX_CMD_SYN); if (packlen > 0) { // printf("SYN %d\n", packlen); hio_write(kcp_io, smux_stream->wbuf.base, packlen); } hio_setcb_read(io, on_recv); hio_read(io); } static void on_kcp_recvfrom(hio_t* io, void* buf, int readbytes) { // printf("on_kcp_recvfrom %d\n", readbytes); kcp_ctx_t* kcp_ctx = (kcp_ctx_t*)hevent_userdata(io); smux_frame_t* frame = &kcp_ctx->frame; if (kcp_ctx->want_readbytes > 0) { frame->data = (const char*)buf; frame->head.length = readbytes; kcp_ctx->want_readbytes -= readbytes; } else { smux_frame_init(frame); int packlen = smux_frame_unpack(frame, buf, readbytes); if (packlen < 0 || frame->head.version > 2 || frame->head.cmd > SMUX_CMD_UPD) { fprintf(stderr, "smux_frame_unpack error: %d\n", packlen); return; } int datalen = packlen - SMUX_HEAD_LENGTH; if (datalen < frame->head.length) { kcp_ctx->want_readbytes = frame->head.length - datalen; frame->head.length = datalen; } } // printf("smux sid=%u cmd=%d length=%d\n", frame->head.sid, (int)frame->head.cmd, (int)frame->head.length); smux_stream_t* smux_stream = smux_session_get_stream(&smux_session, kcp_ctx->frame.head.sid); if (smux_stream == NULL) { if (frame->head.sid != 0 && frame->head.cmd != SMUX_CMD_FIN) { fprintf(stderr, "recvfrom invalid smux package!\n"); } return; } switch (frame->head.cmd) { case SMUX_CMD_SYN: hio_setcb_read(smux_stream->io, on_recv); hio_read(smux_stream->io); break; case SMUX_CMD_FIN: hio_close(smux_stream->io); break; case SMUX_CMD_PSH: hio_write(smux_stream->io, frame->data, frame->head.length); break; case SMUX_CMD_NOP: break; default: break; } } int main(int argc, char** argv) { if (argc < 2) { print_help(); exit(0); } // g_main_ctx main_ctx_init(argc, argv); int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); if (ret != 0) { print_help(); exit(ret); } // help if (get_arg("h")) { print_help(); exit(0); } // version if (get_arg("v")) { print_version(); exit(0); } #ifdef OS_UNIX // daemon if (get_arg("d")) { // nochdir, noclose int ret = daemon(1, 1); if (ret != 0) { printf("daemon error: %d\n", ret); exit(-10); } } #endif const char* arg = get_arg("l"); if (arg) { localaddr = arg; } arg = get_arg("r"); if (arg) { remoteaddr = arg; } arg = get_arg("m"); if (arg) { mode = arg; } arg = get_arg("mtu"); if (arg) { mtu = atoi(arg); } arg = get_arg("sndwnd"); if (arg) { sndwnd = atoi(arg); } arg = get_arg("rcvwnd"); if (arg) { rcvwnd = atoi(arg); } const char* pos = strchr(localaddr, ':'); int len = 0; if (pos) { len = pos - localaddr; if (len > 0) { memcpy(listen_host, localaddr, len); listen_host[len] = '\0'; } listen_port = atoi(pos + 1); } pos = strchr(remoteaddr, ':'); if (pos) { len = pos - remoteaddr; if (len > 0) { memcpy(kcp_host, remoteaddr, len); kcp_host[len] = '\0'; } kcp_port = atoi(pos + 1); } if (strcmp(mode, "normal") == 0) { kcp_setting_init_with_normal_mode(&s_kcp_setting); } else if (strcmp(mode, "fast") == 0) { kcp_setting_init_with_fast_mode(&s_kcp_setting); } else if (strcmp(mode, "fast2") == 0) { kcp_setting_init_with_fast2_mode(&s_kcp_setting); } else if (strcmp(mode, "fast3") == 0) { kcp_setting_init_with_fast3_mode(&s_kcp_setting); } else { fprintf(stderr, "Unknown mode '%s'\n", mode); exit(-20); } s_kcp_setting.conv = hv_getpid(); s_kcp_setting.mtu = mtu; s_kcp_setting.sndwnd = sndwnd; s_kcp_setting.rcvwnd = rcvwnd; printf("smux version: 1\n"); printf("%s:%d => %s:%d\n", listen_host, listen_port, kcp_host, kcp_port); printf("mode: %s\n", mode); printf("mtu: %d\n", mtu); printf("sndwnd: %d rcvwnd: %d\n", sndwnd, rcvwnd); hloop_t* loop = hloop_new(0); listen_io = hloop_create_tcp_server(loop, listen_host, listen_port, on_accept); if (listen_io == NULL) { fprintf(stderr, "create tcp server error!\n"); return -30; } kcp_io = hloop_create_udp_client(loop, kcp_host, kcp_port); if (kcp_io == NULL) { fprintf(stderr, "create udp client error!\n"); return -40; } hio_set_kcp(kcp_io, &s_kcp_setting); kcp_ctx_t* kcp_ctx = NULL; HV_ALLOC_SIZEOF(kcp_ctx); hevent_set_userdata(kcp_io, kcp_ctx); hio_setcb_read(kcp_io, on_kcp_recvfrom); hio_read(kcp_io); // smux smux_config.max_frame_size = 1024; smux_session.next_stream_id = 1; smux_stream0.stream_id = 0; // set heartbeat timer if (smux_config.keepalive_interval > 0) { htimer_t* timer = htimer_add(loop, send_hearbeat, smux_config.keepalive_interval, INFINITE); hevent_set_userdata(timer, &smux_stream0); } hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/kcptun.png000066400000000000000000001012661520575453600306070ustar00rootroot00000000000000PNG  IHDRzX+PLTE6dJsBg\$OwbStяBnχr"Mv\|ℜ3[p-Ԧ0YEio+Uvyux9*ϕbW>dKuζuZz:`kJm)Szi_~Hk|~ş8f `___L?¤??@c_f j$VVV... ߾}?1ߠǬu3$y˹lNHkqIDATx;n0DA~+r& Blg4r{qaDÜq8wq}0ƽ& ʒ^* /.}8\t;/PY^\sua̰>LzE)z'wZRlu㺝t~0>g.:NAݤqp|MߖEe?mLSP1|75tI,̤SP1|}t1&ώ 30&s}-}8\T\|5Y؈=;Ϸ3I)nɴEĭĖq$拳^]gcz%Is"4GKpMw3l8bՋXVl17M=4T =]o̻Y.X8\bSLr0gJwqo<-`t|Ĕ<V8t?K} 0jdݩoN~&㘒瞮t3`:kY+-YWַuݳvFc 7{g6ᤍ+B#CZ"0pّX+B`9" ݻ1tEjBb\K{E\Wo#R2^8kd m/ݤ(FB=P90UKGn_RɹvKGnEz=P 9khUK7_ ~n=".ҎoZ#f0𗢉 @\VѮ3^N$4Gnҕtl r:JmL#K֟/<\T/P]6"ZKw_H:ٹPĂXĹI[5MΕ L13W>9 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o6\\,#;NE n:()B~en#RR޻uP\IT~ ɹ*B8Ô Gw1y{ Q96]Ȥ~Yk ?Ao4DrnDwwH#˷~e5qgMF萸{@i²M\WR4˴#OEr,4:SJ ,O-1vۏ^6dcb,:pu!xYY=5`aZ尦%9?nA +6OB !=@RaaO23ErnRֺW]Do(EG93eTc\[WqlYʝl[Ywˏݶ&:r7$s3G($6qۨGwApQG0>"zR<ƑTɹ)z@^׳@8+Heģ[aX\(,z 0~:vn$rWrU0w}Z8? )be h0y2VʢZoLH1/s5[͊޼34}2?^?B~pkyK,ѻ9!5](F$2PE&ҿހkv2c-&EFЭltzîy;Cꉇαt]$Eoj>Ji[GEX4w[ՠ^9 *W7ϊв[j=6C_ic(L̸/R DǫJB޲Eh+tDr ,NYSXBٱ~=ϼ R-*j↫RqREk# lhD_7}&a+\0慭sӎlf*%V"לbt ?sX15gQ<_ NN^e#~}b\2c }^TB!xV&7U3 GS8p4HVΞ ::4yqs>:IQWp>INrۜ2Ak+9a>Bܽ9zl{}[p!9INr[⎫Fr-z 5hP;kHNryqpBrՎܻ .9INr#܍\h[5<4$w٣+;v Q4KLtFOW.q}ï9~$rǵD6q9\@"q\ H8ksqm. 8$rǵD6q9zl9ӑ8˽cuq\q;qh>q9\@"q\ H8ksqm. 8$rǵD6q9\@"q\ H8ksqm. 8$ruu}q:rqw867.vq\q;qh>q9\@"q\ H8ksc8E . L޸6O|UQ$rǵD6q9\@"q\ H8ksqm. 8$rǵD.s,r8rܾmrq\OqSqqK8sqm. 8$rǵD6q9\@"q\ H8ksqm. 8$rǵD6q9\@"q\[\}#qsqܶqrǽ|8pǽ~20 IENDB`kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/server/000077500000000000000000000000001520575453600300755ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/server/main.cpp000066400000000000000000000240471520575453600315340ustar00rootroot00000000000000/* * kcptun server * * @build: ./configure --with-kcp && make clean && make kcptun examples * @tcp_server: bin/tcp_echo_server 1234 * @kcptun_server: bin/kcptun_server -l :4000 -t 127.0.0.1:1234 * @kcptun_client: bin/kcptun_client -l :8388 -r 127.0.0.1:4000 * @tcp_client: bin/nc 127.0.0.1 8388 * > hello * < hello */ #define WITH_KCP 1 #include "hversion.h" #include "hmain.h" #include "hsocket.h" #include "hloop.h" #include "../smux/smux.h" // config static const char* localaddr = ":4000"; static const char* targetaddr = "127.0.0.1:8080"; static const char* mode = "fast"; static int mtu = 1350; static int sndwnd = 1024; static int rcvwnd = 1024; // long options static const option_t long_options[] = { {'h', "help", NO_ARGUMENT, "Print this information"}, {'v', "version", NO_ARGUMENT, "Print version"}, {'d', "daemon", NO_ARGUMENT, "Daemonize"}, {'l', "listen", REQUIRED_ARGUMENT, "kcp server listen address (default: \":4000\")"}, {'t', "target", REQUIRED_ARGUMENT, "target server address (default: \"127.0.0.1:8080\")"}, {'m', "mode", REQUIRED_ARGUMENT, "profiles: fast3, fast2, fast, normal, (default: \"fast\")"}, { 0, "mtu", REQUIRED_ARGUMENT, "set maxinum transmission unit for UDP packets (default: 1350)"}, { 0, "sndwnd", REQUIRED_ARGUMENT, "set send window size(num of packets) (default: 1024)"}, { 0, "rcvwnd", REQUIRED_ARGUMENT, "set receive window size(num of packets) (default: 1024)"}, }; static void print_version() { printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); } static void print_help() { char detail_options[1024] = {0}; dump_opt_long(long_options, ARRAY_SIZE(long_options), detail_options, sizeof(detail_options)); printf("%s\n", detail_options); } static kcp_setting_t s_kcp_setting; static char kcp_host[64] = "0.0.0.0"; static int kcp_port = 4000; static hio_t* kcp_io = NULL; static char target_host[64] = "127.0.0.1"; static int target_port = 8080; static smux_config_t smux_config; static smux_session_t smux_session; static int verbose = 1; /* workflow: * * hloop_create_udp_server -> on_recvfrom -> * * SYN -> hloop_create_tcp_client -> * on_connect -> hio_write(kcp_io, SYN) -> * on_read -> hio_write(kcp_io) -> * on_close -> hio_write(kcp_io, FIN) -> smux_session_close_stream * * PSH -> smux_session_get_stream -> hio_write(stream_io) * * FIN -> smux_session_get_stream -> hio_close(stream_io) * */ // hloop_create_udp_server -> hio_set_kcp -> on_recvfrom -> // SYN -> hloop_create_tcp_client -> smux_session_open_stream -> // PSH -> hio_write(io) static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("disconnected connfd=%d [%s] => [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(io); if (smux_stream == NULL) return; // FIN int packlen = smux_stream_output(smux_stream, SMUX_CMD_FIN); if (packlen > 0) { // printf("FIN %d\n", packlen); hio_write(kcp_io, smux_stream->wbuf.base, packlen); } // kill timer if (smux_stream->timer) { htimer_del(smux_stream->timer); smux_stream->timer = NULL; } // free buffer HV_FREE(smux_stream->rbuf.base); HV_FREE(smux_stream->wbuf.base); smux_session_close_stream(&smux_session, smux_stream->stream_id); hevent_set_userdata(io, NULL); } static void on_recv(hio_t* io, void* buf, int readbytes) { // printf("on_recv %.*s \n", readbytes, (char*)buf); smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(io); if (smux_stream == NULL) return; // PSH smux_frame_t frame; smux_frame_init(&frame); frame.head.sid = smux_stream->stream_id; frame.head.cmd = SMUX_CMD_PSH; frame.head.length = readbytes; frame.data = (const char*)buf; int packlen = smux_frame_pack(&frame, smux_stream->wbuf.base, smux_stream->wbuf.len); if (packlen > 0) { // printf("PSH %d\n", packlen); int nwrite = hio_write(kcp_io, smux_stream->wbuf.base, packlen); // printf("PSH ret=%d\n", nwrite); } } static void on_connect(hio_t* io) { // printf("on_connect fd=%d\n", hio_fd(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("connected connfd=%d [%s] => [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } smux_stream_t* smux_stream = (smux_stream_t*)hevent_userdata(io); if (smux_stream == NULL) return; // SYN int packlen = smux_stream_output(smux_stream, SMUX_CMD_SYN); if (packlen > 0) { // printf("SYN %d\n", packlen); hio_write(kcp_io, smux_stream->wbuf.base, packlen); } hio_setcb_read(io, on_recv); hio_read(io); } static void on_kcp_recvfrom(hio_t* io, void* buf, int readbytes) { // printf("on_kcp_recvfrom %d\n", readbytes); smux_frame_t frame; smux_frame_init(&frame); int packlen = smux_frame_unpack(&frame, buf, readbytes); assert(packlen == readbytes); if (packlen < 0 || frame.head.version > 2 || frame.head.cmd > SMUX_CMD_UPD) { fprintf(stderr, "smux_frame_unpack error: %d\n", packlen); return; } // printf("smux sid=%u cmd=%d length=%d\n", frame.head.sid, (int)frame.head.cmd, (int)frame.head.length); smux_stream_t* smux_stream = NULL; if (frame.head.cmd == SMUX_CMD_SYN) { hio_t* target_io = hio_create_socket(hevent_loop(kcp_io), target_host, target_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (target_io == NULL) { fprintf(stderr, "create tcp client error!\n"); return; } smux_stream = smux_session_open_stream(&smux_session, frame.head.sid, target_io); // alloc buffer smux_stream->rbuf.len = mtu; smux_stream->wbuf.len = mtu; HV_ALLOC(smux_stream->rbuf.base, smux_stream->rbuf.len); HV_ALLOC(smux_stream->wbuf.base, smux_stream->wbuf.len); hio_set_readbuf(target_io, smux_stream->rbuf.base, smux_config.max_frame_size); hevent_set_userdata(target_io, smux_stream); hio_setcb_connect(target_io, on_connect); hio_setcb_close(target_io, on_close); hio_connect(target_io); } else { smux_stream = smux_session_get_stream(&smux_session, frame.head.sid); } if (smux_stream == NULL) { if (frame.head.sid != 0 && frame.head.cmd != SMUX_CMD_FIN) { fprintf(stderr, "recvfrom invalid smux package!\n"); } return; } switch (frame.head.cmd) { case SMUX_CMD_FIN: hio_close(smux_stream->io); break; case SMUX_CMD_PSH: hio_write(smux_stream->io, frame.data, frame.head.length); break; case SMUX_CMD_NOP: break; default: break; } } int main(int argc, char** argv) { if (argc < 2) { print_help(); exit(0); } // g_main_ctx main_ctx_init(argc, argv); int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); if (ret != 0) { print_help(); exit(ret); } // help if (get_arg("h")) { print_help(); exit(0); } // version if (get_arg("v")) { print_version(); exit(0); } #ifdef OS_UNIX // daemon if (get_arg("d")) { // nochdir, noclose int ret = daemon(1, 1); if (ret != 0) { printf("daemon error: %d\n", ret); exit(-10); } } #endif const char* arg = get_arg("l"); if (arg) { localaddr = arg; } arg = get_arg("t"); if (arg) { targetaddr = arg; } arg = get_arg("m"); if (arg) { mode = arg; } arg = get_arg("mtu"); if (arg) { mtu = atoi(arg); } arg = get_arg("sndwnd"); if (arg) { sndwnd = atoi(arg); } arg = get_arg("rcvwnd"); if (arg) { rcvwnd = atoi(arg); } const char* pos = strchr(localaddr, ':'); int len = 0; if (pos) { len = pos - localaddr; if (len > 0) { memcpy(kcp_host, localaddr, len); kcp_host[len] = '\0'; } kcp_port = atoi(pos + 1); } pos = strchr(targetaddr, ':'); if (pos) { len = pos - targetaddr; if (len > 0) { memcpy(target_host, targetaddr, len); target_host[len] = '\0'; } target_port = atoi(pos + 1); } if (strcmp(mode, "normal") == 0) { kcp_setting_init_with_normal_mode(&s_kcp_setting); } else if (strcmp(mode, "fast") == 0) { kcp_setting_init_with_fast_mode(&s_kcp_setting); } else if (strcmp(mode, "fast2") == 0) { kcp_setting_init_with_fast2_mode(&s_kcp_setting); } else if (strcmp(mode, "fast3") == 0) { kcp_setting_init_with_fast3_mode(&s_kcp_setting); } else { fprintf(stderr, "Unknown mode '%s'\n", mode); exit(-20); } s_kcp_setting.mtu = mtu; s_kcp_setting.sndwnd = sndwnd; s_kcp_setting.rcvwnd = rcvwnd; printf("smux version: 1\n"); printf("%s:%d => %s:%d\n", kcp_host, kcp_port, target_host, target_port); printf("mode: %s\n", mode); printf("mtu: %d\n", mtu); printf("sndwnd: %d rcvwnd: %d\n", sndwnd, rcvwnd); hloop_t* loop = hloop_new(0); kcp_io = hloop_create_udp_server(loop, kcp_host, kcp_port); if (kcp_io == NULL) { fprintf(stderr, "create udp server error!\n"); return -20; } hio_set_kcp(kcp_io, &s_kcp_setting); hio_setcb_read(kcp_io, on_kcp_recvfrom); hio_read(kcp_io); // smux smux_config.max_frame_size = 1024; smux_session.next_stream_id = 0; hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/smux/000077500000000000000000000000001520575453600275635ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/smux/smux.cpp000066400000000000000000000041441520575453600312660ustar00rootroot00000000000000#include "smux.h" #define SMUX_USE_LITTLE_ENDIAN 1 int smux_frame_pack(const smux_frame_t* frame, void* buf, int len) { if (!frame || !buf || !len) return -1; const smux_head_t* head = &(frame->head); unsigned int packlen = smux_package_length(head); // Check is buffer enough if (len < packlen) { return -2; } unsigned char* p = (unsigned char*)buf; *p++ = head->version; *p++ = head->cmd; #if SMUX_USE_LITTLE_ENDIAN *p++ = head->length; *p++ = (head->length >> 8) & 0xFF; #else // hton length *p++ = (head->length >> 8) & 0xFF; *p++ = head->length; #endif uint32_t sid = head->sid; #if SMUX_USE_LITTLE_ENDIAN *p++ = sid & 0xFF; *p++ = (sid >> 8) & 0xFF; *p++ = (sid >> 16) & 0xFF; *p++ = (sid >> 24) & 0xFF; #else // hton sid *p++ = (sid >> 24) & 0xFF; *p++ = (sid >> 16) & 0xFF; *p++ = (sid >> 8) & 0xFF; *p++ = sid & 0xFF; #endif // memcpy data if (frame->data && head->length) { memcpy(p, frame->data, frame->head.length); } return packlen; } int smux_frame_unpack(smux_frame_t* frame, const void* buf, int len) { if (!frame || !buf || !len) return -1; if (len < SMUX_HEAD_LENGTH) return -2; smux_head_t* head = &(frame->head); unsigned char* p = (unsigned char*)buf; head->version = *p++; head->cmd = *p++; #if SMUX_USE_LITTLE_ENDIAN head->length = *p++; head->length |= ((uint16_t)*p++) << 8; #else // ntoh length head->length = ((uint16_t)*p++) << 8; head->length |= *p++; #endif #if SMUX_USE_LITTLE_ENDIAN head->sid = *p++; head->sid |= ((uint32_t)*p++) << 8; head->sid |= ((uint32_t)*p++) << 16; head->sid |= ((uint32_t)*p++) << 24; #else // ntoh sid head->sid = ((uint32_t)*p++) << 24; head->sid |= ((uint32_t)*p++) << 16; head->sid |= ((uint32_t)*p++) << 8; head->sid |= *p++; #endif // NOTE: just shadow copy if (len > SMUX_HEAD_LENGTH) { frame->data = (const char*)buf + SMUX_HEAD_LENGTH; } unsigned int packlen = smux_package_length(head); return MIN(len, packlen); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/kcptun/smux/smux.h000066400000000000000000000070471520575453600307400ustar00rootroot00000000000000#ifndef HV_SMUX_H_ #define HV_SMUX_H_ /* * smux: Simple MUltipleXing used by kcptun * @see: https://github.com/xtaci/smux * */ #include #include "hplatform.h" #include "hbase.h" #include "hbuf.h" #include "hloop.h" typedef enum { // v1 SMUX_CMD_SYN = 0, // stream open SMUX_CMD_FIN = 1, // stream close SMUX_CMD_PSH = 2, // data push SMUX_CMD_NOP = 3, // no operation // v2 SMUX_CMD_UPD = 4, // update } smux_cmd_e; typedef struct { uint8_t version; uint8_t cmd; uint16_t length; uint32_t sid; } smux_head_t; #define SMUX_HEAD_LENGTH 8 typedef struct { smux_head_t head; const char* data; } smux_frame_t; static inline unsigned int smux_package_length(const smux_head_t* head) { return SMUX_HEAD_LENGTH + head->length; } static inline void smux_head_init(smux_head_t* head) { head->version = 1; head->cmd = (uint8_t)SMUX_CMD_PSH; head->length = 0; head->sid = 0; } static inline void smux_frame_init(smux_frame_t* frame) { smux_head_init(&frame->head); frame->data = NULL; } // @retval >0 package_length, <0 error int smux_frame_pack(const smux_frame_t* frame, void* buf, int len); // @retval >0 package_length, <0 error int smux_frame_unpack(smux_frame_t* frame, const void* buf, int len); typedef struct smux_config_s { int version; int keepalive_interval; int keepalive_timeout; int max_frame_size; smux_config_s() { version = 1; keepalive_interval = 10000; keepalive_timeout = 30000; max_frame_size = 1024; } } smux_config_t; typedef struct { uint32_t stream_id; smux_frame_t frame; hbuf_t rbuf; hbuf_t wbuf; hio_t* io; htimer_t* timer; } smux_stream_t; // @retval >0 package_length, <0 error, data => wbuf static inline int smux_stream_output(smux_stream_t* stream, smux_frame_t* frame) { return smux_frame_pack(frame, stream->wbuf.base, stream->wbuf.len); } static inline int smux_stream_output(smux_stream_t* stream, smux_cmd_e cmd) { smux_frame_t frame; smux_frame_init(&frame); frame.head.sid = stream->stream_id; frame.head.cmd = (uint8_t)cmd; return smux_frame_pack(&frame, stream->wbuf.base, stream->wbuf.len); } // @retval >0 package_length, <0 error, data => frame static inline int smux_stream_input(smux_stream_t* stream, const void* buf, int len) { return smux_frame_unpack(&stream->frame, buf, len); } typedef struct { uint32_t next_stream_id; // stream_id => smux_stream_t std::map streams; } smux_session_t; static inline smux_stream_t* smux_session_open_stream(smux_session_t* session, uint32_t stream_id = 0, hio_t* io = NULL) { smux_stream_t* stream = NULL; HV_ALLOC_SIZEOF(stream); if (stream_id == 0) { session->next_stream_id += 2; stream_id = session->next_stream_id; } stream->stream_id = stream_id; session->streams[stream_id] = stream; stream->io = io; return stream; } static inline smux_stream_t* smux_session_get_stream(smux_session_t* session, uint32_t stream_id) { auto iter = session->streams.find(stream_id); if (iter != session->streams.end()) { return iter->second; } return NULL; } static inline void smux_session_close_stream(smux_session_t* session, uint32_t stream_id) { auto iter = session->streams.find(stream_id); if (iter != session->streams.end()) { HV_FREE(iter->second); session->streams.erase(iter); } } #endif // HV_SMUX_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/mqtt/000077500000000000000000000000001520575453600262505ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/mqtt/mqtt_client_test.cpp000066400000000000000000000035201520575453600323360ustar00rootroot00000000000000/* * mqtt client * * @build make examples * * @test bin/mqtt_client_test 127.0.0.1 1883 topic payload * */ #include "mqtt_client.h" using namespace hv; /* * @test MQTTS * #define TEST_SSL 1 * * @build ./configure --with-mqtt --with-openssl && make clean && make * */ #define TEST_SSL 0 #define TEST_AUTH 0 #define TEST_RECONNECT 1 #define TEST_QOS 0 int main(int argc, char** argv) { if (argc < 5) { printf("Usage: %s host port topic payload\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); const char* topic = argv[3]; const char* payload = argv[4]; MqttClient cli; cli.onConnect = [topic, payload](MqttClient* cli) { printf("connected!\n"); #if TEST_QOS cli->subscribe(topic, 1, [topic, payload](MqttClient* cli) { printf("subscribe OK!\n"); cli->publish(topic, payload, 1, 0, [](MqttClient* cli) { printf("publish OK!\n"); }); }); #else cli->subscribe(topic); cli->publish(topic, payload); #endif }; cli.onMessage = [](MqttClient* cli, mqtt_message_t* msg) { printf("topic: %.*s\n", msg->topic_len, msg->topic); printf("payload: %.*s\n", msg->payload_len, msg->payload); cli->disconnect(); cli->stop(); }; cli.onClose = [](MqttClient* cli) { printf("disconnected!\n"); }; #if TEST_AUTH cli.setAuth("test", "123456"); #endif #if TEST_RECONNECT reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; cli.setReconnect(&reconn); #endif cli.setPingInterval(10); int ssl = 0; #if TEST_SSL ssl = 1; #endif cli.connect(host, port, ssl); cli.run(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/mqtt/mqtt_pub.c000066400000000000000000000066671520575453600302660ustar00rootroot00000000000000/* * mqtt publish * * @build make examples * @sub bin/mqtt_sub 127.0.0.1 1883 topic * @pub bin/mqtt_pub 127.0.0.1 1883 topic payload * */ #include "hv.h" #include "mqtt_client.h" /* * @test MQTTS * #define TEST_SSL 1 * * @build ./configure --with-mqtt --with-openssl && make clean && make * */ #define TEST_SSL 0 #define TEST_AUTH 0 /* * workflow: * mqtt_client_new -> mqtt_client_xxx -> mqtt_client_run * * mqtt_client_set_xxx -> * mqtt_client_connect -> * on_connack -> mqtt_client_publish -> * on_puback -> mqtt_client_disconnect -> * on_disconnect -> mqtt_client_stop * */ static void on_mqtt(mqtt_client_t* cli, int type) { printf("on_mqtt type=%d\n", type); switch(type) { case MQTT_TYPE_CONNECT: printf("mqtt connected!\n"); break; case MQTT_TYPE_DISCONNECT: printf("mqtt disconnected!\n"); { mqtt_message_t* msg = (mqtt_message_t*)mqtt_client_get_userdata(cli); HV_FREE(msg); mqtt_client_set_userdata(cli, NULL); mqtt_client_stop(cli); } break; case MQTT_TYPE_CONNACK: printf("mqtt connack!\n"); { mqtt_message_t* msg = (mqtt_message_t*)mqtt_client_get_userdata(cli); if (msg == NULL) return; int mid = mqtt_client_publish(cli, msg); printf("mqtt publish mid=%d\n", mid); if (msg->qos == 0) { mqtt_client_disconnect(cli); } else if (msg->qos == 1) { // wait MQTT_TYPE_PUBACK } else if (msg->qos == 2) { // wait MQTT_TYPE_PUBREC } } break; case MQTT_TYPE_PUBACK: /* qos = 1 */ printf("mqtt puback mid=%d\n", cli->mid); mqtt_client_disconnect(cli); break; case MQTT_TYPE_PUBREC: /* qos = 2 */ printf("mqtt pubrec mid=%d\n", cli->mid); // wait MQTT_TYPE_PUBCOMP break; case MQTT_TYPE_PUBCOMP: /* qos = 2 */ printf("mqtt pubcomp mid=%d\n", cli->mid); mqtt_client_disconnect(cli); break; default: break; } } static int mqtt_publish(const char* host, int port, const char* topic, const char* payload) { mqtt_client_t* cli = mqtt_client_new(NULL); if (cli == NULL) return -1; cli->keepalive = 10; // client_id char client_id[64]; snprintf(client_id, sizeof(client_id), "mqtt_pub_%ld", hv_getpid()); printf("client_id: %s\n", client_id); mqtt_client_set_id(cli, client_id); // will mqtt_message_t will; memset(&will, 0, sizeof(will)); will.topic = "will"; will.payload = "This is a will."; mqtt_client_set_will(cli, &will); #if TEST_AUTH mqtt_client_set_auth(cli, "test", "123456"); #endif mqtt_message_t* msg = NULL; HV_ALLOC_SIZEOF(msg); msg->topic = topic; msg->topic_len = strlen(topic); msg->payload = payload; msg->payload_len = strlen(payload); msg->qos = 1; mqtt_client_set_userdata(cli, msg); mqtt_client_set_callback(cli, on_mqtt); int ssl = 0; #if TEST_SSL ssl = 1; #endif mqtt_client_connect(cli, host, port, ssl); mqtt_client_run(cli); mqtt_client_free(cli); return 0; } int main(int argc, char** argv) { if (argc < 5) { printf("Usage: %s host port topic payload\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); const char* topic = argv[3]; const char* payload = argv[4]; return mqtt_publish(host, port, topic, payload); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/mqtt/mqtt_sub.c000066400000000000000000000056601520575453600302610ustar00rootroot00000000000000/* * mqtt subscribe * * @build make examples * @sub bin/mqtt_sub 127.0.0.1 1883 topic * @pub bin/mqtt_pub 127.0.0.1 1883 topic payload * */ #include "hv.h" #include "mqtt_client.h" /* * @test MQTTS * #define TEST_SSL 1 * * @build ./configure --with-mqtt --with-openssl && make clean && make * */ #define TEST_SSL 0 #define TEST_AUTH 0 #define TEST_RECONNECT 1 /* * workflow: * mqtt_client_new -> mqtt_client_xxx -> mqtt_client_run * * mqtt_client_set_xxx -> * mqtt_client_connect -> * on_connack -> mqtt_client_subscribe -> * on_publish -> handle_message * */ static void handle_message(mqtt_client_t* cli, mqtt_message_t* msg) { printf("topic: %.*s\n", msg->topic_len, msg->topic); printf("payload: %.*s\n", msg->payload_len, msg->payload); } static void on_mqtt(mqtt_client_t* cli, int type) { printf("on_mqtt type=%d\n", type); switch(type) { case MQTT_TYPE_CONNECT: printf("mqtt connected!\n"); if (cli->reconn_setting && cli->reconn_setting->cur_retry_cnt > 0) { printf("mqtt reconnect cnt=%d, delay=%d\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); } break; case MQTT_TYPE_DISCONNECT: printf("mqtt disconnected!\n"); if (cli->reconn_setting && cli->reconn_setting->cur_retry_cnt > 0) { printf("mqtt reconnect cnt=%d, delay=%d\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); } break; case MQTT_TYPE_CONNACK: printf("mqtt connack!\n"); { const char* topic = (const char*)mqtt_client_get_userdata(cli); int mid = mqtt_client_subscribe(cli, topic, 0); printf("mqtt subscribe mid=%d\n", mid); } break; case MQTT_TYPE_SUBACK: printf("mqtt suback mid=%d\n", cli->mid); break; case MQTT_TYPE_PUBLISH: handle_message(cli, &cli->message); default: break; } } static int mqtt_subscribe(const char* host, int port, const char* topic) { mqtt_client_t* cli = mqtt_client_new(NULL); if (cli == NULL) return -1; cli->keepalive = 10; #if TEST_AUTH mqtt_client_set_auth(cli, "test", "123456"); #endif mqtt_client_set_userdata(cli, (void*)topic); mqtt_client_set_callback(cli, on_mqtt); #if TEST_RECONNECT reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; mqtt_client_set_reconnect(cli, &reconn); #endif int ssl = 0; #if TEST_SSL ssl = 1; #endif mqtt_client_connect(cli, host, port, ssl); mqtt_client_run(cli); mqtt_client_free(cli); return 0; } int main(int argc, char** argv) { if (argc < 4) { printf("Usage: %s host port topic\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); const char* topic = argv[3]; return mqtt_subscribe(host, port, topic); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/multi-thread/000077500000000000000000000000001520575453600276625ustar00rootroot00000000000000multi-acceptor-processes.c000066400000000000000000000045561520575453600347150ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/multi-thread/* * * @build make examples * @server bin/multi-acceptor-processes 1234 * @client bin/nc 127.0.0.1 1234 * nc 127.0.0.1 1234 * telnet 127.0.0.1 1234 */ #include "hloop.h" #include "hsocket.h" #include "hthread.h" #include "hproc.h" static char protocol = 't'; static const char* protocolname = "tcp"; static const char* host = "0.0.0.0"; static int port = 1234; static int process_num = 4; static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); } static void on_recv(hio_t* io, void* buf, int readbytes) { // echo hio_write(io, buf, readbytes); } static void on_accept(hio_t* io) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("pid=%ld connfd=%d [%s] <= [%s]\n", (long)hv_getpid(), (int)hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_read(io); } static void loop_proc(void* userdata) { int sockfd = (int)(intptr_t)(userdata); hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE); hio_t* io = hio_get(loop, sockfd); if (protocol == 't') { hio_setcb_accept(io, on_accept); hio_accept(io); } else if (protocol == 'u') { hio_setcb_read(io, on_recv); hio_read(io); } hloop_run(loop); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } int index = 1; if (argv[1][0] == '-') { protocol = argv[1][1]; switch(protocol) { case 't': protocolname = "tcp"; break; case 'u': protocolname = "udp"; break; default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); } ++index; } port = atoi(argv[index++]); int sockfd = -1; if (protocol == 't') { sockfd = Listen(port, host); } else if (protocol == 'u') { sockfd = Bind(port, host, SOCK_DGRAM); } if (sockfd < 0) { exit(1); } proc_ctx_t ctx; memset(&ctx, 0, sizeof(ctx)); ctx.proc = loop_proc; ctx.proc_userdata = (void*)(intptr_t)sockfd; for (int i = 0; i < process_num; ++i) { hproc_spawn(&ctx); } while(1) hv_sleep(1); return 0; } multi-acceptor-threads.c000066400000000000000000000044131520575453600343310ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/multi-thread/* * * @build make examples * @server bin/multi-acceptor-threads 1234 * @client bin/nc 127.0.0.1 1234 * nc 127.0.0.1 1234 * telnet 127.0.0.1 1234 */ #include "hloop.h" #include "hsocket.h" #include "hthread.h" static char protocol = 't'; static const char* protocolname = "tcp"; static const char* host = "0.0.0.0"; static int port = 1234; static int thread_num = 4; static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); } static void on_recv(hio_t* io, void* buf, int readbytes) { // echo hio_write(io, buf, readbytes); } static void on_accept(hio_t* io) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("tid=%ld connfd=%d [%s] <= [%s]\n", (long)hv_gettid(), (int)hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_read(io); } static HTHREAD_ROUTINE(loop_thread) { int sockfd = (int)(intptr_t)(userdata); hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE); hio_t* io = hio_get(loop, sockfd); if (protocol == 't') { hio_setcb_accept(io, on_accept); hio_accept(io); } else if (protocol == 'u') { hio_setcb_read(io, on_recv); hio_read(io); } hloop_run(loop); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd [-tu] port\n"); return -10; } int index = 1; if (argv[1][0] == '-') { protocol = argv[1][1]; switch(protocol) { case 't': protocolname = "tcp"; break; case 'u': protocolname = "udp"; break; default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); } ++index; } port = atoi(argv[index++]); int sockfd = -1; if (protocol == 't') { sockfd = Listen(port, host); } else if (protocol == 'u') { sockfd = Bind(port, host, SOCK_DGRAM); } if (sockfd < 0) { exit(1); } for (int i = 0; i < thread_num; ++i) { hthread_create(loop_thread, (void*)(intptr_t)sockfd); } while(1) hv_sleep(1); return 0; } one-acceptor-multi-workers.c000066400000000000000000000046551520575453600351620ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/multi-thread/* * * @build make examples * @server bin/one-acceptor-multi-workers 1234 * @client bin/nc 127.0.0.1 1234 * nc 127.0.0.1 1234 * telnet 127.0.0.1 1234 */ #include "hloop.h" #include "hsocket.h" #include "hthread.h" static const char* host = "0.0.0.0"; static int port = 1234; static int thread_num = 4; static hloop_t* accept_loop = NULL; static hloop_t** worker_loops = NULL; static hloop_t* get_next_loop() { static int s_cur_index = 0; if (++s_cur_index >= thread_num) { s_cur_index = 0; } return worker_loops[s_cur_index % thread_num]; } static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); } static void on_recv(hio_t* io, void* buf, int readbytes) { // echo hio_write(io, buf, readbytes); } static void new_conn_event(hevent_t* ev) { hloop_t* loop = ev->loop; hio_t* io = (hio_t*)hevent_userdata(ev); hio_attach(loop, io); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("tid=%ld connfd=%d [%s] <= [%s]\n", (long)hv_gettid(), (int)hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_read(io); } static void on_accept(hio_t* io) { hio_detach(io); hloop_t* worker_loop = get_next_loop(); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.loop = worker_loop; ev.cb = new_conn_event; ev.userdata = io; hloop_post_event(worker_loop, &ev); } static HTHREAD_ROUTINE(worker_thread) { hloop_t* loop = (hloop_t*)userdata; hloop_run(loop); return 0; } static HTHREAD_ROUTINE(accept_thread) { hloop_t* loop = (hloop_t*)userdata; hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); if (listenio == NULL) { exit(1); } hloop_run(loop); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: cmd port\n"); return -10; } port = atoi(argv[1]); worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); for (int i = 0; i < thread_num; ++i) { worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); hthread_create(worker_thread, worker_loops[i]); } accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); accept_thread(accept_loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/nc.c000066400000000000000000000143021520575453600260270ustar00rootroot00000000000000/* * network client * * @build: make examples * @server bin/httpd -s restart -d * @usage: bin/nc 127.0.0.1 8080 * > GET / HTTP/1.1 * > Connection: close * > [Enter] * > GET / HTTP/1.1 * > Connection: keep-alive * > [Enter] */ /* * @test udp client * @build ./configure && make examples * @client bin/nc -u 127.0.0.1 1234 * */ /* * @test ssl client * @build ./configure --with-openssl && make clean && make * @client bin/nc -s 127.0.0.1 1234 * */ /* * @test kcp client * @build ./configure --with-kcp && make clean && make * @client bin/nc -k 127.0.0.1 1234 * */ #include "hloop.h" #include "hbase.h" #include "hsocket.h" #include "hssl.h" #define RECV_BUFSIZE 8192 static char recvbuf[RECV_BUFSIZE]; static char protocol = 't'; static const char* protocolname = "tcp"; // for stdin static hio_t* stdinio = NULL; // for socket static hio_t* sockio = NULL; static int verbose = 0; static void send_heartbeat(hio_t* io) { static char buf[] = "PING\r\n"; // printf("send_heartbeat %s", buf); hio_write(io, buf, 6); } static void on_recv(hio_t* io, void* buf, int readbytes) { // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } printf("%.*s", readbytes, (char*)buf); // test hio_set_readbuf in hread_cb #if 0 static int total_readbytes = 0; total_readbytes += readbytes; if (total_readbytes >= RECV_BUFSIZE) { total_readbytes = 0; } hio_set_readbuf(io, recvbuf + total_readbytes, RECV_BUFSIZE - total_readbytes); printf("%.*s", total_readbytes, recvbuf); #endif fflush(stdout); } static void on_stdin(hio_t* io, void* buf, int readbytes) { // printf("on_stdin fd=%d readbytes=%d\n", hio_fd(io), readbytes); // printf("> %s\n", buf); char* str = (char*)buf; // test hio_read_start/hio_read_stop/hio_close/hloop_stop #if 1 if (strncmp(str, "start", 5) == 0) { printf("call hio_read_start\n"); hio_read_start(sockio); return; } else if (strncmp(str, "stop", 4) == 0) { printf("call hio_read_stop\n"); hio_read_stop(sockio); return; } else if (strncmp(str, "close", 5) == 0) { printf("call hio_close\n"); hio_close(sockio); return; } else if (strncmp(str, "quit", 4) == 0) { printf("call hloop_stop\n"); hloop_stop(hevent_loop(io)); return; } #endif // CR|LF => CRLF for test most protocols char eol = str[readbytes-1]; if (eol == '\n' || eol == '\r') { if (readbytes > 1 && str[readbytes-2] == '\r' && eol == '\n') { // have been CRLF } else { ++readbytes; str[readbytes - 2] = '\r'; str[readbytes - 1] = '\n'; } } hio_write(sockio, buf, readbytes); if (strncmp(str, "CLOSE", 5) == 0) { printf("call hio_close\n"); hio_close(sockio); } } static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); hio_del(stdinio, HV_READ); } static void on_connect(hio_t* io) { // printf("on_connect fd=%d\n", hio_fd(io)); if (verbose) { char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("connect connfd=%d [%s] => [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); } hio_read_start(io); // uncomment to test heartbeat // hio_set_heartbeat(sockio, 3000, send_heartbeat); } int main(int argc, char** argv) { if (argc < 3) { printf("\ Usage: nc [-tusk] host port\n\ Options:\n\ -t Use tcp protocol (default)\n\ -u Use udp protocol\n\ -s Use ssl protocol\n\ -k Use kcp protocol\n\ Examples: nc 127.0.0.1 80\n\ nc -u 127.0.0.1 80\n"); return -10; } int index = 1; if (argv[1][0] == '-') { protocol = argv[1][1]; switch(protocol) { case 't': protocolname = "tcp"; break; case 'u': protocolname = "udp"; break; case 's': protocolname = "ssl"; break; case 'k': protocolname = "kcp"; break; default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); } ++index; } const char* host = argv[index++]; int port = atoi(argv[index++]); if (verbose) { printf("%s %s %d\n", protocolname, host, port); } HV_MEMCHECK; hloop_t* loop = hloop_new(HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS); // stdin use default readbuf stdinio = hread(loop, 0, NULL, 0, on_stdin); if (stdinio == NULL) { return -20; } // socket if (protocol == 't' || protocol == 's') { // tcp sockio = hloop_create_tcp_client(loop, host, port, on_connect, on_close); if (sockio == NULL) { return -20; } if (protocol == 's') { if (strcmp(hssl_backend(), "nossl") == 0) { fprintf(stderr, "Please recompile WITH_SSL!\n"); exit(1); } hio_enable_ssl(sockio); } } else if (protocol == 'u' || protocol == 'k') { // udp sockio = hloop_create_udp_client(loop, host, port); if (sockio == NULL) { return -20; } if (protocol == 'k') { #if WITH_KCP static kcp_setting_t s_kcp_setting; kcp_setting_init_with_normal_mode(&s_kcp_setting); s_kcp_setting.conv = hv_rand(1, 999999); hio_set_kcp(sockio, &s_kcp_setting); #else fprintf(stderr, "Please recompile WITH_KCP!\n"); exit(1); #endif } hio_read(sockio); } // printf("sockfd=%d\n", hio_fd(sockio)); hio_setcb_close(sockio, on_close); hio_setcb_read(sockio, on_recv); hio_set_readbuf(sockio, recvbuf, RECV_BUFSIZE); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/nmap/000077500000000000000000000000001520575453600262165ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/nmap/main.cpp000066400000000000000000000062731520575453600276560ustar00rootroot00000000000000#include #include #include #include "nmap.h" #include "hsocket.h" #include "hthreadpool.h" int host_discover_task(std::string segment, void* nmap) { Nmap* hosts= (Nmap*)nmap; return host_discover(segment.c_str(), hosts); } int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: nmap segment\n"); printf("Examples: nmap 192.168.1.123\n"); printf(" nmap 192.168.1.x/24\n"); printf(" nmap 192.168.x.x/16\n"); return -1; } char* segment = argv[1]; char* split = strchr(segment, '/'); int n = 24; if (split) { *split = '\0'; n = atoi(split+1); if (n != 24 && n != 16) { return -2; } } Nmap hosts; char ip[INET_ADDRSTRLEN]; if (n == 24) { host_discover(segment, &hosts); } else if (n == 16) { Nmap segs; int up_nsegs = segment_discover(segment, &segs); if (up_nsegs == 0) return 0; #if 1 for (auto& pair : segs) { if (pair.second == 1) { uint32_t addr = pair.first; uint8_t* p = (uint8_t*)&addr; // 0,255 reserved for (int i = 1; i < 255; ++i) { p[3] = i; hosts[addr] = 0; } } } nmap_discover(&hosts); #else if (up_nsegs == 1) { for (auto& pair : segs) { if (pair.second == 1) { inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip)); host_discover(ip, &hosts); } } } else { // ThreadPool + host_discover Nmap* hosts = new Nmap[up_nsegs]; // use ThreadPool HThreadPool tp(4); tp.start(); std::vector> futures; int i = 0; for (auto& pair : segs) { if (pair.second == 1) { inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip)); auto future = tp.commit(host_discover_task, std::string(ip), &hosts[i++]); futures.push_back(std::move(future)); } } // wait all task done int nhosts = 0; for (auto& future : futures) { nhosts += future.get(); } // filter up hosts std::vector up_hosts; for (int i = 0; i < up_nsegs; ++i) { Nmap& nmap = hosts[i]; for (auto& host : nmap) { if (host.second == 1) { up_hosts.push_back(host.first); } } } delete[] hosts; } #endif } // filter up hosts std::vector up_hosts; for (auto& pair : hosts) { if (pair.second == 1) { up_hosts.push_back(pair.first); } } // print up hosts printf("Up hosts %lu:\n", (unsigned long)up_hosts.size()); for (auto& host : up_hosts) { inet_ntop(AF_INET, (void*)&host, ip, sizeof(ip)); printf("%s\n", ip); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/nmap/nmap.cpp000066400000000000000000000126271520575453600276650ustar00rootroot00000000000000#include "nmap.h" #include "hloop.h" #include "hstring.h" #include "hsocket.h" #include "netinet.h" using namespace hv; #define MAX_RECVFROM_TIMEOUT 5000 // ms #define MAX_SENDTO_PERSOCKET 1024 typedef struct nmap_ctx_s { Nmap* nmap; int send_cnt; int recv_cnt; int up_cnt; int idle_cnt; } nmap_ctx_t; static void on_idle(hidle_t* idle) { hloop_t* loop = hevent_loop(idle); nmap_ctx_t* ctx = (nmap_ctx_t*)hloop_userdata(loop); ctx->idle_cnt++; if (ctx->idle_cnt == 1) { // try again? } hloop_stop(loop); } static void on_timer(htimer_t* timer) { hloop_t* loop = hevent_loop(timer); hloop_stop(loop); } static void on_recvfrom(hio_t* io, void* buf, int readbytes) { //printd("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printd("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ hloop_t* loop = hevent_loop(io); nmap_ctx_t* ctx = (nmap_ctx_t*)hloop_userdata(loop); if (++ctx->recv_cnt == ctx->send_cnt) { //hloop_stop(loop); } Nmap* nmap = ctx->nmap; struct sockaddr_in* peeraddr = (struct sockaddr_in*)hio_peeraddr(io); auto iter = nmap->find(peeraddr->sin_addr.s_addr); if (iter != nmap->end()) { if (iter->second == 0) { iter->second = 1; if (++ctx->up_cnt == nmap->size()) { hloop_stop(loop); } } } } int nmap_discover(Nmap* nmap) { hloop_t* loop = hloop_new(0); uint64_t start_hrtime = hloop_now_hrtime(loop); nmap_ctx_t ctx; ctx.nmap = nmap; ctx.send_cnt = 0; ctx.recv_cnt = 0; ctx.up_cnt = 0; ctx.idle_cnt = 0; hloop_set_userdata(loop, &ctx); char recvbuf[128]; // icmp char sendbuf[44]; // 20IP + 44ICMP = 64 icmp_t* icmp_req = (icmp_t*)sendbuf; icmp_req->icmp_type = ICMP_ECHO; icmp_req->icmp_code = 0; icmp_req->icmp_id = getpid(); for (int i = 0; i < sizeof(sendbuf) - sizeof(icmphdr_t); ++i) { icmp_req->icmp_data[i] = i; } struct sockaddr_in peeraddr; hio_t* io = NULL; for (auto iter = nmap->begin(); iter != nmap->end(); ++iter) { if (iter->second == 1) continue; if (ctx.send_cnt % MAX_SENDTO_PERSOCKET == 0) { // socket int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (sockfd < 0) { perror("socket"); if (errno == EPERM) { fprintf(stderr, "please use root or sudo to create a raw socket.\n"); } return -socket_errno(); } nonblocking(sockfd); so_sndbuf(sockfd, 425984); // 416K io = hio_get(loop, sockfd); if (io == NULL) return -1; hio_set_type(io, HIO_TYPE_IP); struct sockaddr_in localaddr; socklen_t addrlen = sizeof(localaddr); memset(&localaddr, 0, addrlen); localaddr.sin_addr.s_addr = htonl(INADDR_ANY); hio_set_localaddr(io, (struct sockaddr*)&localaddr, addrlen); hrecvfrom(loop, sockfd, recvbuf, sizeof(recvbuf), on_recvfrom); } icmp_req->icmp_seq = iter->first; icmp_req->icmp_cksum = 0; icmp_req->icmp_cksum = checksum((uint8_t*)icmp_req, sizeof(sendbuf)); socklen_t addrlen = sizeof(peeraddr); memset(&peeraddr, 0, addrlen); peeraddr.sin_family = AF_INET; peeraddr.sin_addr.s_addr = iter->first; hio_set_peeraddr(io, (struct sockaddr*)&peeraddr, addrlen); hsendto(loop, hio_fd(io), sendbuf, sizeof(sendbuf), NULL); ++ctx.send_cnt; } htimer_add(loop, on_timer, MAX_RECVFROM_TIMEOUT, 1); hidle_add(loop, on_idle, 3); hloop_run(loop); uint64_t end_hrtime = hloop_now_hrtime(loop); hloop_free(&loop); // print result char ip[INET_ADDRSTRLEN]; auto iter = nmap->begin(); while (iter != nmap->end()) { inet_ntop(AF_INET, (void*)&iter->first, ip, sizeof(ip)); printd("%s\t is %s.\n", ip, iter->second == 0 ? "down" : "up"); ++iter; } printd("Nmap done: %lu IP addresses (%d hosts up) scanned in %.2f seconds\n", (unsigned long)nmap->size(), ctx.up_cnt, (end_hrtime-start_hrtime)/1000000.0f); return ctx.up_cnt; } int segment_discover(const char* segment16, Nmap* nmap) { StringList strlist = split(segment16, '.'); if (strlist.size() != 4) return -1; uint32_t addr = 0; uint8_t* p = (uint8_t*)&addr; p[0] = atoi(strlist[0].c_str()); p[1] = atoi(strlist[1].c_str()); p[3] = 1; printd("Nmap scan %u.%u.x.1...\n", p[0], p[1]); nmap->clear(); for (int i = 0; i < 256; ++i) { p[2] = i; (*nmap)[addr] = 0; } return nmap_discover(nmap); } int host_discover(const char* segment24, Nmap* nmap) { StringList strlist = split(segment24, '.'); if (strlist.size() != 4) return -1; uint32_t addr = 0; uint8_t* p = (uint8_t*)&addr; p[0] = atoi(strlist[0].c_str()); p[1] = atoi(strlist[1].c_str()); p[2] = atoi(strlist[2].c_str()); printd("Nmap scan %u.%u.%u.x...\n", p[0], p[1], p[2]); // 0,255 reserved nmap->clear(); for (int i = 1; i < 255; ++i) { p[3] = i; (*nmap)[addr] = 0; } return nmap_discover(nmap); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/nmap/nmap.h000066400000000000000000000006131520575453600273220ustar00rootroot00000000000000#ifndef HV_NMAP_H_ #define HV_NMAP_H_ #include #include // addr => 0:down 1:up typedef std::map Nmap; // ip = segment + host // segment16: 192.168.x.x // segment24: 192.168.1.x // @return up_cnt int nmap_discover(Nmap* nmap); int segment_discover(const char* segment16, Nmap* nmap); int host_discover(const char* segment24, Nmap* nmap); #endif // HV_NMAP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/pipe_test.c000066400000000000000000000021341520575453600274230ustar00rootroot00000000000000/* * hio_create_pipe test * * @build make examples * @test bin/pipe_test * */ #include "hloop.h" #include "htime.h" static hio_t* pipeio[2] = { NULL, NULL }; static void on_read(hio_t* io, void* buf, int readbytes) { printf("< %.*s\n", readbytes, (char*)buf); } static void on_timer_write(htimer_t* timer) { char str[DATETIME_FMT_BUFLEN] = {0}; datetime_t dt = datetime_now(); datetime_fmt(&dt, str); hio_write(pipeio[1], str, strlen(str)); } static void on_timer_stop(htimer_t* timer) { hio_close(pipeio[0]); hio_close(pipeio[1]); hloop_stop(hevent_loop(timer)); } int main(int argc, char** argv) { hloop_t* loop = hloop_new(0); int ret = hio_create_pipe(loop, pipeio); if (ret != 0) { printf("hio_create_pipe failed!\n"); return -10; } printf("pipefd %d<=>%d\n", hio_fd(pipeio[0]), hio_fd(pipeio[1])); hio_setcb_read(pipeio[0], on_read); hio_read(pipeio[0]); htimer_add(loop, on_timer_write, 1000, INFINITE); htimer_add(loop, on_timer_stop, 10000, 1); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/000077500000000000000000000000001520575453600271335ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/handler/000077500000000000000000000000001520575453600305505ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/handler/calc.h000066400000000000000000000042661520575453600316330ustar00rootroot00000000000000#ifndef HV_PROTO_RPC_HANDLER_CALC_H_ #define HV_PROTO_RPC_HANDLER_CALC_H_ #include "../router.h" #include "../generated/calc.pb.h" void calc_add(const protorpc::Request& req, protorpc::Response* res) { // params if (req.params_size() != 2) { return bad_request(req, res); } protorpc::CalcParam param1, param2; if (!param1.ParseFromString(req.params(0)) || !param2.ParseFromString(req.params(1))) { return bad_request(req, res); } // result protorpc::CalcResult result; result.set_num(param1.num() + param2.num()); res->set_result(result.SerializeAsString()); } void calc_sub(const protorpc::Request& req, protorpc::Response* res) { // params if (req.params_size() != 2) { return bad_request(req, res); } protorpc::CalcParam param1, param2; if (!param1.ParseFromString(req.params(0)) || !param2.ParseFromString(req.params(1))) { return bad_request(req, res); } // result protorpc::CalcResult result; result.set_num(param1.num() - param2.num()); res->set_result(result.SerializeAsString()); } void calc_mul(const protorpc::Request& req, protorpc::Response* res) { // params if (req.params_size() != 2) { return bad_request(req, res); } protorpc::CalcParam param1, param2; if (!param1.ParseFromString(req.params(0)) || !param2.ParseFromString(req.params(1))) { return bad_request(req, res); } // result protorpc::CalcResult result; result.set_num(param1.num() * param2.num()); res->set_result(result.SerializeAsString()); } void calc_div(const protorpc::Request& req, protorpc::Response* res) { // params if (req.params_size() != 2) { return bad_request(req, res); } protorpc::CalcParam param1, param2; if (!param1.ParseFromString(req.params(0)) || !param2.ParseFromString(req.params(1))) { return bad_request(req, res); } if (param2.num() == 0) { return bad_request(req, res); } // result protorpc::CalcResult result; result.set_num(param1.num() / param2.num()); res->set_result(result.SerializeAsString()); } #endif // HV_PROTO_RPC_HANDLER_CALC_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/handler/handler.h000066400000000000000000000010351520575453600323350ustar00rootroot00000000000000#ifndef HV_PROTO_RPC_HANDLER_H_ #define HV_PROTO_RPC_HANDLER_H_ #include "../router.h" void error_response(protorpc::Response* res, int code, const std::string& message) { res->mutable_error()->set_code(code); res->mutable_error()->set_message(message); } void not_found(const protorpc::Request& req, protorpc::Response* res) { error_response(res, 404, "Not Found"); } void bad_request(const protorpc::Request& req, protorpc::Response* res) { error_response(res, 400, "Bad Request"); } #endif // HV_PROTO_RPC_HANDLER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/handler/login.h000066400000000000000000000012241520575453600320300ustar00rootroot00000000000000#ifndef HV_PROTO_RPC_HANDLER_LOGIN_H_ #define HV_PROTO_RPC_HANDLER_LOGIN_H_ #include "../router.h" #include "../generated/login.pb.h" void login(const protorpc::Request& req, protorpc::Response* res) { // params if (req.params_size() == 0) { return bad_request(req, res); } protorpc::LoginParam param; if (!param.ParseFromString(req.params(0))) { return bad_request(req, res); } // result protorpc::LoginResult result; result.set_user_id(123456); result.set_token(param.username() + ":" + param.password()); res->set_result(result.SerializeAsString()); } #endif // HV_PROTO_RPC_HANDLER_LOGIN_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/proto/000077500000000000000000000000001520575453600302765ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/proto/base.proto000066400000000000000000000004631520575453600323000ustar00rootroot00000000000000syntax = "proto3"; package protorpc; message Error { int32 code = 1; string message = 2; } message Request { uint64 id = 1; string method = 2; repeated bytes params = 3; } message Response { uint64 id = 1; bytes result = 2; Error error = 3; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/proto/calc.proto000066400000000000000000000002071520575453600322640ustar00rootroot00000000000000syntax = "proto3"; package protorpc; message CalcParam { int64 num = 1; } message CalcResult { int64 num = 1; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/proto/login.proto000066400000000000000000000003131520575453600324700ustar00rootroot00000000000000syntax = "proto3"; package protorpc; message LoginParam { string username = 1; string password = 2; } message LoginResult { uint64 user_id = 1; string token = 2; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/proto/protoc.sh000077500000000000000000000004711520575453600321450ustar00rootroot00000000000000#!/bin/bash cd `dirname $0` PROTOC=`which protoc` if [ $? -ne 0 ]; then echo "Not found command protoc!" echo "Please install libprotobuf first!" exit 1 fi CPP_OUT_DIR=../generated if [ ! -d "${CPP_OUT_DIR}" ]; then mkdir -p ${CPP_OUT_DIR} fi set -x ${PROTOC} --cpp_out=${CPP_OUT_DIR} *.proto kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/protorpc.c000066400000000000000000000036031520575453600311510ustar00rootroot00000000000000#include "protorpc.h" #include // import memcpy int protorpc_pack(const protorpc_message* msg, void* buf, int len) { if (!msg || !buf || !len) return -1; const protorpc_head* head = &(msg->head); unsigned int packlen = protorpc_package_length(head); // Check is buffer enough if (len < packlen) { return -2; } unsigned char* p = (unsigned char*)buf; *p++ = head->protocol[0]; *p++ = head->protocol[1]; *p++ = head->protocol[2]; *p++ = head->protocol[3]; *p++ = head->version; *p++ = head->flags; *p++ = head->reserved[0]; *p++ = head->reserved[1]; // hton length unsigned int length = head->length; *p++ = (length >> 24) & 0xFF; *p++ = (length >> 16) & 0xFF; *p++ = (length >> 8) & 0xFF; *p++ = length & 0xFF; // memcpy body if (msg->body && head->length) { memcpy(p, msg->body, head->length); } return packlen; } int protorpc_unpack(protorpc_message* msg, const void* buf, int len) { if (!msg || !buf || !len) return -1; if (len < PROTORPC_HEAD_LENGTH) return -2; protorpc_head* head = &(msg->head); const unsigned char* p = (const unsigned char*)buf; head->protocol[0] = *p++; head->protocol[1] = *p++; head->protocol[2] = *p++; head->protocol[3] = *p++; head->version = *p++; head->flags = *p++; head->reserved[0] = *p++; head->reserved[1] = *p++; // ntoh length head->length = ((unsigned int)*p++) << 24; head->length |= ((unsigned int)*p++) << 16; head->length |= ((unsigned int)*p++) << 8; head->length |= *p++; // Check is buffer enough unsigned int packlen = protorpc_package_length(head); if (len < packlen) { return -3; } // NOTE: just shadow copy if (len > PROTORPC_HEAD_LENGTH) { msg->body = (const char*)buf + PROTORPC_HEAD_LENGTH; } return packlen; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/protorpc.h000066400000000000000000000033051520575453600311550ustar00rootroot00000000000000#ifndef HV_PROTO_RPC_H_ #define HV_PROTO_RPC_H_ #include #ifdef __cplusplus extern "C" { #endif #define PROTORPC_NAME "HRPC" #define PROTORPC_VERSION 1 // protocol:4bytes + version:1byte + flags:1byte + reserved:2bytes + length:4bytes = 12bytes #define PROTORPC_HEAD_LENGTH 12 #define PROTORPC_HEAD_LENGTH_FIELD_OFFSET 8 #define PROTORPC_HEAD_LENGTH_FIELD_BYTES 4 typedef struct { unsigned char protocol[4]; unsigned char version; unsigned char flags; unsigned char reserved[2]; unsigned int length; } protorpc_head; typedef const char* protorpc_body; typedef struct { protorpc_head head; protorpc_body body; } protorpc_message; static inline unsigned int protorpc_package_length(const protorpc_head* head) { return PROTORPC_HEAD_LENGTH + head->length; } static inline void protorpc_head_init(protorpc_head* head) { // protocol = HRPC memcpy(head->protocol, PROTORPC_NAME, 4); head->version = PROTORPC_VERSION; head->reserved[0] = head->reserved[1] = 0; head->length = 0; } static inline void protorpc_message_init(protorpc_message* msg) { protorpc_head_init(&msg->head); msg->body = NULL; } static inline int protorpc_head_check(protorpc_head* head) { if (memcmp(head->protocol, PROTORPC_NAME, 4) != 0) { return -1; } if (head->version != PROTORPC_VERSION) { return -2; } return 0; } // @retval >0 package_length, <0 error int protorpc_pack(const protorpc_message* msg, void* buf, int len); // @retval >0 package_length, <0 error int protorpc_unpack(protorpc_message* msg, const void* buf, int len); #ifdef __cplusplus } // extern "C" #endif #endif // HV_PROTO_RPC_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/protorpc_client.cpp000066400000000000000000000210731520575453600330500ustar00rootroot00000000000000/* * proto rpc client * * @build make protorpc * @server bin/protorpc_server 1234 * @client bin/protorpc_client 127.0.0.1 1234 add 1 2 * */ #include "TcpClient.h" #include #include using namespace hv; #include "protorpc.h" #include "generated/base.pb.h" #include "generated/calc.pb.h" #include "generated/login.pb.h" // valgrind --leak-check=full --show-leak-kinds=all class ProtobufRAII { public: ProtobufRAII() { } ~ProtobufRAII() { google::protobuf::ShutdownProtobufLibrary(); } }; static ProtobufRAII s_protobuf; namespace protorpc { typedef std::shared_ptr RequestPtr; typedef std::shared_ptr ResponsePtr; enum ProtoRpcResult { kRpcSuccess = 0, kRpcTimeout = -1, kRpcError = -2, kRpcNoResult = -3, kRpcParseError = -4, }; class ProtoRpcContext { public: protorpc::RequestPtr req; protorpc::ResponsePtr res; private: std::mutex _mutex; std::condition_variable _cond; public: void wait(int timeout_ms) { std::unique_lock locker(_mutex); _cond.wait_for(locker, std::chrono::milliseconds(timeout_ms)); } void notify() { _cond.notify_one(); } }; typedef std::shared_ptr ContextPtr; class ProtoRpcClient : public TcpClient { public: ProtoRpcClient() : TcpClient() { connect_state = kInitialized; setConnectTimeout(5000); reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; setReconnect(&reconn); // init protorpc_unpack_setting unpack_setting_t protorpc_unpack_setting; memset(&protorpc_unpack_setting, 0, sizeof(unpack_setting_t)); protorpc_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; protorpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; protorpc_unpack_setting.body_offset = PROTORPC_HEAD_LENGTH; protorpc_unpack_setting.length_field_offset = PROTORPC_HEAD_LENGTH_FIELD_OFFSET; protorpc_unpack_setting.length_field_bytes = PROTORPC_HEAD_LENGTH_FIELD_BYTES; protorpc_unpack_setting.length_field_coding = ENCODE_BY_BIG_ENDIAN; setUnpack(&protorpc_unpack_setting); onConnection = [this](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { connect_state = kConnected; printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { connect_state = kDisconnectd; printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; onMessage = [this](const SocketChannelPtr& channel, Buffer* buf) { // protorpc_unpack protorpc_message msg; memset(&msg, 0, sizeof(msg)); int packlen = protorpc_unpack(&msg, buf->data(), buf->size()); if (packlen < 0) { printf("protorpc_unpack failed!\n"); return; } assert(packlen == buf->size()); if (protorpc_head_check(&msg.head) != 0) { printf("protorpc_head_check failed!\n"); return; } // Response::ParseFromArray auto res = std::make_shared(); if (!res->ParseFromArray(msg.body, msg.head.length)) { return; } // id => res calls_mutex.lock(); auto iter = calls.find(res->id()); if (iter == calls.end()) { calls_mutex.unlock(); return; } auto ctx = iter->second; calls_mutex.unlock(); ctx->res = res; ctx->notify(); }; } int connect(int port, const char* host = "127.0.0.1") { createsocket(port, host); connect_state = kConnecting; start(); return 0; } protorpc::ResponsePtr call(protorpc::RequestPtr& req, int timeout_ms = 10000) { if (connect_state != kConnected) { return NULL; } static std::atomic s_id = ATOMIC_VAR_INIT(0); req->set_id(++s_id); req->id(); auto ctx = std::make_shared(); ctx->req = req; calls_mutex.lock(); calls[req->id()] = ctx; calls_mutex.unlock(); // Request::SerializeToArray + protorpc_pack protorpc_message msg; protorpc_message_init(&msg); msg.head.length = req->ByteSize(); int packlen = protorpc_package_length(&msg.head); unsigned char* writebuf = NULL; HV_STACK_ALLOC(writebuf, packlen); packlen = protorpc_pack(&msg, writebuf, packlen); if (packlen > 0) { printf("%s\n", req->DebugString().c_str()); req->SerializeToArray(writebuf + PROTORPC_HEAD_LENGTH, msg.head.length); channel->write(writebuf, packlen); } HV_STACK_FREE(writebuf); // wait until response come or timeout ctx->wait(timeout_ms); auto res = ctx->res; calls_mutex.lock(); calls.erase(req->id()); calls_mutex.unlock(); if (res == NULL) { printf("RPC timeout!\n"); } else if (res->has_error()) { printf("RPC error:\n%s\n", res->error().DebugString().c_str()); } return res; } int calc(const char* method, int num1, int num2, int& out) { auto req = std::make_shared(); // method req->set_method(method); // params protorpc::CalcParam param1, param2; param1.set_num(num1); param2.set_num(num2); req->add_params()->assign(param1.SerializeAsString()); req->add_params()->assign(param2.SerializeAsString()); auto res = call(req); if (res == NULL) return kRpcTimeout; if (res->has_error()) return kRpcError; if (res->result().empty()) return kRpcNoResult; protorpc::CalcResult result; if (!result.ParseFromString(res->result())) return kRpcParseError; out = result.num(); return kRpcSuccess; } int login(const protorpc::LoginParam& param, protorpc::LoginResult* result) { auto req = std::make_shared(); // method req->set_method("login"); // params req->add_params()->assign(param.SerializeAsString()); auto res = call(req); if (res == NULL) return kRpcTimeout; if (res->has_error()) return kRpcError; if (res->result().empty()) return kRpcNoResult; if (!result->ParseFromString(res->result())) return kRpcParseError; return kRpcSuccess; } enum { kInitialized, kConnecting, kConnected, kDisconnectd, } connect_state; std::map calls; std::mutex calls_mutex; }; } int main(int argc, char** argv) { if (argc < 6) { printf("Usage: %s host port method param1 param2\n", argv[0]); printf("method = [add, sub, mul, div]\n"); printf("Examples:\n"); printf(" %s 127.0.0.1 1234 add 1 2\n", argv[0]); printf(" %s 127.0.0.1 1234 div 1 0\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); const char* method = argv[3]; const char* param1 = argv[4]; const char* param2 = argv[5]; protorpc::ProtoRpcClient cli; cli.connect(port, host); while (cli.connect_state == protorpc::ProtoRpcClient::kConnecting) hv_msleep(1); if (cli.connect_state == protorpc::ProtoRpcClient::kDisconnectd) { return -20; } // test login { protorpc::LoginParam param; param.set_username("admin"); param.set_password("123456"); protorpc::LoginResult result; if (cli.login(param, &result) == protorpc::kRpcSuccess) { printf("login success!\n"); printf("%s\n", result.DebugString().c_str()); } else { printf("login failed!\n"); } } // test calc { int num1 = atoi(param1); int num2 = atoi(param2); int result = 0; if (cli.calc(method, num1, num2, result) == protorpc::kRpcSuccess) { printf("calc success!\n"); printf("%d %s %d = %d\n", num1, method, num2, result); } else { printf("calc failed!\n"); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/protorpc_server.cpp000066400000000000000000000105311520575453600330750ustar00rootroot00000000000000/* * proto rpc server * * @build make protorpc * @server bin/protorpc_server 1234 * @client bin/protorpc_client 127.0.0.1 1234 add 1 2 * */ #include "TcpServer.h" using namespace hv; #include "protorpc.h" #include "router.h" #include "handler/handler.h" #include "handler/calc.h" #include "handler/login.h" // valgrind --leak-check=full --show-leak-kinds=all class ProtobufRAII { public: ProtobufRAII() { } ~ProtobufRAII() { google::protobuf::ShutdownProtobufLibrary(); } }; static ProtobufRAII s_protobuf; protorpc_router router[] = { {"add", calc_add}, {"sub", calc_sub}, {"mul", calc_mul}, {"div", calc_div}, {"login", login}, }; #define PROTORPC_ROUTER_NUM (sizeof(router)/sizeof(router[0])) class ProtoRpcServer : public TcpServer { public: ProtoRpcServer() : TcpServer() { onConnection = [](const SocketChannelPtr& channel) { std::string peeraddr = channel->peeraddr(); if (channel->isConnected()) { printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } else { printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); } }; onMessage = handleMessage; // init protorpc_unpack_setting unpack_setting_t protorpc_unpack_setting; memset(&protorpc_unpack_setting, 0, sizeof(unpack_setting_t)); protorpc_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; protorpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; protorpc_unpack_setting.body_offset = PROTORPC_HEAD_LENGTH; protorpc_unpack_setting.length_field_offset = PROTORPC_HEAD_LENGTH_FIELD_OFFSET; protorpc_unpack_setting.length_field_bytes = PROTORPC_HEAD_LENGTH_FIELD_BYTES; protorpc_unpack_setting.length_field_coding = ENCODE_BY_BIG_ENDIAN; setUnpack(&protorpc_unpack_setting); } int listen(int port) { return createsocket(port); } private: static void handleMessage(const SocketChannelPtr& channel, Buffer* buf) { // unpack -> Request::ParseFromArray -> router -> Response::SerializeToArray -> pack -> Channel::write // protorpc_unpack protorpc_message msg; memset(&msg, 0, sizeof(msg)); int packlen = protorpc_unpack(&msg, buf->data(), buf->size()); if (packlen < 0) { printf("protorpc_unpack failed!\n"); return; } assert(packlen == buf->size()); if (protorpc_head_check(&msg.head) != 0) { printf("protorpc_head_check failed!\n"); return; } // Request::ParseFromArray protorpc::Request req; protorpc::Response res; if (req.ParseFromArray(msg.body, msg.head.length)) { printf("> %s\n", req.DebugString().c_str()); res.set_id(req.id()); // router const char* method = req.method().c_str(); bool found = false; for (int i = 0; i < PROTORPC_ROUTER_NUM; ++i) { if (strcmp(method, router[i].method) == 0) { found = true; router[i].handler(req, &res); break; } } if (!found) { not_found(req, &res); } } else { bad_request(req, &res); } // Response::SerializeToArray + protorpc_pack protorpc_message_init(&msg); msg.head.length = res.ByteSize(); packlen = protorpc_package_length(&msg.head); unsigned char* writebuf = NULL; HV_STACK_ALLOC(writebuf, packlen); packlen = protorpc_pack(&msg, writebuf, packlen); if (packlen > 0) { printf("< %s\n", res.DebugString().c_str()); res.SerializeToArray(writebuf + PROTORPC_HEAD_LENGTH, msg.head.length); channel->write(writebuf, packlen); } HV_STACK_FREE(writebuf); } }; int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); ProtoRpcServer srv; int listenfd = srv.listen(port); if (listenfd < 0) { return -20; } printf("protorpc_server listen on port %d, listenfd=%d ...\n", port, listenfd); srv.setThreadNum(4); srv.start(); while (1) hv_sleep(1); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/protorpc/router.h000066400000000000000000000015741520575453600306330ustar00rootroot00000000000000#ifndef HV_PROTO_RPC_ROUTER_H_ #define HV_PROTO_RPC_ROUTER_H_ #include "generated/base.pb.h" typedef void (*protorpc_handler)(const protorpc::Request& req, protorpc::Response* res); typedef struct { const char* method; protorpc_handler handler; } protorpc_router; void error_response(protorpc::Response* res, int code, const std::string& message); void not_found(const protorpc::Request& req, protorpc::Response* res); void bad_request(const protorpc::Request& req, protorpc::Response* res); void calc_add(const protorpc::Request& req, protorpc::Response* res); void calc_sub(const protorpc::Request& req, protorpc::Response* res); void calc_mul(const protorpc::Request& req, protorpc::Response* res); void calc_div(const protorpc::Request& req, protorpc::Response* res); void login(const protorpc::Request& req, protorpc::Response* res); #endif // HV_PROTO_RPC_ROUTER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/socks5_proxy_server.c000066400000000000000000000325371520575453600314770ustar00rootroot00000000000000/* * socks5 proxy server * * @build: make examples * * @proxy_server bin/socks5_proxy_server 1080 * bin/socks5_proxy_server 1080 username password * * @proxy_client curl -v http://www.example.com/ --proxy socks5://127.0.0.1:1080 * curl -v http://www.example.com/ --proxy socks5://username:password@127.0.0.1:1080 * */ #include "hv.h" #include "hloop.h" static char proxy_host[64] = "0.0.0.0"; static int proxy_port = 1080; static const char* auth_username = NULL; static const char* auth_password = NULL; #define SOCKS5_VERSION ((uint8_t)5) #define SOCKS5_AUTH_VERSION ((uint8_t)1) #define SOCKS5_AUTH_SUCCESS ((uint8_t)0) #define SOCKS5_AUTH_FAILURE ((uint8_t)1) typedef enum { NoAuth = 0, GssApiAuth = 1, UserPassAuth = 2, } socks5_auth_method; typedef enum { ConnectCommand = 1, BindCommand = 2, AssociateCommand= 3, } socks5_command; typedef enum { IPv4Addr = 1, FqdnAddr = 3, IPv6Addr = 4, } socks5_addr_type; typedef enum { SuccessReply = 0, ServerFailure = 1, RuleFailure = 2, NetworkUnreachable = 3, HostUnreachable = 4, ConnectRefused = 5, TtlExpired = 6, CommandNotSupported = 7, AddrTypeNotSupported= 8, } socks5_reply_code; typedef enum { s_begin, s_auth_methods_count, s_auth_methods, s_auth_username_len, s_auth_username, s_auth_password_len, s_auth_password, s_request, s_dst_addr_type, s_dst_addr_len, s_dst_addr, s_dst_port, s_upstream, s_end, } socks5_state_e; typedef struct { hio_t* io; socks5_state_e state; socks5_addr_type addr_type; sockaddr_u addr; } socks5_conn_t; /* * workflow: * hloop_new -> hloop_create_tcp_server -> hloop_run * on_accept -> HV_ALLOC(socks5_conn_t) -> hio_readbytes(s_auth_methods_count:2) -> * on_recv -> hio_readbytes(s_auth_methods) -> * on_recv -> hio_write(auth_method) -> hio_readbytes(s_auth_username_len:2) -> * on_recv -> hio_readbytes(s_auth_username) -> * on_recv -> hio_readbytes(s_auth_password_len:1) -> * on_recv -> hio_readbytes(s_auth_password) -> hio_write(auth_result) -> * on_recv -> hio_readbytes(s_request:3) -> * on_recv -> hio_readbytes(addr_type:1) -> * on_recv -> hio_readbytes(addr_len:1) -> * on_recv -> hio_readbytes(addr) -> * on_recv -> hio_readbytes(port:2) -> * on_recv -> hio_setup_tcp_upstream(io, addr, port) -> * on_close -> hio_close_upstream -> HV_FREE(socks5_conn_t) * */ static void on_upstream_connect(hio_t* upstream_io) { // printf("on_upstream_connect connfd=%d\n", hio_fd(upstream_io)); socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(upstream_io); sockaddr_u* localaddr = (sockaddr_u*)hio_localaddr(upstream_io); uint8_t resp[32] = { SOCKS5_VERSION, SuccessReply, 0, IPv4Addr, 127,0,0,1, 0,80, 0 }; int resp_len = 3; if (localaddr->sa.sa_family == AF_INET) { resp[resp_len++] = IPv4Addr; memcpy(resp + resp_len, &localaddr->sin.sin_addr, 4); resp_len += 4; memcpy(resp + resp_len, &localaddr->sin.sin_port, 2); resp_len += 2; } else if (localaddr->sa.sa_family == AF_INET6) { resp[resp_len++] = IPv6Addr; memcpy(resp + resp_len, &localaddr->sin6.sin6_addr, 16); resp_len += 16; memcpy(resp + resp_len, &localaddr->sin6.sin6_port, 2); resp_len += 2; } hio_write(conn->io, resp, resp_len); hio_setcb_read(upstream_io, hio_write_upstream); hio_setcb_read(conn->io, hio_write_upstream); hio_read(conn->io); hio_read(upstream_io); } static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(io); if (conn) { hevent_set_userdata(io, NULL); HV_FREE(conn); } hio_close_upstream(io); } static void on_recv(hio_t* io, void* buf, int readbytes) { socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(io); const uint8_t* bytes = (uint8_t*)buf; switch(conn->state) { case s_begin: // printf("s_begin\n"); conn->state = s_auth_methods_count; case s_auth_methods_count: // printf("s_auth_methods_count\n"); { assert(readbytes == 2); uint8_t version = bytes[0]; uint8_t methods_count = bytes[1]; if (version != SOCKS5_VERSION || methods_count == 0) { fprintf(stderr, "Unsupprted socks version: %d\n", (int)version); hio_close(io); return; } conn->state = s_auth_methods; hio_readbytes(io, methods_count); } break; case s_auth_methods: // printf("s_auth_methods\n"); { // TODO: check auth methos uint8_t auth_method = NoAuth; if (auth_username && auth_password) { auth_method = UserPassAuth; } else { // TODO: Implement more auth methods } // send auth mothod uint8_t resp[2] = { SOCKS5_VERSION, NoAuth }; resp[1] = auth_method; hio_write(io, resp, 2); if (auth_method == NoAuth) { conn->state = s_request; hio_readbytes(io, 3); } else if (auth_method == UserPassAuth) { conn->state = s_auth_username_len; hio_readbytes(io, 2); } } break; case s_auth_username_len: // printf("s_auth_username_len\n"); { assert(readbytes == 2); uint8_t auth_version = bytes[0]; uint8_t username_len = bytes[1]; if (auth_version != SOCKS5_AUTH_VERSION || username_len == 0) { fprintf(stderr, "Unsupported auth version: %d\n", (int)auth_version); hio_close(io); return; } conn->state = s_auth_username; hio_readbytes(io, username_len); } break; case s_auth_username: // printf("s_auth_username\n"); { char* username = (char*)bytes; printf("username=%.*s\n", readbytes, username); if (readbytes != strlen(auth_username) || strncmp(username, auth_username, readbytes) != 0) { fprintf(stderr, "User authentication failed!\n"); uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_FAILURE }; hio_write(io, resp, 2); hio_close(io); return; } conn->state = s_auth_password_len; hio_readbytes(io, 1); } break; case s_auth_password_len: // printf("s_auth_password_len\n"); { assert(readbytes == 1); uint8_t password_len = bytes[0]; if (password_len == 0) { fprintf(stderr, "Miss password\n"); uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_FAILURE }; hio_write(io, resp, 2); hio_close(io); return; } conn->state = s_auth_password; hio_readbytes(io, password_len); } break; case s_auth_password: // printf("s_auth_password\n"); { char* password = (char*)bytes; printf("password=%.*s\n", readbytes, password); uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_SUCCESS }; if (readbytes != strlen(auth_password) || strncmp(password, auth_password, readbytes) != 0) { fprintf(stderr, "User authentication failed!\n"); resp[1] = SOCKS5_AUTH_FAILURE; hio_write(io, resp, 2); hio_close(io); return; } hio_write(io, resp, 2); conn->state = s_request; hio_readbytes(io, 3); } break; case s_request: // printf("s_request\n"); { assert(readbytes == 3); uint8_t version = bytes[0]; uint8_t cmd = bytes[1]; if (version != SOCKS5_VERSION || cmd != ConnectCommand) { // TODO: Implement other commands fprintf(stderr, "Unsupported command: %d\n", (int)cmd); hio_close(io); return; } conn->state = s_dst_addr_type; hio_readbytes(io, 1); } break; case s_dst_addr_type: // printf("s_dst_addr_type\n"); { assert(readbytes == 1); conn->addr_type = (socks5_addr_type)bytes[0]; if (conn->addr_type == IPv4Addr) { conn->state = s_dst_addr; hio_readbytes(io, 4); } else if (conn->addr_type == FqdnAddr) { conn->state = s_dst_addr_len; hio_readbytes(io, 1); } else if (conn->addr_type == IPv6Addr) { conn->state = s_dst_addr; hio_readbytes(io, 16); } else { fprintf(stderr, "Unsupported addr type: %d\n", (int)conn->addr_type); hio_close(io); return; } } break; case s_dst_addr_len: // printf("s_dst_addr_len\n"); { uint8_t addr_len = bytes[0]; if (addr_len == 0) { fprintf(stderr, "Miss domain!\n"); hio_close(io); return; } conn->state = s_dst_addr; hio_readbytes(io, addr_len); } break; case s_dst_addr: // printf("s_dst_addr\n"); { if (conn->addr_type == IPv4Addr) { assert(readbytes == 4); conn->addr.sa.sa_family = AF_INET; memcpy(&conn->addr.sin.sin_addr, bytes, 4); } else if (conn->addr_type == IPv6Addr) { assert(readbytes == 16); conn->addr.sa.sa_family = AF_INET6; memcpy(&conn->addr.sin6.sin6_addr, bytes, 16); } else { char* host = NULL; STACK_OR_HEAP_ALLOC(host, readbytes + 1, 256); memcpy(host, bytes, readbytes); host[readbytes] = '\0'; // TODO: async DNS int ret = ResolveAddr(host, &conn->addr); STACK_OR_HEAP_FREE(host); if (ret != 0) { fprintf(stderr, "Resolve %.*s failed!\n", readbytes, (char*)bytes); hio_close(io); return; } } conn->state = s_dst_port; hio_readbytes(io, 2); } break; case s_dst_port: // printf("s_dst_port\n"); { assert(readbytes == 2); uint16_t port = ((uint16_t)bytes[0]) << 8 | bytes[1]; // printf("port=%d\n", port); sockaddr_set_port(&conn->addr, port); hloop_t* loop = hevent_loop(io); // hio_t* upstream_io = hio_setup_tcp_upstream(io, conn->host, conn->port, 0); // hio_t* upstream_io = hio_create_socket(loop, conn->host, conn->port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); int sockfd = socket(conn->addr.sa.sa_family, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); hio_close(io); return; } hio_t* upstream_io = hio_get(loop, sockfd); assert(upstream_io != NULL); hio_set_peeraddr(upstream_io, &conn->addr.sa, sockaddr_len(&conn->addr)); hevent_set_userdata(upstream_io, conn); // io <=> upstream_io hio_setup_upstream(io, upstream_io); hio_setcb_connect(upstream_io, on_upstream_connect); hio_setcb_close(upstream_io, hio_close_upstream); conn->state = s_upstream; // printf("connect to "); // SOCKADDR_PRINT(hio_peeraddr(upstream_io)); hio_connect(upstream_io); } break; case s_upstream: hio_write_upstream(io, buf, readbytes); break; case s_end: break; default: break; } } static void on_accept(hio_t* io) { /* printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ hio_setcb_read(io, on_recv); hio_setcb_close(io, on_close); socks5_conn_t* conn = NULL; HV_ALLOC_SIZEOF(conn); conn->io = io; hevent_set_userdata(io, conn); // start read conn->state = s_auth_methods_count; hio_readbytes(io, 2); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s proxy_port [username] [password]\n", argv[0]); return -10; } proxy_port = atoi(argv[1]); if (argc > 3) { auth_username = argv[2]; auth_password = argv[3]; } hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); if (listenio == NULL) { return -20; } printf("socks5 proxy server listening on %s:%d, listenfd=%d\n", proxy_host, proxy_port, hio_fd(listenio)); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tcp_chat_server.c000066400000000000000000000111231520575453600306000ustar00rootroot00000000000000/* * tcp chat server * * @build make examples * @server bin/tcp_chat_server 1234 * @clients bin/nc 127.0.0.1 1234 * nc 127.0.0.1 1234 * telnet 127.0.0.1 1234 */ #include "hloop.h" #include "hsocket.h" #include "hbase.h" #include "list.h" unpack_setting_t unpack_setting; // hloop_create_tcp_server // on_accept => join // on_recv => broadcast // on_close => leave typedef struct chatroom_s { hloop_t* loop; hio_t* listenio; int roomid; struct list_head conns; } chatroom_t; typedef struct connection_s { hio_t* connio; char addr[SOCKADDR_STRLEN]; struct list_node node; } connection_t; static chatroom_t s_chatroom; static void join(chatroom_t* room, connection_t* conn); static void leave(chatroom_t* room, connection_t* conn); static void broadcast(chatroom_t* room, const char* msg, int msglen); void join(chatroom_t* room, connection_t* conn) { list_add(&conn->node, &room->conns); char msg[256] = {0}; int msglen = 0; struct list_node* node; connection_t* cur; msglen = snprintf(msg, sizeof(msg), "room[%06d] clients:\r\n", room->roomid); hio_write(conn->connio, msg, msglen); list_for_each (node, &room->conns) { cur = list_entry(node, connection_t, node); msglen = snprintf(msg, sizeof(msg), "[%s]\r\n", cur->addr); hio_write(conn->connio, msg, msglen); } hio_write(conn->connio, "\r\n", 2); msglen = snprintf(msg, sizeof(msg), "client[%s] join room[%06d]\r\n", conn->addr, room->roomid); broadcast(room, msg, msglen); } void leave(chatroom_t* room, connection_t* conn) { list_del(&conn->node); char msg[256] = {0}; int msglen = snprintf(msg, sizeof(msg), "client[%s] leave room[%d]\r\n", conn->addr, room->roomid); broadcast(room, msg, msglen); } void broadcast(chatroom_t* room, const char* msg, int msglen) { printf("> %.*s", msglen, msg); struct list_node* node; connection_t* conn; list_for_each (node, &room->conns) { conn = list_entry(node, connection_t, node); hio_write(conn->connio, msg, msglen); } } static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); connection_t* conn = (connection_t*)hevent_userdata(io); if (conn) { hevent_set_userdata(io, NULL); leave(&s_chatroom, conn); HV_FREE(conn); } } static void on_recv(hio_t* io, void* buf, int readbytes) { printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); printf("< %.*s", readbytes, (char*)buf); // broadcast connection_t* conn = (connection_t*)hevent_userdata(io); assert(conn != NULL); char msg[256] = {0}; int msglen = snprintf(msg, sizeof(msg), "client[%s] say: %.*s", conn->addr, readbytes, (char*)buf); broadcast(&s_chatroom, msg, msglen); } static void on_accept(hio_t* io) { printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_set_unpack(io, &unpack_setting); hio_read_start(io); // free on_close connection_t* conn = NULL; HV_ALLOC_SIZEOF(conn); conn->connio = io; strcpy(conn->addr, peeraddrstr); hevent_set_userdata(io, conn); join(&s_chatroom, conn); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); memset(&unpack_setting, 0, sizeof(unpack_setting_t)); unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; unpack_setting.mode = UNPACK_BY_DELIMITER; unpack_setting.delimiter[0] = '\n'; unpack_setting.delimiter_bytes = 1; hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); if (listenio == NULL) { return -20; } printf("listenfd=%d\n", hio_fd(listenio)); s_chatroom.loop = loop; s_chatroom.listenio = listenio; s_chatroom.roomid = hv_rand(100000, 999999); list_init(&s_chatroom.conns); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tcp_client_test.c000066400000000000000000000156771520575453600306320ustar00rootroot00000000000000/* * tcp client demo * * @build make examples * @server bin/tcp_echo_server 1234 * @client bin/tcp_client_test 127.0.0.1 1234 * */ #include "hloop.h" #include "hssl.h" #include "hmutex.h" #include "hbase.h" #include "herr.h" #define TEST_SSL 0 #define TEST_UNPACK 0 #define TEST_RECONNECT 1 // @see mqtt/mqtt_client.h typedef struct tcp_client_s { // connect: host:port char host[256]; int port; int connect_timeout; // ms // reconnect reconn_setting_t* reconn_setting; // flags unsigned char ssl: 1; // Read Only unsigned char alloced_ssl_ctx: 1; // intern unsigned char connected : 1; // privdata hloop_t* loop; hio_t* io; htimer_t* reconn_timer; // SSL/TLS hssl_ctx_t ssl_ctx; // thread-safe hmutex_t mutex_; // ... } tcp_client_t; static tcp_client_t* tcp_client_new(hloop_t* loop DEFAULT(NULL)); static void tcp_client_run (tcp_client_t* cli); static void tcp_client_stop(tcp_client_t* cli); static void tcp_client_free(tcp_client_t* cli); // SSL/TLS static int tcp_client_set_ssl_ctx(tcp_client_t* cli, hssl_ctx_t ssl_ctx); static int tcp_client_new_ssl_ctx(tcp_client_t* cli, hssl_ctx_opt_t* opt); // reconnect static int tcp_client_set_reconnect(tcp_client_t* cli, reconn_setting_t* reconn); static int tcp_client_reconnect(tcp_client_t* cli); static void tcp_client_set_connnect_timeout(tcp_client_t* cli, int timeout_ms); static int tcp_client_connect(tcp_client_t* cli, const char* host, int port, int ssl); static int tcp_client_disconnect(tcp_client_t* cli); static bool tcp_client_is_connected(tcp_client_t* cli); static int tcp_client_send(tcp_client_t* cli, const void* buf, int len); static void reconnect_timer_cb(htimer_t* timer) { tcp_client_t* cli = (tcp_client_t*)hevent_userdata(timer); if (cli == NULL) return; cli->reconn_timer = NULL; tcp_client_reconnect(cli); } static void on_close(hio_t* io) { printf("onclose: connfd=%d error=%d\n", hio_fd(io), hio_error(io)); tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); cli->connected = 0; // reconnect if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); printf("reconnect cnt=%d, delay=%d ...\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); cli->reconn_timer = htimer_add(cli->loop, reconnect_timer_cb, delay, 1); hevent_set_userdata(cli->reconn_timer, cli); } } static void on_message(hio_t* io, void* buf, int len) { printf("onmessage: %.*s\n", len, (char*)buf); tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); // ... } static void on_connect(hio_t* io) { printf("onconnect: connfd=%d\n", hio_fd(io)); tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); cli->connected = 1; #if TEST_UNPACK static unpack_setting_t s_unpack_setting; s_unpack_setting.mode = UNPACK_BY_DELIMITER; s_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; s_unpack_setting.delimiter_bytes = 2; s_unpack_setting.delimiter[0] = '\r'; s_unpack_setting.delimiter[1] = '\n'; hio_set_unpack(io, &s_unpack_setting); #endif hio_write(io, "hello\r\n", 7); hio_setcb_read(io, on_message); hio_read(io); } // hloop_new -> malloc(tcp_client_t) tcp_client_t* tcp_client_new(hloop_t* loop) { if (loop == NULL) { loop = hloop_new(HLOOP_FLAG_AUTO_FREE); if (loop == NULL) return NULL; } tcp_client_t* cli = NULL; HV_ALLOC_SIZEOF(cli); if (cli == NULL) return NULL; cli->loop = loop; hmutex_init(&cli->mutex_); return cli; } // hloop_free -> free(tcp_client_t) void tcp_client_free(tcp_client_t* cli) { if (!cli) return; hmutex_destroy(&cli->mutex_); if (cli->ssl_ctx && cli->alloced_ssl_ctx) { hssl_ctx_free(cli->ssl_ctx); cli->ssl_ctx = NULL; } HV_FREE(cli->reconn_setting); HV_FREE(cli); } void tcp_client_run (tcp_client_t* cli) { if (!cli || !cli->loop) return; hloop_run(cli->loop); } void tcp_client_stop(tcp_client_t* cli) { if (!cli || !cli->loop) return; hloop_stop(cli->loop); } int tcp_client_set_ssl_ctx(tcp_client_t* cli, hssl_ctx_t ssl_ctx) { cli->ssl_ctx = ssl_ctx; return 0; } // hssl_ctx_new(opt) -> tcp_client_set_ssl_ctx int tcp_client_new_ssl_ctx(tcp_client_t* cli, hssl_ctx_opt_t* opt) { opt->endpoint = HSSL_CLIENT; hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; cli->alloced_ssl_ctx = true; return tcp_client_set_ssl_ctx(cli, ssl_ctx); } int tcp_client_set_reconnect(tcp_client_t* cli, reconn_setting_t* reconn) { if (reconn == NULL) { HV_FREE(cli->reconn_setting); return 0; } if (cli->reconn_setting == NULL) { HV_ALLOC_SIZEOF(cli->reconn_setting); } *cli->reconn_setting = *reconn; return 0; } int tcp_client_reconnect(tcp_client_t* cli) { tcp_client_connect(cli, cli->host, cli->port, cli->ssl); return 0; } int tcp_client_connect(tcp_client_t* cli, const char* host, int port, int ssl) { if (!cli) return -1; hv_strncpy(cli->host, host, sizeof(cli->host)); cli->port = port; cli->ssl = ssl; hio_t* io = hio_create_socket(cli->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (io == NULL) return -1; if (ssl) { if (cli->ssl_ctx) { hio_set_ssl_ctx(io, cli->ssl_ctx); } hio_enable_ssl(io); } if (cli->connect_timeout > 0) { hio_set_connect_timeout(io, cli->connect_timeout); } cli->io = io; hevent_set_userdata(io, cli); hio_setcb_connect(io, on_connect); hio_setcb_close(io, on_close); return hio_connect(io); } int tcp_client_disconnect(tcp_client_t* cli) { if (!cli || !cli->io) return -1; // cancel reconnect first tcp_client_set_reconnect(cli, NULL); return hio_close(cli->io); } bool tcp_client_is_connected(tcp_client_t* cli) { return cli && cli->connected; } int tcp_client_send(tcp_client_t* cli, const void* buf, int len) { if (!cli || !cli->io || !buf || len == 0) return -1; if (!cli->connected) return -2; // thread-safe hmutex_lock(&cli->mutex_); int nwrite = hio_write(cli->io, buf, len); hmutex_unlock(&cli->mutex_); return nwrite; } int main(int argc, char** argv) { if (argc < 3) { printf("Usage: %s host port\n", argv[0]); return -10; } const char* host = argv[1]; int port = atoi(argv[2]); tcp_client_t* cli = tcp_client_new(NULL); if (!cli) return -20; #if TEST_RECONNECT reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; tcp_client_set_reconnect(cli, &reconn); #endif int ssl = 0; #if TEST_SSL ssl = 1; #endif tcp_client_connect(cli, host, port, ssl); tcp_client_run(cli); tcp_client_free(cli); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tcp_echo_server.c000066400000000000000000000071251520575453600306060ustar00rootroot00000000000000/* * tcp echo server * * @build make examples * @server bin/tcp_echo_server 1234 * @client bin/nc 127.0.0.1 1234 * nc 127.0.0.1 1234 * telnet 127.0.0.1 1234 */ #include "hloop.h" #include "hsocket.h" #include "hssl.h" /* * @test ssl_server * #define TEST_SSL 1 * * @build ./configure --with-openssl && make clean && make * @server bin/tcp_echo_server 1234 * @client bin/nc -s 127.0.0.1 1234 * */ #define TEST_SSL 0 #define TEST_READ_ONCE 0 #define TEST_READLINE 0 #define TEST_READSTRING 0 #define TEST_READBYTES 0 #define TEST_READ_STOP 0 #define TEST_UNPACK 0 #if TEST_UNPACK static unpack_setting_t unpack_setting; #endif // hloop_create_tcp_server -> on_accept -> hio_read -> on_recv -> hio_write static void on_close(hio_t* io) { printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); } static void on_recv(hio_t* io, void* buf, int readbytes) { printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); printf("< %.*s", readbytes, (char*)buf); // echo printf("> %.*s", readbytes, (char*)buf); hio_write(io, buf, readbytes); #if TEST_READ_STOP hio_read_stop(io); #elif TEST_READ_ONCE hio_read_once(io); #elif TEST_READLINE hio_readline(io); #elif TEST_READSTRING hio_readstring(io); #elif TEST_READBYTES hio_readbytes(io, TEST_READBYTES); #endif } static void on_accept(hio_t* io) { printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); #if TEST_UNPACK hio_set_unpack(io, &unpack_setting); #endif #if TEST_READ_ONCE hio_read_once(io); #elif TEST_READLINE hio_readline(io); #elif TEST_READSTRING hio_readstring(io); #elif TEST_READBYTES hio_readbytes(io, TEST_READBYTES); #else hio_read_start(io); #endif } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port|path\n", argv[0]); return -10; } const char* host = "0.0.0.0"; int port = atoi(argv[1]); #if ENABLE_UDS if (port == 0) { host = argv[1]; port = -1; } #endif #if TEST_UNPACK memset(&unpack_setting, 0, sizeof(unpack_setting_t)); unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; unpack_setting.mode = UNPACK_BY_DELIMITER; unpack_setting.delimiter[0] = '\r'; unpack_setting.delimiter[1] = '\n'; unpack_setting.delimiter_bytes = 2; #endif hloop_t* loop = hloop_new(0); #if TEST_SSL hio_t* listenio = hloop_create_ssl_server(loop, host, port, on_accept); #else hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); #endif if (listenio == NULL) { return -20; } #if TEST_SSL hssl_ctx_opt_t ssl_param; memset(&ssl_param, 0, sizeof(ssl_param)); ssl_param.crt_file = "cert/server.crt"; ssl_param.key_file = "cert/server.key"; ssl_param.endpoint = HSSL_SERVER; if (hio_new_ssl_ctx(listenio, &ssl_param) != 0) { fprintf(stderr, "hssl_ctx_new failed!\n"); return -30; } #endif printf("listenfd=%d\n", hio_fd(listenio)); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tcp_proxy_server.c000066400000000000000000000053001520575453600310420ustar00rootroot00000000000000/* * tcp proxy server * * @build: make clean && make examples WITH_OPENSSL=yes * @http_server: bin/httpd -s restart -d * @proxy_server: bin/tcp_proxy_server 1080 127.0.0.1:8080 * bin/tcp_proxy_server 1080 127.0.0.1:8443 * bin/tcp_proxy_server 1080 www.baidu.com * bin/tcp_proxy_server 1080 www.baidu.com:443 * @client: bin/curl -v 127.0.0.1:1080 * bin/nc 127.0.0.1 1080 * > GET / HTTP/1.1 * > Connection: close * > [Enter] * > GET / HTTP/1.1 * > Connection: keep-alive * > [Enter] * * @benchmark: sudo apt install iperf * iperf -s -p 5001 * bin/tcp_proxy_server 1212 127.0.0.1:5001 * iperf -c 127.0.0.1 -p 5001 -l 8K * iperf -c 127.0.0.1 -p 1212 -l 8K */ #include "hloop.h" #include "hsocket.h" static char proxy_host[64] = "0.0.0.0"; static int proxy_port = 1080; static int proxy_ssl = 0; static char backend_host[64] = "127.0.0.1"; static int backend_port = 80; static int backend_ssl = 0; // hloop_create_tcp_server -> on_accept -> hio_setup_tcp_upstream static void on_accept(hio_t* io) { /* printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ if (backend_port % 1000 == 443) backend_ssl = 1; hio_setup_tcp_upstream(io, backend_host, backend_port, backend_ssl); } int main(int argc, char** argv) { if (argc < 3) { printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]); return -10; } proxy_port = atoi(argv[1]); if (proxy_port % 1000 == 443) proxy_ssl = 1; char* pos = strchr(argv[2], ':'); if (pos) { int len = pos - argv[2]; if (len > 0) { memcpy(backend_host, argv[2], len); backend_host[len] = '\0'; } backend_port = atoi(pos + 1); } else { strncpy(backend_host, argv[2], sizeof(backend_host)); } if (backend_port == 0) backend_port = 80; printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port); hloop_t* loop = hloop_new(0); hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); if (listenio == NULL) { return -20; } printf("listenfd=%d\n", hio_fd(listenio)); if (proxy_ssl) { hio_enable_ssl(listenio); } hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tinyhttpd.c000066400000000000000000000343341520575453600274650ustar00rootroot00000000000000/* * tinyhttpd tiny http server * * @build make examples * * @server bin/tinyhttpd 8000 * * @client bin/curl -v http://127.0.0.1:8000/ * bin/curl -v http://127.0.0.1:8000/ping * bin/curl -v http://127.0.0.1:8000/echo -d "hello,world!" * * @webbench bin/wrk http://127.0.0.1:8000/ping * */ #include "hv.h" #include "hloop.h" /* * workflow: * hloop_new -> hloop_create_tcp_server -> hloop_run -> * on_accept -> HV_ALLOC(http_conn_t) -> hio_readline -> * on_recv -> parse_http_request_line -> hio_readline -> * on_recv -> parse_http_head -> ... -> hio_readbytes(content_length) -> * on_recv -> on_request -> http_reply-> hio_write -> hio_close -> * on_close -> HV_FREE(http_conn_t) * */ static const char* host = "0.0.0.0"; static int port = 8000; static int thread_num = 1; static hloop_t* accept_loop = NULL; static hloop_t** worker_loops = NULL; #define HTTP_KEEPALIVE_TIMEOUT 60000 // ms #define HTTP_MAX_URL_LENGTH 256 #define HTTP_MAX_HEAD_LENGTH 1024 #define HTML_TAG_BEGIN "

" #define HTML_TAG_END "

" // status_message #define HTTP_OK "OK" #define NOT_FOUND "Not Found" #define NOT_IMPLEMENTED "Not Implemented" // Content-Type #define TEXT_PLAIN "text/plain" #define TEXT_HTML "text/html" typedef enum { s_begin, s_first_line, s_request_line = s_first_line, s_status_line = s_first_line, s_head, s_head_end, s_body, s_end } http_state_e; typedef struct { // first line int major_version; int minor_version; union { // request line struct { char method[32]; char path[HTTP_MAX_URL_LENGTH]; }; // status line struct { int status_code; char status_message[64]; }; }; // headers char host[64]; int content_length; char content_type[64]; unsigned keepalive: 1; // char head[HTTP_MAX_HEAD_LENGTH]; // int head_len; // body char* body; int body_len; // body_len = content_length } http_msg_t; typedef struct { hio_t* io; http_state_e state; http_msg_t request; http_msg_t response; // for http_serve_file FILE* fp; hbuf_t filebuf; } http_conn_t; static char s_date[32] = {0}; static void update_date(htimer_t* timer) { uint64_t now = hloop_now(hevent_loop(timer)); gmtime_fmt(now, s_date); } static int http_response_dump(http_msg_t* msg, char* buf, int len) { int offset = 0; // status line offset += snprintf(buf + offset, len - offset, "HTTP/%d.%d %d %s\r\n", msg->major_version, msg->minor_version, msg->status_code, msg->status_message); // headers offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version()); offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close"); if (msg->content_length > 0) { offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length); } if (*msg->content_type) { offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type); } if (*s_date) { offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date); } // TODO: Add your headers offset += snprintf(buf + offset, len - offset, "\r\n"); // body if (msg->body && msg->content_length > 0) { memcpy(buf + offset, msg->body, msg->content_length); offset += msg->content_length; } return offset; } static int http_reply(http_conn_t* conn, int status_code, const char* status_message, const char* content_type, const char* body, int body_len) { http_msg_t* req = &conn->request; http_msg_t* resp = &conn->response; resp->major_version = req->major_version; resp->minor_version = req->minor_version; resp->status_code = status_code; if (status_message) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1); if (content_type) strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1); resp->keepalive = req->keepalive; if (body) { if (body_len <= 0) body_len = strlen(body); resp->content_length = body_len; resp->body = (char*)body; } char* buf = NULL; STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024); int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length); int nwrite = hio_write(conn->io, buf, msglen); STACK_OR_HEAP_FREE(buf); return nwrite < 0 ? nwrite : msglen; } static void http_send_file(http_conn_t* conn) { if (!conn || !conn->fp) return; // alloc filebuf if (!conn->filebuf.base) { conn->filebuf.len = 4096; HV_ALLOC(conn->filebuf, conn->filebuf.len); } char* filebuf = conn->filebuf.base; size_t filebuflen = conn->filebuf.len; // read file int nread = fread(filebuf, 1, filebuflen, conn->fp); if (nread <= 0) { // eof or error hio_close(conn->io); return; } // send file hio_write(conn->io, filebuf, nread); } static void on_write(hio_t* io, const void* buf, int writebytes) { if (!io) return; if (!hio_write_is_complete(io)) return; http_conn_t* conn = (http_conn_t*)hevent_userdata(io); http_send_file(conn); } static int http_serve_file(http_conn_t* conn) { http_msg_t* req = &conn->request; http_msg_t* resp = &conn->response; // GET / HTTP/1.1\r\n const char* filepath = req->path + 1; // homepage if (*filepath == '\0') { filepath = "index.html"; } // open file conn->fp = fopen(filepath, "rb"); if (!conn->fp) { http_reply(conn, 404, NOT_FOUND, TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0); return 404; } // send head size_t filesize = hv_filesize(filepath); resp->content_length = filesize; const char* suffix = hv_suffixname(filepath); const char* content_type = NULL; if (strcmp(suffix, "html") == 0) { content_type = TEXT_HTML; } else { // TODO: set content_type by suffix } hio_setcb_write(conn->io, on_write); int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0); if (nwrite < 0) return nwrite; // disconnected return 200; } static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) { // GET / HTTP/1.1 http_msg_t* req = &conn->request; sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version); if (req->major_version != 1) return false; if (req->minor_version == 1) req->keepalive = 1; // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version); return true; } static bool parse_http_head(http_conn_t* conn, char* buf, int len) { http_msg_t* req = &conn->request; // Content-Type: text/html const char* key = buf; const char* val = buf; char* delim = strchr(buf, ':'); if (!delim) return false; *delim = '\0'; val = delim + 1; // trim space while (*val == ' ') ++val; // printf("%s: %s\r\n", key, val); if (stricmp(key, "Content-Length") == 0) { req->content_length = atoi(val); } else if (stricmp(key, "Content-Type") == 0) { strncpy(req->content_type, val, sizeof(req->content_type) - 1); } else if (stricmp(key, "Connection") == 0) { if (stricmp(val, "close") == 0) { req->keepalive = 0; } } else { // TODO: save other head } return true; } static int on_request(http_conn_t* conn) { http_msg_t* req = &conn->request; // TODO: router if (strcmp(req->method, "GET") == 0) { // GET /ping HTTP/1.1\r\n if (strcmp(req->path, "/ping") == 0) { http_reply(conn, 200, "OK", TEXT_PLAIN, "pong", 4); return 200; } else { // TODO: Add handler for your path } return http_serve_file(conn); } else if (strcmp(req->method, "POST") == 0) { // POST /echo HTTP/1.1\r\n if (strcmp(req->path, "/echo") == 0) { http_reply(conn, 200, "OK", req->content_type, req->body, req->content_length); return 200; } else { // TODO: Add handler for your path } } else { // TODO: handle other method } http_reply(conn, 501, NOT_IMPLEMENTED, TEXT_HTML, HTML_TAG_BEGIN NOT_IMPLEMENTED HTML_TAG_END, 0); return 501; } static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); http_conn_t* conn = (http_conn_t*)hevent_userdata(io); if (conn) { if (conn->fp) { // close file fclose(conn->fp); conn->fp = NULL; } // free filebuf HV_FREE(conn->filebuf.base); HV_FREE(conn); hevent_set_userdata(io, NULL); } } static void on_recv(hio_t* io, void* buf, int readbytes) { char* str = (char*)buf; // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); // printf("%.*s", readbytes, str); http_conn_t* conn = (http_conn_t*)hevent_userdata(io); http_msg_t* req = &conn->request; switch (conn->state) { case s_begin: // printf("s_begin"); conn->state = s_first_line; case s_first_line: // printf("s_first_line\n"); if (readbytes < 2) { fprintf(stderr, "Not match \r\n!"); hio_close(io); return; } str[readbytes - 2] = '\0'; if (parse_http_request_line(conn, str, readbytes - 2) == false) { fprintf(stderr, "Failed to parse http request line:\n%s\n", str); hio_close(io); return; } // start read head conn->state = s_head; hio_readline(io); break; case s_head: // printf("s_head\n"); if (readbytes < 2) { fprintf(stderr, "Not match \r\n!"); hio_close(io); return; } if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') { conn->state = s_head_end; } else { str[readbytes - 2] = '\0'; if (parse_http_head(conn, str, readbytes - 2) == false) { fprintf(stderr, "Failed to parse http head:\n%s\n", str); hio_close(io); return; } hio_readline(io); break; } case s_head_end: // printf("s_head_end\n"); if (req->content_length == 0) { conn->state = s_end; goto s_end; } else { // start read body conn->state = s_body; // WARN: too large content_length should read multiple times! hio_readbytes(io, req->content_length); break; } case s_body: // printf("s_body\n"); req->body = str; req->body_len += readbytes; if (req->body_len == req->content_length) { conn->state = s_end; } else { // WARN: too large content_length should be handled by streaming! break; } case s_end: s_end: // printf("s_end\n"); // received complete request on_request(conn); if (hio_is_closed(io)) return; if (req->keepalive) { // Connection: keep-alive\r\n // reset and receive next request memset(&conn->request, 0, sizeof(http_msg_t)); memset(&conn->response, 0, sizeof(http_msg_t)); conn->state = s_first_line; hio_readline(io); } else { // Connection: close\r\n hio_close(io); } break; default: break; } } static void new_conn_event(hevent_t* ev) { hloop_t* loop = ev->loop; hio_t* io = (hio_t*)hevent_userdata(ev); hio_attach(loop, io); /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("tid=%ld connfd=%d [%s] <= [%s]\n", (long)hv_gettid(), (int)hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT); http_conn_t* conn = NULL; HV_ALLOC_SIZEOF(conn); conn->io = io; hevent_set_userdata(io, conn); // start read first line conn->state = s_first_line; hio_readline(io); } static hloop_t* get_next_loop() { static int s_cur_index = 0; if (s_cur_index == thread_num) { s_cur_index = 0; } return worker_loops[s_cur_index++]; } static void on_accept(hio_t* io) { hio_detach(io); hloop_t* worker_loop = get_next_loop(); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.loop = worker_loop; ev.cb = new_conn_event; ev.userdata = io; hloop_post_event(worker_loop, &ev); } static HTHREAD_ROUTINE(worker_thread) { hloop_t* loop = (hloop_t*)userdata; hloop_run(loop); return 0; } static HTHREAD_ROUTINE(accept_thread) { hloop_t* loop = (hloop_t*)userdata; hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); if (listenio == NULL) { exit(1); } printf("tinyhttpd listening on %s:%d, listenfd=%d, thread_num=%d\n", host, port, hio_fd(listenio), thread_num); // NOTE: add timer to update date every 1s htimer_add(loop, update_date, 1000, INFINITE); hloop_run(loop); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port [thread_num]\n", argv[0]); return -10; } port = atoi(argv[1]); if (argc > 2) { thread_num = atoi(argv[2]); } else { thread_num = get_ncpu(); } if (thread_num == 0) thread_num = 1; worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); for (int i = 0; i < thread_num; ++i) { worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); hthread_create(worker_thread, worker_loops[i]); } accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); accept_thread(accept_loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/tinyproxyd.c000066400000000000000000000352511520575453600276660ustar00rootroot00000000000000/* * tinyproxyd tiny http proxy server * * @build make examples * * @http_server bin/tinyhttpd 8000 * @proxy_server bin/tinyproxyd 1080 * * @proxy_client bin/curl -v www.httpbin.org/get --http-proxy 127.0.0.1:1080 * bin/curl -v www.httpbin.org/post -d hello --http-proxy 127.0.0.1:1080 * curl -v www.httpbin.org/get --proxy http://127.0.0.1:1080 * curl -v www.httpbin.org/post -d hello --proxy http://127.0.0.1:1080 * */ #include "hv.h" #include "hloop.h" /* * workflow: * hloop_new -> hloop_create_tcp_server -> hloop_run -> * on_accept -> HV_ALLOC(http_conn_t) -> hio_readline -> * on_recv -> parse_http_request_line -> hio_readline -> * on_recv -> parse_http_head -> ... -> hio_readline -> * on_head_end -> hio_setup_upstream -> * on_upstream_connect -> hio_write_upstream(head) -> * on_body -> hio_write_upstream(body) -> * on_upstream_close -> hio_close -> * on_close -> HV_FREE(http_conn_t) * */ static char proxy_host[64] = "0.0.0.0"; static int proxy_port = 1080; static int proxy_ssl = 0; static int thread_num = 1; static hloop_t* accept_loop = NULL; static hloop_t** worker_loops = NULL; #define HTTP_KEEPALIVE_TIMEOUT 60000 // ms #define HTTP_MAX_URL_LENGTH 256 #define HTTP_MAX_HEAD_LENGTH 1024 typedef enum { s_begin, s_first_line, s_request_line = s_first_line, s_status_line = s_first_line, s_head, s_head_end, s_body, s_end } http_state_e; typedef struct { // first line int major_version; int minor_version; union { // request line struct { char method[32]; char path[HTTP_MAX_URL_LENGTH]; }; // status line struct { int status_code; char status_message[64]; }; }; // headers char host[64]; int content_length; char content_type[64]; unsigned keepalive: 1; unsigned proxy: 1; char head[HTTP_MAX_HEAD_LENGTH]; int head_len; // body char* body; int body_len; // body_len = content_length } http_msg_t; typedef struct { hio_t* io; http_state_e state; http_msg_t request; // http_msg_t response; } http_conn_t; static int http_request_dump(http_conn_t* conn, char* buf, int len) { http_msg_t* msg = &conn->request; int offset = 0; // request line const char* path = msg->path; if (msg->proxy) { const char* pos = strstr(msg->path, "://"); pos = pos ? pos + 3 : msg->path; path = strchr(pos, '/'); } if (path == NULL) path = "/"; offset += snprintf(buf + offset, len - offset, "%s %s HTTP/%d.%d\r\n", msg->method, path, msg->major_version, msg->minor_version); // headers if (msg->proxy) { if (msg->head_len) { memcpy(buf + offset, msg->head, msg->head_len); offset += msg->head_len; } char peeraddrstr[SOCKADDR_STRLEN] = {0}; SOCKADDR_STR(hio_peeraddr(conn->io), peeraddrstr); offset += snprintf(buf + offset, len - offset, "X-Origin-IP: %s\r\n", peeraddrstr); } else { offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close"); if (msg->content_length > 0) { offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length); } if (*msg->content_type) { offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type); } } // TODO: Add your headers offset += snprintf(buf + offset, len - offset, "\r\n"); // body if (msg->body && msg->content_length > 0) { memcpy(buf + offset, msg->body, msg->content_length); offset += msg->content_length; } return offset; } static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) { // GET / HTTP/1.1 http_msg_t* req = &conn->request; sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version); if (req->major_version != 1) return false; if (req->minor_version == 1) req->keepalive = 1; // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version); return true; } static bool parse_http_head(http_conn_t* conn, char* buf, int len) { http_msg_t* req = &conn->request; // Content-Type: text/html const char* key = buf; const char* val = buf; char* delim = strchr(buf, ':'); if (!delim) return false; *delim = '\0'; val = delim + 1; // trim space while (*val == ' ') ++val; // printf("%s: %s\r\n", key, val); if (stricmp(key, "Host") == 0) { strncpy(req->host, val, sizeof(req->host) - 1); } else if (stricmp(key, "Content-Length") == 0) { req->content_length = atoi(val); } else if (stricmp(key, "Content-Type") == 0) { strncpy(req->content_type, val, sizeof(req->content_type) - 1); } else if (stricmp(key, "Connection") == 0 || stricmp(key, "Proxy-Connection") == 0) { if (stricmp(val, "close") == 0) { req->keepalive = 0; } } return true; } static void on_upstream_connect(hio_t* upstream_io) { // printf("on_upstream_connect\n"); http_conn_t* conn = (http_conn_t*)hevent_userdata(upstream_io); http_msg_t* req = &conn->request; // send head char stackbuf[HTTP_MAX_HEAD_LENGTH + 1024] = {0}; char* buf = stackbuf; int buflen = sizeof(stackbuf); int msglen = http_request_dump(conn, buf, buflen); hio_write(upstream_io, buf, msglen); if (conn->state != s_end) { // start recv body then upstream hio_read_start(conn->io); } else { if (req->keepalive) { // Connection: keep-alive\r\n // reset and receive next request memset(&conn->request, 0, sizeof(http_msg_t)); // memset(&conn->response, 0, sizeof(http_msg_t)); conn->state = s_first_line; hio_readline(conn->io); } } // start recv response hio_read_start(upstream_io); } static int on_head_end(http_conn_t* conn) { http_msg_t* req = &conn->request; if (req->host[0] == '\0') { fprintf(stderr, "No Host header!\n"); return -1; } char backend_host[64] = {0}; strcpy(backend_host, req->host); int backend_port = 80; char* pos = strchr(backend_host, ':'); if (pos) { *pos = '\0'; backend_port = atoi(pos + 1); } if (backend_port == proxy_port && (strcmp(backend_host, proxy_host) == 0 || strcmp(backend_host, "localhost") == 0 || strcmp(backend_host, "127.0.0.1") == 0)) { req->proxy = 0; return 0; } // NOTE: blew for proxy req->proxy = 1; int backend_ssl = strncmp(req->path, "https", 5) == 0 ? 1 : 0; // printf("upstream %s:%d\n", backend_host, backend_port); hloop_t* loop = hevent_loop(conn->io); // hio_t* upstream_io = hio_setup_tcp_upstream(conn->io, backend_host, backend_port, backend_ssl); hio_t* upstream_io = hio_create_socket(loop, backend_host, backend_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (upstream_io == NULL) { fprintf(stderr, "Failed to upstream %s:%d!\n", backend_host, backend_port); return -3; } if (backend_ssl) { hio_enable_ssl(upstream_io); } hevent_set_userdata(upstream_io, conn); hio_setup_upstream(conn->io, upstream_io); hio_setcb_read(upstream_io, hio_write_upstream); hio_setcb_close(upstream_io, hio_close_upstream); hio_setcb_connect(upstream_io, on_upstream_connect); hio_connect(upstream_io); return 0; } static int on_body(http_conn_t* conn, void* buf, int readbytes) { http_msg_t* req = &conn->request; if (req->proxy) { hio_write_upstream(conn->io, buf, readbytes); } return 0; } static int on_request(http_conn_t* conn) { // NOTE: just reply 403, please refer to examples/tinyhttpd if you want to reply other. http_msg_t* req = &conn->request; char buf[256] = {0}; int len = snprintf(buf, sizeof(buf), "HTTP/%d.%d %d %s\r\nContent-Length: 0\r\n\r\n", req->major_version, req->minor_version, 403, "Forbidden"); hio_write(conn->io, buf, len); return 403; } static void on_close(hio_t* io) { // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); http_conn_t* conn = (http_conn_t*)hevent_userdata(io); if (conn) { HV_FREE(conn); hevent_set_userdata(io, NULL); } hio_close_upstream(io); } static void on_recv(hio_t* io, void* buf, int readbytes) { char* str = (char*)buf; // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); // printf("%.*s", readbytes, str); http_conn_t* conn = (http_conn_t*)hevent_userdata(io); http_msg_t* req = &conn->request; switch (conn->state) { case s_begin: // printf("s_begin"); conn->state = s_first_line; case s_first_line: // printf("s_first_line\n"); if (readbytes < 2) { fprintf(stderr, "Not match \r\n!"); hio_close(io); return; } str[readbytes - 2] = '\0'; if (parse_http_request_line(conn, str, readbytes - 2) == false) { fprintf(stderr, "Failed to parse http request line:\n%s\n", str); hio_close(io); return; } // start read head conn->state = s_head; hio_readline(io); break; case s_head: // printf("s_head\n"); if (readbytes < 2) { fprintf(stderr, "Not match \r\n!"); hio_close(io); return; } if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') { conn->state = s_head_end; } else { // NOTE: save head if (strnicmp(str, "Proxy-", 6) != 0) { if (req->head_len + readbytes < HTTP_MAX_HEAD_LENGTH) { memcpy(req->head + req->head_len, buf, readbytes); req->head_len += readbytes; } } str[readbytes - 2] = '\0'; if (parse_http_head(conn, str, readbytes - 2) == false) { fprintf(stderr, "Failed to parse http head:\n%s\n", str); hio_close(io); return; } hio_readline(io); break; } case s_head_end: // printf("s_head_end\n"); if (on_head_end(conn) < 0) { hio_close(io); return; } if (req->content_length == 0) { conn->state = s_end; if (req->proxy) { // NOTE: wait upstream connect! } else { goto s_end; } } else { conn->state = s_body; if (req->proxy) { // NOTE: start read body on_upstream_connect // hio_read_start(io); } else { // WARN: too large content_length should read multiple times! hio_readbytes(io, req->content_length); } break; } case s_body: // printf("s_body\n"); if (on_body(conn, buf, readbytes) < 0) { hio_close(io); return; } req->body = str; req->body_len += readbytes; if (readbytes == req->content_length) { conn->state = s_end; } else { // Not end break; } case s_end: s_end: // printf("s_end\n"); // received complete request if (req->proxy) { // NOTE: reply by upstream } else { on_request(conn); } if (hio_is_closed(io)) return; if (req->keepalive) { // Connection: keep-alive\r\n // reset and receive next request memset(&conn->request, 0, sizeof(http_msg_t)); // memset(&conn->response, 0, sizeof(http_msg_t)); conn->state = s_first_line; hio_readline(io); } else { // Connection: close\r\n if (req->proxy) { // NOTE: wait upstream close! } else { hio_close(io); } } break; default: break; } } static void new_conn_event(hevent_t* ev) { hloop_t* loop = ev->loop; hio_t* io = (hio_t*)hevent_userdata(ev); hio_attach(loop, io); /* char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("tid=%ld connfd=%d [%s] <= [%s]\n", (long)hv_gettid(), (int)hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT); http_conn_t* conn = NULL; HV_ALLOC_SIZEOF(conn); conn->io = io; hevent_set_userdata(io, conn); // start read first line conn->state = s_first_line; hio_readline(io); } static hloop_t* get_next_loop() { static int s_cur_index = 0; if (s_cur_index == thread_num) { s_cur_index = 0; } return worker_loops[s_cur_index++]; } static void on_accept(hio_t* io) { hio_detach(io); hloop_t* worker_loop = get_next_loop(); hevent_t ev; memset(&ev, 0, sizeof(ev)); ev.loop = worker_loop; ev.cb = new_conn_event; ev.userdata = io; hloop_post_event(worker_loop, &ev); } static HTHREAD_ROUTINE(worker_thread) { hloop_t* loop = (hloop_t*)userdata; hloop_run(loop); return 0; } static HTHREAD_ROUTINE(accept_thread) { hloop_t* loop = (hloop_t*)userdata; hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); if (listenio == NULL) { exit(1); } if (proxy_ssl) { hio_enable_ssl(listenio); } printf("tinyproxyd listening on %s:%d, listenfd=%d, thread_num=%d\n", proxy_host, proxy_port, hio_fd(listenio), thread_num); hloop_run(loop); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s proxy_port [thread_num]\n", argv[0]); return -10; } proxy_port = atoi(argv[1]); if (argc > 2) { thread_num = atoi(argv[2]); } else { thread_num = get_ncpu(); } if (thread_num == 0) thread_num = 1; worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); for (int i = 0; i < thread_num; ++i) { worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); hthread_create(worker_thread, worker_loops[i]); } accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); accept_thread(accept_loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/udp_echo_server.c000066400000000000000000000031641520575453600306070ustar00rootroot00000000000000/* * udp echo server * * @build make examples * @server bin/udp_echo_server 1234 * @client bin/nc -u 127.0.0.1 1234 * nc -u 127.0.0.1 1234 * */ #include "hloop.h" #include "hsocket.h" /* * @test kcp_server * #define TEST_KCP 1 * * @build ./configure --with-kcp && make clean && make * @server bin/udp_echo_server 1234 * @client bin/nc -k 127.0.0.1 1234 * */ #define TEST_KCP 0 static void on_recvfrom(hio_t* io, void* buf, int readbytes) { printf("on_recvfrom fd=%d readbytes=%d\n", hio_fd(io), readbytes); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); char* str = (char*)buf; printf("< %.*s", readbytes, str); // echo printf("> %.*s", readbytes, str); hio_write(io, buf, readbytes); #if TEST_KCP if (strncmp(str, "CLOSE", 5) == 0) { hio_close_rudp(io, hio_peeraddr(io)); } #endif } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port|path\n", argv[0]); return -10; } const char* host = "0.0.0.0"; int port = atoi(argv[1]); #if ENABLE_UDS if (port == 0) { host = argv[1]; port = -1; } #endif hloop_t* loop = hloop_new(0); hio_t* io = hloop_create_udp_server(loop, host, port); if (io == NULL) { return -20; } #if TEST_KCP hio_set_kcp(io, NULL); #endif hio_setcb_read(io, on_recvfrom); hio_read(io); hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/udp_proxy_server.c000066400000000000000000000026321520575453600310510ustar00rootroot00000000000000/* * udp proxy server * * @build: make examples * @udp_server: bin/udp_echo_server 1234 * @proxy_server: bin/udp_proxy_server 2222 127.0.0.1:1234 * @client: bin/nc -u 127.0.0.1 2222 * > hello * < hello */ #include "hloop.h" static char proxy_host[64] = "0.0.0.0"; static int proxy_port = 1080; static char backend_host[64] = "127.0.0.1"; static int backend_port = 80; // hloop_create_udp_server -> hio_setup_udp_upstream int main(int argc, char** argv) { if (argc < 3) { printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]); return -10; } proxy_port = atoi(argv[1]); char* pos = strchr(argv[2], ':'); if (pos) { int len = pos - argv[2]; if (len > 0) { memcpy(backend_host, argv[2], len); backend_host[len] = '\0'; } backend_port = atoi(pos + 1); } else { strncpy(backend_host, argv[2], sizeof(backend_host)); } printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port); hloop_t* loop = hloop_new(0); hio_t* io = hloop_create_udp_server(loop, proxy_host, proxy_port); if (io == NULL) { return -20; } hio_t* upstream_io = hio_setup_udp_upstream(io, backend_host, backend_port); if (upstream_io == NULL) { return -30; } hloop_run(loop); hloop_free(&loop); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/websocket_client_test.cpp000066400000000000000000000062571520575453600323640ustar00rootroot00000000000000/* * websocket client * * @build make examples * @server bin/websocket_server_test 8888 * @client bin/websocket_client_test ws://127.0.0.1:8888/test * @clients bin/websocket_client_test ws://127.0.0.1:8888/test 100 * @python scripts/websocket_server.py * @js html/websocket_client.html * */ #include "WebSocketClient.h" using namespace hv; class MyWebSocketClient : public WebSocketClient { public: MyWebSocketClient(EventLoopPtr loop = NULL) : WebSocketClient(loop) {} ~MyWebSocketClient() {} int connect(const char* url) { // set callbacks onopen = [this]() { const HttpResponsePtr& resp = getHttpResponse(); printf("onopen\n%s\n", resp->body.c_str()); // printf("response:\n%s\n", resp->Dump(true, true).c_str()); }; onmessage = [this](const std::string& msg) { printf("onmessage(type=%s len=%d): %.*s\n", opcode() == WS_OPCODE_TEXT ? "text" : "binary", (int)msg.size(), (int)msg.size(), msg.data()); }; onclose = []() { printf("onclose\n"); }; // ping setPingInterval(10000); // reconnect: 1,2,4,8,10,10,10... reconn_setting_t reconn; reconn_setting_init(&reconn); reconn.min_delay = 1000; reconn.max_delay = 10000; reconn.delay_policy = 2; setReconnect(&reconn); /* auto req = std::make_shared(); req->method = HTTP_POST; req->headers["Origin"] = "http://example.com"; req->json["app_id"] = "123456"; req->json["app_secret"] = "abcdefg"; printf("request:\n%s\n", req->Dump(true, true).c_str()); setHttpRequest(req); */ http_headers headers; headers["Origin"] = "http://example.com/"; return open(url, headers); }; }; typedef std::shared_ptr MyWebSocketClientPtr; int TestMultiClientsRunInOneEventLoop(const char* url, int nclients) { auto loop_thread = std::make_shared(); loop_thread->start(); std::map clients; for (int i = 0; i < nclients; ++i) { MyWebSocketClient* client = new MyWebSocketClient(loop_thread->loop()); client->connect(url); clients[i] = MyWebSocketClientPtr(client); } // press Enter to stop while (getchar() != '\n'); loop_thread->stop(); loop_thread->join(); return 0; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s url\n", argv[0]); return -10; } const char* url = argv[1]; int nclients = 0; if (argc > 2) { nclients = atoi(argv[2]); } if (nclients > 0) { return TestMultiClientsRunInOneEventLoop(url, nclients); } MyWebSocketClient ws; ws.connect(url); std::string str; while (std::getline(std::cin, str)) { if (str == "close") { ws.close(); } else if (str == "open") { ws.connect(url); } else if (str == "stop") { ws.stop(); break; } else { if (!ws.isConnected()) break; ws.send(str); } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/websocket_server_test.cpp000066400000000000000000000061071520575453600324060ustar00rootroot00000000000000/* * websocket server * * @build make examples * @server bin/websocket_server_test 9999 * @client bin/websocket_client_test ws://127.0.0.1:9999/ * @python scripts/websocket_server.py * @js html/websocket_client.html * */ #include "WebSocketServer.h" #include "EventLoop.h" #include "htime.h" using namespace hv; /* * #define TEST_WSS 1 * * @build ./configure --with-openssl && make clean && make * * @server bin/websocket_server_test 9999 * * @client bin/websocket_client_test ws://127.0.0.1:9999/ * bin/websocket_client_test wss://127.0.0.1:10000/ * */ #define TEST_WSS 0 using namespace hv; class MyContext { public: MyContext() { printf("MyContext::MyContext()\n"); timerID = INVALID_TIMER_ID; } ~MyContext() { printf("MyContext::~MyContext()\n"); } int handleMessage(const std::string& msg, enum ws_opcode opcode) { printf("onmessage(type=%s len=%d): %.*s\n", opcode == WS_OPCODE_TEXT ? "text" : "binary", (int)msg.size(), (int)msg.size(), msg.data()); return msg.size(); } TimerID timerID; }; int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s port\n", argv[0]); return -10; } int port = atoi(argv[1]); HttpService http; http.GET("/ping", [](const HttpContextPtr& ctx) { return ctx->send("pong"); }); WebSocketService ws; // ws.setPingInterval(10000); ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { printf("onopen: GET %s\n", req->Path().c_str()); auto ctx = channel->newContextPtr(); // send(time) every 1s ctx->timerID = setInterval(1000, [channel](TimerID id) { if (channel->isConnected() && channel->isWriteComplete()) { char str[DATETIME_FMT_BUFLEN] = {0}; datetime_t dt = datetime_now(); datetime_fmt(&dt, str); channel->send(str); } }); }; ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { auto ctx = channel->getContextPtr(); ctx->handleMessage(msg, channel->opcode); }; ws.onclose = [](const WebSocketChannelPtr& channel) { printf("onclose\n"); auto ctx = channel->getContextPtr(); if (ctx->timerID != INVALID_TIMER_ID) { killTimer(ctx->timerID); ctx->timerID = INVALID_TIMER_ID; } // channel->deleteContextPtr(); }; WebSocketServer server; server.port = port; #if TEST_WSS server.https_port = port + 1; hssl_ctx_opt_t param; memset(¶m, 0, sizeof(param)); param.crt_file = "cert/server.crt"; param.key_file = "cert/server.key"; param.endpoint = HSSL_SERVER; if (server.newSslCtx(¶m) != 0) { fprintf(stderr, "new SSL_CTX failed!\n"); return -20; } #endif server.registerHttpService(&http); server.registerWebSocketService(&ws); server.start(); // press Enter to stop while (getchar() != '\n'); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/wget.cpp000066400000000000000000000125171520575453600267430ustar00rootroot00000000000000/* * @build: make examples * @server bin/httpd -s restart -d * @client bin/wget http://127.0.0.1:8080/ */ #include "HttpClient.h" #include "htime.h" using namespace hv; typedef std::function wget_progress_cb; static int wget(const char* url, const char* filepath, wget_progress_cb progress_cb = NULL, bool use_range = true) { int ret = 0; HttpClient cli; HttpRequest req; HttpResponse resp; // HEAD req.method = HTTP_HEAD; req.url = url; ret = cli.send(&req, &resp); if (ret != 0) { fprintf(stderr, "HEAD request error: %d\n", ret); return ret; } printd("%s", resp.Dump(true, false).c_str()); if (resp.status_code == HTTP_STATUS_NOT_FOUND) { fprintf(stderr, "404 Not Found\n"); return 404; } // use Range? int range_bytes = 1 << 20; // 1M long from = 0, to = 0; size_t content_length = hv::from_string(resp.GetHeader("Content-Length")); if (use_range) { use_range = false; std::string accept_ranges = resp.GetHeader("Accept-Ranges"); // use Range if server accept_ranges and content_length > 1M if (resp.status_code == 200 && accept_ranges == "bytes" && content_length > range_bytes) { use_range = true; } } // open file std::string filepath_download(filepath); filepath_download += ".download"; HFile file; if (use_range) { ret = file.open(filepath_download.c_str(), "ab"); from = file.size(); } else { ret = file.open(filepath_download.c_str(), "wb"); } if (ret != 0) { fprintf(stderr, "Failed to open file %s\n", filepath_download.c_str()); return ret; } printf("Save file to %s ...\n", filepath); // GET req.method = HTTP_GET; req.timeout = 3600; // 1h if (!use_range) { size_t received_bytes = 0; req.http_cb = [&file, &content_length, &received_bytes, &progress_cb] (HttpMessage* resp, http_parser_state state, const char* data, size_t size) { if (!resp->headers["Location"].empty()) return; if (state == HP_HEADERS_COMPLETE) { content_length = hv::from_string(resp->GetHeader("Content-Length")); printd("%s", resp->Dump(true, false).c_str()); } else if (state == HP_BODY) { if (data && size) { file.write(data, size); received_bytes += size; if (progress_cb) { progress_cb(received_bytes, content_length); } } } }; ret = cli.send(&req, &resp); if (ret != 0) { fprintf(stderr, "GET request error: %d\n", ret); goto error; } goto success; } // Range: bytes=from-to while (from < content_length) { to = from + range_bytes - 1; if (to >= content_length) to = content_length - 1; req.SetRange(from, to); printd("%s", req.Dump(true, false).c_str()); ret = cli.send(&req, &resp); if (ret != 0) { fprintf(stderr, "GET Range: bytes=%ld-%ld request error: %d\n", from, to, ret); goto error; } printd("%s", resp.Dump(true, false).c_str()); file.write(resp.body.data(), resp.body.size()); // fix: resp.body.size != range_bytes on some server // from = to + 1; from += resp.body.size(); if (progress_cb) { progress_cb(from, content_length); } } success: file.close(); ret = file.rename(filepath); if (ret != 0) { fprintf(stderr, "mv %s => %s failed: %s:%d\n", filepath_download.c_str(), filepath, strerror(ret), ret); } return ret; error: file.close(); // file.remove(); return ret; } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s [--use_range] url [filepath]\n", argv[0]); return -10; } int idx = 1; bool use_range = false; if (strcmp(argv[idx], "--use_range") == 0) { use_range = true; ++idx; } const char* url = argv[idx++]; const char* filepath = "index.html"; if (argv[idx]) { filepath = argv[idx]; } else { const char* path = strrchr(url, '/'); if (path && path[1]) { filepath = path + 1; } } unsigned int start_time = gettick_ms(); int last_progress = 0; wget(url, filepath, [&last_progress](size_t received_bytes, size_t total_bytes) { // print progress if (total_bytes == 0) { printf("\rprogress: %lu/? = ?", (unsigned long)received_bytes); } else { int cur_progress = received_bytes * 100 / total_bytes; if (cur_progress > last_progress) { printf("\rprogress: %lu/%lu = %d%%", (unsigned long)received_bytes, (unsigned long)total_bytes, (int)cur_progress); last_progress = cur_progress; } } fflush(stdout); }, use_range); unsigned int end_time = gettick_ms(); unsigned int cost_time = end_time - start_time; printf("\ncost time %u ms\n", cost_time); // 1B/ms = 1KB/s = 8Kbps printf("download rate = %lu KB/s\n", (unsigned long)hv_filesize(filepath) / cost_time); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/examples/wrk.cpp000066400000000000000000000163701520575453600266010ustar00rootroot00000000000000/* * @build: make examples * @server bin/httpd -s restart -d * @client bin/curl -v http://127.0.0.1:8080/ * @usage: bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ * */ #include "hv.h" #include "hmain.h" // import parse_opt #include "hloop.h" #include "EventLoopThreadPool.h" #include "HttpMessage.h" #include "HttpParser.h" using namespace hv; static const char options[] = "hvc:d:t:"; static const char detail_options[] = R"( -h Print help infomation -v Show verbose infomation -c Number of connections, default: 1000 -d Duration of test, default: 10s -t Number of threads, default: 4 )"; static int connections = 1000; static int duration = 10; static int threads = 4; static bool verbose = false; static const char* url = NULL; static bool https = false; static char ip[64] = "127.0.0.1"; static int port = 80; static bool stop = false; static HttpRequestPtr request; static std::string request_msg; typedef struct connection_s { hio_t* io; HttpParserPtr parser; HttpResponsePtr response; uint64_t request_cnt; uint64_t response_cnt; uint64_t ok_cnt; uint64_t readbytes; connection_s() : parser(HttpParser::New(HTTP_CLIENT, HTTP_V1)) , response(std::make_shared()) , request_cnt(0) , response_cnt(0) , ok_cnt(0) , readbytes(0) { response->http_cb = [](HttpMessage* res, http_parser_state state, const char* data, size_t size) { // wrk no need to save data to body }; } void SendRequest() { hio_write(io, request_msg.data(), request_msg.size()); ++request_cnt; parser->InitResponse(response.get()); } bool RecvResponse(const char* data, int size) { readbytes += size; int nparse = parser->FeedRecvData(data, size); if (nparse != size) { fprintf(stderr, "http parse error!\n"); hio_close(io); return false; } if (parser->IsComplete()) { ++response_cnt; if (response->status_code == HTTP_STATUS_OK) { ++ok_cnt; } return true; } return false; } } connection_t; static connection_t** conns = NULL; static std::atomic connected_num(0); static std::atomic disconnected_num(0); static void print_help() { printf("Usage: wrk [%s] \n", options); printf("Options:\n%s\n", detail_options); } static void print_cmd() { printf("Running %ds test @ %s\n", duration, url); printf("%d threads and %d connections\n", threads, connections); } static void print_result() { uint64_t total_request_cnt = 0; uint64_t total_response_cnt = 0; uint64_t total_ok_cnt = 0; uint64_t total_readbytes = 0; connection_t* conn = NULL; for (int i = 0; i < connections; ++i) { conn = conns[i]; total_request_cnt += conn->request_cnt; total_response_cnt += conn->response_cnt; total_ok_cnt += conn->ok_cnt; total_readbytes += conn->readbytes; } printf("%llu requests, %llu OK, %lluMB read in %ds\n", LLU(total_request_cnt), LLU(total_ok_cnt), LLU(total_readbytes >> 20), duration); printf("Requests/sec: %8llu\n", LLU(total_response_cnt / duration)); printf("Transfer/sec: %8lluMB\n", LLU((total_readbytes / duration) >> 20)); } static void start_reconnect(hio_t* io); static void on_close(hio_t* io) { if (++disconnected_num == connections) { if (verbose) { printf("all disconnected\n"); } } if (!stop) { // NOTE: nginx keepalive_requests = 100 start_reconnect(io); } } static void on_recv(hio_t* io, void* buf, int readbytes) { connection_t* conn = (connection_t*)hevent_userdata(io); if (conn->RecvResponse((const char*)buf, readbytes)) { conn->SendRequest(); } } static void on_connect(hio_t* io) { if (++connected_num == connections) { if (verbose) { printf("all connected\n"); } } connection_t* conn = (connection_t*)hevent_userdata(io); conn->SendRequest(); hio_setcb_read(io, on_recv); hio_read(io); } static void start_connect(hloop_t* loop, connection_t* conn) { hio_t* io = hio_create_socket(loop, ip, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (io == NULL) { perror("socket"); exit(1); } conn->io = io; hevent_set_userdata(io, conn); if (https) { hio_enable_ssl(io); } tcp_nodelay(hio_fd(io), 1); hio_setcb_connect(io, on_connect); hio_setcb_close(io, on_close); hio_connect(io); } static void start_reconnect(hio_t* io) { hloop_t* loop = hevent_loop(io); connection_t* conn = (connection_t*)hevent_userdata(io); start_connect(loop, conn); } int main(int argc, char** argv) { // parse cmdline main_ctx_init(argc, argv); int ret = parse_opt(argc, argv, options); if (ret != 0) { print_help(); exit(ret); } if (get_arg("h") || g_main_ctx.arg_list_size != 1) { print_help(); exit(0); } url = g_main_ctx.arg_list[0]; if (get_arg("v")) { verbose = true; } const char* strConnections = get_arg("c"); const char* strDuration = get_arg("d"); const char* strThreads = get_arg("t"); if (strConnections) connections = atoi(strConnections); if (strDuration) duration = atoi(strDuration); if (strThreads) threads = atoi(strThreads); print_cmd(); // ParseUrl request = std::make_shared(); request->url = url; request->ParseUrl(); https = request->scheme == "https"; const char* host = request->host.c_str(); port = request->port; // ResolveAddr if (is_ipaddr(host)) { strcpy(ip, host); } else { sockaddr_u addr; if (ResolveAddr(host, &addr) != 0) { fprintf(stderr, "Could not resolve host: %s\n", host); exit(1); } sockaddr_ip(&addr, ip, sizeof(ip)); } // Test connect printf("Connect to %s:%d ...\n", ip, port); int connfd = ConnectTimeout(ip, port); if (connfd < 0) { fprintf(stderr, "Could not connect to %s:%d\n", ip, port); exit(1); } else { closesocket(connfd); } // Dump request request->headers["User-Agent"] = std::string("libhv/") + hv_version(); request->headers["Connection"] = "keep-alive"; request_msg = request->Dump(true, true); printf("%s", request_msg.c_str()); // EventLoopThreadPool EventLoopThreadPool loop_threads(threads); loop_threads.start(true); // connections conns = (connection_t**)malloc(sizeof(connection_t*) * connections); for (int i = 0; i < connections; ++i) { conns[i] = new connection_t; EventLoopPtr loop = loop_threads.nextLoop(); hloop_t* hloop = loop->loop(); loop->runInLoop(std::bind(start_connect, loop->loop(), conns[i])); } // stop after duration loop_threads.loop()->setTimeout(duration * 1000, [&loop_threads](TimerID timerID){ stop = true; loop_threads.stop(false); }); // wait loop_threads exit loop_threads.join(); print_result(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/getting_started.sh000077500000000000000000000065561520575453600272070ustar00rootroot00000000000000#!/bin/bash echo "Welcome to libhv!" echo "Press any key to run ..." echo_cmd() { echo -e "\n\033[36m$cmd\033[0m" read -n1 } run_cmd() { echo_cmd $cmd } # compile httpd curl if [ ! -x bin/httpd -o ! -x bin/curl ]; then cmd="make httpd curl" && echo_cmd ./configure make clean make -j4 httpd curl fi # run httpd processes=$(ps aux | grep -v grep | grep httpd | wc -l) if [ $processes -lt 1 ]; then cmd="bin/httpd -c etc/httpd.conf -s restart -d" && run_cmd fi ps aux | grep -v grep | grep httpd # http file service cmd="bin/curl -v localhost:8080" && run_cmd # http indexof service cmd="bin/curl -v localhost:8080/downloads/" && run_cmd cmd="bin/curl -v localhost:8080/downloads/中文.html" && run_cmd # http api service cmd="bin/curl -v localhost:8080/paths" && run_cmd cmd="bin/curl -v localhost:8080/ping" && run_cmd cmd="bin/curl -v localhost:8080/data" && run_cmd cmd="bin/curl -v localhost:8080/html/index.html" && run_cmd cmd="bin/curl -v localhost:8080/get?env=1" && run_cmd cmd="bin/curl -v localhost:8080/service" && run_cmd cmd="bin/curl -v localhost:8080/async" && run_cmd cmd="bin/curl -v localhost:8080/wildcard/test" && run_cmd cmd="bin/curl -v localhost:8080/echo -d 'hello,world!'" && echo_cmd bin/curl -v localhost:8080/echo -d 'hello,world!' cmd="bin/curl -v localhost:8080/query?page_no=1&page_size=10" && run_cmd cmd="bin/curl -v localhost:8080/kv -H 'Content-Type:application/x-www-form-urlencoded' -d 'user=admin&pswd=123456'" && echo_cmd bin/curl -v localhost:8080/kv -H 'Content-Type:application/x-www-form-urlencoded' -d 'user=admin&pswd=123456' cmd="bin/curl -v localhost:8080/json -H 'Content-Type:application/json' -d '{\"user\":\"admin\",\"pswd\":\"123456\"}'" && echo_cmd bin/curl -v localhost:8080/json -H 'Content-Type:application/json' -d '{"user":"admin","pswd":"123456"}' cmd="bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456'" && echo_cmd bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' cmd="bin/curl -v localhost:8080/upload?filename=LICENSE -d '@LICENSE'" && echo_cmd bin/curl -v localhost:8080/upload?filename=LICENSE -d '@LICENSE' cmd="bin/curl -v localhost:8080/upload -F 'file=@LICENSE'" && echo_cmd bin/curl -v localhost:8080/upload -F 'file=@LICENSE' cmd="bin/curl -v localhost:8080/upload/README.md -d '@README.md'" && echo_cmd bin/curl -v localhost:8080/upload/README.md -d '@README.md' cmd="bin/curl -v localhost:8080/test -H 'Content-Type:application/x-www-form-urlencoded' -d 'bool=1&int=123&float=3.14&string=hello'" && echo_cmd bin/curl -v localhost:8080/test -H 'Content-Type:application/x-www-form-urlencoded' -d 'bool=1&int=123&float=3.14&string=hello' cmd="bin/curl -v localhost:8080/test -H 'Content-Type:application/json' -d '{\"bool\":true,\"int\":123,\"float\":3.14,\"string\":\"hello\"}'" && echo_cmd bin/curl -v localhost:8080/test -H 'Content-Type:application/json' -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' cmd="bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello'" && echo_cmd bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' # RESTful API: /group/:group_name/user/:user_id cmd="bin/curl -v -X DELETE localhost:8080/group/test/user/123" && run_cmd # show log cmd="tail -n 50 logs/httpd*.log" && run_cmd echo -e "\nEnjoy libhv!\n" kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/hconfig.h000066400000000000000000000027741520575453600252450ustar00rootroot00000000000000#ifndef HV_CONFIG_H_ #define HV_CONFIG_H_ #ifndef HAVE_STDBOOL_H #define HAVE_STDBOOL_H 1 #endif #ifndef HAVE_STDINT_H #define HAVE_STDINT_H 1 #endif #ifndef HAVE_STDATOMIC_H #define HAVE_STDATOMIC_H 0 #endif #ifndef HAVE_SYS_TYPES_H #define HAVE_SYS_TYPES_H 1 #endif #ifndef HAVE_SYS_STAT_H #define HAVE_SYS_STAT_H 1 #endif #ifndef HAVE_SYS_TIME_H #define HAVE_SYS_TIME_H 1 #endif #ifndef HAVE_FCNTL_H #define HAVE_FCNTL_H 1 #endif #ifndef HAVE_PTHREAD_H #define HAVE_PTHREAD_H 1 #endif #ifndef HAVE_ENDIAN_H #define HAVE_ENDIAN_H 1 #endif #ifndef HAVE_SYS_ENDIAN_H #define HAVE_SYS_ENDIAN_H 0 #endif #ifndef HAVE_GETTID #define HAVE_GETTID 0 #endif #ifndef HAVE_STRLCPY #define HAVE_STRLCPY 1 #endif #ifndef HAVE_STRLCAT #define HAVE_STRLCAT 1 #endif #ifndef HAVE_CLOCK_GETTIME #define HAVE_CLOCK_GETTIME 1 #endif #ifndef HAVE_GETTIMEOFDAY #define HAVE_GETTIMEOFDAY 1 #endif #ifndef HAVE_PTHREAD_SPIN_LOCK #define HAVE_PTHREAD_SPIN_LOCK 0 #endif #ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK #define HAVE_PTHREAD_MUTEX_TIMEDLOCK 0 #endif #ifndef HAVE_SEM_TIMEDWAIT #define HAVE_SEM_TIMEDWAIT 0 #endif #ifndef HAVE_PIPE #define HAVE_PIPE 1 #endif #ifndef HAVE_SOCKETPAIR #define HAVE_SOCKETPAIR 1 #endif #ifndef HAVE_EVENTFD #define HAVE_EVENTFD 1 #endif #ifndef HAVE_SETPROCTITLE #define HAVE_SETPROCTITLE 0 #endif /* #undef WITH_OPENSSL */ /* #undef WITH_GNUTLS */ /* #undef WITH_MBEDTLS */ /* #undef ENABLE_UDS */ /* #undef USE_MULTIMAP */ #define WITH_WEPOLL 1 /* #undef WITH_KCP */ #endif // HV_CONFIG_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/hconfig.h.in000066400000000000000000000036051520575453600256440ustar00rootroot00000000000000#ifndef HV_CONFIG_H_ #define HV_CONFIG_H_ #ifndef HAVE_STDBOOL_H #define HAVE_STDBOOL_H @HAVE_STDBOOL_H@ #endif #ifndef HAVE_STDINT_H #define HAVE_STDINT_H @HAVE_STDINT_H@ #endif #ifndef HAVE_STDATOMIC_H #define HAVE_STDATOMIC_H @HAVE_STDATOMIC_H@ #endif #ifndef HAVE_SYS_TYPES_H #define HAVE_SYS_TYPES_H @HAVE_SYS_TYPES_H@ #endif #ifndef HAVE_SYS_STAT_H #define HAVE_SYS_STAT_H @HAVE_SYS_STAT_H@ #endif #ifndef HAVE_SYS_TIME_H #define HAVE_SYS_TIME_H @HAVE_SYS_TIME_H@ #endif #ifndef HAVE_FCNTL_H #define HAVE_FCNTL_H @HAVE_FCNTL_H@ #endif #ifndef HAVE_PTHREAD_H #define HAVE_PTHREAD_H @HAVE_PTHREAD_H@ #endif #ifndef HAVE_ENDIAN_H #define HAVE_ENDIAN_H @HAVE_ENDIAN_H@ #endif #ifndef HAVE_SYS_ENDIAN_H #define HAVE_SYS_ENDIAN_H @HAVE_SYS_ENDIAN_H@ #endif #ifndef HAVE_GETTID #define HAVE_GETTID @HAVE_GETTID@ #endif #ifndef HAVE_STRLCPY #define HAVE_STRLCPY @HAVE_STRLCPY@ #endif #ifndef HAVE_STRLCAT #define HAVE_STRLCAT @HAVE_STRLCAT@ #endif #ifndef HAVE_CLOCK_GETTIME #define HAVE_CLOCK_GETTIME @HAVE_CLOCK_GETTIME@ #endif #ifndef HAVE_GETTIMEOFDAY #define HAVE_GETTIMEOFDAY @HAVE_GETTIMEOFDAY@ #endif #ifndef HAVE_PTHREAD_SPIN_LOCK #define HAVE_PTHREAD_SPIN_LOCK @HAVE_PTHREAD_SPIN_LOCK@ #endif #ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK #define HAVE_PTHREAD_MUTEX_TIMEDLOCK @HAVE_PTHREAD_MUTEX_TIMEDLOCK@ #endif #ifndef HAVE_SEM_TIMEDWAIT #define HAVE_SEM_TIMEDWAIT @HAVE_SEM_TIMEDWAIT@ #endif #ifndef HAVE_PIPE #define HAVE_PIPE @HAVE_PIPE@ #endif #ifndef HAVE_SOCKETPAIR #define HAVE_SOCKETPAIR @HAVE_SOCKETPAIR@ #endif #ifndef HAVE_EVENTFD #define HAVE_EVENTFD @HAVE_EVENTFD@ #endif #ifndef HAVE_SETPROCTITLE #define HAVE_SETPROCTITLE @HAVE_SETPROCTITLE@ #endif #cmakedefine WITH_OPENSSL 1 #cmakedefine WITH_GNUTLS 1 #cmakedefine WITH_MBEDTLS 1 #cmakedefine ENABLE_UDS 1 #cmakedefine USE_MULTIMAP 1 #cmakedefine WITH_WEPOLL 1 #cmakedefine WITH_KCP 1 #endif // HV_CONFIG_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/hexport.h000066400000000000000000000044651520575453600253200ustar00rootroot00000000000000#ifndef HV_EXPORT_H_ #define HV_EXPORT_H_ // HV_EXPORT #if defined(HV_STATICLIB) || defined(HV_SOURCE) #define HV_EXPORT #elif defined(_MSC_VER) #if defined(HV_DYNAMICLIB) || defined(HV_EXPORTS) || defined(hv_EXPORTS) #define HV_EXPORT __declspec(dllexport) #else #define HV_EXPORT __declspec(dllimport) #endif #elif defined(__GNUC__) #define HV_EXPORT __attribute__((visibility("default"))) #else #define HV_EXPORT #endif // HV_INLINE #define HV_INLINE static inline // HV_DEPRECATED #if defined(HV_NO_DEPRECATED) #define HV_DEPRECATED #elif defined(__GNUC__) || defined(__clang__) #define HV_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define HV_DEPRECATED __declspec(deprecated) #else #define HV_DEPRECATED #endif // HV_UNUSED #if defined(__GNUC__) #define HV_UNUSED __attribute__((visibility("unused"))) #else #define HV_UNUSED #endif #ifdef __cplusplus #ifndef EXTERN_C #define EXTERN_C extern "C" #endif #ifndef BEGIN_EXTERN_C #define BEGIN_EXTERN_C extern "C" { #endif #ifndef END_EXTERN_C #define END_EXTERN_C } // extern "C" #endif #ifndef BEGIN_NAMESPACE #define BEGIN_NAMESPACE(ns) namespace ns { #endif #ifndef END_NAMESPACE #define END_NAMESPACE(ns) } // namespace ns #endif #ifndef USING_NAMESPACE #define USING_NAMESPACE(ns) using namespace ns; #endif #ifndef DEFAULT #define DEFAULT(x) = x #endif #ifndef ENUM #define ENUM(e) enum e #endif #ifndef STRUCT #define STRUCT(s) struct s #endif #else #define EXTERN_C extern #define BEGIN_EXTERN_C #define END_EXTERN_C #define BEGIN_NAMESPACE(ns) #define END_NAMESPACE(ns) #define USING_NAMESPACE(ns) #ifndef DEFAULT #define DEFAULT(x) #endif #ifndef ENUM #define ENUM(e)\ typedef enum e e;\ enum e #endif #ifndef STRUCT #define STRUCT(s)\ typedef struct s s;\ struct s #endif #endif // __cplusplus #define BEGIN_NAMESPACE_HV BEGIN_NAMESPACE(hv) #define END_NAMESPACE_HV END_NAMESPACE(hv) #define USING_NAMESPACE_HV USING_NAMESPACE(hv) // MSVC ports #ifdef _MSC_VER #pragma warning (disable: 4251) // STL dll #pragma warning (disable: 4275) // dll-interface #if _MSC_VER < 1900 // < VS2015 #ifndef __cplusplus #ifndef inline #define inline __inline #endif #endif #ifndef snprintf #define snprintf _snprintf #endif #endif #endif #endif // HV_EXPORT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/000077500000000000000000000000001520575453600244115ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/EventSource.html000066400000000000000000000017551520575453600275510ustar00rootroot00000000000000 EventSource客户端 URL:
kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/WebSocket.html000066400000000000000000000021031520575453600271610ustar00rootroot00000000000000 WebSocket客户端 URL:
kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/downloads/000077500000000000000000000000001520575453600264035ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/downloads/libhv-vs-nginx.png000066400000000000000000006465611520575453600320060ustar00rootroot00000000000000PNG  IHDR@"}H biCCPICC ProfileHWXS[RIhH %A@ *! $]V"]Qt-bw-uq*oB+;9󟒙{gdy.y|Dk|j  ( 2N\\42x\uQqPC)T!n/CzZLaRl5^™jm&1 q#d/@YlȣbWP"@@/8STx^Nٙ_qf?s*Q3oS&Gƫ5;%JiwK3cbUD;(ULRۣ0!vC 68\gfIyقN5ca )8Kh~U$X]$NL F-$@ "7!JmY16re*~"iDKϒke|Hu}]@F׋Ab|`.BQh:wM$Mݗk48Y[Al(LЌGɩǣeq88u{A6fpD@^@"P B4U_]@@o\|r`t[2x 5xX`SSǁhF9$Cp#nx4掳qh  ۓ%ob : &̯3 @vȌ3q{B?<zZ&nUP_\cGqa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;|w}Px8!0q.X#x4o(oZǛ~QGxc:kuG(W=Z6:ul>N#m#3g&ϛ7wMޚ3z!my=$;g=sCڪ߲Ms=@Y^'ݚGy>ʳxK/q3M(]ӈߚy4G=Nc^xmh~w'߅){1yfRbYNplpλfnХKwFl98zC̒Ycա&N(c.ש'/(-+7%fo[{W]vYrF=O|iqO'eKХYoqctʁ[p7'}o gx I_ëv!0qC` &Vwxt3bk{'rQ{3C[ei@]DgRƕ a=J+{HS"J{VݥB޵[޶zM#ϥC_qC!@ 3C&0z`iGJ@h|o Qxڡ 3aJimm88}r|'ވ?ɔyfY|vn#2  >b 0 ֆezOA+=A{6rr9R6:VljM.ʵ\V&:P6.G׳;`[oϸ;Yqʹ;COxr9a'Z9eÚeӆq|UO;zZ_ =aZr51`]:uRuRz<,9@}_.%<\ØF#L-bج2urv?m|+~V}iѾy(TykHgbvqbo{v{ew{ݷ3~8!0q/3 中文测试

欢迎使用 libhv

kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/error.html000066400000000000000000000005571520575453600264370ustar00rootroot00000000000000 Error

An error occurred.

Sorry, the page you are looking for is currently unavailable.
Please try again later.

If you are the system administrator of this resource then you should check the error log for details.

Faithfully yours, httpd.

kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/index.html000066400000000000000000000002661520575453600264120ustar00rootroot00000000000000 libhv

Welcome to libhv

kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/中文路径/000077500000000000000000000000001520575453600307715ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/html/中文路径/中文名称.txt000066400000000000000000000001231520575453600360210ustar00rootroot00000000000000http://127.0.0.1:8080/中文路径/中文名称.txt 用于Windows中文路径测试kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/000077500000000000000000000000001520575453600244245ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/Http1Parser.cpp000066400000000000000000000120061520575453600273040ustar00rootroot00000000000000#include "Http1Parser.h" #define MAX_CONTENT_LENGTH (1 << 24) // 16M static int on_url(http_parser* parser, const char *at, size_t length); static int on_status(http_parser* parser, const char *at, size_t length); static int on_header_field(http_parser* parser, const char *at, size_t length); static int on_header_value(http_parser* parser, const char *at, size_t length); static int on_body(http_parser* parser, const char *at, size_t length); static int on_message_begin(http_parser* parser); static int on_headers_complete(http_parser* parser); static int on_message_complete(http_parser* parser); static int on_chunk_header(http_parser* parser); static int on_chunk_complete(http_parser* parser); http_parser_settings Http1Parser::cbs = { on_message_begin, on_url, on_status, on_header_field, on_header_value, on_headers_complete, on_body, on_message_complete, on_chunk_header, on_chunk_complete }; Http1Parser::Http1Parser(http_session_type type) { http_parser_init(&parser, HTTP_BOTH); parser.data = this; flags = 0; state = HP_START_REQ_OR_RES; submited = NULL; parsed = NULL; } Http1Parser::~Http1Parser() { } int on_url(http_parser* parser, const char *at, size_t length) { printd("on_url:%.*s\n", (int)length, at); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_URL; hp->url.append(at, length); return 0; } int on_status(http_parser* parser, const char *at, size_t length) { printd("on_status:%d %.*s\n", (int)parser->status_code, (int)length, at); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_STATUS; return 0; } int on_header_field(http_parser* parser, const char *at, size_t length) { printd("on_header_field:%.*s\n", (int)length, at); Http1Parser* hp = (Http1Parser*)parser->data; hp->handle_header(); hp->state = HP_HEADER_FIELD; hp->header_field.append(at, length); return 0; } int on_header_value(http_parser* parser, const char *at, size_t length) { printd("on_header_value:%.*s\n", (int)length, at); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_HEADER_VALUE; hp->header_value.append(at, length); return 0; } int on_body(http_parser* parser, const char *at, size_t length) { printd("on_body:%d\n", (int)length); // printd("on_body:%.*s\n", (int)length, at); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_BODY; if (hp->invokeHttpCb(at, length) != 0) { hp->parsed->body.append(at, length); } return 0; } int on_message_begin(http_parser* parser) { printd("on_message_begin\n"); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_MESSAGE_BEGIN; hp->invokeHttpCb(); return 0; } int on_headers_complete(http_parser* parser) { printd("on_headers_complete\n"); Http1Parser* hp = (Http1Parser*)parser->data; hp->handle_header(); bool skip_body = false; hp->parsed->http_major = parser->http_major; hp->parsed->http_minor = parser->http_minor; if (hp->parsed->type == HTTP_REQUEST) { HttpRequest* req = (HttpRequest*)hp->parsed; req->method = (http_method)parser->method; req->url = hp->url; } else if (hp->parsed->type == HTTP_RESPONSE) { HttpResponse* res = (HttpResponse*)hp->parsed; res->status_code = (http_status)parser->status_code; // response to HEAD if (hp->flags & F_SKIPBODY) { skip_body = true; } } auto iter = hp->parsed->headers.find("content-type"); if (iter != hp->parsed->headers.end()) { hp->parsed->content_type = http_content_type_enum(iter->second.c_str()); } iter = hp->parsed->headers.find("content-length"); if (iter != hp->parsed->headers.end()) { size_t content_length = atoll(iter->second.c_str()); hp->parsed->content_length = content_length; size_t reserve_length = MIN(content_length + 1, MAX_CONTENT_LENGTH); if ((!skip_body) && reserve_length > hp->parsed->body.capacity()) { hp->parsed->body.reserve(reserve_length); } } hp->state = HP_HEADERS_COMPLETE; hp->invokeHttpCb(); return skip_body ? 1 : 0; } int on_message_complete(http_parser* parser) { printd("on_message_complete\n"); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_MESSAGE_COMPLETE; hp->invokeHttpCb(); return 0; } int on_chunk_header(http_parser* parser) { printd("on_chunk_header:%llu\n", parser->content_length); Http1Parser* hp = (Http1Parser*)parser->data; int chunk_size = parser->content_length; int reserve_size = MIN(chunk_size + 1, MAX_CONTENT_LENGTH); if (reserve_size > hp->parsed->body.capacity()) { hp->parsed->body.reserve(reserve_size); } hp->state = HP_CHUNK_HEADER; hp->invokeHttpCb(NULL, chunk_size); return 0; } int on_chunk_complete(http_parser* parser) { printd("on_chunk_complete\n"); Http1Parser* hp = (Http1Parser*)parser->data; hp->state = HP_CHUNK_COMPLETE; hp->invokeHttpCb(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/Http1Parser.h000066400000000000000000000073511520575453600267600ustar00rootroot00000000000000#ifndef HV_HTTP1_PARSER_H_ #define HV_HTTP1_PARSER_H_ #include "HttpParser.h" #include "http_parser.h" class Http1Parser : public HttpParser { public: static http_parser_settings cbs; http_parser parser; int flags; http_parser_state state; HttpMessage* submited; HttpMessage* parsed; // tmp std::string url; // for on_url std::string header_field; // for on_header_field std::string header_value; // for on_header_value std::string sendbuf; // for GetSendData Http1Parser(http_session_type type = HTTP_CLIENT); virtual ~Http1Parser(); void handle_header() { if (header_field.size() != 0) { if (stricmp(header_field.c_str(), "Set-CooKie") == 0 || stricmp(header_field.c_str(), "Cookie") == 0) { HttpCookie cookie; if (cookie.parse(header_value)) { parsed->cookies.emplace_back(cookie); header_field.clear(); header_value.clear(); return; } } parsed->headers[header_field] = header_value; header_field.clear(); header_value.clear(); } } virtual int GetSendData(char** data, size_t* len) { if (!submited) { *data = NULL; *len = 0; return 0; } sendbuf = submited->Dump(true, true); submited = NULL; *data = (char*)sendbuf.data(); *len = sendbuf.size(); return sendbuf.size(); } virtual int FeedRecvData(const char* data, size_t len) { return http_parser_execute(&parser, &cbs, data, len); } virtual int GetState() { return (int)state; } virtual bool WantRecv() { return state != HP_MESSAGE_COMPLETE; } virtual bool WantSend() { return state == HP_MESSAGE_COMPLETE; } virtual bool IsComplete() { return state == HP_MESSAGE_COMPLETE; } virtual bool IsEof() { FeedRecvData(NULL, 0); return IsComplete(); } virtual int GetError() { return parser.http_errno; } virtual const char* StrError(int error) { return http_errno_description((enum http_errno)error); } // client // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) virtual int SubmitRequest(HttpRequest* req) { submited = req; if (req) { if (req->method == HTTP_HEAD) { flags |= F_SKIPBODY; } else { flags &= ~F_SKIPBODY; } } return 0; } virtual int InitResponse(HttpResponse* res) { res->Reset(); parsed = res; http_parser_init(&parser, HTTP_RESPONSE); url.clear(); header_field.clear(); header_value.clear(); return 0; } // server // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} virtual int InitRequest(HttpRequest* req) { req->Reset(); parsed = req; http_parser_init(&parser, HTTP_REQUEST); state = HP_START_REQ_OR_RES; url.clear(); header_field.clear(); header_value.clear(); return 0; } virtual int SubmitResponse(HttpResponse* res) { submited = res; return 0; } // HttpMessage::http_cb int invokeHttpCb(const char* data = NULL, size_t size = 0) { if (parsed->http_cb == NULL) return -1; parsed->http_cb(parsed, state, data, size); return 0; } }; #endif // HV_HTTP1_PARSER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/Http2Parser.cpp000066400000000000000000000351501520575453600273120ustar00rootroot00000000000000#ifdef WITH_NGHTTP2 #include "Http2Parser.h" static nghttp2_nv make_nv(const char* name, const char* value) { nghttp2_nv nv; nv.name = (uint8_t*)name; nv.value = (uint8_t*)value; nv.namelen = strlen(name); nv.valuelen = strlen(value); nv.flags = NGHTTP2_NV_FLAG_NONE; return nv; } static nghttp2_nv make_nv2(const char* name, const char* value, int namelen, int valuelen) { nghttp2_nv nv; nv.name = (uint8_t*)name; nv.value = (uint8_t*)value; nv.namelen = namelen; nv.valuelen = valuelen; nv.flags = NGHTTP2_NV_FLAG_NONE; return nv; } static void print_frame_hd(const nghttp2_frame_hd* hd) { printd("[frame] length=%d type=%x flags=%x stream_id=%d\n", (int)hd->length, (int)hd->type, (int)hd->flags, hd->stream_id); } static int on_header_callback(nghttp2_session *session, const nghttp2_frame *frame, const uint8_t *name, size_t namelen, const uint8_t *value, size_t valuelen, uint8_t flags, void *userdata); static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *userdata); static int on_frame_recv_callback(nghttp2_session *session, const nghttp2_frame *frame, void *userdata); /* static ssize_t data_source_read_callback(nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length, uint32_t *data_flags, nghttp2_data_source *source, void *userdata); */ Http2Parser::Http2Parser(http_session_type type) { if (cbs == NULL) { nghttp2_session_callbacks_new(&cbs); nghttp2_session_callbacks_set_on_header_callback(cbs, on_header_callback); nghttp2_session_callbacks_set_on_data_chunk_recv_callback(cbs, on_data_chunk_recv_callback); nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv_callback); } if (type == HTTP_CLIENT) { nghttp2_session_client_new(&session, cbs, this); state = H2_SEND_MAGIC; } else if (type == HTTP_SERVER) { nghttp2_session_server_new(&session, cbs, this); state = H2_WANT_RECV; } //nghttp2_session_set_user_data(session, this); submited = NULL; parsed = NULL; stream_id = -1; stream_closed = 0; nghttp2_settings_entry settings[] = { {NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 100} }; nghttp2_submit_settings(session, NGHTTP2_FLAG_NONE, settings, ARRAY_SIZE(settings)); state = H2_SEND_SETTINGS; //nghttp2_submit_ping(session, NGHTTP2_FLAG_NONE, NULL); //state = H2_SEND_PING; } Http2Parser::~Http2Parser() { if (session) { nghttp2_session_del(session); session = NULL; } } int Http2Parser::GetSendData(char** data, size_t* len) { // HTTP2_MAGIC,HTTP2_SETTINGS,HTTP2_HEADERS *len = nghttp2_session_mem_send(session, (const uint8_t**)data); printd("nghttp2_session_mem_send %d\n", *len); if (*len != 0) return *len; if (submited == NULL) return 0; // HTTP2_DATA if (state == H2_SEND_HEADERS) { void* content = submited->Content(); int content_length = submited->ContentLength(); // HTTP2 DATA framehd state = H2_SEND_DATA_FRAME_HD; http2_frame_hd framehd; framehd.length = content_length; framehd.type = HTTP2_DATA; framehd.flags = HTTP2_FLAG_END_STREAM; framehd.stream_id = stream_id; *data = (char*)frame_hdbuf; *len = HTTP2_FRAME_HDLEN; printd("HTTP2 SEND_DATA_FRAME_HD...\n"); if (submited->ContentType() == APPLICATION_GRPC) { grpc_message_hd msghd; msghd.flags = 0; msghd.length = content_length; printd("grpc_message_hd: flags=%d length=%d\n", msghd.flags, msghd.length); if (type == HTTP_SERVER) { // grpc server send grpc-status in HTTP2 header frame framehd.flags = HTTP2_FLAG_NONE; /* // @test protobuf // message StringMessage { // string str = 1; // } int protobuf_taglen = 0; int tag = PROTOBUF_MAKE_TAG(1, WIRE_TYPE_LENGTH_DELIMITED); unsigned char* p = frame_hdbuf + HTTP2_FRAME_HDLEN + GRPC_MESSAGE_HDLEN; int bytes = varint_encode(tag, p); protobuf_taglen += bytes; p += bytes; bytes = varint_encode(content_length, p); protobuf_taglen += bytes; msghd.length += protobuf_taglen; framehd.length += protobuf_taglen; *len += protobuf_taglen; */ } grpc_message_hd_pack(&msghd, frame_hdbuf + HTTP2_FRAME_HDLEN); framehd.length += GRPC_MESSAGE_HDLEN; *len += GRPC_MESSAGE_HDLEN; } http2_frame_hd_pack(&framehd, frame_hdbuf); } else if (state == H2_SEND_DATA_FRAME_HD) { // HTTP2 DATA void* content = submited->Content(); int content_length = submited->ContentLength(); if (content_length == 0) { // skip send_data goto send_done; } else { printd("HTTP2 SEND_DATA... content_length=%d\n", content_length); state = H2_SEND_DATA; *data = (char*)content; *len = content_length; } } else if (state == H2_SEND_DATA) { send_done: state = H2_SEND_DONE; if (submited->ContentType() == APPLICATION_GRPC) { if (type == HTTP_SERVER && stream_closed) { // grpc HEADERS grpc-status printd("grpc HEADERS grpc-status: 0\n"); int flags = NGHTTP2_FLAG_END_STREAM | NGHTTP2_FLAG_END_HEADERS; nghttp2_nv nv = make_nv("grpc-status", "0"); nghttp2_submit_headers(session, flags, stream_id, NULL, &nv, 1, NULL); *len = nghttp2_session_mem_send(session, (const uint8_t**)data); } } } printd("GetSendData %d\n", *len); return *len; } int Http2Parser::FeedRecvData(const char* data, size_t len) { printd("nghttp2_session_mem_recv %d\n", len); state = H2_WANT_RECV; size_t ret = nghttp2_session_mem_recv(session, (const uint8_t*)data, len); if (ret != len) { error = ret; } return (int)ret; } int Http2Parser::SubmitRequest(HttpRequest* req) { submited = req; req->FillContentType(); req->FillContentLength(); if (req->ContentType() == APPLICATION_GRPC) { req->method = HTTP_POST; req->headers["te"] = "trailers"; req->headers["user-agent"] = "grpc-c++/1.16.0 grpc-c/6.0.0 (linux; nghttp2; hw)"; req->headers["accept-encoding"] = "identity"; req->headers["grpc-accept-encoding"] = "identity"; } std::vector nvs; char c_str[256] = {0}; req->ParseUrl(); nvs.push_back(make_nv(":method", http_method_str(req->method))); nvs.push_back(make_nv(":path", req->path.c_str())); nvs.push_back(make_nv(":scheme", req->scheme.c_str())); if (req->port == 0 || req->port == DEFAULT_HTTP_PORT || req->port == DEFAULT_HTTPS_PORT) { nvs.push_back(make_nv(":authority", req->host.c_str())); } else { snprintf(c_str, sizeof(c_str), "%s:%d", req->host.c_str(), req->port); nvs.push_back(make_nv(":authority", c_str)); } const char* name; const char* value; for (auto& header : req->headers) { name = header.first.c_str(); value = header.second.c_str(); hv_strlower((char*)name); if (strcmp(name, "host") == 0) { // :authority continue; } if (strcmp(name, "connection") == 0) { // HTTP2 default keep-alive continue; } if (strcmp(name, "content-length") == 0) { // HTTP2 have frame_hd.length continue; } nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size())); } int flags = NGHTTP2_FLAG_END_HEADERS; // we set EOS on DATA frame stream_id = nghttp2_submit_headers(session, flags, -1, NULL, &nvs[0], nvs.size(), NULL); // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data // nghttp2_data_provider data_prd; // data_prd.read_callback = data_source_read_callback; //stream_id = nghttp2_submit_request(session, NULL, &nvs[0], nvs.size(), &data_prd, NULL); state = H2_SEND_HEADERS; return 0; } int Http2Parser::SubmitResponse(HttpResponse* res) { submited = res; res->FillContentType(); res->FillContentLength(); if (parsed && parsed->ContentType() == APPLICATION_GRPC) { // correct content_type: application/grpc if (res->ContentType() != APPLICATION_GRPC) { res->content_type = APPLICATION_GRPC; res->headers["content-type"] = http_content_type_str(APPLICATION_GRPC); } //res->headers["accept-encoding"] = "identity"; //res->headers["grpc-accept-encoding"] = "identity"; //res->headers["grpc-status"] = "0"; //res->status_code = HTTP_STATUS_OK; } std::vector nvs; char c_str[256] = {0}; snprintf(c_str, sizeof(c_str), "%d", res->status_code); nvs.push_back(make_nv(":status", c_str)); const char* name; const char* value; for (auto& header : res->headers) { name = header.first.c_str(); value = header.second.c_str(); hv_strlower((char*)name); if (strcmp(name, "connection") == 0) { // HTTP2 default keep-alive continue; } if (strcmp(name, "content-length") == 0) { // HTTP2 have frame_hd.length continue; } nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size())); } int flags = NGHTTP2_FLAG_END_HEADERS; // we set EOS on DATA frame if (stream_id == -1) { // upgrade nghttp2_session_upgrade(session, NULL, 0, NULL); stream_id = 1; } nghttp2_submit_headers(session, flags, stream_id, NULL, &nvs[0], nvs.size(), NULL); // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data // data_prd.read_callback = data_source_read_callback; //nghttp2_submit_response(session, stream_id, &nvs[0], nvs.size(), &data_prd); state = H2_SEND_HEADERS; return 0; } int Http2Parser::InitResponse(HttpResponse* res) { res->Reset(); res->http_major = 2; res->http_minor = 0; parsed = res; return 0; } int Http2Parser::InitRequest(HttpRequest* req) { req->Reset(); req->http_major = 2; req->http_minor = 0; parsed = req; return 0; } nghttp2_session_callbacks* Http2Parser::cbs = NULL; int on_header_callback(nghttp2_session *session, const nghttp2_frame *frame, const uint8_t *_name, size_t namelen, const uint8_t *_value, size_t valuelen, uint8_t flags, void *userdata) { printd("on_header_callback\n"); print_frame_hd(&frame->hd); const char* name = (const char*)_name; const char* value = (const char*)_value; printd("%s: %s\n", name, value); Http2Parser* hp = (Http2Parser*)userdata; if (*name == ':') { if (hp->parsed->type == HTTP_REQUEST) { // :method :path :scheme :authority HttpRequest* req = (HttpRequest*)hp->parsed; if (strcmp(name, ":method") == 0) { req->method = http_method_enum(value); } else if (strcmp(name, ":path") == 0) { req->url = value; } else if (strcmp(name, ":scheme") == 0) { req->headers["Scheme"] = value; } else if (strcmp(name, ":authority") == 0) { req->headers["Host"] = value; } } else if (hp->parsed->type == HTTP_RESPONSE) { HttpResponse* res = (HttpResponse*)hp->parsed; if (strcmp(name, ":status") == 0) { res->status_code = (http_status)atoi(value); if (res->http_cb) { res->http_cb(res, HP_MESSAGE_BEGIN, NULL, 0); } } } } else { hp->parsed->headers[name] = value; if (strcmp(name, "content-type") == 0) { hp->parsed->content_type = http_content_type_enum(value); } } return 0; } int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *userdata) { printd("on_data_chunk_recv_callback\n"); printd("stream_id=%d length=%d\n", stream_id, (int)len); //printd("%.*s\n", (int)len, data); Http2Parser* hp = (Http2Parser*)userdata; if (hp->parsed->ContentType() == APPLICATION_GRPC) { // grpc_message_hd if (len >= GRPC_MESSAGE_HDLEN) { grpc_message_hd msghd; grpc_message_hd_unpack(&msghd, data); printd("grpc_message_hd: flags=%d length=%d\n", msghd.flags, msghd.length); data += GRPC_MESSAGE_HDLEN; len -= GRPC_MESSAGE_HDLEN; //printd("%.*s\n", (int)len, data); } } if (hp->parsed->http_cb) { hp->parsed->http_cb(hp->parsed, HP_BODY, (const char*)data, len); } else { hp->parsed->body.append((const char*)data, len); } return 0; } int on_frame_recv_callback(nghttp2_session *session, const nghttp2_frame *frame, void *userdata) { printd("on_frame_recv_callback\n"); print_frame_hd(&frame->hd); Http2Parser* hp = (Http2Parser*)userdata; switch (frame->hd.type) { case NGHTTP2_DATA: hp->state = H2_RECV_DATA; break; case NGHTTP2_HEADERS: hp->state = H2_RECV_HEADERS; break; case NGHTTP2_SETTINGS: hp->state = H2_RECV_SETTINGS; break; case NGHTTP2_PING: hp->state = H2_RECV_PING; break; case NGHTTP2_RST_STREAM: case NGHTTP2_WINDOW_UPDATE: // ignore return 0; default: break; } if (hp->state == H2_RECV_HEADERS && hp->parsed->http_cb) { hp->parsed->http_cb(hp->parsed, HP_HEADERS_COMPLETE, NULL, 0); } if (frame->hd.stream_id >= hp->stream_id) { hp->stream_id = frame->hd.stream_id; hp->stream_closed = 0; if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { printd("on_stream_closed stream_id=%d\n", hp->stream_id); hp->stream_closed = 1; hp->frame_type_when_stream_closed = frame->hd.type; if (hp->state == H2_RECV_HEADERS || hp->state == H2_RECV_DATA) { if (hp->parsed->http_cb) { hp->parsed->http_cb(hp->parsed, HP_MESSAGE_COMPLETE, NULL, 0); } } } } return 0; } #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/Http2Parser.h000066400000000000000000000043241520575453600267560ustar00rootroot00000000000000#ifndef HV_HTTP2_PARSER_H_ #define HV_HTTP2_PARSER_H_ #ifdef WITH_NGHTTP2 #include "HttpParser.h" #include "http2def.h" #include "grpcdef.h" #include "nghttp2/nghttp2.h" enum http2_session_state { H2_SEND_MAGIC, H2_SEND_SETTINGS, H2_SEND_PING, H2_SEND_HEADERS, H2_SEND_DATA_FRAME_HD, H2_SEND_DATA, H2_SEND_DONE, H2_WANT_SEND, H2_WANT_RECV, H2_RECV_SETTINGS, H2_RECV_PING, H2_RECV_HEADERS, H2_RECV_DATA, }; class Http2Parser : public HttpParser { public: static nghttp2_session_callbacks* cbs; nghttp2_session* session; http2_session_state state; HttpMessage* submited; HttpMessage* parsed; int error; int stream_id; int stream_closed; int frame_type_when_stream_closed; // http2_frame_hd + grpc_message_hd // at least HTTP2_FRAME_HDLEN + GRPC_MESSAGE_HDLEN = 9 + 5 = 14 unsigned char frame_hdbuf[32]; Http2Parser(http_session_type type = HTTP_CLIENT); virtual ~Http2Parser(); virtual int GetSendData(char** data, size_t* len); virtual int FeedRecvData(const char* data, size_t len); virtual int GetState() { return (int)state; } virtual bool WantRecv() { return state == H2_WANT_RECV; } virtual bool WantSend() { return state <= H2_WANT_SEND; } virtual bool IsComplete() { return stream_closed && (frame_type_when_stream_closed == HTTP2_DATA || frame_type_when_stream_closed == HTTP2_HEADERS); } virtual int GetError() { return error; } virtual const char* StrError(int error) { //return nghttp2_http2_strerror(error); return nghttp2_strerror(error); } // client // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) virtual int SubmitRequest(HttpRequest* req); virtual int InitResponse(HttpResponse* res); // server // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} virtual int InitRequest(HttpRequest* req); virtual int SubmitResponse(HttpResponse* res); }; #endif #endif // HV_HTTP2_PARSER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/HttpMessage.cpp000066400000000000000000000541201520575453600273560ustar00rootroot00000000000000#include "HttpMessage.h" #include #include "htime.h" #include "hlog.h" #include "hurl.h" #include "base64.h" using namespace hv; http_headers DefaultHeaders; http_body NoBody; HttpCookie NoCookie; char HttpMessage::s_date[32] = {0}; HttpCookie::HttpCookie() { init(); } void HttpCookie::init() { max_age = 0; secure = false; httponly = false; samesite = Default; priority = NotSet; } void HttpCookie::reset() { init(); name.clear(); value.clear(); domain.clear(); path.clear(); expires.clear(); kv.clear(); } bool HttpCookie::parse(const std::string& str) { std::stringstream ss; ss << str; std::string line; std::string::size_type pos; std::string key; std::string val; reset(); while (std::getline(ss, line, ';')) { pos = line.find_first_of('='); if (pos != std::string::npos) { key = trim(line.substr(0, pos)); val = trim(line.substr(pos+1)); const char* pkey = key.c_str(); if (stricmp(pkey, "Domain") == 0) { domain = val; } else if (stricmp(pkey, "Path") == 0) { path = val; } else if (stricmp(pkey, "Expires") == 0) { expires = val; } else if (stricmp(pkey, "Max-Age") == 0) { max_age = atoi(val.c_str()); } else if (stricmp(pkey, "SameSite") == 0) { samesite = stricmp(val.c_str(), "Strict") == 0 ? HttpCookie::SameSite::Strict : stricmp(val.c_str(), "Lax") == 0 ? HttpCookie::SameSite::Lax : stricmp(val.c_str(), "None") == 0 ? HttpCookie::SameSite::None : HttpCookie::SameSite::Default; } else if (stricmp(pkey, "Priority") == 0) { priority = stricmp(val.c_str(), "Low") == 0 ? HttpCookie::Priority::Low : stricmp(val.c_str(), "Medium") == 0 ? HttpCookie::Priority::Medium : stricmp(val.c_str(), "High") == 0 ? HttpCookie::Priority::High : HttpCookie::Priority::NotSet ; } else { if (name.empty()) { name = key; value = val; } kv[key] = val; } } else { key = trim(line); const char* pkey = key.c_str(); if (stricmp(pkey, "Secure") == 0) { secure = true; } else if (stricmp(pkey, "HttpOnly") == 0) { httponly = true; } else { hlogw("Unrecognized key '%s'", key.c_str()); } } } return !name.empty(); } std::string HttpCookie::dump() const { assert(!name.empty() || !kv.empty()); std::string res; if (!name.empty()) { res = name; res += "="; res += value; } for (auto& pair : kv) { if (pair.first == name) continue; if (!res.empty()) res += "; "; res += pair.first; res += "="; res += pair.second; } if (!domain.empty()) { res += "; Domain="; res += domain; } if (!path.empty()) { res += "; Path="; res += path; } if (max_age > 0) { res += "; Max-Age="; res += hv::to_string(max_age); } else if (!expires.empty()) { res += "; Expires="; res += expires; } if (samesite != HttpCookie::SameSite::Default) { res += "; SameSite="; res += samesite == HttpCookie::SameSite::Strict ? "Strict" : samesite == HttpCookie::SameSite::Lax ? "Lax" : "None" ; } if (priority != HttpCookie::Priority::NotSet) { res += "; Priority="; res += priority == HttpCookie::Priority::Low ? "Low" : priority == HttpCookie::Priority::Medium ? "Medium" : "High" ; } if (secure) { res += "; Secure"; } if (httponly) { res += "; HttpOnly"; } return res; } HttpMessage::HttpMessage() { type = HTTP_BOTH; Init(); } HttpMessage::~HttpMessage() { } void HttpMessage::Init() { http_major = 1; http_minor = 1; content = NULL; content_length = 0; content_type = CONTENT_TYPE_NONE; } void HttpMessage::Reset() { Init(); headers.clear(); cookies.clear(); body.clear(); #ifndef WITHOUT_HTTP_CONTENT json.clear(); form.clear(); kv.clear(); #endif } #ifndef WITHOUT_HTTP_CONTENT // NOTE: json ignore number/string, 123/"123" std::string HttpMessage::GetString(const char* key, const std::string& defvalue) { switch (ContentType()) { case APPLICATION_JSON: { if (json.empty()) { ParseBody(); } if (!json.is_object()) { return defvalue; } const auto& value = json[key]; if (value.is_string()) { return value; } else if (value.is_number()) { return hv::to_string(value); } else if (value.is_boolean()) { bool b = value; return b ? "true" : "false"; } else { return defvalue; } } break; case MULTIPART_FORM_DATA: { if (form.empty()) { ParseBody(); } auto iter = form.find(key); if (iter != form.end()) { return iter->second.content; } } break; case APPLICATION_URLENCODED: { if (kv.empty()) { ParseBody(); } auto iter = kv.find(key); if (iter != kv.end()) { return iter->second; } } break; default: break; } return defvalue; } template<> HV_EXPORT int64_t HttpMessage::Get(const char* key, int64_t defvalue) { if (ContentType() == APPLICATION_JSON) { if (json.empty()) { ParseBody(); } if (!json.is_object()) { return defvalue; } const auto& value = json[key]; if (value.is_number()) { return value; } else if (value.is_string()) { std::string str = value; return atoll(str.c_str()); } else if (value.is_boolean()) { bool b = value; return b ? 1 : 0; } else { return defvalue; } } else { std::string str = GetString(key); return str.empty() ? defvalue : atoll(str.c_str()); } } template<> HV_EXPORT int HttpMessage::Get(const char* key, int defvalue) { return (int)Get(key, defvalue); } template<> HV_EXPORT double HttpMessage::Get(const char* key, double defvalue) { if (ContentType() == APPLICATION_JSON) { if (json.empty()) { ParseBody(); } if (!json.is_object()) { return defvalue; } const auto& value = json[key]; if (value.is_number()) { return value; } else if (value.is_string()) { std::string str = value; return atof(str.c_str()); } else { return defvalue; } } else { std::string str = GetString(key); return str.empty() ? defvalue : atof(str.c_str()); } } template<> HV_EXPORT float HttpMessage::Get(const char* key, float defvalue) { return (float)Get(key, defvalue); } template<> HV_EXPORT bool HttpMessage::Get(const char* key, bool defvalue) { if (ContentType() == APPLICATION_JSON) { if (json.empty()) { ParseBody(); } if (!json.is_object()) { return defvalue; } const auto& value = json[key]; if (value.is_boolean()) { return value; } else if (value.is_string()) { std::string str = value; return hv_getboolean(str.c_str()); } else if (value.is_number()) { return value != 0; } else { return defvalue; } } else { std::string str = GetString(key); return str.empty() ? defvalue : hv_getboolean(str.c_str()); } } bool HttpMessage::GetBool(const char* key, bool defvalue) { return Get(key, defvalue); } int64_t HttpMessage::GetInt(const char* key, int64_t defvalue) { return Get(key, defvalue); } double HttpMessage::GetFloat(const char* key, double defvalue) { return Get(key, defvalue); } #endif void HttpMessage::FillContentType() { auto iter = headers.find("Content-Type"); if (iter != headers.end()) { content_type = http_content_type_enum(iter->second.c_str()); goto append; } #ifndef WITHOUT_HTTP_CONTENT if (content_type == CONTENT_TYPE_NONE) { if (json.size() != 0) { content_type = APPLICATION_JSON; } else if (form.size() != 0) { content_type = MULTIPART_FORM_DATA; } else if (kv.size() != 0) { content_type = X_WWW_FORM_URLENCODED; } else if (body.size() != 0) { content_type = TEXT_PLAIN; } } #endif if (content_type != CONTENT_TYPE_NONE) { headers["Content-Type"] = http_content_type_str(content_type); } append: #ifndef WITHOUT_HTTP_CONTENT if (content_type == MULTIPART_FORM_DATA) { auto iter = headers.find("Content-Type"); if (iter != headers.end()) { const char* boundary = strstr(iter->second.c_str(), "boundary="); if (boundary == NULL) { boundary = DEFAULT_MULTIPART_BOUNDARY; iter->second += "; boundary="; iter->second += boundary; } } } #endif return; } void HttpMessage::FillContentLength() { auto iter = headers.find("Content-Length"); if (iter != headers.end()) { content_length = atoll(iter->second.c_str()); } if (content_length == 0) { DumpBody(); content_length = body.size(); } if (iter == headers.end() && !IsChunked() && content_type != TEXT_EVENT_STREAM) { if (content_length != 0 || type == HTTP_RESPONSE) { headers["Content-Length"] = hv::to_string(content_length); } } } bool HttpMessage::IsChunked() { auto iter = headers.find("Transfer-Encoding"); return iter != headers.end() && stricmp(iter->second.c_str(), "chunked") == 0; } bool HttpMessage::IsKeepAlive() { bool keepalive = true; auto iter = headers.find("connection"); if (iter != headers.end()) { const char* keepalive_value = iter->second.c_str(); if (stricmp(keepalive_value, "keep-alive") == 0) { keepalive = true; } else if (stricmp(keepalive_value, "close") == 0) { keepalive = false; } else if (stricmp(keepalive_value, "upgrade") == 0) { keepalive = true; } } else if (http_major == 1 && http_minor == 0) { keepalive = false; } return keepalive; } bool HttpMessage::IsUpgrade() { auto iter = headers.find("upgrade"); return iter != headers.end(); } // headers void HttpMessage::SetHeader(const char* key, const std::string& value) { headers[key] = value; } std::string HttpMessage::GetHeader(const char* key, const std::string& defvalue) { auto iter = headers.find(key); return iter == headers.end() ? defvalue : iter->second; } // cookies void HttpMessage::AddCookie(const HttpCookie& cookie) { cookies.push_back(cookie); } const HttpCookie& HttpMessage::GetCookie(const std::string& name) { for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) { if (iter->name == name) { return *iter; } auto kv_iter = iter->kv.find(name); if (kv_iter != iter->kv.end()) { iter->name = name; iter->value = kv_iter->second; return *iter; } } return NoCookie; } // body void HttpMessage::SetBody(const std::string& body) { this->body = body; } const std::string& HttpMessage::Body() { return this->body; } void HttpMessage::DumpHeaders(std::string& str) { FillContentType(); FillContentLength(); // headers for (auto& header: headers) { // http2 :method :path :scheme :authority :status if (*str.c_str() != ':') { // %s: %s\r\n str += header.first; str += ": "; // fix CVE-2023-26148 // if the value has \r\n, translate to \\r\\n if (header.second.find("\r") != std::string::npos || header.second.find("\n") != std::string::npos) { std::string newStr = ""; for (size_t i = 0; i < header.second.size(); ++i) { if (header.second[i] == '\r') { newStr += "\\r"; } else if (header.second[i] == '\n') { newStr += "\\n"; } else { newStr += header.second[i]; } } str += newStr; } else { str += header.second; } str += "\r\n"; } } // cookies const char* cookie_field = "Cookie"; if (type == HTTP_RESPONSE) { cookie_field = "Set-Cookie"; } for (auto& cookie : cookies) { str += cookie_field; str += ": "; str += cookie.dump(); str += "\r\n"; } } void HttpMessage::DumpBody() { if (body.size() != 0) { return; } FillContentType(); #ifndef WITHOUT_HTTP_CONTENT switch(content_type) { case APPLICATION_JSON: body = dump_json(json, 2); break; case MULTIPART_FORM_DATA: { auto iter = headers.find("Content-Type"); if (iter == headers.end()) { return; } const char* boundary = strstr(iter->second.c_str(), "boundary="); if (boundary == NULL) { return; } boundary += strlen("boundary="); body = dump_multipart(form, boundary); } break; case X_WWW_FORM_URLENCODED: body = dump_query_params(kv); break; default: // nothing to do break; } #endif } void HttpMessage::DumpBody(std::string& str) { DumpBody(); const char* content = (const char*)Content(); size_t content_length = ContentLength(); if (content && content_length) { str.append(content, content_length); } } int HttpMessage::ParseBody() { if (body.size() == 0) { return -1; } FillContentType(); #ifndef WITHOUT_HTTP_CONTENT switch(content_type) { case APPLICATION_JSON: { std::string errmsg; int ret = parse_json(body.c_str(), json, errmsg); if (ret != 0 && errmsg.size() != 0) { hloge("%s", errmsg.c_str()); } return ret; } case MULTIPART_FORM_DATA: { auto iter = headers.find("Content-Type"); if (iter == headers.end()) { return -1; } const char* boundary = strstr(iter->second.c_str(), "boundary="); if (boundary == NULL) { return -1; } boundary += strlen("boundary="); std::string strBoundary(boundary); strBoundary = trim_pairs(strBoundary, "\"\"\'\'"); return parse_multipart(body, form, strBoundary.c_str()); } case X_WWW_FORM_URLENCODED: return parse_query_params(body.c_str(), kv); default: // nothing to do return 0; } #endif return 0; } std::string HttpMessage::Dump(bool is_dump_headers, bool is_dump_body) { std::string str; if (is_dump_headers) { DumpHeaders(str); } str += "\r\n"; if (is_dump_body) { DumpBody(str); } return str; } HttpRequest::HttpRequest() : HttpMessage() { type = HTTP_REQUEST; Init(); } void HttpRequest::Init() { headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT; headers["Accept"] = "*/*"; method = HTTP_GET; scheme = "http"; host = "127.0.0.1"; port = DEFAULT_HTTP_PORT; path = "/"; timeout = DEFAULT_HTTP_TIMEOUT; connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT; retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT; retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY; redirect = 1; proxy = 0; cancel = 0; } void HttpRequest::Reset() { HttpMessage::Reset(); Init(); url.clear(); query_params.clear(); } void HttpRequest::DumpUrl() { std::string str; if (url.size() != 0 && *url.c_str() != '/' && strstr(url.c_str(), "://") != NULL) { // have been complete url goto query; } // scheme:// str = scheme; str += "://"; // host:port if (url.size() != 0 && *url.c_str() != '/') { // url begin with host str += url; } else { if (port == 0 || port == DEFAULT_HTTP_PORT || port == DEFAULT_HTTPS_PORT) { str += Host(); } else { str += hv::asprintf("%s:%d", host.c_str(), port); } } // /path if (url.size() != 0 && *url.c_str() == '/') { // url begin with path str += url; } else if (path.size() > 1 && *path.c_str() == '/') { str += path; } else if (url.size() == 0) { str += '/'; } url = str; query: // ?query if (strchr(url.c_str(), '?') == NULL && query_params.size() != 0) { url += '?'; url += dump_query_params(query_params); } } void HttpRequest::ParseUrl() { DumpUrl(); hurl_t parser; hv_parse_url(&parser, url.c_str()); // scheme std::string scheme_ = url.substr(parser.fields[HV_URL_SCHEME].off, parser.fields[HV_URL_SCHEME].len); // host std::string host_(host); if (parser.fields[HV_URL_HOST].len > 0) { host_ = url.substr(parser.fields[HV_URL_HOST].off, parser.fields[HV_URL_HOST].len); } // port int port_ = parser.port ? parser.port : strcmp(scheme_.c_str(), "https") ? DEFAULT_HTTP_PORT : DEFAULT_HTTPS_PORT; if (!proxy) { scheme = scheme_; host = host_; port = port_; } FillHost(host_.c_str(), port_); // path if (parser.fields[HV_URL_PATH].len > 0) { path = url.substr(parser.fields[HV_URL_PATH].off); } // query if (parser.fields[HV_URL_QUERY].len > 0) { parse_query_params(url.c_str()+parser.fields[HV_URL_QUERY].off, query_params); } } std::string HttpRequest::Path() { const char* s = path.c_str(); const char* e = s; while (*e && *e != '?' && *e != '#') ++e; return HUrl::unescape(std::string(s, e)); } void HttpRequest::FillHost(const char* host, int port) { if (headers.find("Host") == headers.end()) { if (port == 0 || port == DEFAULT_HTTP_PORT || port == DEFAULT_HTTPS_PORT) { headers["Host"] = host; } else { headers["Host"] = asprintf("%s:%d", host, port); } } } void HttpRequest::SetHost(const char* host, int port) { this->host = host; this->port = port; FillHost(host, port); } void HttpRequest::SetProxy(const char* host, int port) { this->scheme = "http"; this->host = host; this->port = port; proxy = 1; } void HttpRequest::SetAuth(const std::string& auth) { SetHeader("Authorization", auth); } void HttpRequest::SetBasicAuth(const std::string& username, const std::string& password) { std::string strAuth = hv::asprintf("%s:%s", username.c_str(), password.c_str()); std::string base64Auth = hv::Base64Encode((const unsigned char*)strAuth.c_str(), strAuth.size()); SetAuth(std::string("Basic ") + base64Auth); } void HttpRequest::SetBearerTokenAuth(const std::string& token) { SetAuth(std::string("Bearer ") + token); } std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) { ParseUrl(); std::string str; str.reserve(MAX(512, path.size() + 128)); // GET / HTTP/1.1\r\n str = asprintf("%s %s HTTP/%d.%d\r\n", http_method_str(method), proxy ? url.c_str() : path.c_str(), (int)http_major, (int)http_minor); if (is_dump_headers) { DumpHeaders(str); } str += "\r\n"; if (is_dump_body) { DumpBody(str); } return str; } void HttpRequest::SetRange(long from, long to) { SetHeader("Range", hv::asprintf("bytes=%ld-%ld", from, to)); } bool HttpRequest::GetRange(long& from, long& to) { auto iter = headers.find("Range"); if (iter != headers.end()) { sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to); return true; } from = to = 0; return false; } HttpResponse::HttpResponse() : HttpMessage() { type = HTTP_RESPONSE; Init(); } void HttpResponse::Init() { status_code = HTTP_STATUS_OK; } void HttpResponse::Reset() { HttpMessage::Reset(); Init(); } std::string HttpResponse::Dump(bool is_dump_headers, bool is_dump_body) { char c_str[256] = {0}; std::string str; str.reserve(512); // HTTP/1.1 200 OK\r\n snprintf(c_str, sizeof(c_str), "HTTP/%d.%d %d %s\r\n", (int)http_major, (int)http_minor, (int)status_code, http_status_str(status_code)); str = c_str; if (is_dump_headers) { if (*s_date) { headers["Date"] = s_date; } else { headers["Date"] = gmtime_fmt(time(NULL), c_str); } DumpHeaders(str); } str += "\r\n"; if (is_dump_body) { DumpBody(str); } return str; } void HttpResponse::SetRange(long from, long to, long total) { SetHeader("Content-Range", hv::asprintf("bytes %ld-%ld/%ld", from, to, total)); } bool HttpResponse::GetRange(long& from, long& to, long& total) { auto iter = headers.find("Content-Range"); if (iter != headers.end()) { sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total); return true; } from = to = total = 0; return false; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/HttpMessage.h000066400000000000000000000344251520575453600270310ustar00rootroot00000000000000#ifndef HV_HTTP_MESSAGE_H_ #define HV_HTTP_MESSAGE_H_ /* * @class HttpMessage * HttpRequest extends HttpMessage * HttpResponse extends HttpMessage * * @member * request-line: GET / HTTP/1.1\r\n => method path * response-line: HTTP/1.1 200 OK\r\n => status_code * headers, cookies * body * * content, content_length, content_type * json, form, kv * * @function * Content, ContentLength, ContentType * ParseUrl, ParseBody * DumpUrl, DumpHeaders, DumpBody, Dump * GetHeader, GetParam, GetJson, GetFormData, GetUrlEncoded * SetHeader, SetParam, SetBody, SetFormData, SetUrlEncoded * Get, Set * GetString, GetBool, GetInt, GetFloat * String, Data, Json, File, FormFile * * @example * examples/http_server_test.cpp * examples/http_client_test.cpp * examples/httpd * */ #include #include #include #include #include "hexport.h" #include "hbase.h" #include "hstring.h" #include "hfile.h" #include "hpath.h" #include "httpdef.h" #include "http_content.h" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie // Cookie: sessionid=1; domain=.example.com; path=/; max-age=86400; secure; httponly struct HV_EXPORT HttpCookie { std::string name; std::string value; std::string domain; std::string path; std::string expires; int max_age; bool secure; bool httponly; enum SameSite { Default, Strict, Lax, None } samesite; enum Priority { NotSet, Low, Medium, High, } priority; hv::KeyValue kv; // for multiple names HttpCookie(); void init(); void reset(); bool parse(const std::string& str); std::string dump() const; }; typedef std::map http_headers; typedef std::vector http_cookies; typedef std::string http_body; HV_EXPORT extern http_headers DefaultHeaders; HV_EXPORT extern http_body NoBody; HV_EXPORT extern HttpCookie NoCookie; class HV_EXPORT HttpMessage { public: static char s_date[32]; int type; unsigned short http_major; unsigned short http_minor; http_headers headers; http_cookies cookies; http_body body; // http_cb std::function http_cb; // structured content void* content; // DATA_NO_COPY size_t content_length; http_content_type content_type; #ifndef WITHOUT_HTTP_CONTENT hv::Json json; // APPLICATION_JSON hv::MultiPart form; // MULTIPART_FORM_DATA hv::KeyValue kv; // X_WWW_FORM_URLENCODED // T=[bool, int, int64_t, float, double] template T Get(const char* key, T defvalue = 0); std::string GetString(const char* key, const std::string& = ""); bool GetBool(const char* key, bool defvalue = 0); int64_t GetInt(const char* key, int64_t defvalue = 0); double GetFloat(const char* key, double defvalue = 0); template void Set(const char* key, const T& value) { switch (ContentType()) { case APPLICATION_JSON: json[key] = value; break; case MULTIPART_FORM_DATA: form[key] = hv::FormData(value); break; case X_WWW_FORM_URLENCODED: kv[key] = hv::to_string(value); break; default: break; } } /* * @usage https://github.com/nlohmann/json * * null: Json(nullptr); * boolean: Json(true); * number: Json(123); * string: Json("hello"); * object: Json(std::map); * Json(hv::Json::object({ {"k1", "v1"}, {"k2", "v2"} })); * array: Json(std::vector); Json(hv::Json::array( {1, 2, 3} )); */ // Content-Type: application/json template int Json(const T& t) { content_type = APPLICATION_JSON; hv::Json j(t); body = j.dump(2); return 200; } const hv::Json& GetJson() { if (json.empty() && ContentType() == APPLICATION_JSON) { ParseBody(); } return json; } // Content-Type: multipart/form-data template void SetFormData(const char* name, const T& t) { form[name] = hv::FormData(t); } void SetFormFile(const char* name, const char* filepath) { form[name] = hv::FormData(NULL, filepath); } int FormFile(const char* name, const char* filepath) { content_type = MULTIPART_FORM_DATA; form[name] = hv::FormData(NULL, filepath); return 200; } const hv::MultiPart& GetForm() { if (form.empty() && ContentType() == MULTIPART_FORM_DATA) { ParseBody(); } return form; } std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string) { if (form.empty() && ContentType() == MULTIPART_FORM_DATA) { ParseBody(); } auto iter = form.find(name); return iter == form.end() ? defvalue : iter->second.content; } int SaveFormFile(const char* name, const char* path) { if (ContentType() != MULTIPART_FORM_DATA) { return HTTP_STATUS_BAD_REQUEST; } if (form.empty()) { ParseBody(); if (form.empty()) return HTTP_STATUS_BAD_REQUEST; } auto iter = form.find(name); if (iter == form.end()) { return HTTP_STATUS_BAD_REQUEST; } const auto& formdata = iter->second; if (formdata.content.empty()) { return HTTP_STATUS_BAD_REQUEST; } std::string filepath(path); if (HPath::isdir(path)) { filepath = HPath::join(filepath, formdata.filename); } HFile file; if (file.open(filepath.c_str(), "wb") != 0) { return HTTP_STATUS_INTERNAL_SERVER_ERROR; } file.write(formdata.content.data(), formdata.content.size()); return 200; } // Content-Type: application/x-www-form-urlencoded template void SetUrlEncoded(const char* key, const T& t) { kv[key] = hv::to_string(t); } const hv::KeyValue& GetUrlEncoded() { if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) { ParseBody(); } return kv; } std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string) { if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) { ParseBody(); } auto iter = kv.find(key); return iter == kv.end() ? defvalue : iter->second; } #endif HttpMessage(); virtual ~HttpMessage(); void Init(); virtual void Reset(); // structured-content -> content_type <-> headers["Content-Type"] void FillContentType(); // body.size -> content_length <-> headers["Content-Length"] void FillContentLength(); bool IsChunked(); bool IsKeepAlive(); bool IsUpgrade(); // headers void SetHeader(const char* key, const std::string& value); std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string); // cookies void AddCookie(const HttpCookie& cookie); const HttpCookie& GetCookie(const std::string& name); // body void SetBody(const std::string& body); const std::string& Body(); // headers -> string void DumpHeaders(std::string& str); // structured content -> body void DumpBody(); void DumpBody(std::string& str); // body -> structured content // @retval 0:succeed int ParseBody(); virtual std::string Dump(bool is_dump_headers, bool is_dump_body); void* Content() { if (content == NULL && body.size() != 0) { content = (void*)body.data(); content_length = body.size(); } return content; } size_t ContentLength() { if (content_length == 0) { FillContentLength(); } return content_length; } http_content_type ContentType() { if (content_type == CONTENT_TYPE_NONE) { FillContentType(); } return content_type; } void SetContentType(http_content_type type) { content_type = type; } void SetContentType(const char* type) { content_type = http_content_type_enum(type); } void SetContentTypeByFilename(const char* filepath) { const char* suffix = hv_suffixname(filepath); if (suffix) { content_type = http_content_type_enum_by_suffix(suffix); } if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) { content_type = APPLICATION_OCTET_STREAM; } } int String(const std::string& str) { content_type = TEXT_PLAIN; body = str; return 200; } int Data(void* data, int len, bool nocopy = true) { content_type = APPLICATION_OCTET_STREAM; if (nocopy) { content = data; content_length = len; } else { content_length = body.size(); body.resize(content_length + len); memcpy((void*)(body.data() + content_length), data, len); content_length += len; } return 200; } int File(const char* filepath) { HFile file; if (file.open(filepath, "rb") != 0) { return HTTP_STATUS_NOT_FOUND; } SetContentTypeByFilename(filepath); file.readall(body); return 200; } int SaveFile(const char* filepath) { HFile file; if (file.open(filepath, "wb") != 0) { return HTTP_STATUS_NOT_FOUND; } file.write(body.data(), body.size()); return 200; } }; #define DEFAULT_HTTP_USER_AGENT "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" #define DEFAULT_HTTP_TIMEOUT 60 // s #define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s #define DEFAULT_HTTP_FAIL_RETRY_COUNT 1 #define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms class HV_EXPORT HttpRequest : public HttpMessage { public: http_method method; // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] std::string url; // structured url std::string scheme; std::string host; int port; std::string path; hv::QueryParams query_params; // client_addr hv::NetAddr client_addr; // for http server save client addr of request // for HttpClient uint16_t timeout; // unit: s uint16_t connect_timeout;// unit: s uint32_t retry_count; uint32_t retry_delay; // unit: ms unsigned redirect: 1; unsigned proxy : 1; unsigned cancel : 1; HttpRequest(); void Init(); virtual void Reset(); virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false); // method void SetMethod(const char* method) { this->method = http_method_enum(method); } const char* Method() { return http_method_str(method); } // scheme bool IsHttps() { return strncmp(scheme.c_str(), "https", 5) == 0 || strncmp(url.c_str(), "https://", 8) == 0; } // url void SetUrl(const char* url) { this->url = url; } const std::string& Url() { return url; } // structed url -> url void DumpUrl(); // url -> structed url void ParseUrl(); // /path?query#fragment std::string FullPath() { return path; } // /path std::string Path(); // ?query_params template void SetParam(const char* key, const T& t) { query_params[key] = hv::to_string(t); } std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) { auto iter = query_params.find(key); return iter == query_params.end() ? defvalue : iter->second; } // Host: std::string Host() { auto iter = headers.find("Host"); return iter == headers.end() ? host : iter->second; } void FillHost(const char* host, int port = DEFAULT_HTTP_PORT); void SetHost(const char* host, int port = DEFAULT_HTTP_PORT); void SetProxy(const char* host, int port); bool IsProxy() { return proxy; } // Auth void SetAuth(const std::string& auth); void SetBasicAuth(const std::string& username, const std::string& password); void SetBearerTokenAuth(const std::string& token); void SetTimeout(int sec) { timeout = sec; } void SetConnectTimeout(int sec) { connect_timeout = sec; } void AllowRedirect(bool on = true) { redirect = on; } // NOTE: SetRetry just for AsyncHttpClient void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT, int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY) { retry_count = count; retry_delay = delay; } void Cancel() { cancel = 1; } bool IsCanceled() { return cancel == 1; } // Range: bytes=0-4095 void SetRange(long from = 0, long to = -1); bool GetRange(long& from, long& to); }; class HV_EXPORT HttpResponse : public HttpMessage { public: http_status status_code; const char* status_message() { return http_status_str(status_code); } HttpResponse(); void Init(); virtual void Reset(); virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false); // Content-Range: bytes 0-4095/10240000 void SetRange(long from, long to, long total); bool GetRange(long& from, long& to, long& total); int Redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) { status_code = status; SetHeader("Location", location); return status_code; } }; typedef std::shared_ptr HttpRequestPtr; typedef std::shared_ptr HttpResponsePtr; typedef std::function HttpResponseCallback; #endif // HV_HTTP_MESSAGE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/HttpParser.cpp000066400000000000000000000010051520575453600272200ustar00rootroot00000000000000#include "HttpParser.h" #include "Http1Parser.h" #include "Http2Parser.h" HttpParser* HttpParser::New(http_session_type type, http_version version) { HttpParser* hp = NULL; if (version == HTTP_V1) { hp = new Http1Parser(type); } else if (version == HTTP_V2) { #ifdef WITH_NGHTTP2 hp = new Http2Parser(type); #else fprintf(stderr, "Please recompile WITH_NGHTTP2!\n"); #endif } if (hp) { hp->version = version; hp->type = type; } return hp; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/HttpParser.h000066400000000000000000000033311520575453600266710ustar00rootroot00000000000000#ifndef HV_HTTP_PARSER_H_ #define HV_HTTP_PARSER_H_ #include "hexport.h" #include "HttpMessage.h" class HV_EXPORT HttpParser { public: http_version version; http_session_type type; static HttpParser* New(http_session_type type = HTTP_CLIENT, http_version version = HTTP_V1); virtual ~HttpParser() {} virtual int GetSendData(char** data, size_t* len) = 0; virtual int FeedRecvData(const char* data, size_t len) = 0; // Http1Parser: http_parser_state // Http2Parser: http2_session_state virtual int GetState() = 0; // Http1Parser: GetState() != HP_MESSAGE_COMPLETE // Http2Parser: GetState() == H2_WANT_RECV virtual bool WantRecv() = 0; // Http1Parser: GetState() == HP_MESSAGE_COMPLETE // Http2Parser: GetState() == H2_WANT_SEND virtual bool WantSend() = 0; // IsComplete: Is recved HttpRequest or HttpResponse complete? // Http1Parser: GetState() == HP_MESSAGE_COMPLETE // Http2Parser: (state == H2_RECV_HEADERS || state == H2_RECV_DATA) && stream_closed virtual bool IsComplete() = 0; virtual bool IsEof() { return false; } // client // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) virtual int SubmitRequest(HttpRequest* req) = 0; virtual int InitResponse(HttpResponse* res) = 0; // server // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} virtual int InitRequest(HttpRequest* req) = 0; virtual int SubmitResponse(HttpResponse* res) = 0; virtual int GetError() = 0; virtual const char* StrError(int error) = 0; }; typedef std::shared_ptr HttpParserPtr; #endif // HV_HTTP_PARSER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/README.md000066400000000000000000000017331520575453600257070ustar00rootroot00000000000000## 目录结构 ``` . ├── client │   ├── HttpClient.h http客户端对外头文件 │   ├── requests.h 模拟python requests api │   └── axios.h 模拟nodejs axios api ├── httpdef.h http定义 ├── http2def.h http2定义 ├── grpcdef.h grpc定义 ├── HttpParser.h http解析基类 ├── Http1Parser.h http1解析类 ├── Http2Parser.h http2解析类 ├── HttpMessage.h http请求响应类 ├── http_content.h http Content-Type ├── http_parser.h http1解析实现 ├── multipart_parser.h multipart解析 └── server ├── HttpServer.h http服务端对外头文件 ├── HttpHandler.h http处理类 ├── FileCache.h 文件缓存类 ├── http_page.h http页面构造 └── HttpService.h http业务类 (包括api service、web service、indexof service) ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/WebSocketChannel.cpp000066400000000000000000000045641520575453600303200ustar00rootroot00000000000000#include "WebSocketChannel.h" namespace hv { int WebSocketChannel::send(const char* buf, int len, enum ws_opcode opcode /* = WS_OPCODE_BINARY */, bool fin /* = true */) { int fragment = 0xFFFF; // 65535 if (len > fragment) { return send(buf, len, fragment, opcode); } std::lock_guard locker(mutex_); return sendFrame(buf, len, opcode, fin); } /* * websocket fragment * lock -> * sendFrame(p, fragment, opcode, false) -> * sendFrame(p, fragment, WS_OPCODE_CONTINUE, false) -> * ... -> * sendFrame(p, remain, WS_OPCODE_CONTINUE, true) * unlock * */ int WebSocketChannel::send(const char* buf, int len, int fragment, enum ws_opcode opcode /* = WS_OPCODE_BINARY */) { std::lock_guard locker(mutex_); if (len <= fragment) { return sendFrame(buf, len, opcode, true); } // first fragment int nsend = sendFrame(buf, fragment, opcode, false); if (nsend < 0) return nsend; const char* p = buf + fragment; int remain = len - fragment; while (remain > fragment) { nsend = sendFrame(p, fragment, WS_OPCODE_CONTINUE, false); if (nsend < 0) return nsend; p += fragment; remain -= fragment; } // last fragment nsend = sendFrame(p, remain, WS_OPCODE_CONTINUE, true); if (nsend < 0) return nsend; return len; } int WebSocketChannel::sendPing() { std::lock_guard locker(mutex_); if (type == WS_CLIENT) { return write(WS_CLIENT_PING_FRAME, WS_CLIENT_MIN_FRAME_SIZE); } return write(WS_SERVER_PING_FRAME, WS_SERVER_MIN_FRAME_SIZE); } int WebSocketChannel::sendPong() { std::lock_guard locker(mutex_); if (type == WS_CLIENT) { return write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE); } return write(WS_SERVER_PONG_FRAME, WS_SERVER_MIN_FRAME_SIZE); } int WebSocketChannel::sendFrame(const char* buf, int len, enum ws_opcode opcode /* = WS_OPCODE_BINARY */, bool fin /* = true */) { bool has_mask = false; char mask[4] = {0}; if (type == WS_CLIENT) { *(int*)mask = rand(); has_mask = true; } int frame_size = ws_calc_frame_size(len, has_mask); if (sendbuf_.len < (size_t)frame_size) { sendbuf_.resize(ceil2e(frame_size)); } ws_build_frame(sendbuf_.base, buf, len, mask, has_mask, opcode, fin); return write(sendbuf_.base, frame_size); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/WebSocketChannel.h000066400000000000000000000024201520575453600277520ustar00rootroot00000000000000#ifndef HV_WEBSOCKET_CHANNEL_H_ #define HV_WEBSOCKET_CHANNEL_H_ #include #include "Channel.h" #include "wsdef.h" #include "hmath.h" namespace hv { class HV_EXPORT WebSocketChannel : public SocketChannel { public: ws_session_type type; WebSocketChannel(hio_t* io, ws_session_type type = WS_CLIENT) : SocketChannel(io) , type(type) , opcode(WS_OPCODE_CLOSE) {} ~WebSocketChannel() {} // isConnected, send, close int send(const std::string& msg, enum ws_opcode opcode = WS_OPCODE_TEXT, bool fin = true) { return send(msg.c_str(), msg.size(), opcode, fin); } int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); // websocket fragment int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY); int sendPing(); int sendPong(); int close() { return SocketChannel::close(type == WS_SERVER); } protected: int sendFrame(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); public: enum ws_opcode opcode; private: Buffer sendbuf_; std::mutex mutex_; }; } typedef std::shared_ptr WebSocketChannelPtr; #endif // HV_WEBSOCKET_CHANNEL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/WebSocketParser.cpp000066400000000000000000000040521520575453600301740ustar00rootroot00000000000000#include "WebSocketParser.h" #include "websocket_parser.h" #include "hdef.h" #define MAX_PAYLOAD_LENGTH (1 << 24) // 16M static int on_frame_header(websocket_parser* parser) { WebSocketParser* wp = (WebSocketParser*)parser->data; int opcode = parser->flags & WS_OP_MASK; // printf("on_frame_header opcode=%d\n", opcode); if (opcode != WS_OP_CONTINUE) { wp->opcode = opcode; } int length = parser->length; int reserve_length = MIN(length + 1, MAX_PAYLOAD_LENGTH); if (reserve_length > wp->message.capacity()) { wp->message.reserve(reserve_length); } if (wp->state == WS_FRAME_BEGIN || wp->state == WS_FRAME_FIN) { wp->message.clear(); } wp->state = WS_FRAME_HEADER; return 0; } static int on_frame_body(websocket_parser* parser, const char * at, size_t length) { // printf("on_frame_body length=%d\n", (int)length); WebSocketParser* wp = (WebSocketParser*)parser->data; wp->state = WS_FRAME_BODY; if (wp->parser->flags & WS_HAS_MASK) { websocket_parser_decode((char*)at, at, length, wp->parser); } wp->message.append(at, length); return 0; } static int on_frame_end(websocket_parser* parser) { // printf("on_frame_end\n"); WebSocketParser* wp = (WebSocketParser*)parser->data; wp->state = WS_FRAME_END; if (wp->parser->flags & WS_FIN) { wp->state = WS_FRAME_FIN; if (wp->onMessage) { wp->onMessage(wp->opcode, wp->message); } } return 0; } static websocket_parser_settings cbs = { on_frame_header, on_frame_body, on_frame_end }; WebSocketParser::WebSocketParser() { parser = (websocket_parser*)malloc(sizeof(websocket_parser)); websocket_parser_init(parser); parser->data = this; state = WS_FRAME_BEGIN; opcode = WS_OP_CLOSE; } WebSocketParser::~WebSocketParser() { if (parser) { free(parser); parser = NULL; } } int WebSocketParser::FeedRecvData(const char* data, size_t len) { return websocket_parser_execute(parser, &cbs, data, len); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/WebSocketParser.h000066400000000000000000000014441520575453600276430ustar00rootroot00000000000000#ifndef HV_WEBSOCKET_PARSER_H_ #define HV_WEBSOCKET_PARSER_H_ #include "hexport.h" #include #include #include enum websocket_parser_state { WS_FRAME_BEGIN, WS_FRAME_HEADER, WS_FRAME_BODY, WS_FRAME_END, WS_FRAME_FIN, }; struct websocket_parser; class HV_EXPORT WebSocketParser { public: websocket_parser* parser; websocket_parser_state state; int opcode; std::string message; std::function onMessage; WebSocketParser(); ~WebSocketParser(); int FeedRecvData(const char* data, size_t len); }; typedef std::shared_ptr WebSocketParserPtr; #endif // HV_WEBSOCKET_PARSER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/000077500000000000000000000000001520575453600257025ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/AsyncHttpClient.cpp000066400000000000000000000163701520575453600314710ustar00rootroot00000000000000#include "AsyncHttpClient.h" namespace hv { int AsyncHttpClient::send(const HttpRequestPtr& req, HttpResponseCallback resp_cb) { hloop_t* loop = EventLoopThread::hloop(); if (loop == NULL) return -1; auto task = std::make_shared(); task->req = req; task->cb = std::move(resp_cb); task->start_time = hloop_now_hrtime(loop); if (req->retry_count > 0 && req->retry_delay > 0) { req->retry_count = MIN(req->retry_count, req->timeout * 1000 / req->retry_delay - 1); } return send(task); } // createsocket => startConnect => // onconnect => sendRequest => startRead => // onread => HttpParser => resp_cb int AsyncHttpClient::doTask(const HttpClientTaskPtr& task) { const HttpRequestPtr& req = task->req; if (req->cancel) { return -1; } // queueInLoop timeout? uint64_t now_hrtime = hloop_now_hrtime(EventLoopThread::hloop()); int elapsed_ms = (now_hrtime - task->start_time) / 1000; int timeout_ms = req->timeout * 1000; if (timeout_ms > 0 && elapsed_ms >= timeout_ms) { hlogw("%s queueInLoop timeout!", req->url.c_str()); return -10; } req->ParseUrl(); sockaddr_u peeraddr; memset(&peeraddr, 0, sizeof(peeraddr)); const char* host = req->host.c_str(); int ret = sockaddr_set_ipport(&peeraddr, host, req->port); if (ret != 0) { hloge("unknown host %s", host); return -20; } int connfd = -1; // first get from conn_pools char strAddr[SOCKADDR_STRLEN] = {0}; SOCKADDR_STR(&peeraddr, strAddr); auto iter = conn_pools.find(strAddr); if (iter != conn_pools.end()) { // hlogd("get from conn_pools"); iter->second.get(connfd); } if (connfd < 0) { // create socket connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0); if (connfd < 0) { perror("socket"); return -30; } hio_t* connio = hio_get(EventLoopThread::hloop(), connfd); assert(connio != NULL); hio_set_peeraddr(connio, &peeraddr.sa, sockaddr_len(&peeraddr)); addChannel(connio); // https if (req->IsHttps() && !req->IsProxy()) { hio_enable_ssl(connio); if (!is_ipaddr(host)) { hio_set_hostname(connio, host); } } } const SocketChannelPtr& channel = getChannel(connfd); assert(channel != NULL); HttpClientContext* ctx = channel->getContext(); ctx->task = task; channel->onconnect = [&channel]() { sendRequest(channel); }; channel->onread = [this, &channel](Buffer* buf) { HttpClientContext* ctx = channel->getContext(); if (ctx->task == NULL) return; if (ctx->task->req->cancel) { channel->close(); return; } const char* data = (const char*)buf->data(); int len = buf->size(); int nparse = ctx->parser->FeedRecvData(data, len); if (nparse != len) { ctx->errorCallback(); channel->close(); return; } if (ctx->parser->IsComplete()) { auto& req = ctx->task->req; auto& resp = ctx->resp; bool keepalive = req->IsKeepAlive() && resp->IsKeepAlive(); if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) { std::string location = resp->headers["Location"]; if (!location.empty()) { hlogi("redirect %s => %s", req->url.c_str(), location.c_str()); req->url = location; req->ParseUrl(); req->headers["Host"] = req->host; resp->Reset(); send(ctx->task); // NOTE: detatch from original channel->context ctx->cancelTask(); } } else { ctx->successCallback(); } if (keepalive) { // NOTE: add into conn_pools to reuse // hlogd("add into conn_pools"); conn_pools[channel->peeraddr()].add(channel->fd()); } else { channel->close(); } } }; channel->onclose = [this, &channel]() { HttpClientContext* ctx = channel->getContext(); // NOTE: remove from conn_pools // hlogd("remove from conn_pools"); auto iter = conn_pools.find(channel->peeraddr()); if (iter != conn_pools.end()) { iter->second.remove(channel->fd()); } const HttpClientTaskPtr& task = ctx->task; if (task) { if (ctx->parser && ctx->parser->IsEof()) { ctx->successCallback(); } else if (task->req && task->req->cancel == 0 && task->req->retry_count-- > 0) { if (task->req->retry_delay > 0) { // try again after delay setTimeout(task->req->retry_delay, [this, task](TimerID timerID){ hlogi("retry %s %s", http_method_str(task->req->method), task->req->url.c_str()); sendInLoop(task); }); } else { send(task); } } else { ctx->errorCallback(); } } removeChannel(channel); }; // timer if (timeout_ms > 0) { ctx->timerID = setTimeout(timeout_ms - elapsed_ms, [&channel](TimerID timerID){ HttpClientContext* ctx = channel->getContext(); if (ctx && ctx->task) { hlogw("%s timeout!", ctx->task->req->url.c_str()); } if (channel) { channel->close(); } }); } if (channel->isConnected()) { // sendRequest sendRequest(channel); } else { // startConnect if (req->connect_timeout > 0) { channel->setConnectTimeout(req->connect_timeout * 1000); } channel->startConnect(); } return 0; } // InitResponse => SubmitRequest => while(GetSendData) write => startRead int AsyncHttpClient::sendRequest(const SocketChannelPtr& channel) { HttpClientContext* ctx = (HttpClientContext*)channel->context(); assert(ctx != NULL && ctx->task != NULL); if (ctx->resp == NULL) { ctx->resp = std::make_shared(); } HttpRequest* req = ctx->task->req.get(); HttpResponse* resp = ctx->resp.get(); assert(req != NULL && resp != NULL); if (req->http_cb) resp->http_cb = std::move(req->http_cb); if (ctx->parser == NULL) { ctx->parser.reset(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major)); } ctx->parser->InitResponse(resp); ctx->parser->SubmitRequest(req); char* data = NULL; size_t len = 0; while (ctx->parser->GetSendData(&data, &len)) { if (req->cancel) { channel->close(); return -1; } // NOTE: ensure write buffer size is enough if (len > (1 << 22) /* 4M */) { channel->setMaxWriteBufsize(len); } channel->write(data, len); } channel->startRead(); return 0; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/AsyncHttpClient.h000066400000000000000000000071131520575453600311310ustar00rootroot00000000000000#ifndef HV_ASYNC_HTTP_CLIENT_H_ #define HV_ASYNC_HTTP_CLIENT_H_ #include #include #include "EventLoopThread.h" #include "Channel.h" #include "HttpMessage.h" #include "HttpParser.h" namespace hv { template class ConnPool { public: int size() { return conns_.size(); } bool get(Conn& conn) { if (conns_.empty()) return false; conn = conns_.front(); conns_.pop_front(); return true; } bool add(const Conn& conn) { conns_.push_back(conn); return true; } bool remove(const Conn& conn) { auto iter = conns_.begin(); while (iter != conns_.end()) { if (*iter == conn) { iter = conns_.erase(iter); return true; } else { ++iter; } } return false; } private: std::list conns_; }; struct HttpClientTask { HttpRequestPtr req; HttpResponseCallback cb; uint64_t start_time; }; typedef std::shared_ptr HttpClientTaskPtr; struct HttpClientContext { HttpClientTaskPtr task; HttpResponsePtr resp; HttpParserPtr parser; TimerID timerID; HttpClientContext() { timerID = INVALID_TIMER_ID; } ~HttpClientContext() { cancelTimer(); } void cancelTimer() { if (timerID != INVALID_TIMER_ID) { killTimer(timerID); timerID = INVALID_TIMER_ID; } } void cancelTask() { cancelTimer(); task = NULL; } void callback() { cancelTimer(); if (task && task->cb) { task->cb(resp); } // NOTE: task done task = NULL; } void successCallback() { callback(); resp = NULL; } void errorCallback() { resp = NULL; callback(); } }; class HV_EXPORT AsyncHttpClient : private EventLoopThread { public: AsyncHttpClient(EventLoopPtr loop = NULL) : EventLoopThread(loop) { if (loop == NULL) { EventLoopThread::start(true); } } ~AsyncHttpClient() { EventLoopThread::stop(true); } // thread-safe int send(const HttpRequestPtr& req, HttpResponseCallback resp_cb); int send(const HttpClientTaskPtr& task) { EventLoopThread::loop()->queueInLoop(std::bind(&AsyncHttpClient::sendInLoop, this, task)); return 0; } protected: void sendInLoop(HttpClientTaskPtr task) { int err = doTask(task); if (err != 0 && task->cb) { task->cb(NULL); } } int doTask(const HttpClientTaskPtr& task); static int sendRequest(const SocketChannelPtr& channel); // channel const SocketChannelPtr& getChannel(int fd) { return channels[fd]; // return fd < channels.capacity() ? channels[fd] : NULL; } const SocketChannelPtr& addChannel(hio_t* io) { auto channel = std::make_shared(io); channel->newContext(); int fd = channel->fd(); channels[fd] = channel; return channels[fd]; } void removeChannel(const SocketChannelPtr& channel) { channel->deleteContext(); int fd = channel->fd(); channels.erase(fd); } private: // NOTE: just one loop thread, no need mutex. // fd => SocketChannelPtr std::map channels; // peeraddr => ConnPool std::map> conn_pools; }; } #endif // HV_ASYNC_HTTP_CLIENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/HttpClient.cpp000066400000000000000000000523261520575453600304740ustar00rootroot00000000000000#include "HttpClient.h" #include #ifdef WITH_CURL #include "curl/curl.h" #endif #include "herr.h" #include "hlog.h" #include "htime.h" #include "hstring.h" #include "hsocket.h" #include "hssl.h" #include "HttpParser.h" // for async #include "AsyncHttpClient.h" using namespace hv; struct http_client_s { std::string host; int port; int https; int timeout; // s http_headers headers; // http_proxy std::string http_proxy_host; int http_proxy_port; // https_proxy std::string https_proxy_host; int https_proxy_port; // no_proxy StringList no_proxy_hosts; //private: #ifdef WITH_CURL CURL* curl; #endif // for sync int fd; unsigned int keepalive_requests; hssl_t ssl; hssl_ctx_t ssl_ctx; bool alloced_ssl_ctx; HttpParserPtr parser; // for async std::mutex mutex_; std::shared_ptr async_client_; http_client_s() { host = LOCALHOST; port = DEFAULT_HTTP_PORT; https = 0; timeout = DEFAULT_HTTP_TIMEOUT; http_proxy_port = DEFAULT_HTTP_PORT; https_proxy_port = DEFAULT_HTTP_PORT; #ifdef WITH_CURL curl = NULL; #endif fd = -1; keepalive_requests = 0; ssl = NULL; ssl_ctx = NULL; alloced_ssl_ctx = false; } ~http_client_s() { Close(); if (ssl_ctx && alloced_ssl_ctx) { hssl_ctx_free(ssl_ctx); ssl_ctx = NULL; } } void Close() { #ifdef WITH_CURL if (curl) { curl_easy_cleanup(curl); curl = NULL; } #endif if (ssl) { hssl_free(ssl); ssl = NULL; } SAFE_CLOSESOCKET(fd); } }; http_client_t* http_client_new(const char* host, int port, int https) { http_client_t* cli = new http_client_t; if (host) cli->host = host; cli->port = port; cli->https = https; cli->headers["Connection"] = "keep-alive"; return cli; } int http_client_del(http_client_t* cli) { if (cli == NULL) return 0; delete cli; return 0; } int http_client_set_timeout(http_client_t* cli, int timeout) { cli->timeout = timeout; return 0; } int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx) { cli->ssl_ctx = ssl_ctx; return 0; } int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt) { opt->endpoint = HSSL_CLIENT; hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; cli->alloced_ssl_ctx = true; return http_client_set_ssl_ctx(cli, ssl_ctx); } int http_client_clear_headers(http_client_t* cli) { cli->headers.clear(); return 0; } int http_client_set_header(http_client_t* cli, const char* key, const char* value) { cli->headers[key] = value; return 0; } int http_client_del_header(http_client_t* cli, const char* key) { auto iter = cli->headers.find(key); if (iter != cli->headers.end()) { cli->headers.erase(iter); } return 0; } const char* http_client_get_header(http_client_t* cli, const char* key) { auto iter = cli->headers.find(key); if (iter != cli->headers.end()) { return iter->second.c_str(); } return NULL; } int http_client_set_http_proxy(http_client_t* cli, const char* host, int port) { cli->http_proxy_host = host; cli->http_proxy_port = port; return 0; } int http_client_set_https_proxy(http_client_t* cli, const char* host, int port) { cli->https_proxy_host = host; cli->https_proxy_port = port; return 0; } int http_client_add_no_proxy(http_client_t* cli, const char* host) { cli->no_proxy_hosts.push_back(host); return 0; } static int http_client_make_request(http_client_t* cli, HttpRequest* req) { if (req->url.empty() || *req->url.c_str() == '/') { req->scheme = cli->https ? "https" : "http"; req->host = cli->host; req->port = cli->port; } req->ParseUrl(); bool https = req->IsHttps(); bool use_proxy = https ? (!cli->https_proxy_host.empty()) : (!cli->http_proxy_host.empty()); if (use_proxy) { if (req->host == "127.0.0.1" || req->host == "localhost") { use_proxy = false; } } if (use_proxy) { for (const auto& host : cli->no_proxy_hosts) { if (req->host == host) { use_proxy = false; break; } } } if (use_proxy) { req->SetProxy(https ? cli->https_proxy_host.c_str() : cli->http_proxy_host.c_str(), https ? cli->https_proxy_port : cli->http_proxy_port); } if (req->timeout == 0) { req->timeout = cli->timeout; } for (const auto& pair : cli->headers) { if (req->headers.find(pair.first) == req->headers.end()) { req->headers.insert(pair); } } return 0; } int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout) { cli->Close(); int blocktime = DEFAULT_CONNECT_TIMEOUT; if (timeout > 0) { blocktime = MIN(timeout*1000, blocktime); } int connfd = ConnectTimeout(host, port, blocktime); if (connfd < 0) { hloge("connect %s:%d failed!", host, port); return connfd; } tcp_nodelay(connfd, 1); if (https && cli->ssl == NULL) { // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new hssl_ctx_t ssl_ctx = NULL; if (cli->ssl_ctx) { ssl_ctx = cli->ssl_ctx; } else if (g_ssl_ctx) { ssl_ctx = g_ssl_ctx; } else { cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); cli->alloced_ssl_ctx = true; } if (ssl_ctx == NULL) { closesocket(connfd); return NABS(ERR_NEW_SSL_CTX); } cli->ssl = hssl_new(ssl_ctx, connfd); if (cli->ssl == NULL) { closesocket(connfd); return NABS(ERR_NEW_SSL); } if (!is_ipaddr(host)) { hssl_set_sni_hostname(cli->ssl, host); } so_rcvtimeo(connfd, blocktime); int ret = hssl_connect(cli->ssl); if (ret != 0) { fprintf(stderr, "* ssl handshake failed: %d\n", ret); hloge("ssl handshake failed: %d", ret); hssl_free(cli->ssl); cli->ssl = NULL; closesocket(connfd); return NABS(ret); } } cli->fd = connfd; cli->keepalive_requests = 0; return connfd; } int http_client_close(http_client_t* cli) { if (cli == NULL) return 0; cli->Close(); return 0; } int http_client_send_data(http_client_t* cli, const char* data, int size) { if (!cli || !data || size <= 0) return -1; if (cli->ssl) { return hssl_write(cli->ssl, data, size); } return send(cli->fd, data, size, 0); } int http_client_recv_data(http_client_t* cli, char* data, int size) { if (!cli || !data || size <= 0) return -1; if (cli->ssl) { return hssl_read(cli->ssl, data, size); } return recv(cli->fd, data, size, 0); } static int http_client_exec(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { // connect -> send -> recv -> http_parser int err = 0; int connfd = cli->fd; bool https = req->IsHttps() && !req->IsProxy(); bool keepalive = true; time_t connect_timeout = MIN(req->connect_timeout, req->timeout); time_t timeout_ms = req->timeout * 1000; time_t start_time = gettick_ms(); time_t cur_time = start_time, left_time = INFINITE; #define CHECK_TIMEOUT \ do { \ if (timeout_ms > 0) { \ cur_time = gettick_ms(); \ if (cur_time - start_time >= timeout_ms) { \ goto timeout; \ } \ left_time = timeout_ms - (cur_time - start_time); \ } \ } while(0); uint32_t retry_count = req->retry_count; if (cli->keepalive_requests > 0 && retry_count == 0) { // maybe keep-alive timeout, retry at least once retry_count = 1; } if (cli->parser == NULL) { cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major)); if (cli->parser == NULL) { hloge("New HttpParser failed!"); return ERR_NULL_POINTER; } } if (connfd <= 0 || cli->host != req->host || cli->port != req->port) { cli->host = req->host; cli->port = req->port; connect: connfd = http_client_connect(cli, req->host.c_str(), req->port, https, connect_timeout); if (connfd < 0) { return connfd; } } cli->parser->SubmitRequest(req); char recvbuf[1024] = {0}; int total_nsend, nsend, nrecv; total_nsend = nsend = nrecv = 0; send: char* data = NULL; size_t len = 0; while (cli->parser->GetSendData(&data, &len)) { total_nsend = 0; while (total_nsend < len) { CHECK_TIMEOUT if (left_time != INFINITE) { so_sndtimeo(cli->fd, left_time); } if (req->cancel) goto disconnect; nsend = http_client_send_data(cli, data + total_nsend, len - total_nsend); if (req->cancel) goto disconnect; if (nsend <= 0) { CHECK_TIMEOUT err = socket_errno(); if (err == EINTR) continue; if (retry_count-- > 0 && left_time > req->retry_delay + connect_timeout * 1000) { err = 0; if (req->retry_delay > 0) hv_msleep(req->retry_delay); goto connect; } goto disconnect; } total_nsend += nsend; } } if (resp == NULL) return 0; cli->parser->InitResponse(resp); recv: do { CHECK_TIMEOUT if (left_time != INFINITE) { so_rcvtimeo(cli->fd, left_time); } if (req->cancel) goto disconnect; nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf)); if (req->cancel) goto disconnect; if (nrecv <= 0) { CHECK_TIMEOUT err = socket_errno(); if (err == EINTR) continue; if (cli->parser->IsEof()) { err = 0; goto disconnect; } if (retry_count-- > 0 && left_time > req->retry_delay + connect_timeout * 1000) { err = 0; if (req->retry_delay > 0) hv_msleep(req->retry_delay); goto connect; } goto disconnect; } int nparse = cli->parser->FeedRecvData(recvbuf, nrecv); if (nparse != nrecv) { return ERR_PARSE; } } while(!cli->parser->IsComplete()); keepalive = req->IsKeepAlive() && resp->IsKeepAlive(); if (keepalive) { ++cli->keepalive_requests; } else { cli->Close(); } return 0; timeout: err = ERR_TASK_TIMEOUT; disconnect: cli->Close(); return err; } int http_client_send_header(http_client_t* cli, HttpRequest* req) { if (!cli || !req) return ERR_NULL_POINTER; http_client_make_request(cli, req); return http_client_exec(cli, req, NULL); } int http_client_recv_response(http_client_t* cli, HttpResponse* resp) { if (!cli || !resp) return ERR_NULL_POINTER; if (!cli->parser) { hloge("Call http_client_send_header first!"); return ERR_NULL_POINTER; } char recvbuf[1024] = {0}; cli->parser->InitResponse(resp); do { int nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf)); if (nrecv <= 0) { int err = socket_errno(); if (err == EINTR) continue; cli->Close(); return err; } int nparse = cli->parser->FeedRecvData(recvbuf, nrecv); if (nparse != nrecv) { return ERR_PARSE; } } while(!cli->parser->IsComplete()); return 0; } #ifdef WITH_CURL static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) { if (buf == NULL || userdata == NULL) return 0; size_t len = size * cnt; std::string str(buf, len); HttpResponse* resp = (HttpResponse*)userdata; std::string::size_type pos = str.find_first_of(':'); if (pos == std::string::npos) { if (strncmp(buf, "HTTP/", 5) == 0) { // status line //hlogd("%s", buf); int http_major = 1, http_minor = 1, status_code = 200; if (buf[5] == '1') { // HTTP/1.1 200 OK\r\n sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code); } else if (buf[5] == '2') { // HTTP/2 200\r\n sscanf(buf, "HTTP/%d %d", &http_major, &status_code); http_minor = 0; } resp->http_major = http_major; resp->http_minor = http_minor; resp->status_code = (http_status)status_code; if (resp->http_cb) { resp->http_cb(resp, HP_MESSAGE_BEGIN, NULL, 0); } } } else { // headers std::string key = trim(str.substr(0, pos)); std::string value = trim(str.substr(pos+1)); resp->headers[key] = value; } return len; } static size_t s_body_cb(char* buf, size_t size, size_t cnt, void *userdata) { if (buf == NULL || userdata == NULL) return 0; size_t len = size * cnt; HttpMessage* resp = (HttpMessage*)userdata; if (resp->http_cb) { if (resp->content == NULL && resp->content_length == 0) { resp->content = buf; resp->content_length = len; resp->http_cb(resp, HP_HEADERS_COMPLETE, NULL, 0); } resp->http_cb(resp, HP_BODY, buf, len); } else { resp->body.append(buf, len); } return len; } static int http_client_exec_curl(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { if (cli->curl == NULL) { cli->curl = curl_easy_init(); } CURL* curl = cli->curl; // proxy if (req->IsProxy()) { curl_easy_setopt(curl, CURLOPT_PROXY, req->host.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYPORT, req->port); } // SSL if (req->IsHttps()) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); } // http2 if (req->http_major == 2) { #if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0 curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0); #else // No Connection: Upgrade curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE); #endif } // TCP_NODELAY curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); // method curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method)); // url req->DumpUrl(); curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str()); //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor); // headers req->FillContentType(); struct curl_slist *headers = NULL; for (auto& pair : req->headers) { std::string header = pair.first; header += ": "; header += pair.second; headers = curl_slist_append(headers, header.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // body //struct curl_httppost* httppost = NULL; //struct curl_httppost* lastpost = NULL; if (req->body.size() == 0) { req->DumpBody(); /* if (req->body.size() == 0 && req->content_type == MULTIPART_FORM_DATA) { for (auto& pair : req->mp) { if (pair.second.filename.size() != 0) { curl_formadd(&httppost, &lastpost, CURLFORM_COPYNAME, pair.first.c_str(), CURLFORM_FILE, pair.second.filename.c_str(), CURLFORM_END); } else if (pair.second.content.size() != 0) { curl_formadd(&httppost, &lastpost, CURLFORM_COPYNAME, pair.first.c_str(), CURLFORM_COPYCONTENTS, pair.second.content.c_str(), CURLFORM_END); } } if (httppost) { curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost); } } */ } if (req->body.size() != 0) { curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size()); } if (req->connect_timeout > 0) { curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, req->connect_timeout); } if (req->timeout > 0) { curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout); } curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb); curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp); int ret = curl_easy_perform(curl); /* if (ret != 0) { hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret)); } if (resp->body.length() != 0) { hlogd("[Response]\n%s", resp->body.c_str()); } double total_time, name_time, conn_time, pre_time; curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time); curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time); curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time); curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time); hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time); */ if (headers) { curl_slist_free_all(headers); } /* if (httppost) { curl_formfree(httppost); } */ if (resp->http_cb) { resp->http_cb(resp, HP_MESSAGE_COMPLETE, NULL, 0); } return ret; } const char* http_client_strerror(int errcode) { return curl_easy_strerror((CURLcode)errcode); } #else const char* http_client_strerror(int errcode) { return socket_strerror(errcode); } #endif static int http_client_redirect(HttpRequest* req, HttpResponse* resp) { std::string location = resp->headers["Location"]; if (!location.empty()) { hlogi("redirect %s => %s", req->url.c_str(), location.c_str()); req->url = location; req->ParseUrl(); req->headers["Host"] = req->host; resp->Reset(); return http_client_send(req, resp); } return 0; } int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { if (!cli || !req || !resp) return ERR_NULL_POINTER; http_client_make_request(cli, req); if (req->http_cb) resp->http_cb = std::move(req->http_cb); #if WITH_CURL int ret = http_client_exec_curl(cli, req, resp); #else int ret = http_client_exec(cli, req, resp); #endif if (ret != 0) return ret; // redirect if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) { return http_client_redirect(req, resp); } return 0; } int http_client_send(HttpRequest* req, HttpResponse* resp) { if (!req || !resp) return ERR_NULL_POINTER; http_client_t cli; return http_client_send(&cli, req, resp); } // below for async static int http_client_exec_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) { if (cli->async_client_ == NULL) { cli->mutex_.lock(); if (cli->async_client_ == NULL) { cli->async_client_ = std::make_shared(); } cli->mutex_.unlock(); } return cli->async_client_->send(req, std::move(resp_cb)); } int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) { if (!cli || !req) return ERR_NULL_POINTER; http_client_make_request(cli, req.get()); return http_client_exec_async(cli, req, std::move(resp_cb)); } static http_client_t* s_async_http_client = NULL; static void hv_destroy_default_async_http_client() { hlogi("destory default http async client"); if (s_async_http_client) { http_client_del(s_async_http_client); s_async_http_client = NULL; } } static http_client_t* hv_default_async_http_client() { static std::mutex s_mutex; if (s_async_http_client == NULL) { s_mutex.lock(); if (s_async_http_client == NULL) { hlogi("create default http async client"); s_async_http_client = http_client_new(); // NOTE: I have No better idea atexit(hv_destroy_default_async_http_client); } s_mutex.unlock(); } return s_async_http_client; } int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) { if (req == NULL) return ERR_NULL_POINTER; if (req->timeout == 0) { req->timeout = DEFAULT_HTTP_TIMEOUT; } return http_client_exec_async(hv_default_async_http_client(), req, std::move(resp_cb)); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/HttpClient.h000066400000000000000000000126311520575453600301340ustar00rootroot00000000000000#ifndef HV_HTTP_CLIENT_H_ #define HV_HTTP_CLIENT_H_ #include "hexport.h" #include "hssl.h" #include "HttpMessage.h" /* #include #include "HttpClient.h" int main(int argc, char* argv[]) { HttpRequest req; req.method = HTTP_GET; req.url = "http://www.example.com"; HttpResponse res; int ret = http_client_send(&req, &res); printf("%s\n", req.Dump(true,true).c_str()); if (ret != 0) { printf("* Failed:%s:%d\n", http_client_strerror(ret), ret); } else { printf("%s\n", res.Dump(true,true).c_str()); } return ret; } */ typedef struct http_client_s http_client_t; HV_EXPORT http_client_t* http_client_new(const char* host = NULL, int port = DEFAULT_HTTP_PORT, int https = 0); HV_EXPORT int http_client_del(http_client_t* cli); HV_EXPORT const char* http_client_strerror(int errcode); // timeout: s HV_EXPORT int http_client_set_timeout(http_client_t* cli, int timeout); // SSL/TLS HV_EXPORT int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx); // hssl_ctx_new(opt) -> http_client_set_ssl_ctx HV_EXPORT int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt); // common headers HV_EXPORT int http_client_clear_headers(http_client_t* cli); HV_EXPORT int http_client_set_header(http_client_t* cli, const char* key, const char* value); HV_EXPORT int http_client_del_header(http_client_t* cli, const char* key); HV_EXPORT const char* http_client_get_header(http_client_t* cli, const char* key); // http_proxy HV_EXPORT int http_client_set_http_proxy(http_client_t* cli, const char* host, int port); // https_proxy HV_EXPORT int http_client_set_https_proxy(http_client_t* cli, const char* host, int port); // no_proxy HV_EXPORT int http_client_add_no_proxy(http_client_t* cli, const char* host); // sync HV_EXPORT int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp); // async // Intern will start an EventLoopThread when http_client_send_async first called, // http_client_del will destroy the thread. HV_EXPORT int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); // top-level api // http_client_new -> http_client_send -> http_client_del HV_EXPORT int http_client_send(HttpRequest* req, HttpResponse* resp); // http_client_send_async(&default_async_client, ...) HV_EXPORT int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); // low-level api // @retval >=0 connfd, <0 error HV_EXPORT int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout); HV_EXPORT int http_client_send_header(http_client_t* cli, HttpRequest* req); HV_EXPORT int http_client_send_data(http_client_t* cli, const char* data, int size); HV_EXPORT int http_client_recv_data(http_client_t* cli, char* data, int size); HV_EXPORT int http_client_recv_response(http_client_t* cli, HttpResponse* resp); HV_EXPORT int http_client_close(http_client_t* cli); namespace hv { class HttpClient { public: HttpClient(const char* host = NULL, int port = DEFAULT_HTTP_PORT, int https = 0) { _client = http_client_new(host, port, https); } ~HttpClient() { if (_client) { http_client_del(_client); _client = NULL; } } // timeout: s int setTimeout(int timeout) { return http_client_set_timeout(_client, timeout); } // SSL/TLS int setSslCtx(hssl_ctx_t ssl_ctx) { return http_client_set_ssl_ctx(_client, ssl_ctx); } int newSslCtx(hssl_ctx_opt_t* opt) { return http_client_new_ssl_ctx(_client, opt); } // headers int clearHeaders() { return http_client_clear_headers(_client); } int setHeader(const char* key, const char* value) { return http_client_set_header(_client, key, value); } int delHeader(const char* key) { return http_client_del_header(_client, key); } const char* getHeader(const char* key) { return http_client_get_header(_client, key); } // http_proxy int setHttpProxy(const char* host, int port) { return http_client_set_http_proxy(_client, host, port); } // https_proxy int setHttpsProxy(const char* host, int port) { return http_client_set_https_proxy(_client, host, port); } // no_proxy int addNoProxy(const char* host) { return http_client_add_no_proxy(_client, host); } // sync int send(HttpRequest* req, HttpResponse* resp) { return http_client_send(_client, req, resp); } // async int sendAsync(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL) { return http_client_send_async(_client, req, std::move(resp_cb)); } // low-level api int connect(const char* host, int port = DEFAULT_HTTP_PORT, int https = 0, int timeout = DEFAULT_HTTP_CONNECT_TIMEOUT) { return http_client_connect(_client, host, port, https, timeout); } int sendHeader(HttpRequest* req) { return http_client_send_header(_client, req); } int sendData(const char* data, int size) { return http_client_send_data(_client, data, size); } int recvData(char* data, int size) { return http_client_recv_data(_client, data, size); } int recvResponse(HttpResponse* resp) { return http_client_recv_response(_client, resp); } int close() { return http_client_close(_client); } private: http_client_t* _client; }; } #endif // HV_HTTP_CLIENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/WebSocketClient.cpp000066400000000000000000000171421520575453600314400ustar00rootroot00000000000000#include "WebSocketClient.h" #include "base64.h" #include "hlog.h" #define DEFAULT_WS_PING_INTERVAL 3000 // ms namespace hv { WebSocketClient::WebSocketClient(EventLoopPtr loop) : TcpClientTmpl(loop) { state = WS_CLOSED; ping_interval = DEFAULT_WS_PING_INTERVAL; ping_cnt = 0; } WebSocketClient::~WebSocketClient() { stop(); } /* * ParseUrl => createsocket => start => * TCP::onConnection => websocket_handshake => WS::onopen => * TCP::onMessage => WebSocketParser => WS::onmessage => * TCP::onConnection => WS::onclose */ int WebSocketClient::open(const char* _url, const http_headers& headers) { close(); // ParseUrl if (_url) { if (strncmp(_url, "ws", 2) != 0) { url = "ws://"; url += _url; } else { url = _url; } } hlogi("%s", url.c_str()); if (!http_req_) { http_req_ = std::make_shared(); } // ws => http http_req_->url = "http" + url.substr(2, -1); http_req_->ParseUrl(); int connfd = createsocket(http_req_->port, http_req_->host.c_str()); if (connfd < 0) { hloge("createsocket %s:%d return %d!", http_req_->host.c_str(), http_req_->port, connfd); return connfd; } // wss bool wss = strncmp(url.c_str(), "wss", 3) == 0; if (wss) { withTLS(); } for (auto& header : headers) { http_req_->headers[header.first] = header.second; } onConnection = [this](const WebSocketChannelPtr& channel) { if (channel->isConnected()) { state = CONNECTED; // websocket_handshake http_req_->headers["Connection"] = "Upgrade"; http_req_->headers["Upgrade"] = "websocket"; if (http_req_->GetHeader(SEC_WEBSOCKET_KEY).empty()) { // generate SEC_WEBSOCKET_KEY unsigned char rand_key[16] = {0}; int *p = (int*)rand_key; for (int i = 0; i < 4; ++i, ++p) { *p = rand(); } char ws_key[32] = {0}; hv_base64_encode(rand_key, 16, ws_key); http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key; } if (http_req_->GetHeader(SEC_WEBSOCKET_VERSION).empty()) { http_req_->headers[SEC_WEBSOCKET_VERSION] = "13"; } std::string http_msg = http_req_->Dump(true, true); // printf("%s", http_msg.c_str()); // NOTE: not use WebSocketChannel::send channel->write(http_msg); state = WS_UPGRADING; // prepare HttpParser http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1)); http_resp_ = std::make_shared(); http_parser_->InitResponse(http_resp_.get()); } else { state = WS_CLOSED; if (onclose) onclose(); } }; onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) { const char* data = (const char*)buf->data(); size_t size = buf->size(); if (state == WS_UPGRADING) { int nparse = http_parser_->FeedRecvData(data, size); if (nparse != size && http_parser_->GetError()) { hloge("http parse error!"); channel->close(); return; } data += nparse; size -= nparse; if (http_parser_->IsComplete()) { if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) { // printf("websocket response:\n%s\n", http_resp_->Dump(true, true).c_str()); if (http_req_->redirect && HTTP_STATUS_IS_REDIRECT(http_resp_->status_code)) { std::string location = http_resp_->headers["Location"]; if (!location.empty()) { hlogi("redirect %s => %s", http_req_->url.c_str(), location.c_str()); std::string ws_url = location; if (hv::startswith(location, "http")) { ws_url = hv::replace(location, "http", "ws"); } // NOTE: not triggle onclose when redirecting. channel->onclose = NULL; open(ws_url.c_str()); return; } } hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code); channel->close(); return; } std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY); char ws_accept[32] = {0}; ws_encode_key(ws_key.c_str(), ws_accept); std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT); if (strcmp(ws_accept, ws_accept2.c_str()) != 0) { hloge("Sec-WebSocket-Accept not match!"); channel->close(); return; } ws_parser_ = std::make_shared(); // websocket_onmessage ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) { channel->opcode = (enum ws_opcode)opcode; switch (opcode) { case WS_OPCODE_CLOSE: channel->send(msg, WS_OPCODE_CLOSE); channel->close(); break; case WS_OPCODE_PING: { // printf("recv ping\n"); // printf("send pong\n"); channel->send(msg, WS_OPCODE_PONG); break; } case WS_OPCODE_PONG: // printf("recv pong\n"); ping_cnt = 0; break; case WS_OPCODE_TEXT: case WS_OPCODE_BINARY: if (onmessage) onmessage(msg); break; default: break; } }; state = WS_OPENED; // ping if (ping_interval > 0) { ping_cnt = 0; channel->setHeartbeat(ping_interval, [this](){ auto& channel = this->channel; if (channel == NULL) return; if (ping_cnt++ == 3) { hloge("websocket no pong!"); channel->close(); return; } // printf("send ping\n"); channel->sendPing(); }); } if (onopen) onopen(); } } if (state == WS_OPENED && size != 0) { int nparse = ws_parser_->FeedRecvData(data, size); if (nparse != size) { hloge("websocket parse error!"); channel->close(); return; } } }; state = CONNECTING; start(); return 0; } int WebSocketClient::close() { closesocket(); state = WS_CLOSED; return 0; } int WebSocketClient::send(const std::string& msg) { return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT); } int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) { if (channel == NULL) return -1; return channel->send(buf, len, opcode); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/WebSocketClient.h000066400000000000000000000033321520575453600311010ustar00rootroot00000000000000#ifndef HV_WEBSOCKET_CLIENT_H_ #define HV_WEBSOCKET_CLIENT_H_ /* * @demo examples/websocket_client_test.cpp */ #include "hexport.h" #include "TcpClient.h" #include "WebSocketChannel.h" #include "HttpParser.h" #include "WebSocketParser.h" namespace hv { class HV_EXPORT WebSocketClient : public TcpClientTmpl { public: std::string url; std::function onopen; std::function onclose; std::function onmessage; // PATCH: onmessage not given opcode enum ws_opcode opcode() { return channel ? channel->opcode : WS_OPCODE_CLOSE; } WebSocketClient(EventLoopPtr loop = NULL); virtual ~WebSocketClient(); // url = ws://ip:port/path // url = wss://ip:port/path int open(const char* url, const http_headers& headers = DefaultHeaders); int close(); int send(const std::string& msg); int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY); // setConnectTimeout / setPingInterval / setReconnect void setPingInterval(int ms) { ping_interval = ms; } // NOTE: call before open void setHttpRequest(const HttpRequestPtr& req) { http_req_ = req; } // NOTE: call when onopen const HttpResponsePtr& getHttpResponse() { return http_resp_; } private: enum State { CONNECTING, CONNECTED, WS_UPGRADING, WS_OPENED, WS_CLOSED, } state; HttpParserPtr http_parser_; HttpRequestPtr http_req_; HttpResponsePtr http_resp_; WebSocketParserPtr ws_parser_; // ping/pong int ping_interval; int ping_cnt; }; } #endif // HV_WEBSOCKET_CLIENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/axios.h000066400000000000000000000113211520575453600271740ustar00rootroot00000000000000#ifndef HV_AXIOS_H_ #define HV_AXIOS_H_ #include "json.hpp" #include "requests.h" /* * Inspired by js axios * * @code #include "axios.h" int main() { const char* strReq = R"( { "method": "POST", "url": "http://127.0.0.1:8080/echo", "timeout": 10, "params": { "page_no": "1", "page_size": "10" }, "headers": { "Content-Type": "application/json" }, "body": { "app_id": "123456", "app_secret": "abcdefg" } } )"; // sync auto resp = axios::axios(strReq); if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } // async int finished = 0; axios::axios(strReq, [&finished](const HttpResponsePtr& resp) { if (resp == NULL) { printf("request failed!\n"); } else { printf("%s\n", resp->body.c_str()); } finished = 1; }); // wait async finished while (!finished) hv_sleep(1); return 0; } **/ using nlohmann::json; using requests::Request; using requests::Response; using requests::ResponseCallback; namespace axios { HV_INLINE Request newRequestFromJson(const json& jreq) { auto req = std::make_shared(); // url if (jreq.contains("url")) { req->url = jreq["url"]; } // params if (jreq.contains("params")) { req->query_params = jreq["params"].get(); } // headers if (jreq.contains("headers")) { req->headers = jreq["headers"].get(); } // body/data const char* body_field = nullptr; if (jreq.contains("body")) { body_field = "body"; } else if (jreq.contains("data")) { body_field = "data"; } if (body_field) { const json& jbody = jreq[body_field]; if (jbody.is_object() || jbody.is_array()) { req->json = jbody; } else if (jbody.is_string()) { req->body = jbody; } } // method if (jreq.contains("method")) { std::string method = jreq["method"]; req->method = http_method_enum(method.c_str()); } else if (body_field) { req->method = HTTP_POST; } else { req->method = HTTP_GET; } // timeout if (jreq.contains("timeout")) { req->timeout = jreq["timeout"]; } return req; } HV_INLINE Request newRequestFromJsonString(const char* req_str) { return newRequestFromJson(json::parse(req_str)); } // sync HV_INLINE Response axios(const json& jreq, http_method method = HTTP_GET, const char* url = nullptr) { auto req = newRequestFromJson(jreq); if (method != HTTP_GET) { req->method = method; } if (url) { req->url = url; } return req ? requests::request(req) : nullptr; } HV_INLINE Response axios(const char* req_str, http_method method = HTTP_GET, const char* url = nullptr) { return req_str ? axios(json::parse(req_str), method, url) : requests::request(method, url); } HV_INLINE Response head(const char* url, const json& jreq) { return axios(jreq, HTTP_HEAD, url); } HV_INLINE Response head(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_HEAD, url); } HV_INLINE Response get(const char* url, const json& jreq) { return axios(jreq, HTTP_GET, url); } HV_INLINE Response get(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_GET, url); } HV_INLINE Response post(const char* url, const json& jreq) { return axios(jreq, HTTP_POST, url); } HV_INLINE Response post(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_POST, url); } HV_INLINE Response put(const char* url, const json& jreq) { return axios(jreq, HTTP_PUT, url); } HV_INLINE Response put(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_PUT, url); } HV_INLINE Response patch(const char* url, const json& jreq) { return axios(jreq, HTTP_PATCH, url); } HV_INLINE Response patch(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_PATCH, url); } HV_INLINE Response Delete(const char* url, const json& jreq) { return axios(jreq, HTTP_DELETE, url); } HV_INLINE Response Delete(const char* url, const char* req_str = nullptr) { return axios(req_str, HTTP_DELETE, url); } // async HV_INLINE int axios(const json& jreq, ResponseCallback resp_cb) { auto req = newRequestFromJson(jreq); return req ? requests::async(req, std::move(resp_cb)) : -1; } HV_INLINE int axios(const char* req_str, ResponseCallback resp_cb) { return axios(json::parse(req_str), std::move(resp_cb)); } } #endif // HV_AXIOS_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/client/requests.h000066400000000000000000000161521520575453600277330ustar00rootroot00000000000000#ifndef HV_REQUESTS_H_ #define HV_REQUESTS_H_ /* * Inspired by python requests * * @code #include "requests.h" int main() { auto resp = requests::get("http://127.0.0.1:8080/ping"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } resp = requests::post("http://127.0.0.1:8080/echo", "hello,world!"); if (resp == NULL) { printf("request failed!\n"); } else { printf("%d %s\r\n", resp->status_code, resp->status_message()); printf("%s\n", resp->body.c_str()); } return 0; } **/ #include #include "HttpClient.h" namespace requests { typedef HttpRequestPtr Request; typedef HttpResponsePtr Response; typedef HttpResponseCallback ResponseCallback; HV_INLINE Response request(Request req) { auto resp = std::make_shared(); int ret = http_client_send(req.get(), resp.get()); return ret ? NULL : resp; } HV_INLINE Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { auto req = std::make_shared(); req->method = method; req->url = url; if (&body != &NoBody) { req->body = body; } if (&headers != &DefaultHeaders) { req->headers = headers; } return request(req); } HV_INLINE Response head(const char* url, const http_headers& headers = DefaultHeaders) { return request(HTTP_HEAD, url, NoBody, headers); } HV_INLINE Response get(const char* url, const http_headers& headers = DefaultHeaders) { return request(HTTP_GET, url, NoBody, headers); } HV_INLINE Response post(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { return request(HTTP_POST, url, body, headers); } HV_INLINE Response put(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { return request(HTTP_PUT, url, body, headers); } HV_INLINE Response patch(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { return request(HTTP_PATCH, url, body, headers); } // delete is c++ keyword, we have to replace delete with Delete. HV_INLINE Response Delete(const char* url, const http_headers& headers = DefaultHeaders) { return request(HTTP_DELETE, url, NoBody, headers); } HV_INLINE int async(Request req, ResponseCallback resp_cb) { return http_client_send_async(req, std::move(resp_cb)); } // Sample codes for uploading and downloading files HV_INLINE Response uploadFile(const char* url, const char* filepath, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { auto req = std::make_shared(); req->method = method; req->url = url; req->timeout = 600; // 10min if (req->File(filepath) != 200) return NULL; if (&headers != &DefaultHeaders) { req->headers = headers; } return request(req); } #ifndef WITHOUT_HTTP_CONTENT HV_INLINE Response uploadFormFile(const char* url, const char* name, const char* filepath, std::map& params = hv::empty_map, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { auto req = std::make_shared(); req->method = method; req->url = url; req->timeout = 600; // 10min req->content_type = MULTIPART_FORM_DATA; req->SetFormFile(name, filepath); for (auto& param : params) { req->SetFormData(param.first.c_str(), param.second); } if (&headers != &DefaultHeaders) { req->headers = headers; } return request(req); } #endif typedef std::function upload_progress_cb; HV_INLINE Response uploadLargeFile(const char* url, const char* filepath, upload_progress_cb progress_cb = NULL, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { // open file HFile file; int ret = file.open(filepath, "rb"); if (ret != 0) { return NULL; } hv::HttpClient cli; auto req = std::make_shared(); req->method = method; req->url = url; req->timeout = 3600; // 1h if (&headers != &DefaultHeaders) { req->headers = headers; } // connect req->ParseUrl(); int connfd = cli.connect(req->host.c_str(), req->port, req->IsHttps(), req->connect_timeout); if (connfd < 0) { return NULL; } // send header size_t total_bytes = file.size(filepath); req->SetHeader("Content-Length", hv::to_string(total_bytes)); ret = cli.sendHeader(req.get()); if (ret != 0) { return NULL; } // send file size_t sended_bytes = 0; char filebuf[40960]; // 40K int filebuflen = sizeof(filebuf); int nread = 0, nsend = 0; while (sended_bytes < total_bytes) { nread = file.read(filebuf, filebuflen); if (nread <= 0) { return NULL; } nsend = cli.sendData(filebuf, nread); if (nsend != nread) { return NULL; } sended_bytes += nsend; if (progress_cb) { progress_cb(sended_bytes, total_bytes); } } // recv response auto resp = std::make_shared(); ret = cli.recvResponse(resp.get()); if (ret != 0) { return NULL; } return resp; } // see examples/wget.cpp typedef std::function download_progress_cb; HV_INLINE size_t downloadFile(const char* url, const char* filepath, download_progress_cb progress_cb = NULL) { // open file std::string filepath_download(filepath); filepath_download += ".download"; HFile file; int ret = file.open(filepath_download.c_str(), "wb"); if (ret != 0) { return 0; } // download auto req = std::make_shared(); req->method = HTTP_GET; req->url = url; req->timeout = 3600; // 1h size_t content_length = 0; size_t received_bytes = 0; req->http_cb = [&file, &content_length, &received_bytes, &progress_cb] (HttpMessage* resp, http_parser_state state, const char* data, size_t size) { if (!resp->headers["Location"].empty()) return; if (state == HP_HEADERS_COMPLETE) { content_length = hv::from_string(resp->GetHeader("Content-Length")); } else if (state == HP_BODY) { if (data && size) { // write file file.write(data, size); received_bytes += size; if (progress_cb) { progress_cb(received_bytes, content_length); } } } }; auto resp = request(req); file.close(); if (resp == NULL || resp->status_code != 200) { return 0; } // check filesize if (content_length != 0 && hv_filesize(filepath_download.c_str()) != content_length) { remove(filepath_download.c_str()); return 0; } rename(filepath_download.c_str(), filepath); return hv_filesize(filepath); } } #endif // HV_REQUESTS_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/grpcdef.h000066400000000000000000000045551520575453600262200ustar00rootroot00000000000000#ifndef HV_GRPC_DEF_H_ #define HV_GRPC_DEF_H_ #ifdef __cplusplus extern "C" { #endif // Length-Prefixed-Message // flags:1byte + length:4bytes = 5bytes #define GRPC_MESSAGE_HDLEN 5 typedef struct { unsigned char flags; unsigned int length; } grpc_message_hd; typedef struct { unsigned char flags; unsigned int length; unsigned char* message; } grpc_message; static inline void grpc_message_hd_pack(const grpc_message_hd* hd, unsigned char* buf) { unsigned char* p = buf; // flags *p++ = hd->flags; // hton length unsigned int length = hd->length; *p++ = (length >> 24) & 0xFF; *p++ = (length >> 16) & 0xFF; *p++ = (length >> 8) & 0xFF; *p++ = length & 0xFF; } static inline void grpc_message_hd_unpack(grpc_message_hd* hd, const unsigned char* buf) { const unsigned char* p = buf; // flags hd->flags = *p++; // ntoh length hd->length = ((unsigned int)*p++) << 24; hd->length |= ((unsigned int)*p++) << 16; hd->length |= ((unsigned int)*p++) << 8; hd->length |= *p++; } // protobuf // tag = field_num << 3 | wire_type // varint(tag) [+ varint(length_delimited)] + value; typedef enum { WIRE_TYPE_VARINT = 0, WIRE_TYPE_FIXED64 = 1, WIRE_TYPE_LENGTH_DELIMITED = 2, WIRE_TYPE_START_GROUP = 3, WIRE_TYPE_END_GROUP = 4, WIRE_TYPE_FIXED32 = 5, } wire_type; typedef enum { FIELD_TYPE_DOUBLE = 1, FIELD_TYPE_FLOAT = 2, FIELD_TYPE_INT64 = 3, FIELD_TYPE_UINT64 = 4, FIELD_TYPE_INT32 = 5, FIELD_TYPE_FIXED64 = 6, FIELD_TYPE_FIXED32 = 7, FIELD_TYPE_BOOL = 8, FIELD_TYPE_STRING = 9, FIELD_TYPE_GROUP = 10, FIELD_TYPE_MESSAGE = 11, FIELD_TYPE_BYTES = 12, FIELD_TYPE_UINT32 = 13, FIELD_TYPE_ENUM = 14, FIELD_TYPE_SFIXED32 = 15, FIELD_TYPE_SFIXED64 = 16, FIELD_TYPE_SINT32 = 17, FIELD_TYPE_SINT64 = 18, MAX_FIELD_TYPE = 18, } field_type; #define PROTOBUF_MAKE_TAG(field_number, wire_type) ((field_number) << 3 | (wire_type)) #define PROTOBUF_FILED_NUMBER(tag) ((tag) >> 3) #define PROTOBUF_WIRE_TYPE(tag) ((tag) & 0x07) #ifdef __cplusplus } #endif #endif // HV_GRPC_DEF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/http2def.h000066400000000000000000000042331520575453600263170ustar00rootroot00000000000000#ifndef HV_HTTP2_DEF_H_ #define HV_HTTP2_DEF_H_ #ifdef __cplusplus extern "C" { #endif #define HTTP2_MAGIC "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" #define HTTP2_MAGIC_LEN 24 // length:3bytes + type:1byte + flags:1byte + stream_id:4bytes = 9bytes #define HTTP2_FRAME_HDLEN 9 #define HTTP2_UPGRADE_RESPONSE \ "HTTP/1.1 101 Switching Protocols\r\n"\ "Connection: Upgrade\r\n"\ "Upgrade: h2c\r\n\r\n" typedef enum { HTTP2_DATA = 0, HTTP2_HEADERS = 0x01, HTTP2_PRIORITY = 0x02, HTTP2_RST_STREAM = 0x03, HTTP2_SETTINGS = 0x04, HTTP2_PUSH_PROMISE = 0x05, HTTP2_PING = 0x06, HTTP2_GOAWAY = 0x07, HTTP2_WINDOW_UPDATE = 0x08, HTTP2_CONTINUATION = 0x09, HTTP2_ALTSVC = 0x0a, HTTP2_ORIGIN = 0x0c } http2_frame_type; typedef enum { HTTP2_FLAG_NONE = 0, HTTP2_FLAG_END_STREAM = 0x01, HTTP2_FLAG_END_HEADERS = 0x04, HTTP2_FLAG_PADDED = 0x08, HTTP2_FLAG_PRIORITY = 0x20 } http2_flag; typedef struct { int length; http2_frame_type type; http2_flag flags; int stream_id; } http2_frame_hd; static inline void http2_frame_hd_pack(const http2_frame_hd* hd, unsigned char* buf) { // hton int length = hd->length; int stream_id = hd->stream_id; unsigned char* p = buf; *p++ = (length >> 16) & 0xFF; *p++ = (length >> 8) & 0xFF; *p++ = length & 0xFF; *p++ = (unsigned char)hd->type; *p++ = (unsigned char)hd->flags; *p++ = (stream_id >> 24) & 0xFF; *p++ = (stream_id >> 16) & 0xFF; *p++ = (stream_id >> 8) & 0xFF; *p++ = stream_id & 0xFF; } static inline void http2_frame_hd_unpack(const unsigned char* buf, http2_frame_hd* hd) { // ntoh const unsigned char* p = buf; hd->length = *p++ << 16; hd->length += *p++ << 8; hd->length += *p++; hd->type = (http2_frame_type)*p++; hd->flags = (http2_flag)*p++; hd->stream_id = *p++ << 24; hd->stream_id += *p++ << 16; hd->stream_id += *p++ << 8; hd->stream_id += *p++; } #ifdef __cplusplus } #endif #endif // HV_HTTP2_DEF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/http_content.cpp000066400000000000000000000203731520575453600276460ustar00rootroot00000000000000#include "http_content.h" #include "hurl.h" #include BEGIN_NAMESPACE_HV std::string dump_query_params(const QueryParams& query_params) { std::string query_string; for (auto& pair : query_params) { if (query_string.size() != 0) { query_string += '&'; } query_string += HUrl::escape(pair.first); query_string += '='; query_string += HUrl::escape(pair.second); } return query_string; } int parse_query_params(const char* query_string, QueryParams& query_params) { const char* p = strchr(query_string, '?'); p = p ? p+1 : query_string; enum { s_key, s_value, } state = s_key; const char* key = p; const char* value = NULL; int key_len = 0; int value_len = 0; while (*p != '\0') { if (*p == '&') { if (key_len /* && value_len */) { std::string strkey = std::string(key, key_len); std::string strvalue = std::string(value, value_len); query_params[HUrl::unescape(strkey)] = HUrl::unescape(strvalue); key_len = value_len = 0; } state = s_key; key = p+1; } else if (*p == '=' && state == s_key) { state = s_value; value = p+1; } else { state == s_key ? ++key_len : ++value_len; } ++p; } if (key_len /* && value_len */) { std::string strkey = std::string(key, key_len); std::string strvalue = std::string(value, value_len); query_params[HUrl::unescape(strkey)] = HUrl::unescape(strvalue); key_len = value_len = 0; } return query_params.size() == 0 ? -1 : 0; } #ifndef WITHOUT_HTTP_CONTENT #include "hstring.h" // for split #include "hfile.h" #include "httpdef.h" // for http_content_type_str_by_suffix std::string dump_multipart(MultiPart& mp, const char* boundary) { char c_str[256] = {0}; std::string str; if (mp.empty()) return str; for (auto& pair : mp) { str += "--"; str += boundary; str += "\r\n"; str += "Content-Disposition: form-data"; snprintf(c_str, sizeof(c_str), "; name=\"%s\"", pair.first.c_str()); str += c_str; auto& form = pair.second; if (form.filename.size() != 0) { if (form.content.size() == 0) { HFile file; if (file.open(form.filename.c_str(), "rb") == 0) { file.readall(form.content); } } snprintf(c_str, sizeof(c_str), "; filename=\"%s\"", hv_basename(form.filename.c_str())); str += c_str; const char* suffix = strrchr(form.filename.c_str(), '.'); if (suffix) { const char* stype = http_content_type_str_by_suffix(++suffix); if (stype && *stype != '\0') { str += "\r\n"; str += "Content-Type: "; str += stype; } } } str += "\r\n\r\n"; str += form.content; str += "\r\n"; } str += "--"; str += boundary; str += "--\r\n"; return str; } #include "multipart_parser.h" enum multipart_parser_state_e { MP_START, MP_PART_DATA_BEGIN, MP_HEADER_FIELD, MP_HEADER_VALUE, MP_HEADERS_COMPLETE, MP_PART_DATA, MP_PART_DATA_END, MP_BODY_END }; struct multipart_parser_userdata { MultiPart* mp; // tmp multipart_parser_state_e state; std::string header_field; std::string header_value; std::string part_data; std::string name; std::string filename; void handle_header() { if (header_field.size() == 0 || header_value.size() == 0) return; if (stricmp(header_field.c_str(), "Content-Disposition") == 0) { StringList strlist = split(header_value, ';'); for (auto& str : strlist) { StringList kv = split(trim(str, " "), '='); if (kv.size() == 2) { const char* key = kv.begin()->c_str(); std::string value = *(kv.begin() + 1); value = trim_pairs(value, "\"\"\'\'"); if (strcmp(key, "name") == 0) { name = value; } else if (strcmp(key, "filename") == 0) { filename = value; } } } } header_field.clear(); header_value.clear(); } void handle_data() { if (name.size() != 0) { FormData formdata; formdata.content = part_data; formdata.filename = filename; (*mp)[name] = formdata; } name.clear(); filename.clear(); part_data.clear(); } }; static int on_header_field(multipart_parser* parser, const char *at, size_t length) { //printf("on_header_field:%.*s\n", (int)length, at); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->handle_header(); userdata->state = MP_HEADER_FIELD; userdata->header_field.append(at, length); return 0; } static int on_header_value(multipart_parser* parser, const char *at, size_t length) { //printf("on_header_value:%.*s\n", (int)length, at); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->state = MP_HEADER_VALUE; userdata->header_value.append(at, length); return 0; } static int on_part_data(multipart_parser* parser, const char *at, size_t length) { //printf("on_part_data:%.*s\n", (int)length, at); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->state = MP_PART_DATA; userdata->part_data.append(at, length); return 0; } static int on_part_data_begin(multipart_parser* parser) { //printf("on_part_data_begin\n"); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->state = MP_PART_DATA_BEGIN; return 0; } static int on_headers_complete(multipart_parser* parser) { //printf("on_headers_complete\n"); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->handle_header(); userdata->state = MP_HEADERS_COMPLETE; return 0; } static int on_part_data_end(multipart_parser* parser) { //printf("on_part_data_end\n"); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->state = MP_PART_DATA_END; userdata->handle_data(); return 0; } static int on_body_end(multipart_parser* parser) { //printf("on_body_end\n"); multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); userdata->state = MP_BODY_END; return 0; } int parse_multipart(const std::string& str, MultiPart& mp, const char* boundary) { //printf("boundary=%s\n", boundary); std::string __boundary("--"); __boundary += boundary; multipart_parser_settings settings; settings.on_header_field = on_header_field; settings.on_header_value = on_header_value; settings.on_part_data = on_part_data; settings.on_part_data_begin = on_part_data_begin; settings.on_headers_complete = on_headers_complete; settings.on_part_data_end = on_part_data_end; settings.on_body_end = on_body_end; multipart_parser* parser = multipart_parser_init(__boundary.c_str(), &settings); multipart_parser_userdata userdata; userdata.state = MP_START; userdata.mp = ∓ multipart_parser_set_data(parser, &userdata); size_t nparse = multipart_parser_execute(parser, str.c_str(), str.size()); multipart_parser_free(parser); return nparse == str.size() ? 0 : -1; } std::string dump_json(const hv::Json& json, int indent) { if (json.empty()) return ""; return json.dump(indent); } int parse_json(const char* str, hv::Json& json, std::string& errmsg) { try { json = nlohmann::json::parse(str); } catch(nlohmann::detail::exception e) { errmsg = e.what(); return -1; } return (json.is_discarded() || json.is_null()) ? -1 : 0; } #endif END_NAMESPACE_HV kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/http_content.h000066400000000000000000000041251520575453600273100ustar00rootroot00000000000000#ifndef HV_HTTP_CONTENT_H_ #define HV_HTTP_CONTENT_H_ #include "hexport.h" #include "hstring.h" // NOTE: WITHOUT_HTTP_CONTENT // ndk-r10e no std::to_string and can't compile modern json.hpp #ifndef WITHOUT_HTTP_CONTENT #include "json.hpp" // https://github.com/nlohmann/json #endif BEGIN_NAMESPACE_HV // QueryParams using QueryParams = hv::KeyValue; HV_EXPORT std::string dump_query_params(const QueryParams& query_params); HV_EXPORT int parse_query_params(const char* query_string, QueryParams& query_params); #ifndef WITHOUT_HTTP_CONTENT /**************multipart/form-data************************************* --boundary Content-Disposition: form-data; name="user" content --boundary Content-Disposition: form-data; name="avatar"; filename="user.jpg" Content-Type: image/jpeg content --boundary-- ***********************************************************************/ // FormData struct FormData { std::string filename; std::string content; FormData(const char* content = NULL, const char* filename = NULL) { if (content) { this->content = content; } if (filename) { this->filename = filename; } } template FormData(T num) { content = hv::to_string(num); } }; // FormFile struct FormFile : public FormData { FormFile(const char* filename = NULL) { if (filename) { this->filename = filename; } } }; // MultiPart // name => FormData typedef HV_MAP MultiPart; #define DEFAULT_MULTIPART_BOUNDARY "----WebKitFormBoundary7MA4YWxkTrZu0gW" HV_EXPORT std::string dump_multipart(MultiPart& mp, const char* boundary = DEFAULT_MULTIPART_BOUNDARY); HV_EXPORT int parse_multipart(const std::string& str, MultiPart& mp, const char* boundary); // Json using Json = nlohmann::json; // using Json = nlohmann::ordered_json; HV_EXPORT std::string dump_json(const hv::Json& json, int indent = -1); HV_EXPORT int parse_json(const char* str, hv::Json& json, std::string& errmsg); #endif END_NAMESPACE_HV #endif // HV_HTTP_CONTENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/http_parser.c000066400000000000000000002147211520575453600271320ustar00rootroot00000000000000/* Copyright Joyent, Inc. and other Node contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "http_parser.h" #include #include #include #include #include static uint32_t max_header_size = HTTP_MAX_HEADER_SIZE; #ifndef ULLONG_MAX # define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ #endif #ifndef MIN # define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif #ifndef ARRAY_SIZE # define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif #ifndef BIT_AT # define BIT_AT(a, i) \ (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \ (1 << ((unsigned int) (i) & 7)))) #endif #ifndef ELEM_AT # define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) #endif #define SET_ERRNO(e) \ do { \ parser->nread = nread; \ parser->http_errno = (e); \ } while(0) #define CURRENT_STATE() p_state #define UPDATE_STATE(V) p_state = (enum state) (V); #define RETURN(V) \ do { \ parser->nread = nread; \ parser->state = CURRENT_STATE(); \ return (V); \ } while (0); #define REEXECUTE() \ goto reexecute; \ #ifdef __GNUC__ # define LIKELY(X) __builtin_expect(!!(X), 1) # define UNLIKELY(X) __builtin_expect(!!(X), 0) #else # define LIKELY(X) (X) # define UNLIKELY(X) (X) #endif /* Run the notify callback FOR, returning ER if it fails */ #define CALLBACK_NOTIFY_(FOR, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ \ /* We either errored above or got paused; get out */ \ if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ return (ER); \ } \ } \ } while (0) /* Run the notify callback FOR and consume the current byte */ #define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) /* Run the notify callback FOR and don't consume the current byte */ #define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) /* Run data callback FOR with LEN bytes, returning ER if it fails */ #define CALLBACK_DATA_(FOR, LEN, ER) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (FOR##_mark) { \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ if (UNLIKELY(0 != \ settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ \ /* We either errored above or got paused; get out */ \ if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ return (ER); \ } \ } \ FOR##_mark = NULL; \ } \ } while (0) /* Run the data callback FOR and consume the current byte */ #define CALLBACK_DATA(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) /* Run the data callback FOR and don't consume the current byte */ #define CALLBACK_DATA_NOADVANCE(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) /* Set the mark FOR; non-destructive if mark is already set */ #define MARK(FOR) \ do { \ if (!FOR##_mark) { \ FOR##_mark = p; \ } \ } while (0) /* Don't allow the total size of the HTTP headers (including the status * line) to exceed max_header_size. This check is here to protect * embedders against denial-of-service attacks where the attacker feeds * us a never-ending header that the embedder keeps buffering. * * This check is arguably the responsibility of embedders but we're doing * it on the embedder's behalf because most won't bother and this way we * make the web a little safer. max_header_size is still far bigger * than any reasonable request or response so this should never affect * day-to-day operation. */ #define COUNT_HEADER_SIZE(V) \ do { \ nread += (uint32_t)(V); \ if (UNLIKELY(nread > max_header_size)) { \ SET_ERRNO(HPE_HEADER_OVERFLOW); \ goto error; \ } \ } while (0) #define PROXY_CONNECTION "proxy-connection" #define CONNECTION "connection" #define CONTENT_LENGTH "content-length" #define TRANSFER_ENCODING "transfer-encoding" #define UPGRADE "upgrade" #define CHUNKED "chunked" #define KEEP_ALIVE "keep-alive" #define CLOSE "close" static const char *method_strings[] = { #define XX(num, name, string) #string, HTTP_METHOD_MAP(XX) #undef XX }; /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ static const char tokens[256] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0, 0, 0, 0, 0, 0, 0, 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0, 0, 0, 0, 0, 0, 0, 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0, 0, 0, 0, 0, 0, 0, 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0, 0, 0, 0, 0, 0, 0, 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ ' ', '!', 0, '#', '$', '%', '&', '\'', /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 0, 0, '*', '+', 0, '-', '.', 0, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ '0', '1', '2', '3', '4', '5', '6', '7', /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ '8', '9', 0, 0, 0, 0, 0, 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 'x', 'y', 'z', 0, 0, 0, '^', '_', /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 'x', 'y', 'z', 0, '|', 0, '~', 0 }; static const int8_t unhex[256] = {-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 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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 }; #if HTTP_PARSER_STRICT # define T(v) 0 #else # define T(v) v #endif static const uint8_t normal_url_char[32] = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, }; #undef T enum state { s_dead = 1 /* important that this is > 0 */ , s_start_req_or_res , s_res_or_resp_H , s_start_res , s_res_H , s_res_HT , s_res_HTT , s_res_HTTP , s_res_http_major , s_res_http_dot , s_res_http_minor , s_res_http_end , s_res_first_status_code , s_res_status_code , s_res_status_start , s_res_status , s_res_line_almost_done , s_start_req , s_req_method , s_req_spaces_before_url , s_req_schema , s_req_schema_slash , s_req_schema_slash_slash , s_req_server_start , s_req_server , s_req_server_with_at , s_req_path , s_req_query_string_start , s_req_query_string , s_req_fragment_start , s_req_fragment , s_req_http_start , s_req_http_H , s_req_http_HT , s_req_http_HTT , s_req_http_HTTP , s_req_http_I , s_req_http_IC , s_req_http_major , s_req_http_dot , s_req_http_minor , s_req_http_end , s_req_line_almost_done , s_header_field_start , s_header_field , s_header_value_discard_ws , s_header_value_discard_ws_almost_done , s_header_value_discard_lws , s_header_value_start , s_header_value , s_header_value_lws , s_header_almost_done , s_chunk_size_start , s_chunk_size , s_chunk_parameters , s_chunk_size_almost_done , s_headers_almost_done , s_headers_done /* Important: 's_headers_done' must be the last 'header' state. All * states beyond this must be 'body' states. It is used for overflow * checking. See the PARSING_HEADER() macro. */ , s_chunk_data , s_chunk_data_almost_done , s_chunk_data_done , s_body_identity , s_body_identity_eof , s_message_done }; #define PARSING_HEADER(state) (state <= s_headers_done) enum header_states { h_general = 0 , h_C , h_CO , h_CON , h_matching_connection , h_matching_proxy_connection , h_matching_content_length , h_matching_transfer_encoding , h_matching_upgrade , h_connection , h_content_length , h_content_length_num , h_content_length_ws , h_transfer_encoding , h_upgrade , h_matching_transfer_encoding_chunked , h_matching_connection_token_start , h_matching_connection_keep_alive , h_matching_connection_close , h_matching_connection_upgrade , h_matching_connection_token , h_transfer_encoding_chunked , h_connection_keep_alive , h_connection_close , h_connection_upgrade }; enum http_host_state { s_http_host_dead = 1 , s_http_userinfo_start , s_http_userinfo , s_http_host_start , s_http_host_v6_start , s_http_host , s_http_host_v6 , s_http_host_v6_end , s_http_host_v6_zone_start , s_http_host_v6_zone , s_http_host_port_start , s_http_host_port }; /* Macros for character classes; depends on strict-mode */ #define CR '\r' #define LF '\n' #define LOWER(c) (unsigned char)(c | 0x20) #define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') #define IS_NUM(c) ((c) >= '0' && (c) <= '9') #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) #define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) #define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ (c) == ')') #define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ (c) == '$' || (c) == ',') #define STRICT_TOKEN(c) ((c == ' ') ? 0 : tokens[(unsigned char)c]) #if HTTP_PARSER_STRICT #define TOKEN(c) STRICT_TOKEN(c) #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') #else #define TOKEN(c) tokens[(unsigned char)c] #define IS_URL_CHAR(c) \ (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) #define IS_HOST_CHAR(c) \ (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') #endif /** * Verify that a char is a valid visible (printable) US-ASCII * character or %x80-FF **/ #define IS_HEADER_CHAR(ch) \ (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127)) #define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) #if HTTP_PARSER_STRICT # define STRICT_CHECK(cond) \ do { \ if (cond) { \ SET_ERRNO(HPE_STRICT); \ goto error; \ } \ } while (0) # define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) #else # define STRICT_CHECK(cond) # define NEW_MESSAGE() start_state #endif /* Map errno values to strings for human-readable output */ #define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, static struct { const char *name; const char *description; } http_strerror_tab[] = { HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) }; #undef HTTP_STRERROR_GEN int http_message_needs_eof(const http_parser *parser); /* Our URL parser. * * This is designed to be shared by http_parser_execute() for URL validation, * hence it has a state transition + byte-for-byte interface. In addition, it * is meant to be embedded in http_parser_parse_url(), which does the dirty * work of turning state transitions URL components for its API. * * This function should only be invoked with non-space characters. It is * assumed that the caller cares about (and can detect) the transition between * URL and non-URL states by looking for these. */ static enum state parse_url_char(enum state s, const char ch) { if (ch == ' ' || ch == '\r' || ch == '\n') { return s_dead; } #if HTTP_PARSER_STRICT if (ch == '\t' || ch == '\f') { return s_dead; } #endif switch (s) { case s_req_spaces_before_url: /* Proxied requests are followed by scheme of an absolute URI (alpha). * All methods except CONNECT are followed by '/' or '*'. */ if (ch == '/' || ch == '*') { return s_req_path; } if (IS_ALPHA(ch)) { return s_req_schema; } break; case s_req_schema: if (IS_ALPHA(ch)) { return s; } if (ch == ':') { return s_req_schema_slash; } break; case s_req_schema_slash: if (ch == '/') { return s_req_schema_slash_slash; } break; case s_req_schema_slash_slash: if (ch == '/') { return s_req_server_start; } break; case s_req_server_with_at: if (ch == '@') { return s_dead; } /* fall through */ case s_req_server_start: case s_req_server: if (ch == '/') { return s_req_path; } if (ch == '?') { return s_req_query_string_start; } if (ch == '@') { return s_req_server_with_at; } if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { return s_req_server; } break; case s_req_path: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': return s_req_query_string_start; case '#': return s_req_fragment_start; } break; case s_req_query_string_start: case s_req_query_string: if (IS_URL_CHAR(ch)) { return s_req_query_string; } switch (ch) { case '?': /* allow extra '?' in query string */ return s_req_query_string; case '#': return s_req_fragment_start; } break; case s_req_fragment_start: if (IS_URL_CHAR(ch)) { return s_req_fragment; } switch (ch) { case '?': return s_req_fragment; case '#': return s; } break; case s_req_fragment: if (IS_URL_CHAR(ch)) { return s; } switch (ch) { case '?': case '#': return s; } break; default: break; } /* We should never fall out of the switch above unless there's an error */ return s_dead; } size_t http_parser_execute (http_parser *parser, const http_parser_settings *settings, const char *data, size_t len) { char c, ch; int8_t unhex_val; const char *p = data; const char *header_field_mark = 0; const char *header_value_mark = 0; const char *url_mark = 0; const char *body_mark = 0; const char *status_mark = 0; enum state p_state = (enum state) parser->state; const unsigned int lenient = parser->lenient_http_headers; uint32_t nread = parser->nread; /* We're in an error state. Don't bother doing anything. */ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { return 0; } if (len == 0) { switch (CURRENT_STATE()) { case s_body_identity_eof: /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if * we got paused. */ CALLBACK_NOTIFY_NOADVANCE(message_complete); return 0; case s_dead: case s_start_req_or_res: case s_start_res: case s_start_req: return 0; default: SET_ERRNO(HPE_INVALID_EOF_STATE); return 1; } } if (CURRENT_STATE() == s_header_field) header_field_mark = data; if (CURRENT_STATE() == s_header_value) header_value_mark = data; switch (CURRENT_STATE()) { case s_req_path: case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_server: case s_req_server_with_at: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: url_mark = data; break; case s_res_status: status_mark = data; break; default: break; } for (p=data; p != data + len; p++) { ch = *p; if (PARSING_HEADER(CURRENT_STATE())) COUNT_HEADER_SIZE(1); reexecute: switch (CURRENT_STATE()) { case s_dead: /* this state is used after a 'Connection: close' message * the parser will error out if it reads another message */ if (LIKELY(ch == CR || ch == LF)) break; SET_ERRNO(HPE_CLOSED_CONNECTION); goto error; case s_start_req_or_res: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (ch == 'H') { UPDATE_STATE(s_res_or_resp_H); CALLBACK_NOTIFY(message_begin); } else { parser->type = HTTP_REQUEST; UPDATE_STATE(s_start_req); REEXECUTE(); } break; } case s_res_or_resp_H: if (ch == 'T') { parser->type = HTTP_RESPONSE; UPDATE_STATE(s_res_HT); } else { if (UNLIKELY(ch != 'E')) { SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } parser->type = HTTP_REQUEST; parser->method = HTTP_HEAD; parser->index = 2; UPDATE_STATE(s_req_method); } break; case s_start_res: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (ch == 'H') { UPDATE_STATE(s_res_H); } else { SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } CALLBACK_NOTIFY(message_begin); break; } case s_res_H: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_res_HT); break; case s_res_HT: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_res_HTT); break; case s_res_HTT: STRICT_CHECK(ch != 'P'); UPDATE_STATE(s_res_HTTP); break; case s_res_HTTP: STRICT_CHECK(ch != '/'); UPDATE_STATE(s_res_http_major); break; case s_res_http_major: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; UPDATE_STATE(s_res_http_dot); break; case s_res_http_dot: { if (UNLIKELY(ch != '.')) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } UPDATE_STATE(s_res_http_minor); break; } case s_res_http_minor: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; UPDATE_STATE(s_res_http_end); break; case s_res_http_end: { if (UNLIKELY(ch != ' ')) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } UPDATE_STATE(s_res_first_status_code); break; } case s_res_first_status_code: { if (!IS_NUM(ch)) { if (ch == ' ') { break; } SET_ERRNO(HPE_INVALID_STATUS); goto error; } parser->status_code = ch - '0'; UPDATE_STATE(s_res_status_code); break; } case s_res_status_code: { if (!IS_NUM(ch)) { switch (ch) { case ' ': UPDATE_STATE(s_res_status_start); break; case CR: case LF: UPDATE_STATE(s_res_status_start); REEXECUTE(); break; default: SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } parser->status_code *= 10; parser->status_code += ch - '0'; if (UNLIKELY(parser->status_code > 999)) { SET_ERRNO(HPE_INVALID_STATUS); goto error; } break; } case s_res_status_start: { MARK(status); UPDATE_STATE(s_res_status); parser->index = 0; if (ch == CR || ch == LF) REEXECUTE(); break; } case s_res_status: if (ch == CR) { UPDATE_STATE(s_res_line_almost_done); CALLBACK_DATA(status); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); CALLBACK_DATA(status); break; } break; case s_res_line_almost_done: STRICT_CHECK(ch != LF); UPDATE_STATE(s_header_field_start); break; case s_start_req: { if (ch == CR || ch == LF) break; parser->flags = 0; parser->content_length = ULLONG_MAX; if (UNLIKELY(!IS_ALPHA(ch))) { SET_ERRNO(HPE_INVALID_METHOD); goto error; } parser->method = (enum http_method) 0; parser->index = 1; switch (ch) { case 'A': parser->method = HTTP_ACL; break; case 'B': parser->method = HTTP_BIND; break; case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; case 'D': parser->method = HTTP_DELETE; break; case 'G': parser->method = HTTP_GET; break; case 'H': parser->method = HTTP_HEAD; break; case 'L': parser->method = HTTP_LOCK; /* or LINK */ break; case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break; case 'N': parser->method = HTTP_NOTIFY; break; case 'O': parser->method = HTTP_OPTIONS; break; case 'P': parser->method = HTTP_POST; /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ break; case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break; case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH, SOURCE */ break; case 'T': parser->method = HTTP_TRACE; break; case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break; default: SET_ERRNO(HPE_INVALID_METHOD); goto error; } UPDATE_STATE(s_req_method); CALLBACK_NOTIFY(message_begin); break; } case s_req_method: { const char *matcher; if (UNLIKELY(ch == '\0')) { SET_ERRNO(HPE_INVALID_METHOD); goto error; } matcher = method_strings[parser->method]; if (ch == ' ' && matcher[parser->index] == '\0') { UPDATE_STATE(s_req_spaces_before_url); } else if (ch == matcher[parser->index]) { ; /* nada */ } else if ((ch >= 'A' && ch <= 'Z') || ch == '-') { switch (parser->method << 16 | parser->index << 8 | ch) { #define XX(meth, pos, ch, new_meth) \ case (HTTP_##meth << 16 | pos << 8 | ch): \ parser->method = HTTP_##new_meth; break; XX(POST, 1, 'U', PUT) XX(POST, 1, 'A', PATCH) XX(POST, 1, 'R', PROPFIND) XX(PUT, 2, 'R', PURGE) XX(CONNECT, 1, 'H', CHECKOUT) XX(CONNECT, 2, 'P', COPY) XX(MKCOL, 1, 'O', MOVE) XX(MKCOL, 1, 'E', MERGE) XX(MKCOL, 1, '-', MSEARCH) XX(MKCOL, 2, 'A', MKACTIVITY) XX(MKCOL, 3, 'A', MKCALENDAR) XX(SUBSCRIBE, 1, 'E', SEARCH) XX(SUBSCRIBE, 1, 'O', SOURCE) XX(REPORT, 2, 'B', REBIND) XX(PROPFIND, 4, 'P', PROPPATCH) XX(LOCK, 1, 'I', LINK) XX(UNLOCK, 2, 'S', UNSUBSCRIBE) XX(UNLOCK, 2, 'B', UNBIND) XX(UNLOCK, 3, 'I', UNLINK) #undef XX default: SET_ERRNO(HPE_INVALID_METHOD); goto error; } } else { SET_ERRNO(HPE_INVALID_METHOD); goto error; } ++parser->index; break; } case s_req_spaces_before_url: { if (ch == ' ') break; MARK(url); if (parser->method == HTTP_CONNECT) { UPDATE_STATE(s_req_server_start); } UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } break; } case s_req_schema: case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: { switch (ch) { /* No whitespace allowed here */ case ' ': case CR: case LF: SET_ERRNO(HPE_INVALID_URL); goto error; default: UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_server: case s_req_server_with_at: case s_req_path: case s_req_query_string_start: case s_req_query_string: case s_req_fragment_start: case s_req_fragment: { switch (ch) { case ' ': UPDATE_STATE(s_req_http_start); CALLBACK_DATA(url); break; case CR: case LF: parser->http_major = 0; parser->http_minor = 9; UPDATE_STATE((ch == CR) ? s_req_line_almost_done : s_header_field_start); CALLBACK_DATA(url); break; default: UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); if (UNLIKELY(CURRENT_STATE() == s_dead)) { SET_ERRNO(HPE_INVALID_URL); goto error; } } break; } case s_req_http_start: switch (ch) { case ' ': break; case 'H': UPDATE_STATE(s_req_http_H); break; case 'I': if (parser->method == HTTP_SOURCE) { UPDATE_STATE(s_req_http_I); break; } /* fall through */ default: SET_ERRNO(HPE_INVALID_CONSTANT); goto error; } break; case s_req_http_H: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_req_http_HT); break; case s_req_http_HT: STRICT_CHECK(ch != 'T'); UPDATE_STATE(s_req_http_HTT); break; case s_req_http_HTT: STRICT_CHECK(ch != 'P'); UPDATE_STATE(s_req_http_HTTP); break; case s_req_http_I: STRICT_CHECK(ch != 'C'); UPDATE_STATE(s_req_http_IC); break; case s_req_http_IC: STRICT_CHECK(ch != 'E'); UPDATE_STATE(s_req_http_HTTP); /* Treat "ICE" as "HTTP". */ break; case s_req_http_HTTP: STRICT_CHECK(ch != '/'); UPDATE_STATE(s_req_http_major); break; case s_req_http_major: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_major = ch - '0'; UPDATE_STATE(s_req_http_dot); break; case s_req_http_dot: { if (UNLIKELY(ch != '.')) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } UPDATE_STATE(s_req_http_minor); break; } case s_req_http_minor: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_VERSION); goto error; } parser->http_minor = ch - '0'; UPDATE_STATE(s_req_http_end); break; case s_req_http_end: { if (ch == CR) { UPDATE_STATE(s_req_line_almost_done); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); break; } SET_ERRNO(HPE_INVALID_VERSION); goto error; break; } /* end of request line */ case s_req_line_almost_done: { if (UNLIKELY(ch != LF)) { SET_ERRNO(HPE_LF_EXPECTED); goto error; } UPDATE_STATE(s_header_field_start); break; } case s_header_field_start: { if (ch == CR) { UPDATE_STATE(s_headers_almost_done); break; } if (ch == LF) { /* they might be just sending \n instead of \r\n so this would be * the second \n to denote the end of headers*/ UPDATE_STATE(s_headers_almost_done); REEXECUTE(); } c = TOKEN(ch); if (UNLIKELY(!c)) { SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } MARK(header_field); parser->index = 0; UPDATE_STATE(s_header_field); switch (c) { case 'c': parser->header_state = h_C; break; case 'p': parser->header_state = h_matching_proxy_connection; break; case 't': parser->header_state = h_matching_transfer_encoding; break; case 'u': parser->header_state = h_matching_upgrade; break; default: parser->header_state = h_general; break; } break; } case s_header_field: { const char* start = p; for (; p != data + len; p++) { ch = *p; c = TOKEN(ch); if (!c) break; switch (parser->header_state) { case h_general: { size_t limit = data + len - p; limit = MIN(limit, max_header_size); while (p+1 < data + limit && TOKEN(p[1])) { p++; } break; } case h_C: parser->index++; parser->header_state = (c == 'o' ? h_CO : h_general); break; case h_CO: parser->index++; parser->header_state = (c == 'n' ? h_CON : h_general); break; case h_CON: parser->index++; switch (c) { case 'n': parser->header_state = h_matching_connection; break; case 't': parser->header_state = h_matching_content_length; break; default: parser->header_state = h_general; break; } break; /* connection */ case h_matching_connection: parser->index++; if (parser->index > sizeof(CONNECTION)-1 || c != CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONNECTION)-2) { parser->header_state = h_connection; } break; /* proxy-connection */ case h_matching_proxy_connection: parser->index++; if (parser->index > sizeof(PROXY_CONNECTION)-1 || c != PROXY_CONNECTION[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { parser->header_state = h_connection; } break; /* content-length */ case h_matching_content_length: parser->index++; if (parser->index > sizeof(CONTENT_LENGTH)-1 || c != CONTENT_LENGTH[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { parser->header_state = h_content_length; } break; /* transfer-encoding */ case h_matching_transfer_encoding: parser->index++; if (parser->index > sizeof(TRANSFER_ENCODING)-1 || c != TRANSFER_ENCODING[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { parser->header_state = h_transfer_encoding; } break; /* upgrade */ case h_matching_upgrade: parser->index++; if (parser->index > sizeof(UPGRADE)-1 || c != UPGRADE[parser->index]) { parser->header_state = h_general; } else if (parser->index == sizeof(UPGRADE)-2) { parser->header_state = h_upgrade; } break; case h_connection: case h_content_length: case h_transfer_encoding: case h_upgrade: if (ch != ' ') parser->header_state = h_general; break; default: assert(0 && "Unknown header_state"); break; } } if (p == data + len) { --p; COUNT_HEADER_SIZE(p - start); break; } COUNT_HEADER_SIZE(p - start); if (ch == ':') { UPDATE_STATE(s_header_value_discard_ws); CALLBACK_DATA(header_field); break; } SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } case s_header_value_discard_ws: if (ch == ' ' || ch == '\t') break; if (ch == CR) { UPDATE_STATE(s_header_value_discard_ws_almost_done); break; } if (ch == LF) { UPDATE_STATE(s_header_value_discard_lws); break; } /* fall through */ case s_header_value_start: { MARK(header_value); UPDATE_STATE(s_header_value); parser->index = 0; c = LOWER(ch); switch (parser->header_state) { case h_upgrade: parser->flags |= F_UPGRADE; parser->header_state = h_general; break; case h_transfer_encoding: /* looking for 'Transfer-Encoding: chunked' */ if ('c' == c) { parser->header_state = h_matching_transfer_encoding_chunked; } else { parser->header_state = h_general; } break; case h_content_length: if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } if (parser->flags & F_CONTENTLENGTH) { SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); goto error; } parser->flags |= F_CONTENTLENGTH; parser->content_length = ch - '0'; parser->header_state = h_content_length_num; break; /* when obsolete line folding is encountered for content length * continue to the s_header_value state */ case h_content_length_ws: break; case h_connection: /* looking for 'Connection: keep-alive' */ if (c == 'k') { parser->header_state = h_matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (c == 'c') { parser->header_state = h_matching_connection_close; } else if (c == 'u') { parser->header_state = h_matching_connection_upgrade; } else { parser->header_state = h_matching_connection_token; } break; /* Multi-value `Connection` header */ case h_matching_connection_token_start: break; default: parser->header_state = h_general; break; } break; } case s_header_value: { const char* start = p; enum header_states h_state = (enum header_states) parser->header_state; for (; p != data + len; p++) { ch = *p; if (ch == CR) { UPDATE_STATE(s_header_almost_done); parser->header_state = h_state; CALLBACK_DATA(header_value); break; } if (ch == LF) { UPDATE_STATE(s_header_almost_done); COUNT_HEADER_SIZE(p - start); parser->header_state = h_state; CALLBACK_DATA_NOADVANCE(header_value); REEXECUTE(); } if (!lenient && !IS_HEADER_CHAR(ch)) { SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } c = LOWER(ch); switch (h_state) { case h_general: { const char* limit = p + MIN(data + len - p, max_header_size); for (; p != limit; p++) { ch = *p; if (ch == CR || ch == LF) { --p; break; } if (!lenient && !IS_HEADER_CHAR(ch)) { SET_ERRNO(HPE_INVALID_HEADER_TOKEN); goto error; } } if (p == data + len) --p; break; } case h_connection: case h_transfer_encoding: assert(0 && "Shouldn't get here."); break; case h_content_length: if (ch == ' ') break; h_state = h_content_length_num; /* fall through */ case h_content_length_num: { uint64_t t; if (ch == ' ') { h_state = h_content_length_ws; break; } if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); parser->header_state = h_state; goto error; } t = parser->content_length; t *= 10; t += ch - '0'; /* Overflow? Test against a conservative limit for simplicity. */ if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); parser->header_state = h_state; goto error; } parser->content_length = t; break; } case h_content_length_ws: if (ch == ' ') break; SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); parser->header_state = h_state; goto error; /* Transfer-Encoding: chunked */ case h_matching_transfer_encoding_chunked: parser->index++; if (parser->index > sizeof(CHUNKED)-1 || c != CHUNKED[parser->index]) { h_state = h_general; } else if (parser->index == sizeof(CHUNKED)-2) { h_state = h_transfer_encoding_chunked; } break; case h_matching_connection_token_start: /* looking for 'Connection: keep-alive' */ if (c == 'k') { h_state = h_matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (c == 'c') { h_state = h_matching_connection_close; } else if (c == 'u') { h_state = h_matching_connection_upgrade; } else if (STRICT_TOKEN(c)) { h_state = h_matching_connection_token; } else if (c == ' ' || c == '\t') { /* Skip lws */ } else { h_state = h_general; } break; /* looking for 'Connection: keep-alive' */ case h_matching_connection_keep_alive: parser->index++; if (parser->index > sizeof(KEEP_ALIVE)-1 || c != KEEP_ALIVE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(KEEP_ALIVE)-2) { h_state = h_connection_keep_alive; } break; /* looking for 'Connection: close' */ case h_matching_connection_close: parser->index++; if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(CLOSE)-2) { h_state = h_connection_close; } break; /* looking for 'Connection: upgrade' */ case h_matching_connection_upgrade: parser->index++; if (parser->index > sizeof(UPGRADE) - 1 || c != UPGRADE[parser->index]) { h_state = h_matching_connection_token; } else if (parser->index == sizeof(UPGRADE)-2) { h_state = h_connection_upgrade; } break; case h_matching_connection_token: if (ch == ',') { h_state = h_matching_connection_token_start; parser->index = 0; } break; case h_transfer_encoding_chunked: if (ch != ' ') h_state = h_general; break; case h_connection_keep_alive: case h_connection_close: case h_connection_upgrade: if (ch == ',') { if (h_state == h_connection_keep_alive) { parser->flags |= F_CONNECTION_KEEP_ALIVE; } else if (h_state == h_connection_close) { parser->flags |= F_CONNECTION_CLOSE; } else if (h_state == h_connection_upgrade) { parser->flags |= F_CONNECTION_UPGRADE; } h_state = h_matching_connection_token_start; parser->index = 0; } else if (ch != ' ') { h_state = h_matching_connection_token; } break; default: UPDATE_STATE(s_header_value); h_state = h_general; break; } } parser->header_state = h_state; if (p == data + len) --p; COUNT_HEADER_SIZE(p - start); break; } case s_header_almost_done: { if (UNLIKELY(ch != LF)) { SET_ERRNO(HPE_LF_EXPECTED); goto error; } UPDATE_STATE(s_header_value_lws); break; } case s_header_value_lws: { if (ch == ' ' || ch == '\t') { if (parser->header_state == h_content_length_num) { /* treat obsolete line folding as space */ parser->header_state = h_content_length_ws; } UPDATE_STATE(s_header_value_start); REEXECUTE(); } /* finished the header */ switch (parser->header_state) { case h_connection_keep_alive: parser->flags |= F_CONNECTION_KEEP_ALIVE; break; case h_connection_close: parser->flags |= F_CONNECTION_CLOSE; break; case h_transfer_encoding_chunked: parser->flags |= F_CHUNKED; break; case h_connection_upgrade: parser->flags |= F_CONNECTION_UPGRADE; break; default: break; } UPDATE_STATE(s_header_field_start); REEXECUTE(); } case s_header_value_discard_ws_almost_done: { STRICT_CHECK(ch != LF); UPDATE_STATE(s_header_value_discard_lws); break; } case s_header_value_discard_lws: { if (ch == ' ' || ch == '\t') { UPDATE_STATE(s_header_value_discard_ws); break; } else { switch (parser->header_state) { case h_connection_keep_alive: parser->flags |= F_CONNECTION_KEEP_ALIVE; break; case h_connection_close: parser->flags |= F_CONNECTION_CLOSE; break; case h_connection_upgrade: parser->flags |= F_CONNECTION_UPGRADE; break; case h_transfer_encoding_chunked: parser->flags |= F_CHUNKED; break; case h_content_length: /* do not allow empty content length */ SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; break; default: break; } /* header value was empty */ MARK(header_value); UPDATE_STATE(s_header_field_start); CALLBACK_DATA_NOADVANCE(header_value); REEXECUTE(); } } case s_headers_almost_done: { STRICT_CHECK(ch != LF); if (parser->flags & F_TRAILING) { /* End of a chunked request */ UPDATE_STATE(s_message_done); CALLBACK_NOTIFY_NOADVANCE(chunk_complete); REEXECUTE(); } /* Cannot use chunked encoding and a content-length header together per the HTTP specification. */ if ((parser->flags & F_CHUNKED) && (parser->flags & F_CONTENTLENGTH)) { SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); goto error; } UPDATE_STATE(s_headers_done); /* Set this here so that on_headers_complete() callbacks can see it */ if ((parser->flags & F_UPGRADE) && (parser->flags & F_CONNECTION_UPGRADE)) { /* For responses, "Upgrade: foo" and "Connection: upgrade" are * mandatory only when it is a 101 Switching Protocols response, * otherwise it is purely informational, to announce support. */ parser->upgrade = (parser->type == HTTP_REQUEST || parser->status_code == 101); } else { parser->upgrade = (parser->method == HTTP_CONNECT); } /* Here we call the headers_complete callback. This is somewhat * different than other callbacks because if the user returns 1, we * will interpret that as saying that this message has no body. This * is needed for the annoying case of recieving a response to a HEAD * request. * * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so * we have to simulate it by handling a change in errno below. */ if (settings->on_headers_complete) { switch (settings->on_headers_complete(parser)) { case 0: break; case 2: parser->upgrade = 1; /* fall through */ case 1: parser->flags |= F_SKIPBODY; break; default: SET_ERRNO(HPE_CB_headers_complete); RETURN(p - data); /* Error */ } } if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { RETURN(p - data); } REEXECUTE(); } case s_headers_done: { int hasBody; STRICT_CHECK(ch != LF); parser->nread = 0; nread = 0; hasBody = parser->flags & F_CHUNKED || (parser->content_length > 0 && parser->content_length != ULLONG_MAX); if (parser->upgrade && (parser->method == HTTP_CONNECT || (parser->flags & F_SKIPBODY) || !hasBody)) { /* Exit, the rest of the message is in a different protocol. */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); RETURN((p - data) + 1); } if (parser->flags & F_SKIPBODY) { UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else if (parser->flags & F_CHUNKED) { /* chunked encoding - ignore Content-Length header */ UPDATE_STATE(s_chunk_size_start); } else { if (parser->content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else if (parser->content_length != ULLONG_MAX) { /* Content-Length header given and non-zero */ UPDATE_STATE(s_body_identity); } else { if (!http_message_needs_eof(parser)) { /* Assume content-length 0 - read the next */ UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); } else { /* Read body until EOF */ UPDATE_STATE(s_body_identity_eof); } } } break; } case s_body_identity: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* The difference between advancing content_length and p is because * the latter will automaticaly advance on the next loop iteration. * Further, if content_length ends up at 0, we want to see the last * byte again for our message complete callback. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { UPDATE_STATE(s_message_done); /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. * * The alternative to doing this is to wait for the next byte to * trigger the data callback, just as in every other case. The * problem with this is that this makes it difficult for the test * harness to distinguish between complete-on-EOF and * complete-on-length. It's not clear that this distinction is * important for applications, but let's keep it for now. */ CALLBACK_DATA_(body, p - body_mark + 1, p - data); REEXECUTE(); } break; } /* read until EOF */ case s_body_identity_eof: MARK(body); p = data + len - 1; break; case s_message_done: UPDATE_STATE(NEW_MESSAGE()); CALLBACK_NOTIFY(message_complete); if (parser->upgrade) { /* Exit, the rest of the message is in a different protocol. */ RETURN((p - data) + 1); } break; case s_chunk_size_start: { assert(nread == 1); assert(parser->flags & F_CHUNKED); unhex_val = unhex[(unsigned char)ch]; if (UNLIKELY(unhex_val == -1)) { SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } parser->content_length = unhex_val; UPDATE_STATE(s_chunk_size); break; } case s_chunk_size: { uint64_t t; assert(parser->flags & F_CHUNKED); if (ch == CR) { UPDATE_STATE(s_chunk_size_almost_done); break; } unhex_val = unhex[(unsigned char)ch]; if (unhex_val == -1) { if (ch == ';' || ch == ' ') { UPDATE_STATE(s_chunk_parameters); break; } SET_ERRNO(HPE_INVALID_CHUNK_SIZE); goto error; } t = parser->content_length; t *= 16; t += unhex_val; /* Overflow? Test against a conservative limit for simplicity. */ if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); goto error; } parser->content_length = t; break; } case s_chunk_parameters: { assert(parser->flags & F_CHUNKED); /* just ignore this shit. TODO check for overflow */ if (ch == CR) { UPDATE_STATE(s_chunk_size_almost_done); break; } break; } case s_chunk_size_almost_done: { assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; nread = 0; if (parser->content_length == 0) { parser->flags |= F_TRAILING; UPDATE_STATE(s_header_field_start); } else { UPDATE_STATE(s_chunk_data); } CALLBACK_NOTIFY(chunk_header); break; } case s_chunk_data: { uint64_t to_read = MIN(parser->content_length, (uint64_t) ((data + len) - p)); assert(parser->flags & F_CHUNKED); assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); /* See the explanation in s_body_identity for why the content * length and data pointers are managed this way. */ MARK(body); parser->content_length -= to_read; p += to_read - 1; if (parser->content_length == 0) { UPDATE_STATE(s_chunk_data_almost_done); } break; } case s_chunk_data_almost_done: assert(parser->flags & F_CHUNKED); assert(parser->content_length == 0); STRICT_CHECK(ch != CR); UPDATE_STATE(s_chunk_data_done); CALLBACK_DATA(body); break; case s_chunk_data_done: assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; nread = 0; UPDATE_STATE(s_chunk_size_start); CALLBACK_NOTIFY(chunk_complete); break; default: assert(0 && "unhandled state"); SET_ERRNO(HPE_INVALID_INTERNAL_STATE); goto error; } } /* Run callbacks for any marks that we have leftover after we ran out of * bytes. There should be at most one of these set, so it's OK to invoke * them in series (unset marks will not result in callbacks). * * We use the NOADVANCE() variety of callbacks here because 'p' has already * overflowed 'data' and this allows us to correct for the off-by-one that * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' * value that's in-bounds). */ assert(((header_field_mark ? 1 : 0) + (header_value_mark ? 1 : 0) + (url_mark ? 1 : 0) + (body_mark ? 1 : 0) + (status_mark ? 1 : 0)) <= 1); CALLBACK_DATA_NOADVANCE(header_field); CALLBACK_DATA_NOADVANCE(header_value); CALLBACK_DATA_NOADVANCE(url); CALLBACK_DATA_NOADVANCE(body); CALLBACK_DATA_NOADVANCE(status); RETURN(len); error: if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { SET_ERRNO(HPE_UNKNOWN); } RETURN(p - data); } /* Does the parser need to see an EOF to find the end of the message? */ int http_message_needs_eof (const http_parser *parser) { if (parser->type == HTTP_REQUEST) { return 0; } /* See RFC 2616 section 4.4 */ if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ parser->status_code == 204 || /* No Content */ parser->status_code == 304 || /* Not Modified */ parser->flags & F_SKIPBODY) { /* response to a HEAD request */ return 0; } if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { return 0; } return 1; } int http_should_keep_alive (const http_parser *parser) { if (parser->http_major > 0 && parser->http_minor > 0) { /* HTTP/1.1 */ if (parser->flags & F_CONNECTION_CLOSE) { return 0; } } else { /* HTTP/1.0 or earlier */ if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { return 0; } } return !http_message_needs_eof(parser); } void http_parser_init (http_parser *parser, enum http_parser_type t) { void *data = parser->data; /* preserve application data */ memset(parser, 0, sizeof(*parser)); parser->data = data; parser->type = t; parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); parser->http_errno = HPE_OK; } void http_parser_settings_init(http_parser_settings *settings) { memset(settings, 0, sizeof(*settings)); } const char * http_errno_name(enum http_errno err) { assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); return http_strerror_tab[err].name; } const char * http_errno_description(enum http_errno err) { assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); return http_strerror_tab[err].description; } #ifdef WITH_HTTP_PRASER_URL static enum http_host_state http_parse_host_char(enum http_host_state s, const char ch) { switch(s) { case s_http_userinfo: case s_http_userinfo_start: if (ch == '@') { return s_http_host_start; } if (IS_USERINFO_CHAR(ch)) { return s_http_userinfo; } break; case s_http_host_start: if (ch == '[') { return s_http_host_v6_start; } if (IS_HOST_CHAR(ch)) { return s_http_host; } break; case s_http_host: if (IS_HOST_CHAR(ch)) { return s_http_host; } /* fall through */ case s_http_host_v6_end: if (ch == ':') { return s_http_host_port_start; } break; case s_http_host_v6: if (ch == ']') { return s_http_host_v6_end; } /* fall through */ case s_http_host_v6_start: if (IS_HEX(ch) || ch == ':' || ch == '.') { return s_http_host_v6; } if (s == s_http_host_v6 && ch == '%') { return s_http_host_v6_zone_start; } break; case s_http_host_v6_zone: if (ch == ']') { return s_http_host_v6_end; } /* fall through */ case s_http_host_v6_zone_start: /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */ if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' || ch == '~') { return s_http_host_v6_zone; } break; case s_http_host_port: case s_http_host_port_start: if (IS_NUM(ch)) { return s_http_host_port; } break; default: break; } return s_http_host_dead; } static int http_parse_host(const char * buf, struct http_parser_url *u, int found_at) { enum http_host_state s; const char *p; size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; assert(u->field_set & (1 << UF_HOST)); u->field_data[UF_HOST].len = 0; s = found_at ? s_http_userinfo_start : s_http_host_start; for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { enum http_host_state new_s = http_parse_host_char(s, *p); if (new_s == s_http_host_dead) { return 1; } switch(new_s) { case s_http_host: if (s != s_http_host) { u->field_data[UF_HOST].off = (uint16_t)(p - buf); } u->field_data[UF_HOST].len++; break; case s_http_host_v6: if (s != s_http_host_v6) { u->field_data[UF_HOST].off = (uint16_t)(p - buf); } u->field_data[UF_HOST].len++; break; case s_http_host_v6_zone_start: case s_http_host_v6_zone: u->field_data[UF_HOST].len++; break; case s_http_host_port: if (s != s_http_host_port) { u->field_data[UF_PORT].off = (uint16_t)(p - buf); u->field_data[UF_PORT].len = 0; u->field_set |= (1 << UF_PORT); } u->field_data[UF_PORT].len++; break; case s_http_userinfo: if (s != s_http_userinfo) { u->field_data[UF_USERINFO].off = (uint16_t)(p - buf); u->field_data[UF_USERINFO].len = 0; u->field_set |= (1 << UF_USERINFO); } u->field_data[UF_USERINFO].len++; break; default: break; } s = new_s; } /* Make sure we don't end somewhere unexpected */ switch (s) { case s_http_host_start: case s_http_host_v6_start: case s_http_host_v6: case s_http_host_v6_zone_start: case s_http_host_v6_zone: case s_http_host_port_start: case s_http_userinfo: case s_http_userinfo_start: return 1; default: break; } return 0; } void http_parser_url_init(struct http_parser_url *u) { memset(u, 0, sizeof(*u)); } int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u) { enum state s; const char *p; enum http_parser_url_fields uf, old_uf; int found_at = 0; if (buflen == 0) { return 1; } u->port = u->field_set = 0; s = is_connect ? s_req_server_start : s_req_spaces_before_url; old_uf = UF_MAX; for (p = buf; p < buf + buflen; p++) { s = parse_url_char(s, *p); /* Figure out the next field that we're operating on */ switch (s) { case s_dead: return 1; /* Skip delimeters */ case s_req_schema_slash: case s_req_schema_slash_slash: case s_req_server_start: case s_req_query_string_start: case s_req_fragment_start: continue; case s_req_schema: uf = UF_SCHEMA; break; case s_req_server_with_at: found_at = 1; /* fall through */ case s_req_server: uf = UF_HOST; break; case s_req_path: uf = UF_PATH; break; case s_req_query_string: uf = UF_QUERY; break; case s_req_fragment: uf = UF_FRAGMENT; break; default: assert(!"Unexpected state"); return 1; } /* Nothing's changed; soldier on */ if (uf == old_uf) { u->field_data[uf].len++; continue; } u->field_data[uf].off = (uint16_t)(p - buf); u->field_data[uf].len = 1; u->field_set |= (1 << uf); old_uf = uf; } /* host must be present if there is a schema */ /* parsing http:///toto will fail */ if ((u->field_set & (1 << UF_SCHEMA)) && (u->field_set & (1 << UF_HOST)) == 0) { return 1; } if (u->field_set & (1 << UF_HOST)) { if (http_parse_host(buf, u, found_at) != 0) { return 1; } } /* CONNECT requests can only contain "hostname:port" */ if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { return 1; } if (u->field_set & (1 << UF_PORT)) { uint16_t off; uint16_t len; const char* p; const char* end; unsigned long v; off = u->field_data[UF_PORT].off; len = u->field_data[UF_PORT].len; end = buf + off + len; /* NOTE: The characters are already validated and are in the [0-9] range */ assert(off + len <= buflen && "Port number overflow"); v = 0; for (p = buf + off; p < end; p++) { v *= 10; v += *p - '0'; /* Ports have a max value of 2^16 */ if (v > 0xffff) { return 1; } } u->port = (uint16_t) v; } return 0; } #endif void http_parser_pause(http_parser *parser, int paused) { /* Users should only be pausing/unpausing a parser that is not in an error * state. In non-debug builds, there's not much that we can do about this * other than ignore it. */ if (HTTP_PARSER_ERRNO(parser) == HPE_OK || HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { uint32_t nread = parser->nread; /* used by the SET_ERRNO macro */ SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); } else { assert(0 && "Attempting to pause parser in error state"); } } int http_body_is_final(const struct http_parser *parser) { return parser->state == s_message_done; } unsigned long http_parser_version(void) { return HTTP_PARSER_VERSION_MAJOR * 0x10000 | HTTP_PARSER_VERSION_MINOR * 0x00100 | HTTP_PARSER_VERSION_PATCH * 0x00001; } void http_parser_set_max_header_size(uint32_t size) { max_header_size = size; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/http_parser.h000066400000000000000000000276661520575453600271510ustar00rootroot00000000000000/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef http_parser_h #define http_parser_h #ifdef __cplusplus extern "C" { #endif #include "httpdef.h" /* Also update SONAME in the Makefile whenever you change these. */ #define HTTP_PARSER_VERSION_MAJOR 2 #define HTTP_PARSER_VERSION_MINOR 9 #define HTTP_PARSER_VERSION_PATCH 1 #include #if defined(_WIN32) && !defined(__MINGW32__) && \ (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__) #include typedef __int8 int8_t; typedef unsigned __int8 uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include #endif /* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run * faster */ #ifndef HTTP_PARSER_STRICT # define HTTP_PARSER_STRICT 1 #endif /* Maximium header size allowed. If the macro is not defined * before including this header then the default is used. To * change the maximum header size, define the macro in the build * environment (e.g. -DHTTP_MAX_HEADER_SIZE=). To remove * the effective limit on the size of the header, define the macro * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff) */ #ifndef HTTP_MAX_HEADER_SIZE # define HTTP_MAX_HEADER_SIZE (80*1024) #endif typedef struct http_parser http_parser; typedef struct http_parser_settings http_parser_settings; /* Callbacks should return non-zero to indicate an error. The parser will * then halt execution. * * The one exception is on_headers_complete. In a HTTP_RESPONSE parser * returning '1' from on_headers_complete will tell the parser that it * should not expect a body. This is used when receiving a response to a * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: * chunked' headers that indicate the presence of a body. * * Returning `2` from on_headers_complete will tell parser that it should not * expect neither a body nor any futher responses on this connection. This is * useful for handling responses to a CONNECT request which may not contain * `Upgrade` or `Connection: upgrade` headers. * * http_data_cb does not return data chunks. It will be called arbitrarily * many times for each string. E.G. you might get 10 callbacks for "on_url" * each providing just a few characters more data. */ typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); typedef int (*http_cb) (http_parser*); /* Flag values for http_parser.flags field */ enum flags { F_CHUNKED = 1 << 0 , F_CONNECTION_KEEP_ALIVE = 1 << 1 , F_CONNECTION_CLOSE = 1 << 2 , F_CONNECTION_UPGRADE = 1 << 3 , F_TRAILING = 1 << 4 , F_UPGRADE = 1 << 5 , F_SKIPBODY = 1 << 6 , F_CONTENTLENGTH = 1 << 7 }; /* Map for errno-related constants * * The provided argument should be a macro that takes 2 arguments. */ #define HTTP_ERRNO_MAP(XX) \ /* No error */ \ XX(OK, "success") \ \ /* Callback-related errors */ \ XX(CB_message_begin, "the on_message_begin callback failed") \ XX(CB_url, "the on_url callback failed") \ XX(CB_header_field, "the on_header_field callback failed") \ XX(CB_header_value, "the on_header_value callback failed") \ XX(CB_headers_complete, "the on_headers_complete callback failed") \ XX(CB_body, "the on_body callback failed") \ XX(CB_message_complete, "the on_message_complete callback failed") \ XX(CB_status, "the on_status callback failed") \ XX(CB_chunk_header, "the on_chunk_header callback failed") \ XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ \ /* Parsing-related errors */ \ XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ XX(HEADER_OVERFLOW, \ "too many header bytes seen; overflow detected") \ XX(CLOSED_CONNECTION, \ "data received after completed connection: close message") \ XX(INVALID_VERSION, "invalid HTTP version") \ XX(INVALID_STATUS, "invalid HTTP status code") \ XX(INVALID_METHOD, "invalid HTTP method") \ XX(INVALID_URL, "invalid URL") \ XX(INVALID_HOST, "invalid host") \ XX(INVALID_PORT, "invalid port") \ XX(INVALID_PATH, "invalid path") \ XX(INVALID_QUERY_STRING, "invalid query string") \ XX(INVALID_FRAGMENT, "invalid fragment") \ XX(LF_EXPECTED, "LF character expected") \ XX(INVALID_HEADER_TOKEN, "invalid character in header") \ XX(INVALID_CONTENT_LENGTH, \ "invalid character in content-length header") \ XX(UNEXPECTED_CONTENT_LENGTH, \ "unexpected content-length header") \ XX(INVALID_CHUNK_SIZE, \ "invalid character in chunk size header") \ XX(INVALID_CONSTANT, "invalid constant string") \ XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\ XX(STRICT, "strict mode assertion failed") \ XX(PAUSED, "parser is paused") \ XX(UNKNOWN, "an unknown error occurred") /* Define HPE_* values for each errno value above */ #define HTTP_ERRNO_GEN(n, s) HPE_##n, enum http_errno { HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) }; #undef HTTP_ERRNO_GEN /* Get an http_errno value from an http_parser */ #define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno) struct http_parser { /** PRIVATE **/ unsigned int type : 2; /* enum http_parser_type */ unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */ unsigned int state : 7; /* enum state from http_parser.c */ unsigned int header_state : 7; /* enum header_state from http_parser.c */ unsigned int index : 7; /* index into current matcher */ unsigned int lenient_http_headers : 1; uint32_t nread; /* # bytes read in various scenarios */ uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ /** READ-ONLY **/ unsigned short http_major; unsigned short http_minor; unsigned int status_code : 16; /* responses only */ unsigned int method : 8; /* requests only */ unsigned int http_errno : 7; /* 1 = Upgrade header was present and the parser has exited because of that. * 0 = No upgrade header present. * Should be checked when http_parser_execute() returns in addition to * error checking. */ unsigned int upgrade : 1; /** PUBLIC **/ void *data; /* A pointer to get hook to the "connection" or "socket" object */ }; struct http_parser_settings { http_cb on_message_begin; http_data_cb on_url; http_data_cb on_status; http_data_cb on_header_field; http_data_cb on_header_value; http_cb on_headers_complete; http_data_cb on_body; http_cb on_message_complete; /* When on_chunk_header is called, the current chunk length is stored * in parser->content_length. */ http_cb on_chunk_header; http_cb on_chunk_complete; }; #ifdef WITH_HTTP_PRASER_URL enum http_parser_url_fields { UF_SCHEMA = 0 , UF_HOST = 1 , UF_PORT = 2 , UF_PATH = 3 , UF_QUERY = 4 , UF_FRAGMENT = 5 , UF_USERINFO = 6 , UF_MAX = 7 }; /* Result structure for http_parser_parse_url(). * * Callers should index into field_data[] with UF_* values iff field_set * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and * because we probably have padding left over), we convert any port to * a uint16_t. */ struct http_parser_url { uint16_t field_set; /* Bitmask of (1 << UF_*) values */ uint16_t port; /* Converted UF_PORT string */ struct { uint16_t off; /* Offset into buffer in which field starts */ uint16_t len; /* Length of run in buffer */ } field_data[UF_MAX]; }; #endif /* Returns the library version. Bits 16-23 contain the major version number, * bits 8-15 the minor version number and bits 0-7 the patch level. * Usage example: * * unsigned long version = http_parser_version(); * unsigned major = (version >> 16) & 255; * unsigned minor = (version >> 8) & 255; * unsigned patch = version & 255; * printf("http_parser v%u.%u.%u\n", major, minor, patch); */ unsigned long http_parser_version(void); void http_parser_init(http_parser *parser, enum http_parser_type type); /* Initialize http_parser_settings members to 0 */ void http_parser_settings_init(http_parser_settings *settings); /* Executes the parser. Returns number of parsed bytes. Sets * `parser->http_errno` on error. */ size_t http_parser_execute(http_parser *parser, const http_parser_settings *settings, const char *data, size_t len); /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns 0, then this should be * the last message on the connection. * If you are the server, respond with the "Connection: close" header. * If you are the client, close the connection. */ int http_should_keep_alive(const http_parser *parser); /* Return a string name of the given error */ const char *http_errno_name(enum http_errno err); /* Return a string description of the given error */ const char *http_errno_description(enum http_errno err); #ifdef WITH_HTTP_PRASER_URL /* Initialize all http_parser_url members to 0 */ void http_parser_url_init(struct http_parser_url *u); /* Parse a URL; return nonzero on failure */ int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u); #endif /* Pause or un-pause the parser; a nonzero value pauses */ void http_parser_pause(http_parser *parser, int paused); /* Checks if this is the final chunk of the body. */ int http_body_is_final(const http_parser *parser); /* Change the maximum header size provided at compile time. */ void http_parser_set_max_header_size(uint32_t size); #ifdef __cplusplus } #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/httpdef.c000066400000000000000000000046741520575453600262410ustar00rootroot00000000000000#include "httpdef.h" #include static int strstartswith(const char* str, const char* start) { while (*str && *start && *str == *start) { ++str; ++start; } return *start == '\0'; } const char* http_status_str(enum http_status status) { switch (status) { #define XX(num, name, string) case HTTP_STATUS_##name: return #string; HTTP_STATUS_MAP(XX) #undef XX default: return ""; } } const char* http_method_str(enum http_method method) { switch (method) { #define XX(num, name, string) case HTTP_##name: return #string; HTTP_METHOD_MAP(XX) #undef XX default: return ""; } } const char* http_content_type_str(enum http_content_type type) { switch (type) { #define XX(name, string, suffix) case name: return #string; HTTP_CONTENT_TYPE_MAP(XX) #undef XX default: return ""; } } enum http_status http_status_enum(const char* str) { #define XX(num, name, string) \ if (strcmp(str, #string) == 0) { \ return HTTP_STATUS_##name; \ } HTTP_STATUS_MAP(XX) #undef XX return HTTP_CUSTOM_STATUS; } enum http_method http_method_enum(const char* str) { #define XX(num, name, string) \ if (strcmp(str, #string) == 0) { \ return HTTP_##name; \ } HTTP_METHOD_MAP(XX) #undef XX return HTTP_CUSTOM_METHOD; } enum http_content_type http_content_type_enum(const char* str) { if (!str || !*str) { return CONTENT_TYPE_NONE; } #define XX(name, string, suffix) \ if (strstartswith(str, #string)) { \ return name; \ } HTTP_CONTENT_TYPE_MAP(XX) #undef XX return CONTENT_TYPE_UNDEFINED; } const char* http_content_type_suffix(enum http_content_type type) { switch (type) { #define XX(name, string, suffix) case name: return #suffix; HTTP_CONTENT_TYPE_MAP(XX) #undef XX default: return ""; } } const char* http_content_type_str_by_suffix(const char* str) { if (!str || !*str) { return ""; } #define XX(name, string, suffix) \ if (strcmp(str, #suffix) == 0) { \ return #string; \ } HTTP_CONTENT_TYPE_MAP(XX) #undef XX return ""; } enum http_content_type http_content_type_enum_by_suffix(const char* str) { if (!str || !*str) { return CONTENT_TYPE_NONE; } #define XX(name, string, suffix) \ if (strcmp(str, #suffix) == 0) { \ return name; \ } HTTP_CONTENT_TYPE_MAP(XX) #undef XX return CONTENT_TYPE_UNDEFINED; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/httpdef.h000066400000000000000000000342761520575453600262470ustar00rootroot00000000000000#ifndef HV_HTTP_DEF_H_ #define HV_HTTP_DEF_H_ #include "hexport.h" #define DEFAULT_HTTP_PORT 80 #define DEFAULT_HTTPS_PORT 443 enum http_version { HTTP_V1 = 1, HTTP_V2 = 2 }; enum http_session_type { HTTP_CLIENT, HTTP_SERVER }; enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; enum http_parser_state { HP_START_REQ_OR_RES, HP_MESSAGE_BEGIN, HP_URL, HP_STATUS, HP_HEADER_FIELD, HP_HEADER_VALUE, HP_HEADERS_COMPLETE, HP_CHUNK_HEADER, HP_BODY, HP_CHUNK_COMPLETE, HP_MESSAGE_COMPLETE, HP_ERROR }; // http_status // XX(num, name, string) #define HTTP_STATUS_MAP(XX) \ XX(100, CONTINUE, Continue) \ XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ XX(102, PROCESSING, Processing) \ XX(200, OK, OK) \ XX(201, CREATED, Created) \ XX(202, ACCEPTED, Accepted) \ XX(203, NON_AUTHORITATIVE_INFORMATION, Non-Authoritative Information) \ XX(204, NO_CONTENT, No Content) \ XX(205, RESET_CONTENT, Reset Content) \ XX(206, PARTIAL_CONTENT, Partial Content) \ XX(207, MULTI_STATUS, Multi-Status) \ XX(208, ALREADY_REPORTED, Already Reported) \ XX(226, IM_USED, IM Used) \ XX(300, MULTIPLE_CHOICES, Multiple Choices) \ XX(301, MOVED_PERMANENTLY, Moved Permanently) \ XX(302, FOUND, Found) \ XX(303, SEE_OTHER, See Other) \ XX(304, NOT_MODIFIED, Not Modified) \ XX(305, USE_PROXY, Use Proxy) \ XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ XX(400, BAD_REQUEST, Bad Request) \ XX(401, UNAUTHORIZED, Unauthorized) \ XX(402, PAYMENT_REQUIRED, Payment Required) \ XX(403, FORBIDDEN, Forbidden) \ XX(404, NOT_FOUND, Not Found) \ XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ XX(406, NOT_ACCEPTABLE, Not Acceptable) \ XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ XX(408, REQUEST_TIMEOUT, Request Timeout) \ XX(409, CONFLICT, Conflict) \ XX(410, GONE, Gone) \ XX(411, LENGTH_REQUIRED, Length Required) \ XX(412, PRECONDITION_FAILED, Precondition Failed) \ XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ XX(414, URI_TOO_LONG, URI Too Long) \ XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ XX(417, EXPECTATION_FAILED, Expectation Failed) \ XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ XX(423, LOCKED, Locked) \ XX(424, FAILED_DEPENDENCY, Failed Dependency) \ XX(426, UPGRADE_REQUIRED, Upgrade Required) \ XX(428, PRECONDITION_REQUIRED, Precondition Required) \ XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ XX(501, NOT_IMPLEMENTED, Not Implemented) \ XX(502, BAD_GATEWAY, Bad Gateway) \ XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ XX(508, LOOP_DETECTED, Loop Detected) \ XX(510, NOT_EXTENDED, Not Extended) \ XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) \ // HTTP_STATUS_##name enum http_status { #define XX(num, name, string) HTTP_STATUS_##name = num, HTTP_STATUS_MAP(XX) #undef XX HTTP_CUSTOM_STATUS }; #define HTTP_STATUS_IS_REDIRECT(status) \ ( \ (status) == HTTP_STATUS_MOVED_PERMANENTLY || \ (status) == HTTP_STATUS_FOUND || \ (status) == HTTP_STATUS_SEE_OTHER || \ (status) == HTTP_STATUS_TEMPORARY_REDIRECT || \ (status) == HTTP_STATUS_PERMANENT_REDIRECT \ ) // http_mehtod // XX(num, name, string) #define HTTP_METHOD_MAP(XX) \ XX(0, DELETE, DELETE) \ XX(1, GET, GET) \ XX(2, HEAD, HEAD) \ XX(3, POST, POST) \ XX(4, PUT, PUT) \ /* pathological */ \ XX(5, CONNECT, CONNECT) \ XX(6, OPTIONS, OPTIONS) \ XX(7, TRACE, TRACE) \ /* WebDAV */ \ XX(8, COPY, COPY) \ XX(9, LOCK, LOCK) \ XX(10, MKCOL, MKCOL) \ XX(11, MOVE, MOVE) \ XX(12, PROPFIND, PROPFIND) \ XX(13, PROPPATCH, PROPPATCH) \ XX(14, SEARCH, SEARCH) \ XX(15, UNLOCK, UNLOCK) \ XX(16, BIND, BIND) \ XX(17, REBIND, REBIND) \ XX(18, UNBIND, UNBIND) \ XX(19, ACL, ACL) \ /* subversion */ \ XX(20, REPORT, REPORT) \ XX(21, MKACTIVITY, MKACTIVITY) \ XX(22, CHECKOUT, CHECKOUT) \ XX(23, MERGE, MERGE) \ /* upnp */ \ XX(24, MSEARCH, M-SEARCH) \ XX(25, NOTIFY, NOTIFY) \ XX(26, SUBSCRIBE, SUBSCRIBE) \ XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ /* RFC-5789 */ \ XX(28, PATCH, PATCH) \ XX(29, PURGE, PURGE) \ /* CalDAV */ \ XX(30, MKCALENDAR, MKCALENDAR) \ /* RFC-2068, section 19.6.1.2 */ \ XX(31, LINK, LINK) \ XX(32, UNLINK, UNLINK) \ /* icecast */ \ XX(33, SOURCE, SOURCE) \ // HTTP_##name enum http_method { #define XX(num, name, string) HTTP_##name = num, HTTP_METHOD_MAP(XX) #undef XX HTTP_CUSTOM_METHOD }; // MIME: https://www.iana.org/assignments/media-types/media-types.xhtml // XX(name, mime, suffix) #define MIME_TYPE_TEXT_MAP(XX) \ XX(TEXT_PLAIN, text/plain, txt) \ XX(TEXT_HTML, text/html, html) \ XX(TEXT_CSS, text/css, css) \ XX(TEXT_CSV, text/csv, csv) \ XX(TEXT_MARKDOWN, text/markdown, md) \ XX(TEXT_EVENT_STREAM, text/event-stream, sse) \ #define MIME_TYPE_APPLICATION_MAP(XX) \ XX(APPLICATION_JAVASCRIPT, application/javascript, js) \ XX(APPLICATION_JSON, application/json, json) \ XX(APPLICATION_XML, application/xml, xml) \ XX(APPLICATION_URLENCODED, application/x-www-form-urlencoded, kv) \ XX(APPLICATION_OCTET_STREAM,application/octet-stream, bin) \ XX(APPLICATION_ZIP, application/zip, zip) \ XX(APPLICATION_GZIP, application/gzip, gzip) \ XX(APPLICATION_7Z, application/x-7z-compressed, 7z) \ XX(APPLICATION_RAR, application/x-rar-compressed, rar) \ XX(APPLICATION_PDF, application/pdf, pdf) \ XX(APPLICATION_RTF, application/rtf, rtf) \ XX(APPLICATION_GRPC, application/grpc, grpc) \ XX(APPLICATION_WASM, application/wasm, wasm) \ XX(APPLICATION_JAR, application/java-archive, jar) \ XX(APPLICATION_XHTML, application/xhtml+xml, xhtml) \ XX(APPLICATION_ATOM, application/atom+xml, atom) \ XX(APPLICATION_RSS, application/rss+xml, rss) \ XX(APPLICATION_WORD, application/msword, doc) \ XX(APPLICATION_EXCEL, application/vnd.ms-excel, xls) \ XX(APPLICATION_PPT, application/vnd.ms-powerpoint, ppt) \ XX(APPLICATION_EOT, application/vnd.ms-fontobject, eot) \ XX(APPLICATION_M3U8, application/vnd.apple.mpegurl, m3u8) \ XX(APPLICATION_DOCX, application/vnd.openxmlformats-officedocument.wordprocessingml.document, docx) \ XX(APPLICATION_XLSX, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, xlsx) \ XX(APPLICATION_PPTX, application/vnd.openxmlformats-officedocument.presentationml.presentation, pptx) \ #define MIME_TYPE_MULTIPART_MAP(XX) \ XX(MULTIPART_FORM_DATA, multipart/form-data, mp) \ #define MIME_TYPE_IMAGE_MAP(XX) \ XX(IMAGE_JPEG, image/jpeg, jpg) \ XX(IMAGE_PNG, image/png, png) \ XX(IMAGE_GIF, image/gif, gif) \ XX(IMAGE_ICO, image/x-icon, ico) \ XX(IMAGE_BMP, image/x-ms-bmp, bmp) \ XX(IMAGE_SVG, image/svg+xml, svg) \ XX(IMAGE_TIFF, image/tiff, tiff) \ XX(IMAGE_WEBP, image/webp, webp) \ #define MIME_TYPE_VIDEO_MAP(XX) \ XX(VIDEO_MP4, video/mp4, mp4) \ XX(VIDEO_FLV, video/x-flv, flv) \ XX(VIDEO_M4V, video/x-m4v, m4v) \ XX(VIDEO_MNG, video/x-mng, mng) \ XX(VIDEO_TS, video/mp2t, ts) \ XX(VIDEO_MPEG, video/mpeg, mpeg) \ XX(VIDEO_WEBM, video/webm, webm) \ XX(VIDEO_MOV, video/quicktime, mov) \ XX(VIDEO_3GPP, video/3gpp, 3gpp) \ XX(VIDEO_AVI, video/x-msvideo, avi) \ XX(VIDEO_WMV, video/x-ms-wmv, wmv) \ XX(VIDEO_ASF, video/x-ms-asf, asf) \ #define MIME_TYPE_AUDIO_MAP(XX) \ XX(AUDIO_MP3, audio/mpeg, mp3) \ XX(AUDIO_OGG, audio/ogg, ogg) \ XX(AUDIO_M4A, audio/x-m4a, m4a) \ XX(AUDIO_AAC, audio/aac, aac) \ XX(AUDIO_PCMA, audio/PCMA, pcma) \ XX(AUDIO_OPUS, audio/opus, opus) \ #define MIME_TYPE_FONT_MAP(XX) \ XX(FONT_TTF, font/ttf, ttf) \ XX(FONT_OTF, font/otf, otf) \ XX(FONT_WOFF, font/woff, woff) \ XX(FONT_WOFF2, font/woff2, woff2) \ #define HTTP_CONTENT_TYPE_MAP(XX) \ MIME_TYPE_TEXT_MAP(XX) \ MIME_TYPE_APPLICATION_MAP(XX) \ MIME_TYPE_MULTIPART_MAP(XX) \ MIME_TYPE_IMAGE_MAP(XX) \ MIME_TYPE_VIDEO_MAP(XX) \ MIME_TYPE_AUDIO_MAP(XX) \ MIME_TYPE_FONT_MAP(XX) \ #define X_WWW_FORM_URLENCODED APPLICATION_URLENCODED // for compatibility enum http_content_type { #define XX(name, string, suffix) name, CONTENT_TYPE_NONE = 0, CONTENT_TYPE_TEXT = 100, MIME_TYPE_TEXT_MAP(XX) CONTENT_TYPE_APPLICATION = 200, MIME_TYPE_APPLICATION_MAP(XX) CONTENT_TYPE_MULTIPART = 300, MIME_TYPE_MULTIPART_MAP(XX) CONTENT_TYPE_IMAGE = 400, MIME_TYPE_IMAGE_MAP(XX) CONTENT_TYPE_VIDEO = 500, MIME_TYPE_VIDEO_MAP(XX) CONTENT_TYPE_AUDIO = 600, MIME_TYPE_AUDIO_MAP(XX) CONTENT_TYPE_FONT = 700, MIME_TYPE_FONT_MAP(XX) CONTENT_TYPE_UNDEFINED = 1000 #undef XX }; BEGIN_EXTERN_C HV_EXPORT const char* http_status_str(enum http_status status); HV_EXPORT const char* http_method_str(enum http_method method); HV_EXPORT const char* http_content_type_str(enum http_content_type type); HV_EXPORT enum http_status http_status_enum(const char* str); HV_EXPORT enum http_method http_method_enum(const char* str); HV_EXPORT enum http_content_type http_content_type_enum(const char* str); HV_EXPORT const char* http_content_type_suffix(enum http_content_type type); HV_EXPORT const char* http_content_type_str_by_suffix(const char* suffix); HV_EXPORT enum http_content_type http_content_type_enum_by_suffix(const char* suffix); END_EXTERN_C #endif // HV_HTTP_DEF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/multipart_parser.c000066400000000000000000000175141520575453600301750ustar00rootroot00000000000000/* Based on node-formidable by Felix Geisendörfer * Igor Afonov - afonov@gmail.com - 2012 * MIT License - http://www.opensource.org/licenses/mit-license.php */ #include "multipart_parser.h" #include #include #include static void multipart_log(const char * format, ...) { #ifdef DEBUG_MULTIPART va_list args; va_start(args, format); fprintf(stderr, "[HTTP_MULTIPART_PARSER] %s:%d: ", __FILE__, __LINE__); vfprintf(stderr, format, args); fprintf(stderr, "\n"); va_end(args); #endif } #define NOTIFY_CB(FOR) \ do { \ if (p->settings->on_##FOR) { \ if (p->settings->on_##FOR(p) != 0) { \ return i; \ } \ } \ } while (0) #define EMIT_DATA_CB(FOR, ptr, len) \ do { \ if (p->settings->on_##FOR) { \ if (p->settings->on_##FOR(p, ptr, len) != 0) { \ return i; \ } \ } \ } while (0) #define LF 10 #define CR 13 struct multipart_parser { void * data; size_t index; size_t boundary_length; unsigned char state; const multipart_parser_settings* settings; char* lookbehind; char multipart_boundary[1]; }; enum state { s_uninitialized = 1, s_start, s_start_boundary, s_header_field_start, s_header_field, s_headers_almost_done, s_header_value_start, s_header_value, s_header_value_almost_done, s_part_data_start, s_part_data, s_part_data_almost_boundary, s_part_data_boundary, s_part_data_almost_end, s_part_data_end, s_part_data_final_hyphen, s_end }; multipart_parser* multipart_parser_init (const char *boundary, const multipart_parser_settings* settings) { multipart_parser* p = (multipart_parser*)malloc(sizeof(multipart_parser) + strlen(boundary) + strlen(boundary) + 9); strcpy(p->multipart_boundary, boundary); p->boundary_length = strlen(boundary); p->lookbehind = (p->multipart_boundary + p->boundary_length + 1); p->index = 0; p->state = s_start; p->settings = settings; return p; } void multipart_parser_free(multipart_parser* p) { free(p); } void multipart_parser_set_data(multipart_parser *p, void *data) { p->data = data; } void *multipart_parser_get_data(multipart_parser *p) { return p->data; } size_t multipart_parser_execute(multipart_parser* p, const char *buf, size_t len) { size_t i = 0; size_t mark = 0; char c, cl; int is_last = 0; while(i < len) { c = buf[i]; is_last = (i == (len - 1)); switch (p->state) { case s_start: multipart_log("s_start"); p->index = 0; p->state = s_start_boundary; /* fallthrough */ case s_start_boundary: multipart_log("s_start_boundary"); if (p->index == p->boundary_length) { if (c != CR) { return i; } p->index++; break; } else if (p->index == (p->boundary_length + 1)) { if (c != LF) { return i; } p->index = 0; NOTIFY_CB(part_data_begin); p->state = s_header_field_start; break; } if (c != p->multipart_boundary[p->index]) { return i; } p->index++; break; case s_header_field_start: multipart_log("s_header_field_start"); mark = i; p->state = s_header_field; /* fallthrough */ case s_header_field: multipart_log("s_header_field"); if (c == CR) { p->state = s_headers_almost_done; break; } if (c == ':') { EMIT_DATA_CB(header_field, buf + mark, i - mark); p->state = s_header_value_start; break; } cl = tolower(c); if ((c != '-') && (cl < 'a' || cl > 'z')) { multipart_log("invalid character in header name"); return i; } if (is_last) EMIT_DATA_CB(header_field, buf + mark, (i - mark) + 1); break; case s_headers_almost_done: multipart_log("s_headers_almost_done"); if (c != LF) { return i; } p->state = s_part_data_start; break; case s_header_value_start: multipart_log("s_header_value_start"); if (c == ' ') { break; } mark = i; p->state = s_header_value; /* fallthrough */ case s_header_value: multipart_log("s_header_value"); if (c == CR) { EMIT_DATA_CB(header_value, buf + mark, i - mark); p->state = s_header_value_almost_done; break; } if (is_last) EMIT_DATA_CB(header_value, buf + mark, (i - mark) + 1); break; case s_header_value_almost_done: multipart_log("s_header_value_almost_done"); if (c != LF) { return i; } p->state = s_header_field_start; break; case s_part_data_start: multipart_log("s_part_data_start"); NOTIFY_CB(headers_complete); mark = i; p->state = s_part_data; /* fallthrough */ case s_part_data: multipart_log("s_part_data"); if (c == CR) { EMIT_DATA_CB(part_data, buf + mark, i - mark); mark = i; p->state = s_part_data_almost_boundary; p->lookbehind[0] = CR; break; } if (is_last) EMIT_DATA_CB(part_data, buf + mark, (i - mark) + 1); break; case s_part_data_almost_boundary: multipart_log("s_part_data_almost_boundary"); if (c == LF) { p->state = s_part_data_boundary; p->lookbehind[1] = LF; p->index = 0; break; } EMIT_DATA_CB(part_data, p->lookbehind, 1); p->state = s_part_data; mark = i --; break; case s_part_data_boundary: multipart_log("s_part_data_boundary"); if (p->multipart_boundary[p->index] != c) { EMIT_DATA_CB(part_data, p->lookbehind, 2 + p->index); p->state = s_part_data; mark = i --; break; } p->lookbehind[2 + p->index] = c; if ((++ p->index) == p->boundary_length) { NOTIFY_CB(part_data_end); p->state = s_part_data_almost_end; } break; case s_part_data_almost_end: multipart_log("s_part_data_almost_end"); if (c == '-') { p->state = s_part_data_final_hyphen; break; } if (c == CR) { p->state = s_part_data_end; break; } return i; case s_part_data_final_hyphen: multipart_log("s_part_data_final_hyphen"); if (c == '-') { NOTIFY_CB(body_end); p->state = s_end; break; } return i; case s_part_data_end: multipart_log("s_part_data_end"); if (c == LF) { p->state = s_header_field_start; NOTIFY_CB(part_data_begin); break; } return i; case s_end: multipart_log("s_end: %02X", (int) c); break; default: multipart_log("Multipart parser unrecoverable error"); return 0; } ++ i; } return len; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/multipart_parser.h000066400000000000000000000025111520575453600301710ustar00rootroot00000000000000/* Based on node-formidable by Felix Geisendörfer * Igor Afonov - afonov@gmail.com - 2012 * MIT License - http://www.opensource.org/licenses/mit-license.php */ #ifndef _multipart_parser_h #define _multipart_parser_h #ifdef __cplusplus extern "C" { #endif #include #include typedef struct multipart_parser multipart_parser; typedef struct multipart_parser_settings multipart_parser_settings; typedef struct multipart_parser_state multipart_parser_state; typedef int (*multipart_data_cb) (multipart_parser*, const char *at, size_t length); typedef int (*multipart_notify_cb) (multipart_parser*); struct multipart_parser_settings { multipart_data_cb on_header_field; multipart_data_cb on_header_value; multipart_data_cb on_part_data; multipart_notify_cb on_part_data_begin; multipart_notify_cb on_headers_complete; multipart_notify_cb on_part_data_end; multipart_notify_cb on_body_end; }; multipart_parser* multipart_parser_init (const char *boundary, const multipart_parser_settings* settings); void multipart_parser_free(multipart_parser* p); size_t multipart_parser_execute(multipart_parser* p, const char *buf, size_t len); void multipart_parser_set_data(multipart_parser* p, void* data); void * multipart_parser_get_data(multipart_parser* p); #ifdef __cplusplus } /* extern "C" */ #endif #endif kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/000077500000000000000000000000001520575453600257325ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/FileCache.cpp000066400000000000000000000124251520575453600302450ustar00rootroot00000000000000#include "FileCache.h" #include "herr.h" #include "hscope.h" #include "htime.h" #include "hlog.h" #include "httpdef.h" // import http_content_type_str_by_suffix #include "http_page.h" // import make_index_of_page #ifdef _MSC_VER #include #endif #define ETAG_FMT "\"%zx-%zx\"" FileCache::FileCache() { stat_interval = 10; // s expired_time = 60; // s } static int hv_open(char const* filepath, int flags) { #ifdef _MSC_VER std::wstring_convert> conv; auto wfilepath = conv.from_bytes(filepath); int fd = _wopen(wfilepath.c_str(), flags); #else int fd = open(filepath, flags); #endif return fd; } file_cache_ptr FileCache::Open(const char* filepath, OpenParam* param) { std::lock_guard locker(mutex_); file_cache_ptr fc = Get(filepath); bool modified = false; if (fc) { time_t now = time(NULL); if (now - fc->stat_time > stat_interval) { modified = fc->is_modified(); fc->stat_time = now; fc->stat_cnt++; } if (param->need_read) { if (!modified && fc->is_complete()) { param->need_read = false; } } } if (fc == NULL || modified || param->need_read) { int flags = O_RDONLY; #ifdef O_BINARY flags |= O_BINARY; #endif int fd = hv_open(filepath, flags); if (fd < 0) { #ifdef OS_WIN // NOTE: open(dir) return -1 on windows if (!hv_isdir(filepath)) { param->error = ERR_OPEN_FILE; return NULL; } #else param->error = ERR_OPEN_FILE; return NULL; #endif } defer(if (fd > 0) { close(fd); }) if (fc == NULL) { struct stat st; if (fd > 0) { fstat(fd, &st); } else { stat(filepath, &st); } if (S_ISREG(st.st_mode) || (S_ISDIR(st.st_mode) && filepath[strlen(filepath)-1] == '/')) { fc = std::make_shared(); fc->filepath = filepath; fc->st = st; time(&fc->open_time); fc->stat_time = fc->open_time; fc->stat_cnt = 1; cached_files[filepath] = fc; } else { param->error = ERR_MISMATCH; return NULL; } } if (S_ISREG(fc->st.st_mode)) { param->filesize = fc->st.st_size; // FILE if (param->need_read) { if (fc->st.st_size > param->max_read) { param->error = ERR_OVER_LIMIT; return NULL; } fc->resize_buf(fc->st.st_size); int nread = read(fd, fc->filebuf.base, fc->filebuf.len); if (nread != fc->filebuf.len) { hloge("Failed to read file: %s", filepath); param->error = ERR_READ_FILE; return NULL; } } const char* suffix = strrchr(filepath, '.'); if (suffix) { http_content_type content_type = http_content_type_enum_by_suffix(suffix+1); if (content_type == TEXT_HTML) { fc->content_type = "text/html; charset=utf-8"; } else if (content_type == TEXT_PLAIN) { fc->content_type = "text/plain; charset=utf-8"; } else { fc->content_type = http_content_type_str_by_suffix(suffix+1); } } } else if (S_ISDIR(fc->st.st_mode)) { // DIR std::string page; make_index_of_page(filepath, page, param->path); fc->resize_buf(page.size()); memcpy(fc->filebuf.base, page.c_str(), page.size()); fc->content_type = "text/html; charset=utf-8"; } gmtime_fmt(fc->st.st_mtime, fc->last_modified); snprintf(fc->etag, sizeof(fc->etag), ETAG_FMT, (size_t)fc->st.st_mtime, (size_t)fc->st.st_size); } return fc; } bool FileCache::Close(const char* filepath) { std::lock_guard locker(mutex_); auto iter = cached_files.find(filepath); if (iter != cached_files.end()) { iter = cached_files.erase(iter); return true; } return false; } bool FileCache::Close(const file_cache_ptr& fc) { std::lock_guard locker(mutex_); auto iter = cached_files.begin(); while (iter != cached_files.end()) { if (iter->second == fc) { iter = cached_files.erase(iter); return true; } else { ++iter; } } return false; } file_cache_ptr FileCache::Get(const char* filepath) { auto iter = cached_files.find(filepath); if (iter != cached_files.end()) { return iter->second; } return NULL; } void FileCache::RemoveExpiredFileCache() { std::lock_guard locker(mutex_); time_t now = time(NULL); auto iter = cached_files.begin(); while (iter != cached_files.end()) { if (now - iter->second->stat_time > expired_time) { iter = cached_files.erase(iter); } else { ++iter; } } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/FileCache.h000066400000000000000000000043221520575453600277070ustar00rootroot00000000000000#ifndef HV_FILE_CACHE_H_ #define HV_FILE_CACHE_H_ #include #include #include #include #include "hbuf.h" #include "hstring.h" #define HTTP_HEADER_MAX_LENGTH 1024 // 1K #define FILE_CACHE_MAX_SIZE (1 << 22) // 4M typedef struct file_cache_s { std::string filepath; struct stat st; time_t open_time; time_t stat_time; uint32_t stat_cnt; HBuf buf; // http_header + file_content hbuf_t filebuf; hbuf_t httpbuf; char last_modified[64]; char etag[64]; std::string content_type; file_cache_s() { stat_cnt = 0; } bool is_modified() { time_t mtime = st.st_mtime; stat(filepath.c_str(), &st); return mtime != st.st_mtime; } bool is_complete() { return filebuf.len == st.st_size; } void resize_buf(int filesize) { buf.resize(HTTP_HEADER_MAX_LENGTH + filesize); filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH; filebuf.len = filesize; } void prepend_header(const char* header, int len) { if (len > HTTP_HEADER_MAX_LENGTH) return; httpbuf.base = filebuf.base - len; httpbuf.len = len + filebuf.len; memcpy(httpbuf.base, header, len); } } file_cache_t; typedef std::shared_ptr file_cache_ptr; // filepath => file_cache_ptr typedef std::map FileCacheMap; class FileCache { public: FileCacheMap cached_files; std::mutex mutex_; int stat_interval; int expired_time; FileCache(); struct OpenParam { bool need_read; int max_read; const char* path; size_t filesize; int error; OpenParam() { need_read = true; max_read = FILE_CACHE_MAX_SIZE; path = "/"; filesize = 0; error = 0; } }; file_cache_ptr Open(const char* filepath, OpenParam* param); bool Close(const char* filepath); bool Close(const file_cache_ptr& fc); void RemoveExpiredFileCache(); protected: file_cache_ptr Get(const char* filepath); }; #endif // HV_FILE_CACHE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpContext.h000066400000000000000000000120331520575453600303660ustar00rootroot00000000000000#ifndef HV_HTTP_CONTEXT_H_ #define HV_HTTP_CONTEXT_H_ #include "hexport.h" #include "HttpMessage.h" #include "HttpResponseWriter.h" namespace hv { struct HttpService; struct HV_EXPORT HttpContext { HttpService* service; HttpRequestPtr request; HttpResponsePtr response; HttpResponseWriterPtr writer; void* userdata; HttpContext() { service = NULL; userdata = NULL; } // HttpRequest aliases // return request->xxx std::string ip() { return request->client_addr.ip; } int port() { return request->client_addr.port; } http_method method() { return request->method; } std::string url() { return request->url; } std::string path() { return request->Path(); } std::string fullpath() { return request->FullPath(); } std::string host() { return request->Host(); } const http_headers& headers() { return request->headers; } std::string header(const char* key, const std::string& defvalue = hv::empty_string) { return request->GetHeader(key, defvalue); } const hv::QueryParams& params() { return request->query_params; } std::string param(const char* key, const std::string& defvalue = hv::empty_string) { return request->GetParam(key, defvalue); } const HttpCookie& cookie(const char* name) { return request->GetCookie(name); } int length() { return request->ContentLength(); } http_content_type type() { return request->ContentType(); } bool is(http_content_type content_type) { return request->ContentType() == content_type; } bool is(const char* content_type) { return request->ContentType() == http_content_type_enum(content_type); } std::string& body() { return request->body; } #ifndef WITHOUT_HTTP_CONTENT // Content-Type: application/json const hv::Json& json() { return request->GetJson(); } // Content-Type: multipart/form-data const hv::MultiPart& form() { return request->GetForm(); } std::string form(const char* name, const std::string& defvalue = hv::empty_string) { return request->GetFormData(name, defvalue); } // Content-Type: application/x-www-form-urlencoded const hv::KeyValue& urlencoded() { return request->GetUrlEncoded(); } std::string urlencoded(const char* key, const std::string& defvalue = hv::empty_string) { return request->GetUrlEncoded(key, defvalue); } // T=[bool, int, int64_t, float, double] template T get(const char* key, T defvalue = 0) { return request->Get(key, defvalue); } std::string get(const char* key, const std::string& defvalue = hv::empty_string) { return request->GetString(key, defvalue); } #endif // HttpResponse aliases // response->xxx = xxx void setStatus(http_status status) { response->status_code = status; } void setContentType(http_content_type type) { response->content_type = type; } void setContentType(const char* type) { response->content_type = http_content_type_enum(type); } void setHeader(const char* key, const std::string& value) { response->SetHeader(key, value); if (stricmp(key, "Content-Type") == 0) { setContentType(value.c_str()); } } void setCookie(const HttpCookie& cookie) { response->AddCookie(cookie); } void setBody(const std::string& body) { response->body = body; } // response->sendXxx int send() { if (writer) { writer->End(); } return response->status_code; } int send(const std::string& str, http_content_type type = APPLICATION_JSON) { response->content_type = type; response->body = str; return send(); } int sendString(const std::string& str) { response->String(str); return send(); } int sendData(void* data, int len, bool nocopy = true) { response->Data(data, len, nocopy); return send(); } int sendFile(const char* filepath) { response->File(filepath); return send(); } #ifndef WITHOUT_HTTP_CONTENT // T=[bool, int, int64_t, float, double, string] template void set(const char* key, const T& value) { response->Set(key, value); } // @see HttpMessage::Json // @usage https://github.com/nlohmann/json template int sendJson(const T& t) { response->Json(t); return send(); } #endif int redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) { response->Redirect(location, status); return send(); } int close() { return writer ? writer->close(true) : -1; } }; } // end namespace hv typedef std::shared_ptr HttpContextPtr; #endif // HV_HTTP_CONTEXT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpHandler.cpp000066400000000000000000001022721520575453600306570ustar00rootroot00000000000000#include "HttpHandler.h" #include "hversion.h" #include "herr.h" #include "hlog.h" #include "htime.h" #include "hurl.h" #include "hasync.h" // import hv::async for http_async_handler #include "httpdef.h" #include "http2def.h" #include "wsdef.h" #include "http_page.h" #include "EventLoop.h" // import hv::setInterval using namespace hv; #define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n" #define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF #define HTTP_100_CONTINUE_RESPONSE "HTTP/1.1 100 Continue\r\n\r\n" #define HTTP_100_CONTINUE_RESPONSE_LEN 25 #define HTTP_200_CONNECT_RESPONSE "HTTP/1.1 200 Connection established\r\n\r\n" #define HTTP_200_CONNECT_RESPONSE_LEN 39 HttpHandler::HttpHandler(hio_t* io) : protocol(HttpHandler::UNKNOWN), state(WANT_RECV), error(0), // flags ssl(0), keepalive(1), upgrade(0), proxy(0), proxy_connected(0), forward_proxy(0), reverse_proxy(0), ip{'\0'}, port(0), pid(0), tid(0), // for http io(io), service(NULL), api_handler(NULL), // for websocket ws_service(NULL), last_send_ping_time(0), last_recv_pong_time(0), // for sendfile files(NULL), file(NULL), // for proxy proxy_port(0) { // Init(); } HttpHandler::~HttpHandler() { Close(); } bool HttpHandler::Init(int http_version) { parser.reset(HttpParser::New(HTTP_SERVER, (enum http_version)http_version)); if (parser == NULL) { return false; } req = std::make_shared(); resp = std::make_shared(); if(http_version == 1) { protocol = HTTP_V1; } else if (http_version == 2) { protocol = HTTP_V2; resp->http_major = req->http_major = 2; resp->http_minor = req->http_minor = 0; } if (io) { hloop_t* loop = hevent_loop(io); pid = hloop_pid(loop); tid = hloop_tid(loop); writer = std::make_shared(io, resp); writer->status = hv::SocketChannel::CONNECTED; } else { pid = hv_getpid(); tid = hv_gettid(); } parser->InitRequest(req.get()); // NOTE: hook http_cb req->http_cb = [this](HttpMessage* msg, http_parser_state state, const char* data, size_t size) { if (this->state == WANT_CLOSE) return; switch (state) { case HP_HEADERS_COMPLETE: if (this->error != 0) return; onHeadersComplete(); break; case HP_BODY: if (this->error != 0) return; onBody(data, size); break; case HP_MESSAGE_COMPLETE: onMessageComplete(); break; default: break; } }; return true; } void HttpHandler::Reset() { state = WANT_RECV; error = 0; req->Reset(); resp->Reset(); ctx = NULL; api_handler = NULL; closeFile(); if (writer) { writer->Begin(); writer->onwrite = NULL; writer->onclose = NULL; } parser->InitRequest(req.get()); } void HttpHandler::Close() { if (writer) { writer->status = hv::SocketChannel::DISCONNECTED; } if (api_handler && api_handler->state_handler) { if (parser && !parser->IsComplete()) { api_handler->state_handler(context(), HP_ERROR, NULL, 0); } return; } // close proxy closeProxy(); // close file closeFile(); // onclose if (protocol == HttpHandler::WEBSOCKET) { WebSocketOnClose(); } else { if (writer && writer->onclose) { writer->onclose(); } } } bool HttpHandler::SwitchHTTP2() { HttpParser* http2_parser = HttpParser::New(HTTP_SERVER, ::HTTP_V2); if (http2_parser == NULL) { return false; } parser.reset(http2_parser); protocol = HTTP_V2; resp->http_major = req->http_major = 2; resp->http_minor = req->http_minor = 0; parser->InitRequest(req.get()); return true; } bool HttpHandler::SwitchWebSocket() { if(!io) return false; protocol = WEBSOCKET; ws_parser = std::make_shared(); ws_channel = std::make_shared(io, WS_SERVER); ws_parser->onMessage = [this](int opcode, const std::string& msg){ ws_channel->opcode = (enum ws_opcode)opcode; switch(opcode) { case WS_OPCODE_CLOSE: ws_channel->send(msg, WS_OPCODE_CLOSE); ws_channel->close(); break; case WS_OPCODE_PING: // printf("recv ping\n"); // printf("send pong\n"); ws_channel->send(msg, WS_OPCODE_PONG); break; case WS_OPCODE_PONG: // printf("recv pong\n"); this->last_recv_pong_time = gethrtime_us(); break; case WS_OPCODE_TEXT: case WS_OPCODE_BINARY: // onmessage if (ws_service && ws_service->onmessage) { ws_service->onmessage(ws_channel, msg); } break; default: break; } }; // NOTE: cancel keepalive timer, judge alive by heartbeat. ws_channel->setKeepaliveTimeout(0); if (ws_service && ws_service->ping_interval > 0) { int ping_interval = MAX(ws_service->ping_interval, 1000); ws_channel->setHeartbeat(ping_interval, [this](){ if (last_recv_pong_time < last_send_ping_time) { hlogw("[%s:%d] websocket no pong!", ip, port); ws_channel->close(); } else { // printf("send ping\n"); ws_channel->sendPing(); last_send_ping_time = gethrtime_us(); } }); } return true; } const HttpContextPtr& HttpHandler::context() { if (!ctx) { ctx = std::make_shared(); ctx->service = service; ctx->request = req; ctx->response = resp; ctx->writer = writer; } return ctx; } int HttpHandler::customHttpHandler(const http_handler& handler) { return invokeHttpHandler(&handler); } int HttpHandler::invokeHttpHandler(const http_handler* handler) { int status_code = HTTP_STATUS_NOT_IMPLEMENTED; if (handler->sync_handler) { // NOTE: sync_handler run on IO thread status_code = handler->sync_handler(req.get(), resp.get()); } else if (handler->async_handler) { // NOTE: async_handler run on hv::async threadpool hv::async(std::bind(handler->async_handler, req, writer)); status_code = HTTP_STATUS_NEXT; } else if (handler->ctx_handler) { // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing. status_code = handler->ctx_handler(context()); } else if (handler->state_handler) { status_code = handler->state_handler(context(), HP_MESSAGE_COMPLETE, NULL, 0); } return status_code; } void HttpHandler::onHeadersComplete() { // printf("onHeadersComplete\n"); int status_code = handleRequestHeaders(); if (status_code != HTTP_STATUS_OK) { error = ERR_REQUEST; return; } HttpRequest* pReq = req.get(); if (service && service->pathHandlers.size() != 0) { service->GetRoute(pReq, &api_handler); } if (api_handler && api_handler->state_handler) { api_handler->state_handler(context(), HP_HEADERS_COMPLETE, NULL, 0); return; } if (proxy) { handleProxy(); return; } // Expect: 100-continue handleExpect100(); } void HttpHandler::onBody(const char* data, size_t size) { if (api_handler && api_handler->state_handler) { api_handler->state_handler(context(), HP_BODY, data, size); return; } if (proxy && proxy_connected) { if (io) hio_write_upstream(io, (void*)data, size); return; } req->body.append(data, size); return; } void HttpHandler::onMessageComplete() { // printf("onMessageComplete\n"); int status_code = HTTP_STATUS_OK; if (error) { SendHttpStatusResponse(resp->status_code); return; } if (proxy) { if (proxy_connected) Reset(); return; } addResponseHeaders(); // upgrade ? handleUpgrade : HandleHttpRequest if (upgrade) { auto iter_upgrade = req->headers.find("upgrade"); if (iter_upgrade != req->headers.end()) { handleUpgrade(iter_upgrade->second.c_str()); status_code = resp->status_code; } } else { status_code = HandleHttpRequest(); if (status_code != HTTP_STATUS_NEXT) { SendHttpResponse(); } } // access log if (service && service->enable_access_log) { hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]", pid, tid, ip, port, http_method_str(req->method), req->path.c_str(), resp->status_code, resp->status_message()); } if (status_code != HTTP_STATUS_NEXT) { // keepalive ? Reset : Close if (keepalive) { Reset(); } else { state = WANT_CLOSE; } } } int HttpHandler::handleRequestHeaders() { HttpRequest* pReq = req.get(); pReq->scheme = ssl ? "https" : "http"; pReq->client_addr.ip = ip; pReq->client_addr.port = port; // keepalive keepalive = pReq->IsKeepAlive(); // upgrade upgrade = pReq->IsUpgrade(); // proxy proxy = forward_proxy = reverse_proxy = 0; if (hv::startswith(pReq->url, "http")) { // forward proxy proxy = forward_proxy = 1; } else if (pReq->method == HTTP_CONNECT) { // proxy tunnel // CONNECT ip:port HTTP/1.1\r\n pReq->url = "https://" + pReq->url; proxy = forward_proxy = 1; keepalive = true; } // printf("url=%s\n", pReq->url.c_str()); pReq->ParseUrl(); // printf("path=%s\n", pReq->path.c_str()); // fix CVE-2023-26147 if (pReq->path.find("%") != std::string::npos) { std::string unescaped_path = HUrl::unescape(pReq->path); if (unescaped_path.find("\r\n") != std::string::npos) { hlogw("Illegal path: %s\n", unescaped_path.c_str()); resp->status_code = HTTP_STATUS_BAD_REQUEST; return resp->status_code; } } if (proxy) { // Proxy-Connection auto iter = pReq->headers.find("Proxy-Connection"); if (iter != pReq->headers.end()) { const char* keepalive_value = iter->second.c_str(); if (stricmp(keepalive_value, "keep-alive") == 0) { keepalive = true; } else if (stricmp(keepalive_value, "close") == 0) { keepalive = false; } else if (stricmp(keepalive_value, "upgrade") == 0) { keepalive = true; } } } else { // reverse proxy std::string proxy_url = service->GetProxyUrl(pReq->path.c_str()); if (!proxy_url.empty()) { pReq->url = proxy_url; proxy = reverse_proxy = 1; } } // TODO: rewrite url return HTTP_STATUS_OK; } void HttpHandler::handleExpect100() { // Expect: 100-continue auto iter = req->headers.find("Expect"); if (iter != req->headers.end() && stricmp(iter->second.c_str(), "100-continue") == 0) { if (io) hio_write(io, HTTP_100_CONTINUE_RESPONSE, HTTP_100_CONTINUE_RESPONSE_LEN); } } void HttpHandler::addResponseHeaders() { HttpResponse* pResp = resp.get(); // Server: pResp->headers["Server"] = "libhv/" HV_VERSION_STRING; // Connection: pResp->headers["Connection"] = keepalive ? "keep-alive" : "close"; } int HttpHandler::HandleHttpRequest() { // preprocessor -> middleware -> processor -> postprocessor HttpRequest* pReq = req.get(); HttpResponse* pResp = resp.get(); // NOTE: Not all users want to parse body, we comment it out. // pReq->ParseBody(); int status_code = pResp->status_code; if (status_code != HTTP_STATUS_OK) { goto postprocessor; } preprocessor: state = HANDLE_BEGIN; if (service->preprocessor) { status_code = customHttpHandler(service->preprocessor); if (status_code != HTTP_STATUS_NEXT) { goto postprocessor; } } middleware: for (const auto& middleware : service->middleware) { status_code = customHttpHandler(middleware); if (status_code != HTTP_STATUS_NEXT) { goto postprocessor; } } processor: if (service->processor) { status_code = customHttpHandler(service->processor); } else { status_code = defaultRequestHandler(); } postprocessor: if (status_code >= 100 && status_code < 600) { pResp->status_code = (http_status)status_code; if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) { if (service->errorHandler) { customHttpHandler(service->errorHandler); } else { defaultErrorHandler(); } } } if (fc) { pResp->content = fc->filebuf.base; pResp->content_length = fc->filebuf.len; pResp->headers["Content-Type"] = fc->content_type; pResp->headers["Last-Modified"] = fc->last_modified; pResp->headers["Etag"] = fc->etag; } if (service->postprocessor) { customHttpHandler(service->postprocessor); } if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) { status_code = HTTP_STATUS_NEXT; } if (status_code == HTTP_STATUS_NEXT) { state = HANDLE_CONTINUE; } else { state = HANDLE_END; } return status_code; } int HttpHandler::defaultRequestHandler() { int status_code = HTTP_STATUS_OK; if (api_handler) { status_code = invokeHttpHandler(api_handler); } else if (req->method == HTTP_GET || req->method == HTTP_HEAD) { // static handler if (service->staticHandler) { status_code = customHttpHandler(service->staticHandler); } else if (service->staticDirs.size() > 0) { status_code = defaultStaticHandler(); } else { status_code = HTTP_STATUS_NOT_FOUND; } } else { // Not Implemented status_code = HTTP_STATUS_NOT_IMPLEMENTED; } return status_code; } int HttpHandler::defaultStaticHandler() { // file service std::string path = req->Path(); const char* req_path = path.c_str(); // path safe check if (req_path[0] != '/' || strstr(req_path, "/..") || strstr(req_path, "\\..")) { return HTTP_STATUS_BAD_REQUEST; } std::string filepath; bool is_dir = path.back() == '/' && service->index_of.size() > 0 && hv_strstartswith(req_path, service->index_of.c_str()); if (is_dir) { filepath = service->document_root + path; } else { filepath = service->GetStaticFilepath(req_path); } if (filepath.empty()) { return HTTP_STATUS_NOT_FOUND; } int status_code = HTTP_STATUS_OK; // Range: bool has_range = false; long from, to = 0; if (req->GetRange(from, to)) { has_range = true; if (openFile(filepath.c_str()) != 0) { return HTTP_STATUS_NOT_FOUND; } long total = file->size(); if (to == 0 || to >= total) to = total - 1; file->seek(from); status_code = HTTP_STATUS_PARTIAL_CONTENT; resp->status_code = HTTP_STATUS_PARTIAL_CONTENT; resp->content_length = to - from + 1; resp->SetContentTypeByFilename(filepath.c_str()); resp->SetRange(from, to, total); if(resp->content_length < service->max_file_cache_size) { // read into body directly int nread = file->readrange(resp->body, from, to); closeFile(); if (nread != resp->content_length) { resp->content_length = 0; resp->body.clear(); return HTTP_STATUS_INTERNAL_SERVER_ERROR; } } else { if (service->largeFileHandler) { status_code = customHttpHandler(service->largeFileHandler); } else { status_code = defaultLargeFileHandler(); } } return status_code; } // FileCache FileCache::OpenParam param; param.max_read = service->max_file_cache_size; param.need_read = !(req->method == HTTP_HEAD || has_range); param.path = req_path; if (files) { fc = files->Open(filepath.c_str(), ¶m); } if (fc == NULL) { if (param.error == ERR_OVER_LIMIT) { if (service->largeFileHandler) { status_code = customHttpHandler(service->largeFileHandler); } else { status_code = defaultLargeFileHandler(); } } else { status_code = HTTP_STATUS_NOT_FOUND; } } else { // Not Modified auto iter = req->headers.find("if-none-match"); if (iter != req->headers.end() && strcmp(iter->second.c_str(), fc->etag) == 0) { fc = NULL; return HTTP_STATUS_NOT_MODIFIED; } iter = req->headers.find("if-modified-since"); if (iter != req->headers.end() && strcmp(iter->second.c_str(), fc->last_modified) == 0) { fc = NULL; return HTTP_STATUS_NOT_MODIFIED; } } return status_code; } int HttpHandler::defaultLargeFileHandler() { if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED; if (!isFileOpened()) { std::string filepath = service->GetStaticFilepath(req->Path().c_str()); if (filepath.empty() || openFile(filepath.c_str()) != 0) { return HTTP_STATUS_NOT_FOUND; } resp->content_length = file->size(); resp->SetContentTypeByFilename(filepath.c_str()); } if (service->limit_rate == 0) { // forbidden to send large file resp->content_length = 0; resp->status_code = HTTP_STATUS_FORBIDDEN; } else { size_t bufsize = 40960; // 40K file->buf.resize(bufsize); if (service->limit_rate < 0) { // unlimited: sendFile when writable writer->onwrite = [this](HBuf* buf) { if (writer->isWriteComplete()) { sendFile(); } }; } else { // limit_rate=40KB/s interval_ms=1000 // limit_rate=500KB/s interval_ms=80 int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate; // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps if (interval_ms == 0) interval_ms = 1; // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms); file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this)); } } writer->EndHeaders(); return HTTP_STATUS_UNFINISHED; } int HttpHandler::defaultErrorHandler() { // error page if (service->error_page.size() != 0) { std::string filepath = service->document_root + '/' + service->error_page; if (files) { // cache and load error page FileCache::OpenParam param; fc = files->Open(filepath.c_str(), ¶m); } } // status page if (fc == NULL && resp->body.size() == 0) { resp->content_type = TEXT_HTML; make_http_status_page(resp->status_code, resp->body); } return 0; } int HttpHandler::FeedRecvData(const char* data, size_t len) { if (protocol == HttpHandler::UNKNOWN) { int http_version = 1; #if WITH_NGHTTP2 if (strncmp(data, HTTP2_MAGIC, MIN(len, HTTP2_MAGIC_LEN)) == 0) { http_version = 2; } #else // check request-line if (len < MIN_HTTP_REQUEST_LEN) { hloge("[%s:%d] http request-line too small", ip, port); error = ERR_REQUEST; return -1; } for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) { if (!IS_GRAPH(data[i])) { hloge("[%s:%d] http request-line not plain", ip, port); error = ERR_REQUEST; return -1; } } #endif if (!Init(http_version)) { hloge("[%s:%d] unsupported HTTP%d", ip, port, http_version); error = ERR_INVALID_PROTOCOL; return -1; } } int nfeed = 0; switch (protocol) { case HttpHandler::HTTP_V1: case HttpHandler::HTTP_V2: if (state != WANT_RECV) { Reset(); } nfeed = parser->FeedRecvData(data, len); // printf("FeedRecvData %d=>%d\n", (int)len, nfeed); if (nfeed != len) { hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError())); error = ERR_PARSE; return -1; } break; case HttpHandler::WEBSOCKET: nfeed = ws_parser->FeedRecvData(data, len); if (nfeed != len) { hloge("[%s:%d] websocket parse error!", ip, port); error = ERR_PARSE; return -1; } break; default: hloge("[%s:%d] unknown protocol", ip, port); error = ERR_INVALID_PROTOCOL; return -1; } if (state == WANT_CLOSE) return 0; return error ? -1 : nfeed; } int HttpHandler::GetSendData(char** data, size_t* len) { if (state == HANDLE_CONTINUE) { return 0; } HttpRequest* pReq = req.get(); HttpResponse* pResp = resp.get(); if (protocol == HTTP_V1) { switch(state) { case WANT_RECV: if (parser->IsComplete()) state = WANT_SEND; else return 0; case HANDLE_END: state = WANT_SEND; case WANT_SEND: state = SEND_HEADER; case SEND_HEADER: { size_t content_length = 0; const char* content = NULL; // HEAD if (pReq->method == HTTP_HEAD) { if (fc) { pResp->headers["Accept-Ranges"] = "bytes"; pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size); } else { pResp->headers["Content-Type"] = "text/html"; pResp->headers["Content-Length"] = "0"; } state = SEND_DONE; goto return_nobody; } // File service if (fc) { // FileCache // NOTE: no copy filebuf, more efficient header = pResp->Dump(true, false); fc->prepend_header(header.c_str(), header.size()); *data = fc->httpbuf.base; *len = fc->httpbuf.len; state = SEND_DONE; return *len; } // API service content_length = pResp->ContentLength(); content = (const char*)pResp->Content(); if (content) { if (content_length > (1 << 20)) { state = SEND_BODY; goto return_header; } else { // NOTE: header+body in one package if <= 1M header = pResp->Dump(true, false); header.append(content, content_length); state = SEND_DONE; goto return_header; } } else { state = SEND_DONE; goto return_header; } return_nobody: pResp->content_length = 0; return_header: if (header.empty()) header = pResp->Dump(true, false); *data = (char*)header.c_str(); *len = header.size(); return *len; } case SEND_BODY: { *data = (char*)pResp->Content(); *len = pResp->ContentLength(); state = SEND_DONE; return *len; } case SEND_DONE: { // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) { files->Close(fc); } fc = NULL; header.clear(); return 0; } default: return 0; } } else if (protocol == HTTP_V2) { int ret = parser->GetSendData(data, len); if (ret == 0) state = SEND_DONE; return ret; } return 0; } int HttpHandler::SendHttpResponse(bool submit) { if (!io || !parser) return -1; char* data = NULL; size_t len = 0, total_len = 0; if (submit) parser->SubmitResponse(resp.get()); while (GetSendData(&data, &len)) { // printf("GetSendData %d\n", (int)len); if (data && len) { hio_write(io, data, len); total_len += len; } } return total_len; } int HttpHandler::SendHttpStatusResponse(http_status status_code) { if (state > WANT_SEND) return 0; resp->status_code = status_code; addResponseHeaders(); HandleHttpRequest(); state = WANT_SEND; return SendHttpResponse(); } //------------------sendfile-------------------------------------- int HttpHandler::openFile(const char* filepath) { closeFile(); file = new LargeFile; file->timer = INVALID_TIMER_ID; return file->open(filepath, "rb"); } bool HttpHandler::isFileOpened() { return file && file->isopen(); } int HttpHandler::sendFile() { if (!writer || !writer->isWriteComplete() || !isFileOpened() || file->buf.len == 0 || resp->content_length == 0) { return -1; } int readbytes = MIN(file->buf.len, resp->content_length); size_t nread = file->read(file->buf.base, readbytes); if (nread <= 0) { hloge("read file error!"); error = ERR_READ_FILE; writer->close(true); return nread; } int nwrite = writer->WriteBody(file->buf.base, nread); if (nwrite < 0) { // disconnectd writer->close(true); return nwrite; } resp->content_length -= nread; if (resp->content_length == 0) { writer->End(); closeFile(); } return nread; } void HttpHandler::closeFile() { if (file) { if (file->timer != INVALID_TIMER_ID) { killTimer(file->timer); file->timer = INVALID_TIMER_ID; } delete file; file = NULL; } } //------------------upgrade-------------------------------------- int HttpHandler::handleUpgrade(const char* upgrade_protocol) { hlogi("[%s:%d] Upgrade: %s", ip, port, upgrade_protocol); // websocket if (stricmp(upgrade_protocol, "websocket") == 0) { return upgradeWebSocket(); } // h2/h2c if (strnicmp(upgrade_protocol, "h2", 2) == 0) { return upgradeHTTP2(); } hloge("[%s:%d] unsupported Upgrade: %s", ip, port, upgrade_protocol); return SetError(ERR_INVALID_PROTOCOL); } int HttpHandler::upgradeWebSocket() { /* HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: websocket Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= */ resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS; resp->headers["Connection"] = "Upgrade"; resp->headers["Upgrade"] = "websocket"; // Sec-WebSocket-Accept: auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY); if (iter_key != req->headers.end()) { char ws_accept[32] = {0}; ws_encode_key(iter_key->second.c_str(), ws_accept); resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept; } // Sec-WebSocket-Protocol: auto iter_protocol = req->headers.find(SEC_WEBSOCKET_PROTOCOL); if (iter_protocol != req->headers.end()) { hv::StringList subprotocols = hv::split(iter_protocol->second, ','); if (subprotocols.size() > 0) { hlogw("%s: %s => just select first protocol %s", SEC_WEBSOCKET_PROTOCOL, iter_protocol->second.c_str(), subprotocols[0].c_str()); resp->headers[SEC_WEBSOCKET_PROTOCOL] = subprotocols[0]; } } SendHttpResponse(); if (!SwitchWebSocket()) { hloge("[%s:%d] unsupported websocket", ip, port); return SetError(ERR_INVALID_PROTOCOL); } // onopen WebSocketOnOpen(); return 0; } int HttpHandler::upgradeHTTP2() { /* HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: h2c */ resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS; resp->headers["Connection"] = "Upgrade"; resp->headers["Upgrade"] = "h2c"; SendHttpResponse(); if (!SwitchHTTP2()) { hloge("[%s:%d] unsupported HTTP2", ip, port); return SetError(ERR_INVALID_PROTOCOL); } // NOTE: send HTTP2_SETTINGS frame SendHttpResponse(false); return 0; } //------------------proxy-------------------------------------- int HttpHandler::handleProxy() { if (forward_proxy) { return handleForwardProxy(); } if (reverse_proxy) { return handleReverseProxy(); } return 0; } int HttpHandler::handleForwardProxy() { if (service && service->enable_forward_proxy) { return connectProxy(req->url); } else { hlogw("Forbidden to forward proxy %s", req->url.c_str()); SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN); } return 0; } int HttpHandler::handleReverseProxy() { return connectProxy(req->url); } int HttpHandler::connectProxy(const std::string& strUrl) { if (!io) return ERR_NULL_POINTER; HUrl url; url.parse(strUrl); hlogi("[%s:%d] proxy_pass %s", ip, port, strUrl.c_str()); if (proxy_connected) { if (url.host == proxy_host && url.port == proxy_port) { // reuse keepalive connection sendProxyRequest(); return 0; } else { // detach and close previous connection hio_t* upstream_io = hio_get_upstream(io); if (upstream_io) { hio_setcb_close(upstream_io, NULL); closeProxy(); } } } if (forward_proxy && !service->IsTrustProxy(url.host.c_str())) { hlogw("Forbidden to proxy %s", url.host.c_str()); SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN); return 0; } hloop_t* loop = hevent_loop(io); proxy = 1; proxy_host = url.host; proxy_port = url.port; hio_t* upstream_io = hio_create_socket(loop, proxy_host.c_str(), proxy_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (upstream_io == NULL) { return SetError(ERR_SOCKET, HTTP_STATUS_BAD_GATEWAY); } if (url.scheme == "https") { hio_enable_ssl(upstream_io); } hevent_set_userdata(upstream_io, this); hio_setup_upstream(io, upstream_io); hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect); hio_setcb_close(upstream_io, HttpHandler::onProxyClose); if (service->proxy_connect_timeout > 0) { hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout); } if (service->proxy_read_timeout > 0) { hio_set_read_timeout(io, service->proxy_read_timeout); } if (service->proxy_write_timeout > 0) { hio_set_write_timeout(io, service->proxy_write_timeout); } hio_connect(upstream_io); // NOTE: wait upstream_io connected then start read hio_read_stop(io); return 0; } int HttpHandler::closeProxy() { if (proxy && proxy_connected) { proxy_connected = 0; if (io) hio_close_upstream(io); } return 0; } int HttpHandler::sendProxyRequest() { if (!io || !proxy_connected) return -1; req->headers.erase("Host"); req->FillHost(proxy_host.c_str(), proxy_port); req->headers.erase("Proxy-Connection"); req->headers["Connection"] = keepalive ? "keep-alive" : "close"; req->headers["X-Real-IP"] = ip; // NOTE: send head + received body std::string msg = req->Dump(true, false) + req->body; // printf("%s\n", msg.c_str()); req->Reset(); hio_write_upstream(io, (void*)msg.c_str(), msg.size()); if (parser->IsComplete()) state = WANT_SEND; return msg.size(); } void HttpHandler::onProxyConnect(hio_t* upstream_io) { // printf("onProxyConnect\n"); HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io); hio_t* io = hio_get_upstream(upstream_io); assert(handler != NULL && io != NULL); handler->proxy_connected = 1; if (handler->req->method == HTTP_CONNECT) { // handler->resp->status_code = HTTP_STATUS_OK; // handler->SendHttpResponse(); hio_write(io, HTTP_200_CONNECT_RESPONSE, HTTP_200_CONNECT_RESPONSE_LEN); handler->state = SEND_DONE; // NOTE: recv request then upstream hio_setcb_read(io, hio_write_upstream); } else { handler->sendProxyRequest(); } // NOTE: start recv request continue then upstream if (handler->upgrade) hio_setcb_read(io, hio_write_upstream); hio_read_start(io); // NOTE: start recv response then upstream hio_setcb_read(upstream_io, hio_write_upstream); hio_read_start(upstream_io); } void HttpHandler::onProxyClose(hio_t* upstream_io) { // printf("onProxyClose\n"); HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io); if (handler == NULL) return; handler->proxy_connected = 0; hevent_set_userdata(upstream_io, NULL); int error = hio_error(upstream_io); if (error == ETIMEDOUT) { handler->SendHttpStatusResponse(HTTP_STATUS_GATEWAY_TIMEOUT); } handler->error = error; hio_close_upstream(upstream_io); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpHandler.h000066400000000000000000000114341520575453600303230ustar00rootroot00000000000000#ifndef HV_HTTP_HANDLER_H_ #define HV_HTTP_HANDLER_H_ #include "HttpService.h" #include "HttpParser.h" #include "FileCache.h" #include "WebSocketServer.h" #include "WebSocketParser.h" class HttpHandler { public: enum ProtocolType { UNKNOWN, HTTP_V1, HTTP_V2, WEBSOCKET, } protocol; enum State { WANT_RECV, HANDLE_BEGIN, HANDLE_CONTINUE, HANDLE_END, WANT_SEND, SEND_HEADER, SEND_BODY, SEND_DONE, WANT_CLOSE, } state; // errno int error; // flags unsigned ssl :1; unsigned keepalive :1; unsigned upgrade :1; unsigned proxy :1; unsigned proxy_connected :1; unsigned forward_proxy :1; unsigned reverse_proxy :1; // peeraddr char ip[64]; int port; // for log long pid; long tid; // for http hio_t *io; HttpService *service; HttpRequestPtr req; HttpResponsePtr resp; HttpResponseWriterPtr writer; HttpParserPtr parser; HttpContextPtr ctx; http_handler* api_handler; // for GetSendData std::string header; // std::string body; // for websocket WebSocketService* ws_service; WebSocketChannelPtr ws_channel; WebSocketParserPtr ws_parser; uint64_t last_send_ping_time; uint64_t last_recv_pong_time; // for sendfile FileCache *files; file_cache_ptr fc; // cache small file struct LargeFile : public HFile { HBuf buf; uint64_t timer; } *file; // for large file // for proxy std::string proxy_host; int proxy_port; HttpHandler(hio_t* io = NULL); ~HttpHandler(); bool Init(int http_version = 1); void Reset(); void Close(); /* @workflow: * HttpServer::on_recv -> HttpHandler::FeedRecvData -> Init -> HttpParser::InitRequest -> HttpRequest::http_cb -> * onHeadersComplete -> proxy ? handleProxy -> connectProxy : * onMessageComplete -> upgrade ? handleUpgrade : HandleHttpRequest -> HttpParser::SubmitResponse -> * SendHttpResponse -> while(GetSendData) hio_write -> * keepalive ? Reset : Close -> hio_close * * @return * == len: ok * == 0: WANT_CLOSE * < 0: error */ int FeedRecvData(const char* data, size_t len); /* @workflow: * preprocessor -> middleware -> processor -> postprocessor * * @return status_code * == 0: HANDLE_CONTINUE * != 0: HANDLE_END */ int HandleHttpRequest(); int GetSendData(char** data, size_t* len); int SendHttpResponse(bool submit = true); int SendHttpStatusResponse(http_status status_code); // HTTP2 bool SwitchHTTP2(); // websocket bool SwitchWebSocket(); void WebSocketOnOpen() { ws_channel->status = hv::SocketChannel::CONNECTED; if (ws_service && ws_service->onopen) { ws_service->onopen(ws_channel, req); } } void WebSocketOnClose() { ws_channel->status = hv::SocketChannel::DISCONNECTED; if (ws_service && ws_service->onclose) { ws_service->onclose(ws_channel); } } int SetError(int error_code, http_status status_code = HTTP_STATUS_BAD_REQUEST) { error = error_code; if (resp) resp->status_code = status_code; return error; } private: const HttpContextPtr& context(); int handleRequestHeaders(); // Expect: 100-continue void handleExpect100(); void addResponseHeaders(); // http_cb void onHeadersComplete(); void onBody(const char* data, size_t size); void onMessageComplete(); // default handlers int defaultRequestHandler(); int defaultStaticHandler(); int defaultLargeFileHandler(); int defaultErrorHandler(); int customHttpHandler(const http_handler& handler); int invokeHttpHandler(const http_handler* handler); // sendfile int openFile(const char* filepath); int sendFile(); void closeFile(); bool isFileOpened(); // upgrade int handleUpgrade(const char* upgrade_protocol); int upgradeWebSocket(); int upgradeHTTP2(); // proxy int handleProxy(); int handleForwardProxy(); int handleReverseProxy(); int connectProxy(const std::string& url); int closeProxy(); int sendProxyRequest(); static void onProxyConnect(hio_t* upstream_io); static void onProxyClose(hio_t* upstream_io); }; #endif // HV_HTTP_HANDLER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpMiddleware.cpp000066400000000000000000000011651520575453600313560ustar00rootroot00000000000000#include "HttpMiddleware.h" #include "HttpService.h" BEGIN_NAMESPACE_HV int HttpMiddleware::CORS(HttpRequest* req, HttpResponse* resp) { resp->headers["Access-Control-Allow-Origin"] = req->GetHeader("Origin", "*"); if (req->method == HTTP_OPTIONS) { resp->headers["Access-Control-Allow-Methods"] = req->GetHeader("Access-Control-Request-Method", "OPTIONS, HEAD, GET, POST, PUT, DELETE, PATCH"); resp->headers["Access-Control-Allow-Headers"] = req->GetHeader("Access-Control-Request-Headers", "Content-Type"); return HTTP_STATUS_NO_CONTENT; } return HTTP_STATUS_NEXT; } END_NAMESPACE_HV kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpMiddleware.h000066400000000000000000000004201520575453600310140ustar00rootroot00000000000000#ifndef HV_HTTP_MIDDLEWARE_H_ #define HV_HTTP_MIDDLEWARE_H_ #include "hexport.h" #include "HttpContext.h" BEGIN_NAMESPACE_HV class HttpMiddleware { public: static int CORS(HttpRequest* req, HttpResponse* resp); }; END_NAMESPACE_HV #endif // HV_HTTP_MIDDLEWARE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpResponseWriter.cpp000066400000000000000000000063351520575453600323000ustar00rootroot00000000000000#include "HttpResponseWriter.h" namespace hv { int HttpResponseWriter::EndHeaders(const char* key /* = NULL */, const char* value /* = NULL */) { if (state != SEND_BEGIN) return -1; if (key && value) { response->SetHeader(key, value); } std::string headers = response->Dump(true, false); // erase Content-Length: 0\r\n std::string content_length_0("Content-Length: 0\r\n"); auto pos = headers.find(content_length_0); if (pos != std::string::npos) { headers.erase(pos, content_length_0.size()); } state = SEND_HEADER; return write(headers); } int HttpResponseWriter::WriteChunked(const char* buf, int len /* = -1 */) { int ret = 0; if (len == -1) len = strlen(buf); if (state == SEND_BEGIN) { EndHeaders("Transfer-Encoding", "chunked"); } char chunked_header[64]; int chunked_header_len = snprintf(chunked_header, sizeof(chunked_header), "%x\r\n", len); write(chunked_header, chunked_header_len); if (buf && len) { state = SEND_CHUNKED; ret = write(buf, len); } else { state = SEND_CHUNKED_END; } write("\r\n", 2); return ret; } int HttpResponseWriter::WriteBody(const char* buf, int len /* = -1 */) { if (response->IsChunked()) { return WriteChunked(buf, len); } if (len == -1) len = strlen(buf); if (state == SEND_BEGIN) { response->body.append(buf, len); return len; } else { state = SEND_BODY; return write(buf, len); } } int HttpResponseWriter::WriteResponse(HttpResponse* resp) { if (resp == NULL) { response->status_code = HTTP_STATUS_INTERNAL_SERVER_ERROR; return 0; } bool is_dump_headers = state == SEND_BEGIN ? true : false; std::string msg = resp->Dump(is_dump_headers, true); state = SEND_BODY; return write(msg); } int HttpResponseWriter::SSEvent(const std::string& data, const char* event /* = "message" */) { if (state == SEND_BEGIN) { EndHeaders("Content-Type", "text/event-stream"); } std::string msg; if (event) { msg = "event: "; msg += event; msg += "\n"; } msg += "data: "; msg += data; msg += "\n\n"; state = SEND_BODY; return write(msg); } int HttpResponseWriter::End(const char* buf /* = NULL */, int len /* = -1 */) { if (end == SEND_END) return 0; end = SEND_END; if (!isConnected()) { return -1; } int ret = 0; bool keepAlive = response->IsKeepAlive(); if (state == SEND_CHUNKED) { if (buf) { ret = WriteChunked(buf, len); } if (state == SEND_CHUNKED) { EndChunked(); } } else { if (buf) { ret = WriteBody(buf, len); } bool is_dump_headers = true; bool is_dump_body = true; if (state == SEND_HEADER) { is_dump_headers = false; } else if (state == SEND_BODY) { is_dump_headers = false; is_dump_body = false; } if (is_dump_body) { std::string msg = response->Dump(is_dump_headers, is_dump_body); state = SEND_BODY; ret = write(msg); } } if (!keepAlive) { close(true); } return ret; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpResponseWriter.h000066400000000000000000000051001520575453600317320ustar00rootroot00000000000000#ifndef HV_HTTP_RESPONSE_WRITER_H_ #define HV_HTTP_RESPONSE_WRITER_H_ #include "Channel.h" #include "HttpMessage.h" namespace hv { class HV_EXPORT HttpResponseWriter : public SocketChannel { public: HttpResponsePtr response; enum State { SEND_BEGIN = 0, SEND_HEADER, SEND_BODY, SEND_CHUNKED, SEND_CHUNKED_END, SEND_END, } state: 8, end: 8; HttpResponseWriter(hio_t* io, const HttpResponsePtr& resp) : SocketChannel(io) , response(resp) , state(SEND_BEGIN) , end(SEND_BEGIN) {} ~HttpResponseWriter() {} // Begin -> End // Begin -> WriteResponse -> End // Begin -> WriteStatus -> WriteHeader -> WriteBody -> End // Begin -> EndHeaders("Content-Type", "text/event-stream") -> write -> write -> ... -> close // Begin -> EndHeaders("Content-Length", content_length) -> WriteBody -> WriteBody -> ... -> End // Begin -> EndHeaders("Transfer-Encoding", "chunked") -> WriteChunked -> WriteChunked -> ... -> End int Begin() { state = end = SEND_BEGIN; return 0; } int WriteStatus(http_status status_codes) { response->status_code = status_codes; return 0; } int WriteHeader(const char* key, const char* value) { response->SetHeader(key, value); return 0; } template int WriteHeader(const char* key, T num) { response->SetHeader(key, hv::to_string(num)); return 0; } int WriteCookie(const HttpCookie& cookie) { response->cookies.push_back(cookie); return 0; } int EndHeaders(const char* key = NULL, const char* value = NULL); template int EndHeaders(const char* key, T num) { std::string value = hv::to_string(num); return EndHeaders(key, value.c_str()); } int WriteChunked(const char* buf, int len = -1); int WriteChunked(const std::string& str) { return WriteChunked(str.c_str(), str.size()); } int EndChunked() { return WriteChunked(NULL, 0); } int WriteBody(const char* buf, int len = -1); int WriteBody(const std::string& str) { return WriteBody(str.c_str(), str.size()); } int WriteResponse(HttpResponse* resp); int SSEvent(const std::string& data, const char* event = "message"); int End(const char* buf = NULL, int len = -1); int End(const std::string& str) { return End(str.c_str(), str.size()); } }; } typedef std::shared_ptr HttpResponseWriterPtr; #endif // HV_HTTP_RESPONSE_WRITER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpServer.cpp000066400000000000000000000227771520575453600305630ustar00rootroot00000000000000#include "HttpServer.h" #include "hmain.h" // import master_workers_run #include "herr.h" #include "hlog.h" #include "htime.h" #include "EventLoop.h" using namespace hv; #include "HttpHandler.h" static void on_accept(hio_t* io); static void on_recv(hio_t* io, void* _buf, int readbytes); static void on_close(hio_t* io); struct HttpServerPrivdata { std::vector loops; std::vector threads; std::mutex mutex_; std::shared_ptr service; FileCache filecache; }; static void on_recv(hio_t* io, void* buf, int readbytes) { // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); HttpHandler* handler = (HttpHandler*)hevent_userdata(io); assert(handler != NULL); int nfeed = handler->FeedRecvData((const char*)buf, readbytes); if (nfeed != readbytes) { hio_close(io); return; } } static void on_close(hio_t* io) { HttpHandler* handler = (HttpHandler*)hevent_userdata(io); if (handler == NULL) return; hevent_set_userdata(io, NULL); delete handler; EventLoop* loop = currentThreadEventLoop; if (loop) { --loop->connectionNum; } } static void on_accept(hio_t* io) { http_server_t* server = (http_server_t*)hevent_userdata(io); HttpService* service = server->service; /* printf("on_accept connfd=%d\n", hio_fd(io)); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); */ EventLoop* loop = currentThreadEventLoop; if (loop->connectionNum >= server->worker_connections) { hlogw("over worker_connections"); hio_close(io); return; } ++loop->connectionNum; hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); hio_read(io); if (service->keepalive_timeout > 0) { hio_set_keepalive_timeout(io, service->keepalive_timeout); } // new HttpHandler, delete on_close HttpHandler* handler = new HttpHandler(io); // ssl handler->ssl = hio_is_ssl(io); // ip:port sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io); sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip)); handler->port = sockaddr_port(peeraddr); // http service handler->service = service; // websocket service handler->ws_service = server->ws; // FileCache HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; handler->files = &privdata->filecache; hevent_set_userdata(io, handler); } static void loop_thread(void* userdata) { http_server_t* server = (http_server_t*)userdata; HttpService* service = server->service; auto loop = std::make_shared(); hloop_t* hloop = loop->loop(); // http if (server->listenfd[0] >= 0) { hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept); hevent_set_userdata(listenio, server); } // https if (server->listenfd[1] >= 0) { hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept); hevent_set_userdata(listenio, server); hio_enable_ssl(listenio); if (server->ssl_ctx) { hio_set_ssl_ctx(listenio, server->ssl_ctx); } } HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; privdata->mutex_.lock(); if (privdata->loops.size() == 0) { // NOTE: fsync logfile when idle hlog_disable_fsync(); hidle_add(hloop, [](hidle_t*) { hlog_fsync(); }, INFINITE); // NOTE: add timer to update s_date every 1s htimer_add(hloop, [](htimer_t* timer) { gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date); }, 1000); // document_root if (service->document_root.size() > 0 && service->GetStaticFilepath("/").empty()) { service->Static("/", service->document_root.c_str()); } // FileCache FileCache* filecache = &privdata->filecache; filecache->stat_interval = service->file_cache_stat_interval; filecache->expired_time = service->file_cache_expired_time; if (filecache->expired_time > 0) { // NOTE: add timer to remove expired file cache htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) { FileCache* filecache = (FileCache*)hevent_userdata(timer); filecache->RemoveExpiredFileCache(); }, filecache->expired_time * 1000); hevent_set_userdata(timer, filecache); } } privdata->loops.push_back(loop); privdata->mutex_.unlock(); hlogi("EventLoop started, pid=%ld tid=%ld", hv_getpid(), hv_gettid()); if (server->onWorkerStart) { loop->queueInLoop([server](){ server->onWorkerStart(); }); } loop->run(); if (server->onWorkerStop) { server->onWorkerStop(); } hlogi("EventLoop stopped, pid=%ld tid=%ld", hv_getpid(), hv_gettid()); } /* @workflow: * http_server_run -> Listen -> master_workers_run / hthread_create -> * loop_thread -> accept -> EventLoop::run -> * on_accept -> new HttpHandler -> hio_read -> * on_recv -> HttpHandler::FeedRecvData -> * on_close -> delete HttpHandler */ int http_server_run(http_server_t* server, int wait) { // http_port if (server->port > 0) { server->listenfd[0] = Listen(server->port, server->host); if (server->listenfd[0] < 0) return server->listenfd[0]; hlogi("http server listening on %s:%d", server->host, server->port); } // https_port if (server->https_port > 0 && HV_WITH_SSL) { server->listenfd[1] = Listen(server->https_port, server->host); if (server->listenfd[1] < 0) return server->listenfd[1]; hlogi("https server listening on %s:%d", server->host, server->https_port); } // SSL_CTX if (server->listenfd[1] >= 0) { if (server->ssl_ctx == NULL) { server->ssl_ctx = hssl_ctx_instance(); } if (server->ssl_ctx == NULL) { hloge("new SSL_CTX failed!"); return ERR_NEW_SSL_CTX; } #ifdef WITH_NGHTTP2 #ifdef WITH_OPENSSL static unsigned char s_alpn_protos[] = "\x02h2\x08http/1.1\x08http/1.0\x08http/0.9"; hssl_ctx_set_alpn_protos(server->ssl_ctx, s_alpn_protos, sizeof(s_alpn_protos) - 1); #endif #endif } HttpServerPrivdata* privdata = new HttpServerPrivdata; server->privdata = privdata; if (server->service == NULL) { privdata->service = std::make_shared(); server->service = privdata->service.get(); } if (server->worker_processes) { // multi-processes return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait); } else { // multi-threads if (server->worker_threads == 0) server->worker_threads = 1; for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) { hthread_t thrd = hthread_create((hthread_routine)loop_thread, server); privdata->threads.push_back(thrd); } if (wait) { loop_thread(server); } return 0; } } /* @workflow: * http_server_stop -> EventLoop::stop -> hthread_join */ int http_server_stop(http_server_t* server) { HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; if (privdata == NULL) return 0; #ifdef OS_UNIX if (server->worker_processes) { signal_handle("stop"); return 0; } #endif // wait for all threads started and all loops running while (1) { hv_delay(1); std::lock_guard locker(privdata->mutex_); // wait for all loops created if (privdata->loops.size() < server->worker_threads) { continue; } // wait for all loops running bool all_loops_running = true; for (auto& loop : privdata->loops) { if (loop->status() < hv::Status::kRunning) { all_loops_running = false; break; } } if (all_loops_running) break; } // stop all loops for (auto& loop : privdata->loops) { loop->stop(); } // join all threads for (auto& thrd : privdata->threads) { hthread_join(thrd); } if (server->alloced_ssl_ctx && server->ssl_ctx) { hssl_ctx_free(server->ssl_ctx); server->alloced_ssl_ctx = 0; server->ssl_ctx = NULL; } delete privdata; server->privdata = NULL; return 0; } namespace hv { std::shared_ptr HttpServer::loop(int idx) { HttpServerPrivdata* privdata = (HttpServerPrivdata*)this->privdata; if (privdata == NULL) return NULL; std::lock_guard locker(privdata->mutex_); if (privdata->loops.empty()) return NULL; if (idx >= 0 && idx < (int)privdata->loops.size()) { return privdata->loops[idx]; } EventLoop* cur = currentThreadEventLoop; for (auto& loop : privdata->loops) { if (loop.get() == cur) return loop; } return NULL; } size_t HttpServer::connectionNum() { HttpServerPrivdata* privdata = (HttpServerPrivdata*)this->privdata; if (privdata == NULL) return 0; std::lock_guard locker(privdata->mutex_); if (privdata->loops.empty()) return 0; size_t total = 0; for (auto& loop : privdata->loops) { total += loop->connectionNum; } return total; } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpServer.h000066400000000000000000000077071520575453600302240ustar00rootroot00000000000000#ifndef HV_HTTP_SERVER_H_ #define HV_HTTP_SERVER_H_ #include "hexport.h" #include "hssl.h" // #include "EventLoop.h" #include "HttpService.h" // #include "WebSocketServer.h" namespace hv { class EventLoop; struct WebSocketService; } using hv::HttpService; using hv::WebSocketService; typedef struct http_server_s { char host[64]; int port; // http_port int https_port; int http_version; int worker_processes; int worker_threads; uint32_t worker_connections; // max_connections = workers * worker_connections HttpService* service; // http service WebSocketService* ws; // websocket service void* userdata; int listenfd[2]; // 0: http, 1: https void* privdata; // hooks std::function onWorkerStart; std::function onWorkerStop; // SSL/TLS hssl_ctx_t ssl_ctx; unsigned alloced_ssl_ctx: 1; #ifdef __cplusplus http_server_s() { strcpy(host, "0.0.0.0"); // port = DEFAULT_HTTP_PORT; // https_port = DEFAULT_HTTPS_PORT; // port = 8080; // https_port = 8443; port = https_port = 0; http_version = 1; worker_processes = 0; worker_threads = 0; worker_connections = 1024; service = NULL; ws = NULL; listenfd[0] = listenfd[1] = -1; userdata = NULL; privdata = NULL; // SSL/TLS ssl_ctx = NULL; alloced_ssl_ctx = 0; } #endif } http_server_t; // @param wait: Whether to occupy current thread HV_EXPORT int http_server_run(http_server_t* server, int wait = 1); // NOTE: stop all loops and join all threads HV_EXPORT int http_server_stop(http_server_t* server); /* #include "HttpServer.h" using namespace hv; int main() { HttpService service; service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { resp->body = "pong"; return 200; }); HttpServer server(&service); server.setThreadNum(4); server.run(":8080"); return 0; } */ namespace hv { class HV_EXPORT HttpServer : public http_server_t { public: HttpServer(HttpService* service = NULL) : http_server_t() { this->service = service; } ~HttpServer() { stop(); } void registerHttpService(HttpService* service) { this->service = service; } std::shared_ptr loop(int idx = -1); void setHost(const char* host = "0.0.0.0") { if (host) strcpy(this->host, host); } void setPort(int port = 0, int ssl_port = 0) { if (port >= 0) this->port = port; if (ssl_port >= 0) this->https_port = ssl_port; } void setListenFD(int fd = -1, int ssl_fd = -1) { if (fd >= 0) this->listenfd[0] = fd; if (ssl_fd >= 0) this->listenfd[1] = ssl_fd; } void setProcessNum(int num) { this->worker_processes = num; } void setThreadNum(int num) { this->worker_threads = num; } void setMaxWorkerConnectionNum(uint32_t num) { this->worker_connections = num; } size_t connectionNum(); // SSL/TLS int setSslCtx(hssl_ctx_t ssl_ctx) { this->ssl_ctx = ssl_ctx; return 0; } int newSslCtx(hssl_ctx_opt_t* opt) { // NOTE: hssl_ctx_free in http_server_stop hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); if (ssl_ctx == NULL) return -1; this->alloced_ssl_ctx = 1; return setSslCtx(ssl_ctx); } // run(":8080") // run("0.0.0.0:8080") // run("[::]:8080") int run(const char* ip_port = NULL, bool wait = true) { if (ip_port) { hv::NetAddr listen_addr(ip_port); if (listen_addr.ip.size() != 0) setHost(listen_addr.ip.c_str()); if (listen_addr.port != 0) setPort(listen_addr.port); } return http_server_run(this, wait); } int start(const char* ip_port = NULL) { return run(ip_port, false); } int stop() { return http_server_stop(this); } }; } #endif // HV_HTTP_SERVER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpService.cpp000066400000000000000000000142041520575453600306770ustar00rootroot00000000000000#include "HttpService.h" #include "HttpMiddleware.h" #include "hbase.h" // import hv_strendswith namespace hv { void HttpService::AddRoute(const char* path, http_method method, const http_handler& handler) { std::shared_ptr method_handlers = NULL; auto iter = pathHandlers.find(path); if (iter == pathHandlers.end()) { // add path method_handlers = std::make_shared(); pathHandlers[path] = method_handlers; } else { method_handlers = iter->second; } for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { if (iter->method == method) { // update iter->handler = handler; return; } } // add method_handlers->push_back(http_method_handler(method, handler)); } int HttpService::GetRoute(const char* url, http_method method, http_handler** handler) { // {base_url}/path?query const char* s = url; const char* b = base_url.c_str(); while (*s && *b && *s == *b) {++s;++b;} if (*b != '\0') { return HTTP_STATUS_NOT_FOUND; } const char* e = s; while (*e && *e != '?') ++e; std::string path = std::string(s, e); auto iter = pathHandlers.find(path); if (iter == pathHandlers.end()) { if (handler) *handler = NULL; return HTTP_STATUS_NOT_FOUND; } auto method_handlers = iter->second; for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { if (iter->method == method) { if (handler) *handler = &iter->handler; return 0; } } if (handler) *handler = NULL; return HTTP_STATUS_METHOD_NOT_ALLOWED; } int HttpService::GetRoute(HttpRequest* req, http_handler** handler) { // {base_url}/path?query const char* s = req->path.c_str(); const char* b = base_url.c_str(); while (*s && *b && *s == *b) {++s;++b;} if (*b != '\0') { return HTTP_STATUS_NOT_FOUND; } const char* e = s; while (*e && *e != '?') ++e; std::string path = std::string(s, e); const char *kp, *ks, *vp, *vs; bool match; for (auto iter = pathHandlers.begin(); iter != pathHandlers.end(); ++iter) { kp = iter->first.c_str(); vp = path.c_str(); match = false; std::map params; while (*kp && *vp) { if (kp[0] == '*') { // wildcard * match = hv_strendswith(vp, kp+1); break; } else if (*kp != *vp) { match = false; break; } else if (kp[0] == '/' && (kp[1] == ':' || kp[1] == '{')) { // RESTful /:field/ // RESTful /{field}/ kp += 2; ks = kp; while (*kp && *kp != '/') {++kp;} vp += 1; vs = vp; while (*vp && *vp != '/') {++vp;} int klen = kp - ks; if (*(ks-1) == '{' && *(kp-1) == '}') { --klen; } params[std::string(ks, klen)] = std::string(vs, vp-vs); continue; } else { ++kp; ++vp; } } match = match ? match : (*kp == '\0' && *vp == '\0'); if (match) { auto method_handlers = iter->second; for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { if (iter->method == req->method) { for (auto& param : params) { // RESTful /:field/ => req->query_params[field] req->query_params[param.first] = param.second; } if (handler) *handler = &iter->handler; return 0; } } if (params.size() == 0) { if (handler) *handler = NULL; return HTTP_STATUS_METHOD_NOT_ALLOWED; } } } if (handler) *handler = NULL; return HTTP_STATUS_NOT_FOUND; } void HttpService::Static(const char* path, const char* dir) { std::string strPath(path); if (strPath.back() != '/') strPath += '/'; std::string strDir(dir); if (strDir.back() == '/') strDir.pop_back(); staticDirs[strPath] = strDir; } std::string HttpService::GetStaticFilepath(const char* path) { std::string filepath; for (auto iter = staticDirs.begin(); iter != staticDirs.end(); ++iter) { if (hv_strstartswith(path, iter->first.c_str())) { filepath = iter->second + (path + iter->first.length() - 1); break; } } if (filepath.empty()) { return filepath; } if (filepath.back() == '/') { filepath += home_page; } return filepath; } void HttpService::Proxy(const char* path, const char* url) { proxies[path] = url; } std::string HttpService::GetProxyUrl(const char* path) { std::string url; for (auto iter = proxies.begin(); iter != proxies.end(); ++iter) { if (hv_strstartswith(path, iter->first.c_str())) { url = iter->second + (path + iter->first.length()); break; } } return url; } void HttpService::AddTrustProxy(const char* host) { trustProxies.emplace_back(host); } void HttpService::AddNoProxy(const char* host) { noProxies.emplace_back(host); } bool HttpService::IsTrustProxy(const char* host) { if (!host || *host == '\0') return false; bool trust = true; if (trustProxies.size() != 0) { trust = false; for (const auto& trust_proxy : trustProxies) { if (hv_wildcard_match(host, trust_proxy.c_str())) { trust = true; break; } } } if (noProxies.size() != 0) { for (const auto& no_proxy : noProxies) { if (hv_wildcard_match(host, no_proxy.c_str())) { trust = false; break; } } } return trust; } void HttpService::AllowCORS() { Use(HttpMiddleware::CORS); } } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/HttpService.h000066400000000000000000000227151520575453600303520ustar00rootroot00000000000000#ifndef HV_HTTP_SERVICE_H_ #define HV_HTTP_SERVICE_H_ #include #include #include #include #include #include #include #include "hexport.h" #include "HttpMessage.h" #include "HttpResponseWriter.h" #include "HttpContext.h" #define DEFAULT_BASE_URL "/api/v1" #define DEFAULT_DOCUMENT_ROOT "/var/www/html" #define DEFAULT_HOME_PAGE "index.html" #define DEFAULT_ERROR_PAGE "error.html" #define DEFAULT_INDEXOF_DIR "/downloads/" #define DEFAULT_KEEPALIVE_TIMEOUT 75000 // ms // for FileCache #define MAX_FILE_CACHE_SIZE (1 << 22) // 4M #define DEFAULT_FILE_CACHE_STAT_INTERVAL 10 // s #define DEFAULT_FILE_CACHE_EXPIRED_TIME 60 // s /* * @param[in] req: parsed structured http request * @param[out] resp: structured http response * @return 0: handle next * http_status_code: handle done */ #define HTTP_STATUS_NEXT 0 #define HTTP_STATUS_UNFINISHED 0 // NOTE: http_sync_handler run on IO thread typedef std::function http_sync_handler; // NOTE: http_async_handler run on hv::async threadpool typedef std::function http_async_handler; // NOTE: http_ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing. typedef std::function http_ctx_handler; // NOTE: http_state_handler run on IO thread typedef std::function http_state_handler; struct http_handler { http_sync_handler sync_handler; http_async_handler async_handler; http_ctx_handler ctx_handler; http_state_handler state_handler; http_handler() {} http_handler(http_sync_handler fn) : sync_handler(std::move(fn)) {} http_handler(http_async_handler fn) : async_handler(std::move(fn)) {} http_handler(http_ctx_handler fn) : ctx_handler(std::move(fn)) {} http_handler(http_state_handler fn) : state_handler(std::move(fn)) {} http_handler(const http_handler& rhs) : sync_handler(std::move(const_cast(rhs).sync_handler)) , async_handler(std::move(const_cast(rhs).async_handler)) , ctx_handler(std::move(const_cast(rhs).ctx_handler)) , state_handler(std::move(const_cast(rhs).state_handler)) {} const http_handler& operator=(http_sync_handler fn) { sync_handler = std::move(fn); return *this; } const http_handler& operator=(http_async_handler fn) { async_handler = std::move(fn); return *this; } const http_handler& operator=(http_ctx_handler fn) { ctx_handler = std::move(fn); return *this; } const http_handler& operator=(http_state_handler fn) { state_handler = std::move(fn); return *this; } bool isNull() { return sync_handler == NULL && async_handler == NULL && ctx_handler == NULL; } operator bool() { return !isNull(); } }; typedef std::vector http_handlers; struct http_method_handler { http_method method; http_handler handler; http_method_handler() {} http_method_handler(http_method m, const http_handler& h) : method(m), handler(h) {} }; // method => http_method_handler typedef std::list http_method_handlers; // path => http_method_handlers typedef std::unordered_map> http_path_handlers; namespace hv { struct HV_EXPORT HttpService { /* handler chain */ // preprocessor -> middleware -> processor -> postprocessor http_handler preprocessor; http_handlers middleware; // processor: pathHandlers -> staticHandler -> errorHandler http_handler processor; http_handler postprocessor; /* API handlers */ std::string base_url; http_path_handlers pathHandlers; /* Static file service */ http_handler staticHandler; http_handler largeFileHandler; std::string document_root; std::string home_page; std::string error_page; // nginx: location => root std::map> staticDirs; /* Indexof directory service */ std::string index_of; http_handler errorHandler; /* Proxy service */ /* Reverse proxy service */ // nginx: location => proxy_pass std::map> proxies; /* Forward proxy service */ StringList trustProxies; StringList noProxies; int proxy_connect_timeout; int proxy_read_timeout; int proxy_write_timeout; // options int keepalive_timeout; int max_file_cache_size; // cache small file int file_cache_stat_interval; // stat file is modified int file_cache_expired_time; // remove expired file cache /* * @test limit_rate * @build make examples * @server bin/httpd -c etc/httpd.conf -s restart -d * @client bin/wget http://127.0.0.1:8080/downloads/test.zip */ int limit_rate; // limit send rate, unit: KB/s unsigned enable_access_log :1; unsigned enable_forward_proxy :1; HttpService() { // base_url = DEFAULT_BASE_URL; document_root = DEFAULT_DOCUMENT_ROOT; home_page = DEFAULT_HOME_PAGE; // error_page = DEFAULT_ERROR_PAGE; // index_of = DEFAULT_INDEXOF_DIR; proxy_connect_timeout = DEFAULT_CONNECT_TIMEOUT; proxy_read_timeout = 0; proxy_write_timeout = 0; keepalive_timeout = DEFAULT_KEEPALIVE_TIMEOUT; max_file_cache_size = MAX_FILE_CACHE_SIZE; file_cache_stat_interval = DEFAULT_FILE_CACHE_STAT_INTERVAL; file_cache_expired_time = DEFAULT_FILE_CACHE_EXPIRED_TIME; limit_rate = -1; // unlimited enable_access_log = 1; enable_forward_proxy = 0; } void AddRoute(const char* path, http_method method, const http_handler& handler); // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED int GetRoute(const char* url, http_method method, http_handler** handler); // RESTful API /:field/ => req->query_params["field"] int GetRoute(HttpRequest* req, http_handler** handler); // Static("/", "/var/www/html") void Static(const char* path, const char* dir); // @retval / => /var/www/html/index.html std::string GetStaticFilepath(const char* path); // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS void AllowCORS(); // proxy // forward proxy void EnableForwardProxy() { enable_forward_proxy = 1; } void AddTrustProxy(const char* host); void AddNoProxy(const char* host); bool IsTrustProxy(const char* host); // reverse proxy // Proxy("/api/v1/", "http://www.httpbin.org/"); void Proxy(const char* path, const char* url); // @retval /api/v1/test => http://www.httpbin.org/test std::string GetProxyUrl(const char* path); hv::StringList Paths() { hv::StringList paths; for (auto& pair : pathHandlers) { paths.emplace_back(pair.first); } return paths; } // Handler = [ http_sync_handler, http_ctx_handler ] template void Use(Handler handlerFunc) { middleware.emplace_back(handlerFunc); } // Inspired by github.com/gin-gonic/gin // Handler = [ http_sync_handler, http_async_handler, http_ctx_handler, http_state_handler ] template void Handle(const char* httpMethod, const char* relativePath, Handler handlerFunc) { AddRoute(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc)); } // HEAD template void HEAD(const char* relativePath, Handler handlerFunc) { Handle("HEAD", relativePath, handlerFunc); } // GET template void GET(const char* relativePath, Handler handlerFunc) { Handle("GET", relativePath, handlerFunc); } // POST template void POST(const char* relativePath, Handler handlerFunc) { Handle("POST", relativePath, handlerFunc); } // PUT template void PUT(const char* relativePath, Handler handlerFunc) { Handle("PUT", relativePath, handlerFunc); } // DELETE // NOTE: Windows #define DELETE as a macro, we have to replace DELETE with Delete. template void Delete(const char* relativePath, Handler handlerFunc) { Handle("DELETE", relativePath, handlerFunc); } // PATCH template void PATCH(const char* relativePath, Handler handlerFunc) { Handle("PATCH", relativePath, handlerFunc); } // Any template void Any(const char* relativePath, Handler handlerFunc) { Handle("HEAD", relativePath, handlerFunc); Handle("GET", relativePath, handlerFunc); Handle("POST", relativePath, handlerFunc); Handle("PUT", relativePath, handlerFunc); Handle("DELETE", relativePath, handlerFunc); Handle("PATCH", relativePath, handlerFunc); } }; } #endif // HV_HTTP_SERVICE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/WebSocketServer.h000066400000000000000000000021111520575453600311530ustar00rootroot00000000000000#ifndef HV_WEBSOCKET_SERVER_H_ #define HV_WEBSOCKET_SERVER_H_ /* * @demo examples/websocket_server_test.cpp */ #include "HttpServer.h" #include "WebSocketChannel.h" #define websocket_server_t http_server_t #define websocket_server_run http_server_run #define websocket_server_stop http_server_stop namespace hv { struct WebSocketService { std::function onopen; std::function onmessage; std::function onclose; int ping_interval; WebSocketService() : ping_interval(0) {} void setPingInterval(int ms) { ping_interval = ms; } }; class WebSocketServer : public HttpServer { public: WebSocketServer(WebSocketService* service = NULL) : HttpServer() { this->ws = service; } ~WebSocketServer() { stop(); } void registerWebSocketService(WebSocketService* service) { this->ws = service; } }; } #endif // HV_WEBSOCKET_SERVER_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/http_page.cpp000066400000000000000000000062141520575453600304140ustar00rootroot00000000000000#include "http_page.h" #include "hdir.h" #include "hurl.h" #define AUTOINDEX_FILENAME_MAXLEN 50 void make_http_status_page(http_status status_code, std::string& page) { char szCode[8]; snprintf(szCode, sizeof(szCode), "%d ", status_code); const char* status_message = http_status_str(status_code); page += R"( )"; page += szCode; page += status_message; page += R"(

)"; page += szCode; page += status_message; page += R"(


)"; } void make_index_of_page(const char* dir, std::string& page, const char* url) { char c_str[1024] = {0}; snprintf(c_str, sizeof(c_str), R"( Index of %s

Index of %s


)", url, url); page += c_str; page += " \n"; page += R"( )"; #define _ADD_TD_(page, td) \ page += " \n"; \ std::list dirs; listdir(dir, dirs); std::string escaped_name; for (auto& item : dirs) { if (item.name[0] == '.' && item.name[1] == '\0') continue; page += " \n"; // fix CVE-2023-26146 escaped_name = hv::escapeHTML(item.name); const char* filename = escaped_name.c_str(); size_t len = escaped_name.size() + (item.type == 'd'); // name snprintf(c_str, sizeof(c_str), "%s%s", filename, item.type == 'd' ? "/" : "", len < AUTOINDEX_FILENAME_MAXLEN ? filename : std::string(filename, filename+AUTOINDEX_FILENAME_MAXLEN-4).append("...").c_str(), item.type == 'd' ? "/" : ""); _ADD_TD_(page, c_str) if (strcmp(filename, "..") != 0) { // mtime struct tm* tm = localtime(&item.mtime); snprintf(c_str, sizeof(c_str), "%04d-%02d-%02d %02d:%02d:%02d", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); _ADD_TD_(page, c_str) // size if (item.type == 'd') { page += '-'; } else { float hsize; if (item.size < 1024) { snprintf(c_str, sizeof(c_str), "%lu", (unsigned long)item.size); } else if ((hsize = item.size/1024.0f) < 1024.0f) { snprintf(c_str, sizeof(c_str), "%.1fK", hsize); } else if ((hsize /= 1024.0f) < 1024.0f) { snprintf(c_str, sizeof(c_str), "%.1fM", hsize); } else { hsize /= 1024.0f; snprintf(c_str, sizeof(c_str), "%.1fG", hsize); } _ADD_TD_(page, c_str) } } page += " \n"; } #undef _ADD_TD_ page += R"(
Name Date Size
"; \ page += td; \ page += "

)"; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/server/http_page.h000066400000000000000000000020631520575453600300570ustar00rootroot00000000000000#ifndef HV_HTTP_PAGE_H_ #define HV_HTTP_PAGE_H_ #include #include "httpdef.h" /* 404 Not Found

404 Not Found


*/ void make_http_status_page(http_status status_code, std::string& page); /* Index of /downloads/

Index of /downloads/


Name Date Size
../
libhv-vs-nginx.png 2021-03-10 12:33:57 211.4K
中文.html 2022-04-25 15:37:12 191

*/ void make_index_of_page(const char* dir, std::string& page, const char* url = ""); #endif // HV_HTTP_PAGE_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/websocket_parser.c000066400000000000000000000204161520575453600301350ustar00rootroot00000000000000#include "websocket_parser.h" #include #include #ifdef assert # define assertFalse(msg) assert(0 && msg) #else # define assertFalse(msg) #endif #define SET_STATE(V) parser->state = V #define HAS_DATA() (p < end ) #define CC (*p) #define GET_NPARSED() ( (p == end) ? len : (p - data) ) #define NOTIFY_CB(FOR) \ do { \ if (settings->on_##FOR) { \ if (settings->on_##FOR(parser) != 0) { \ return GET_NPARSED(); \ } \ } \ } while (0) #define EMIT_DATA_CB(FOR, ptr, len) \ do { \ if (settings->on_##FOR) { \ if (settings->on_##FOR(parser, ptr, len) != 0) { \ return GET_NPARSED(); \ } \ } \ } while (0) enum state { s_start, s_head, s_length, s_mask, s_body, }; void websocket_parser_init(websocket_parser * parser) { void *data = parser->data; /* preserve application data */ memset(parser, 0, sizeof(*parser)); parser->data = data; parser->state = s_start; } void websocket_parser_settings_init(websocket_parser_settings *settings) { memset(settings, 0, sizeof(*settings)); } size_t websocket_parser_execute(websocket_parser *parser, const websocket_parser_settings *settings, const char *data, size_t len) { const char * p; const char * end = data + len; size_t frame_offset = 0; for(p = data; p != end; p++) { switch(parser->state) { case s_start: parser->offset = 0; parser->length = 0; parser->mask_offset = 0; parser->flags = (websocket_flags) (CC & WS_OP_MASK); if(CC & (1<<7)) { parser->flags |= WS_FIN; } SET_STATE(s_head); frame_offset++; break; case s_head: parser->length = (size_t)CC & 0x7F; if(CC & 0x80) { parser->flags |= WS_HAS_MASK; } if(parser->length >= 126) { if(parser->length == 127) { parser->require = 8; } else { parser->require = 2; } parser->length = 0; SET_STATE(s_length); } else if (parser->flags & WS_HAS_MASK) { SET_STATE(s_mask); parser->require = 4; } else if (parser->length) { SET_STATE(s_body); parser->require = parser->length; NOTIFY_CB(frame_header); } else { SET_STATE(s_start); NOTIFY_CB(frame_header); NOTIFY_CB(frame_end); } frame_offset++; break; case s_length: while(HAS_DATA() && parser->require) { parser->length <<= 8; parser->length |= (unsigned char)CC; parser->require--; frame_offset++; p++; } p--; if(!parser->require) { if (parser->flags & WS_HAS_MASK) { SET_STATE(s_mask); parser->require = 4; } else if (parser->length) { SET_STATE(s_body); parser->require = parser->length; NOTIFY_CB(frame_header); } else { SET_STATE(s_start); NOTIFY_CB(frame_header); NOTIFY_CB(frame_end); } } break; case s_mask: while(HAS_DATA() && parser->require) { parser->mask[4 - parser->require--] = CC; frame_offset++; p++; } p--; if(!parser->require) { if(parser->length) { SET_STATE(s_body); parser->require = parser->length; NOTIFY_CB(frame_header); } else { SET_STATE(s_start); NOTIFY_CB(frame_header); NOTIFY_CB(frame_end); } } break; case s_body: if(parser->require) { if(p + parser->require <= end) { EMIT_DATA_CB(frame_body, p, parser->require); p += parser->require; parser->require = 0; frame_offset = p - data; } else { EMIT_DATA_CB(frame_body, p, end - p); parser->require -= end - p; p = end; parser->offset += p - data - frame_offset; frame_offset = 0; } p--; } if(!parser->require) { SET_STATE(s_start); NOTIFY_CB(frame_end); } break; default: assertFalse("Unreachable case"); } } return GET_NPARSED(); } void websocket_parser_decode(char * dst, const char * src, size_t len, websocket_parser * parser) { size_t i = 0; for(; i < len; i++) { dst[i] = src[i] ^ parser->mask[(i + parser->mask_offset) % 4]; } parser->mask_offset = (uint8_t) ((i + parser->mask_offset) % 4); } uint8_t websocket_decode(char * dst, const char * src, size_t len, const char mask[4], uint8_t mask_offset) { size_t i = 0; for(; i < len; i++) { dst[i] = src[i] ^ mask[(i + mask_offset) % 4]; } return (uint8_t) ((i + mask_offset) % 4); } size_t websocket_calc_frame_size(websocket_flags flags, size_t data_len) { size_t size = data_len + 2; // body + 2 bytes of head if(data_len >= 126) { if(data_len > 0xFFFF) { size += 8; } else { size += 2; } } if(flags & WS_HAS_MASK) { size += 4; } return size; } size_t websocket_build_frame(char * frame, websocket_flags flags, const char mask[4], const char * data, size_t data_len) { size_t body_offset = 0; frame[0] = 0; frame[1] = 0; if(flags & WS_FIN) { frame[0] = (char) (1 << 7); } frame[0] |= flags & WS_OP_MASK; if(flags & WS_HAS_MASK) { frame[1] = (char) (1 << 7); } if(data_len < 126) { frame[1] |= data_len; body_offset = 2; } else if(data_len <= 0xFFFF) { frame[1] |= 126; frame[2] = (char) (data_len >> 8); frame[3] = (char) (data_len & 0xFF); body_offset = 4; } else { frame[1] |= 127; frame[2] = (char) ((data_len >> 56) & 0xFF); frame[3] = (char) ((data_len >> 48) & 0xFF); frame[4] = (char) ((data_len >> 40) & 0xFF); frame[5] = (char) ((data_len >> 32) & 0xFF); frame[6] = (char) ((data_len >> 24) & 0xFF); frame[7] = (char) ((data_len >> 16) & 0xFF); frame[8] = (char) ((data_len >> 8) & 0xFF); frame[9] = (char) ((data_len) & 0xFF); body_offset = 10; } if(flags & WS_HAS_MASK) { if(mask != NULL) { memcpy(&frame[body_offset], mask, 4); } websocket_decode(&frame[body_offset + 4], data, data_len, &frame[body_offset], 0); body_offset += 4; } else { memcpy(&frame[body_offset], data, data_len); } return body_offset + data_len; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/websocket_parser.h000066400000000000000000000055441520575453600301470ustar00rootroot00000000000000#ifndef WEBSOCKET_PARSER_H #define WEBSOCKET_PARSER_H #ifdef __cplusplus extern "C" { #endif #include #if defined(_WIN32) && !defined(__MINGW32__) && \ (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__) #include #include typedef __int8 int8_t; typedef unsigned __int8 uint8_t; typedef __int16 int16_t; typedef unsigned __int16 uint16_t; typedef __int32 int32_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include #endif #define WEBSOCKET_UUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" typedef struct websocket_parser websocket_parser; typedef struct websocket_parser_settings websocket_parser_settings; typedef enum websocket_flags { // opcodes WS_OP_CONTINUE = 0x0, WS_OP_TEXT = 0x1, WS_OP_BINARY = 0x2, WS_OP_CLOSE = 0x8, WS_OP_PING = 0x9, WS_OP_PONG = 0xA, // marks WS_FINAL_FRAME = 0x10, WS_HAS_MASK = 0x20, } websocket_flags; #define WS_OP_MASK 0xF #define WS_FIN WS_FINAL_FRAME typedef int (*websocket_data_cb) (websocket_parser*, const char * at, size_t length); typedef int (*websocket_cb) (websocket_parser*); struct websocket_parser { uint32_t state; websocket_flags flags; char mask[4]; uint8_t mask_offset; size_t length; size_t require; size_t offset; void * data; }; struct websocket_parser_settings { websocket_cb on_frame_header; websocket_data_cb on_frame_body; websocket_cb on_frame_end; }; void websocket_parser_init(websocket_parser *parser); void websocket_parser_settings_init(websocket_parser_settings *settings); size_t websocket_parser_execute( websocket_parser * parser, const websocket_parser_settings *settings, const char * data, size_t len ); // Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and store mask's offset void websocket_parser_decode(char * dst, const char * src, size_t len, websocket_parser * parser); // Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and return mask's offset uint8_t websocket_decode(char * dst, const char * src, size_t len, const char mask[4], uint8_t mask_offset); #define websocket_encode(dst, src, len, mask, mask_offset) websocket_decode(dst, src, len, mask, mask_offset) // Calculate frame size using flags and data length size_t websocket_calc_frame_size(websocket_flags flags, size_t data_len); // Create string representation of frame size_t websocket_build_frame(char * frame, websocket_flags flags, const char mask[4], const char * data, size_t data_len); #define websocket_parser_get_opcode(p) (p->flags & WS_OP_MASK) #define websocket_parser_has_mask(p) (p->flags & WS_HAS_MASK) #define websocket_parser_has_final(p) (p->flags & WS_FIN) #ifdef __cplusplus } #endif #endif //WEBSOCKET_PARSER_H kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/wsdef.c000066400000000000000000000023201520575453600256750ustar00rootroot00000000000000#include "wsdef.h" #include #include "sha1.h" #include "base64.h" #include "websocket_parser.h" // base64_encode( SHA1(key + magic) ) void ws_encode_key(const char* key, char accept[]) { char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; unsigned char digest[20] = {0}; HV_SHA1_CTX ctx; HV_SHA1Init(&ctx); HV_SHA1Update(&ctx, (unsigned char*)key, (uint32_t)strlen(key)); HV_SHA1Update(&ctx, (unsigned char*)magic, (uint32_t)strlen(magic)); HV_SHA1Final(digest, &ctx); hv_base64_encode(digest, 20, accept); } // fix-header[2] + var-length[2/8] + mask[4] + data[data_len] int ws_calc_frame_size(int data_len, bool has_mask) { int size = data_len + 2; if (data_len >=126) { if (data_len > 0xFFFF) { size += 8; } else { size += 2; } } if (has_mask) size += 4; return size; } int ws_build_frame( char* out, const char* data, int data_len, const char mask[4], bool has_mask, enum ws_opcode opcode, bool fin) { int flags = opcode; if (fin) flags |= WS_FIN; if (has_mask) flags |= WS_HAS_MASK; return (int)websocket_build_frame(out, (websocket_flags)flags, mask, data, data_len); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/http/wsdef.h000066400000000000000000000044641520575453600257150ustar00rootroot00000000000000#ifndef HV_WS_DEF_H_ #define HV_WS_DEF_H_ #include "hexport.h" #include #include // import rand #define SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version" #define SEC_WEBSOCKET_KEY "Sec-WebSocket-Key" #define SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept" #define SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol" #define SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions" #define WS_SERVER_MIN_FRAME_SIZE 2 // 1000 1001 0000 0000 #define WS_SERVER_PING_FRAME "\211\0" // 1000 1010 0000 0000 #define WS_SERVER_PONG_FRAME "\212\0" #define WS_CLIENT_MIN_FRAME_SIZE 6 // 1000 1001 1000 0000 #define WS_CLIENT_PING_FRAME "\211\200WSWS" // 1000 1010 1000 0000 #define WS_CLIENT_PONG_FRAME "\212\200WSWS" enum ws_session_type { WS_CLIENT, WS_SERVER, }; enum ws_opcode { WS_OPCODE_CONTINUE = 0x0, WS_OPCODE_TEXT = 0x1, WS_OPCODE_BINARY = 0x2, WS_OPCODE_CLOSE = 0x8, WS_OPCODE_PING = 0x9, WS_OPCODE_PONG = 0xA, }; BEGIN_EXTERN_C // Sec-WebSocket-Key => Sec-WebSocket-Accept HV_EXPORT void ws_encode_key(const char* key, char accept[]); // fix-header[2] + var-length[2/8] + mask[4] + data[data_len] HV_EXPORT int ws_calc_frame_size(int data_len, bool has_mask DEFAULT(false)); HV_EXPORT int ws_build_frame( char* out, const char* data, int data_len, const char mask[4], bool has_mask DEFAULT(false), enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), bool fin DEFAULT(true)); HV_INLINE int ws_client_build_frame( char* out, const char* data, int data_len, /* const char mask[4] */ /* bool has_mask = true */ enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), bool fin DEFAULT(true)) { char mask[4] = {0}; int i = 0; int imask = rand(); for (i = 0; i < 4; i++) { mask[i] = (imask >> (8 * i)) & 0xff; } return ws_build_frame(out, data, data_len, mask, true, opcode, fin); } HV_INLINE int ws_server_build_frame( char* out, const char* data, int data_len, /* const char mask[4] */ /* bool has_mask = false */ enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), bool fin DEFAULT(true)) { char mask[4] = {0}; return ws_build_frame(out, data, data_len, mask, false, opcode, fin); } END_EXTERN_C #endif // HV_WS_DEF_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/hv.h000066400000000000000000000013111520575453600242270ustar00rootroot00000000000000#ifndef HV_H_ #define HV_H_ /** * @copyright 2018 HeWei, all rights reserved. */ // platform #include "hconfig.h" #include "hexport.h" #include "hplatform.h" // c #include "hdef.h" // #include "hatomic.h"// #include "herr.h" // #include "htime.h" // #include "hmath.h" // #include "hbase.h" #include "hversion.h" #include "hsysinfo.h" #include "hproc.h" #include "hthread.h" #include "hmutex.h" #include "hsocket.h" #include "hlog.h" #include "hbuf.h" // cpp #ifdef __cplusplus #include "hmap.h" // #include "hstring.h" // #include "hfile.h" #include "hpath.h" #include "hdir.h" #include "hurl.h" #endif #endif // HV_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/misc/000077500000000000000000000000001520575453600244005ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/misc/grpc_server.h000066400000000000000000000024721520575453600270770ustar00rootroot00000000000000#ifndef GRPC_SERVER_H #define GRPC_SERVER_H #include "grpcpp/grpcpp.h" using grpc::ServerBuilder; using grpc::Server; using grpc::Service; using grpc::ServerCompletionQueue; // GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH = 4M // GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH = 4M #define GRPC_MAX_RECV_MESSAGE_LENGTH 1<<24 // 16M #define GRPC_MAX_SEND_MESSAGE_LENGTH 1<<24 // 16M class GrpcServer { public: GrpcServer(int port) : _port(port) { char srvaddr[128] = {0}; snprintf(srvaddr, sizeof(srvaddr), "%s:%d", "0.0.0.0", _port); build_.AddListeningPort(srvaddr, grpc::InsecureServerCredentials()); build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS, 30000); build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 5000); build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); build_.SetMaxReceiveMessageSize(GRPC_MAX_RECV_MESSAGE_LENGTH); build_.SetMaxSendMessageSize(GRPC_MAX_SEND_MESSAGE_LENGTH); } void RegisterService(Service* service) { build_.RegisterService(service); } void Run(bool wait=true) { server_ = build_.BuildAndStart(); if (wait) { server_->Wait(); } } public: int _port; ServerBuilder build_; std::unique_ptr server_; }; #endif // GRPC_SERVER_H kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/misc/win32_getopt.h000066400000000000000000000441111520575453600270760ustar00rootroot00000000000000#ifndef __GETOPT_H__ /** * DISCLAIMER * This file is part of the mingw-w64 runtime package. * * The mingw-w64 runtime package and its code is distributed in the hope that it * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* * Copyright (c) 2002 Todd C. Miller * * 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" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, 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. * * Sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F39502-99-1-0512. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ #pragma warning(disable:4996) #define __GETOPT_H__ /* All the headers include this file. */ #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ #ifdef REPLACE_GETOPT int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ #undef optreset /* see getopt.h */ #define optreset __mingw_optreset int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #endif //extern int optind; /* index of first non-option in argv */ //extern int optopt; /* single option character, as parsed */ //extern int opterr; /* flag to enable built-in diagnostics... */ // /* (user may set to zero, to suppress) */ // //extern char *optarg; /* pointer to argument of current option */ #define PRINT_ERROR ((opterr) && (*options != ':')) #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ /* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #ifndef __CYGWIN__ #define __progname __argv[0] #else extern char __declspec(dllimport) *__progname; #endif #ifdef __CYGWIN__ static char EMSG[] = ""; #else #define EMSG (char*)"" #endif static int getopt_internal(int, char * const *, const char *, const struct option *, int *, int); static int parse_long_options(char * const *, const char *, const struct option *, int *, int); static int gcd(int, int); static void permute_args(int, int, int, char * const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c"; static const char recargstring[] = "option requires an argument -- %s"; static const char ambig[] = "ambiguous option -- %.*s"; static const char noarg[] = "option doesn't take an argument -- %.*s"; static const char illoptchar[] = "unknown option -- %c"; static const char illoptstring[] = "unknown option -- %s"; static void _vwarnx(const char *fmt,va_list ap) { (void)fprintf(stderr,"%s: ",__progname); if (fmt != NULL) (void)vfprintf(stderr,fmt,ap); (void)fprintf(stderr,"\n"); } static void warnx(const char *fmt,...) { va_list ap; va_start(ap,fmt); _vwarnx(fmt,ap); va_end(ap); } /* * Compute the greatest common divisor of a and b. */ static int gcd(int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char * const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd(nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end+i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **)nargv)[cstart] = swap; } } } #ifdef REPLACE_GETOPT /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the BSD getopt] */ int getopt(int nargc, char * const *nargv, const char *options) { /* * We don't pass FLAG_PERMUTE to getopt_internal() since * the BSD getopt(3) (unlike GNU) has never done this. * * Furthermore, since many privileged programs call getopt() * before dropping privileges it makes sense to keep things * as simple (and bug-free) as possible. */ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); } #endif /* REPLACE_GETOPT */ //extern int getopt(int nargc, char * const *nargv, const char *options); #ifdef _BSD_SOURCE /* * BSD adds the non-standard `optreset' feature, for reinitialisation * of `getopt' parsing. We support this feature, for applications which * proclaim their BSD heritage, before including this header; however, * to maintain portability, developers are advised to avoid it. */ # define optreset __mingw_optreset extern int optreset; #endif #ifdef __cplusplus } #endif /* * POSIX requires the `getopt' API to be specified in `unistd.h'; * thus, `unistd.h' includes this header. However, we do not want * to expose the `getopt_long' or `getopt_long_only' APIs, when * included in this manner. Thus, close the standard __GETOPT_H__ * declarations block, and open an additional __GETOPT_LONG_H__ * specific block, only when *not* __UNISTD_H_SOURCED__, in which * to declare the extended API. */ #endif /* !defined(__GETOPT_H__) */ #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) #define __GETOPT_LONG_H__ #ifdef __cplusplus extern "C" { #endif struct option /* specification for a long form option... */ { const char *name; /* option name, without leading hyphens */ int has_arg; /* does it take an argument? */ int *flag; /* where to save its status, or NULL */ int val; /* its associated status value */ }; enum /* permitted values for its `has_arg' field... */ { no_argument = 0, /* option never takes an argument */ required_argument, /* option always requires an argument */ optional_argument /* option may take an argument */ }; /* * parse_long_options -- * Parse long options in argc/argv argument vector. * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options(char * const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, ambiguous, match; #define IDENTICAL_INTERPRETATION(_x, _y) \ (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ long_options[(_x)].flag == long_options[(_y)].flag && \ long_options[(_x)].val == long_options[(_y)].val) current_argv = place; match = -1; ambiguous = 0; optind++; if ((has_equal = strchr(current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen(current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == current_argv_len) { /* exact match */ match = i; ambiguous = 0; break; } /* * If this is a known short option, don't allow * a partial match of a single character. */ if (short_too && current_argv_len == 1) continue; if (match == -1) /* partial match */ match = i; else if (!IDENTICAL_INTERPRETATION(i, match)) ambiguous = 1; } if (ambiguous) { /* ambiguous abbreviation */ if (PRINT_ERROR) warnx(ambig, (int)current_argv_len, current_argv); optopt = 0; return (BADCH); } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) warnx(noarg, (int)current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return (BADARG); } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no error * should be generated. */ if (PRINT_ERROR) warnx(recargstring, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return (BADARG); } } else { /* unknown option */ if (short_too) { --optind; return (-1); } if (PRINT_ERROR) warnx(illoptstring, current_argv); optopt = 0; return (BADCH); } if (idx) *idx = match; if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; return (0); } else return (long_options[match].val); #undef IDENTICAL_INTERPRETATION } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); /* * XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX using optreset. Work around this braindamage. */ if (optind == 0) optind = optreset = 1; /* * Disable GNU extensions if POSIXLY_CORRECT is set or options * string begins with a '+'. * * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or * optreset != 0 for GNU compatibility. */ if (posixly_correct == -1 || optreset != 0) posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); if (*options == '-') flags |= FLAG_ALLARGS; else if (posixly_correct || *options == '+') flags &= ~FLAG_PERMUTE; if (*options == '+' || *options == '-') options++; optarg = NULL; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { /* * If no permutation wanted, stop parsing * at first non-option. */ return (-1); } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; /* * If we have "-" do nothing, if "--" we are done. */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } } /* * Check long options if: * 1) we were passed some * 2) the arg is not just "-" * 3) either the arg starts with -- we are getopt_long_only() */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') place++; /* --foo long option */ else if (*place != ':' && strchr(options, *place) != NULL) short_too = 1; /* could be short option too */ optchar = parse_long_options(nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); } } if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = (char*)strchr(options, optchar)) == NULL) { /* * If the user specified "-" and '-' isn't listed in * options, return -1 (non-option) as per POSIX. * Otherwise, it is an unknown option character (or ':'). */ if (optchar == (int)'-' && *place == '\0') return (-1); if (!*place) ++optind; if (PRINT_ERROR) warnx(illoptchar, optchar); optopt = optchar; return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { /* -W long-option */ if (*place) /* no space */ /* NOTHING */; else if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else /* white space */ place = nargv[optind]; optchar = parse_long_options(nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); } else optarg = nargv[optind]; } place = EMSG; ++optind; } /* dump back option letter */ return (optchar); } /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* * getopt_long_only -- * Parse argc/argv argument vector. */ int getopt_long_only(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE|FLAG_LONGONLY)); } //extern int getopt_long(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); //extern int getopt_long_only(int nargc, char * const *nargv, const char *options, // const struct option *long_options, int *idx); /* * Previous MinGW implementation had... */ #ifndef HAVE_DECL_GETOPT /* * ...for the long form API only; keep this for compatibility. */ # define HAVE_DECL_GETOPT 1 #endif #ifdef __cplusplus } #endif #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/mqtt/000077500000000000000000000000001520575453600244325ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/mqtt/mqtt_client.c000066400000000000000000000443461520575453600271340ustar00rootroot00000000000000#include "mqtt_client.h" #include "hbase.h" #include "hlog.h" #include "herr.h" #include "hendian.h" #include "hsocket.h" static unsigned short mqtt_next_mid() { static unsigned short s_mid = 0; return ++s_mid; } static int mqtt_client_send(mqtt_client_t* cli, const void* buf, int len) { // thread-safe hmutex_lock(&cli->mutex_); int nwrite = hio_write(cli->io, buf, len); hmutex_unlock(&cli->mutex_); return nwrite; } static int mqtt_send_head(hio_t* io, int type, int length) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = type; head.length = length; unsigned char headbuf[8] = { 0 }; int headlen = mqtt_head_pack(&head, headbuf); return mqtt_client_send(cli, headbuf, headlen); } static int mqtt_send_head_with_mid(hio_t* io, int type, unsigned short mid) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = type; if (head.type == MQTT_TYPE_PUBREL) { head.qos = 1; } head.length = 2; unsigned char headbuf[8] = { 0 }; unsigned char* p = headbuf; int headlen = mqtt_head_pack(&head, p); p += headlen; PUSH16(p, mid); return mqtt_client_send(cli, headbuf, headlen + 2); } static void mqtt_send_ping(hio_t* io) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); if (cli->ping_cnt++ == 3) { hloge("mqtt no pong!"); hio_close(io); return; } mqtt_send_head(io, MQTT_TYPE_PINGREQ, 0); } static void mqtt_send_pong(hio_t* io) { mqtt_send_head(io, MQTT_TYPE_PINGRESP, 0); } static void mqtt_send_disconnect(hio_t* io) { mqtt_send_head(io, MQTT_TYPE_DISCONNECT, 0); } /* * MQTT_TYPE_CONNECT * 2 + protocol_name + 1 protocol_version + 1 conn_flags + 2 keepalive + 2 + [client_id] + * [2 + will_topic + 2 + will_payload] + * [2 + username] + [2 + password] */ static int mqtt_client_login(mqtt_client_t* cli) { int len = 2 + 1 + 1 + 2 + 2; unsigned short cid_len = 0, will_topic_len = 0, will_payload_len = 0, username_len = 0, password_len = 0; unsigned char conn_flags = 0; // protocol_name_len len += cli->protocol_version == MQTT_PROTOCOL_V31 ? 6 : 4; if (*cli->client_id) { cid_len = strlen(cli->client_id); } else { cid_len = 20; hv_random_string(cli->client_id, cid_len); hlogi("MQTT client_id: %.*s", (int)cid_len, cli->client_id); } len += cid_len; if (cid_len == 0) cli->clean_session = 1; if (cli->clean_session) { conn_flags |= MQTT_CONN_CLEAN_SESSION; } if (cli->will && cli->will->topic && cli->will->payload) { will_topic_len = cli->will->topic_len ? cli->will->topic_len : strlen(cli->will->topic); will_payload_len = cli->will->payload_len ? cli->will->payload_len : strlen(cli->will->payload); if (will_topic_len && will_payload_len) { conn_flags |= MQTT_CONN_HAS_WILL; conn_flags |= ((cli->will->qos & 3) << 3); if (cli->will->retain) { conn_flags |= MQTT_CONN_WILL_RETAIN; } len += 2 + will_topic_len; len += 2 + will_payload_len; } } if (*cli->username) { username_len = strlen(cli->username); if (username_len) { conn_flags |= MQTT_CONN_HAS_USERNAME; len += 2 + username_len; } } if (*cli->password) { password_len = strlen(cli->password); if (password_len) { conn_flags |= MQTT_CONN_HAS_PASSWORD; len += 2 + password_len; } } mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = MQTT_TYPE_CONNECT; head.length = len; int buflen = mqtt_estimate_length(&head); unsigned char* buf = NULL; HV_STACK_ALLOC(buf, buflen); unsigned char* p = buf; int headlen = mqtt_head_pack(&head, p); p += headlen; // TODO: Not implement MQTT_PROTOCOL_V5 if (cli->protocol_version == MQTT_PROTOCOL_V31) { PUSH16(p, 6); PUSH_N(p, MQTT_PROTOCOL_NAME_v31, 6); } else { PUSH16(p, 4); PUSH_N(p, MQTT_PROTOCOL_NAME, 4); } PUSH8(p, cli->protocol_version); PUSH8(p, conn_flags); PUSH16(p, cli->keepalive); PUSH16(p, cid_len); if (cid_len > 0) { PUSH_N(p, cli->client_id, cid_len); } if (conn_flags & MQTT_CONN_HAS_WILL) { PUSH16(p, will_topic_len); PUSH_N(p, cli->will->topic, will_topic_len); PUSH16(p, will_payload_len); PUSH_N(p, cli->will->payload, will_payload_len); } if (conn_flags & MQTT_CONN_HAS_USERNAME) { PUSH16(p, username_len); PUSH_N(p, cli->username, username_len); } if (conn_flags & MQTT_CONN_HAS_PASSWORD) { PUSH16(p, password_len); PUSH_N(p, cli->password, password_len); } int nwrite = mqtt_client_send(cli, buf, p - buf); HV_STACK_FREE(buf); return nwrite < 0 ? nwrite : 0; } static void connect_timeout_cb(htimer_t* timer) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(timer); if (cli == NULL) return; cli->timer = NULL; cli->error = ETIMEDOUT; hio_t* io = cli->io; if (io == NULL) return; char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; hlogw("connect timeout [%s] <=> [%s]", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); hio_close(io); } static void reconnect_timer_cb(htimer_t* timer) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(timer); if (cli == NULL) return; cli->timer = NULL; mqtt_client_reconnect(cli); } static void on_close(hio_t* io) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); cli->connected = 0; if (cli->cb) { cli->head.type = MQTT_TYPE_DISCONNECT; cli->cb(cli, cli->head.type); } // reconnect if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); cli->timer = htimer_add(cli->loop, reconnect_timer_cb, delay, 1); hevent_set_userdata(cli->timer, cli); } } static void on_packet(hio_t* io, void* buf, int len) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); unsigned char* p = (unsigned char*)buf; unsigned char* end = p + len; memset(&cli->head, 0, sizeof(mqtt_head_t)); int headlen = mqtt_head_unpack(&cli->head, p, len); if (headlen <= 0) return; p += headlen; switch (cli->head.type) { // case MQTT_TYPE_CONNECT: case MQTT_TYPE_CONNACK: { if (cli->head.length < 2) { hloge("MQTT CONNACK malformed!"); hio_close(io); return; } unsigned char conn_flags = 0, rc = 0; POP8(p, conn_flags); POP8(p, rc); if (rc != MQTT_CONNACK_ACCEPTED) { cli->error = rc; hloge("MQTT CONNACK error=%d", cli->error); hio_close(io); return; } cli->connected = 1; if (cli->timer) { htimer_del(cli->timer); cli->timer = NULL; } if (cli->keepalive) { cli->ping_cnt = 0; hio_set_heartbeat(io, cli->keepalive * 1000, mqtt_send_ping); } } break; case MQTT_TYPE_PUBLISH: { if (cli->head.length < 2) { hloge("MQTT PUBLISH malformed!"); hio_close(io); return; } memset(&cli->message, 0, sizeof(mqtt_message_t)); POP16(p, cli->message.topic_len); if (end - p < cli->message.topic_len) { hloge("MQTT PUBLISH malformed!"); hio_close(io); return; } // NOTE: Not deep copy cli->message.topic = (char*)p; p += cli->message.topic_len; if (cli->head.qos > 0) { if (end - p < 2) { hloge("MQTT PUBLISH malformed!"); hio_close(io); return; } POP16(p, cli->mid); } cli->message.payload_len = end - p; if (cli->message.payload_len > 0) { // NOTE: Not deep copy cli->message.payload = (char*)p; } cli->message.qos = cli->head.qos; if (cli->message.qos == 0) { // Do nothing } else if (cli->message.qos == 1) { mqtt_send_head_with_mid(io, MQTT_TYPE_PUBACK, cli->mid); } else if (cli->message.qos == 2) { mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREC, cli->mid); } } break; case MQTT_TYPE_PUBACK: case MQTT_TYPE_PUBREC: case MQTT_TYPE_PUBREL: case MQTT_TYPE_PUBCOMP: { if (cli->head.length < 2) { hloge("MQTT PUBACK malformed!"); hio_close(io); return; } POP16(p, cli->mid); if (cli->head.type == MQTT_TYPE_PUBREC) { mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREL, cli->mid); } else if (cli->head.type == MQTT_TYPE_PUBREL) { mqtt_send_head_with_mid(io, MQTT_TYPE_PUBCOMP, cli->mid); } } break; // case MQTT_TYPE_SUBSCRIBE: // break; case MQTT_TYPE_SUBACK: { if (cli->head.length < 2) { hloge("MQTT SUBACK malformed!"); hio_close(io); return; } POP16(p, cli->mid); } break; // case MQTT_TYPE_UNSUBSCRIBE: // break; case MQTT_TYPE_UNSUBACK: { if (cli->head.length < 2) { hloge("MQTT UNSUBACK malformed!"); hio_close(io); return; } POP16(p, cli->mid); } break; case MQTT_TYPE_PINGREQ: // printf("recv ping\n"); // printf("send pong\n"); mqtt_send_pong(io); return; case MQTT_TYPE_PINGRESP: // printf("recv pong\n"); cli->ping_cnt = 0; return; case MQTT_TYPE_DISCONNECT: hio_close(io); return; default: hloge("MQTT client received wrong type=%d", (int)cli->head.type); hio_close(io); return; } if (cli->cb) { cli->cb(cli, cli->head.type); } } static void on_connect(hio_t* io) { mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); if (cli->cb) { cli->head.type = MQTT_TYPE_CONNECT; cli->cb(cli, cli->head.type); } if (cli->reconn_setting) { reconn_setting_reset(cli->reconn_setting); } static unpack_setting_t mqtt_unpack_setting; mqtt_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; mqtt_unpack_setting.package_max_length = DEFAULT_MQTT_PACKAGE_MAX_LENGTH; mqtt_unpack_setting.body_offset = 2; mqtt_unpack_setting.length_field_offset = 1; mqtt_unpack_setting.length_field_bytes = 1; mqtt_unpack_setting.length_field_coding = ENCODE_BY_VARINT; hio_set_unpack(io, &mqtt_unpack_setting); // start recv packet hio_setcb_read(io, on_packet); hio_read(io); mqtt_client_login(cli); } mqtt_client_t* mqtt_client_new(hloop_t* loop) { if (loop == NULL) { loop = hloop_new(HLOOP_FLAG_AUTO_FREE); if (loop == NULL) return NULL; } mqtt_client_t* cli = NULL; HV_ALLOC_SIZEOF(cli); if (cli == NULL) return NULL; cli->loop = loop; cli->protocol_version = MQTT_PROTOCOL_V311; cli->keepalive = DEFAULT_MQTT_KEEPALIVE; hmutex_init(&cli->mutex_); return cli; } void mqtt_client_free(mqtt_client_t* cli) { if (!cli) return; hmutex_destroy(&cli->mutex_); if (cli->ssl_ctx && cli->alloced_ssl_ctx) { hssl_ctx_free(cli->ssl_ctx); cli->ssl_ctx = NULL; } HV_FREE(cli->reconn_setting); HV_FREE(cli->will); HV_FREE(cli); } void mqtt_client_run (mqtt_client_t* cli) { if (!cli || !cli->loop) return; hloop_run(cli->loop); } void mqtt_client_stop(mqtt_client_t* cli) { if (!cli || !cli->loop) return; hloop_stop(cli->loop); } void mqtt_client_set_id(mqtt_client_t* cli, const char* id) { if (!cli || !id) return; hv_strncpy(cli->client_id, id, sizeof(cli->client_id)); } void mqtt_client_set_will(mqtt_client_t* cli, mqtt_message_t* will) { if (!cli || !will) return; if (cli->will == NULL) { HV_ALLOC_SIZEOF(cli->will); } memcpy(cli->will, will, sizeof(mqtt_message_t)); } void mqtt_client_set_auth(mqtt_client_t* cli, const char* username, const char* password) { if (!cli) return; if (username) { hv_strncpy(cli->username, username, sizeof(cli->username)); } if (password) { hv_strncpy(cli->password, password, sizeof(cli->password)); } } void mqtt_client_set_callback(mqtt_client_t* cli, mqtt_client_cb cb) { if (!cli) return; cli->cb = cb; } void mqtt_client_set_userdata(mqtt_client_t* cli, void* userdata) { if (!cli) return; cli->userdata = userdata; } void* mqtt_client_get_userdata(mqtt_client_t* cli) { if (!cli) return NULL; return cli->userdata; } int mqtt_client_get_last_error(mqtt_client_t* cli) { if (!cli) return -1; return cli->error; } int mqtt_client_set_ssl_ctx(mqtt_client_t* cli, hssl_ctx_t ssl_ctx) { cli->ssl_ctx = ssl_ctx; return 0; } int mqtt_client_new_ssl_ctx(mqtt_client_t* cli, hssl_ctx_opt_t* opt) { opt->endpoint = HSSL_CLIENT; hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; cli->alloced_ssl_ctx = true; return mqtt_client_set_ssl_ctx(cli, ssl_ctx); } int mqtt_client_set_reconnect(mqtt_client_t* cli, reconn_setting_t* reconn) { if (reconn == NULL) { HV_FREE(cli->reconn_setting); return 0; } if (cli->reconn_setting == NULL) { HV_ALLOC_SIZEOF(cli->reconn_setting); } *cli->reconn_setting = *reconn; return 0; } int mqtt_client_reconnect(mqtt_client_t* cli) { mqtt_client_connect(cli, cli->host, cli->port, cli->ssl); return 0; } void mqtt_client_set_connect_timeout(mqtt_client_t* cli, int ms) { cli->connect_timeout = ms; } void mqtt_client_set_host(mqtt_client_t* cli, const char* host, int port, int ssl) { hv_strncpy(cli->host, host, sizeof(cli->host)); cli->port = port; cli->ssl = ssl; } int mqtt_client_connect(mqtt_client_t* cli, const char* host, int port, int ssl) { if (!cli) return -1; hv_strncpy(cli->host, host, sizeof(cli->host)); cli->port = port; cli->ssl = ssl; hio_t* io = hio_create_socket(cli->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); if (io == NULL) return -1; if (ssl) { if (cli->ssl_ctx) { hio_set_ssl_ctx(io, cli->ssl_ctx); } hio_enable_ssl(io); } cli->io = io; hevent_set_userdata(io, cli); hio_setcb_connect(io, on_connect); hio_setcb_close(io, on_close); if (cli->connect_timeout > 0) { cli->timer = htimer_add(cli->loop, connect_timeout_cb, cli->connect_timeout, 1); hevent_set_userdata(cli->timer, cli); } return hio_connect(io); } bool mqtt_client_is_connected(mqtt_client_t* cli) { return cli && cli->connected; } int mqtt_client_disconnect(mqtt_client_t* cli) { if (!cli || !cli->io) return -1; // cancel reconnect first mqtt_client_set_reconnect(cli, NULL); mqtt_send_disconnect(cli->io); return hio_close(cli->io); } int mqtt_client_publish(mqtt_client_t* cli, mqtt_message_t* msg) { if (!cli || !cli->io || !msg) return -1; if (!cli->connected) return -2; int topic_len = msg->topic_len ? msg->topic_len : strlen(msg->topic); int payload_len = msg->payload_len ? msg->payload_len : strlen(msg->payload); int len = 2 + topic_len + payload_len; if (msg->qos > 0) len += 2; // mid unsigned short mid = 0; mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = MQTT_TYPE_PUBLISH; head.qos = msg->qos & 3; head.retain = msg->retain; head.length = len; int buflen = mqtt_estimate_length(&head); // NOTE: send payload alone buflen -= payload_len; unsigned char* buf = NULL; HV_STACK_ALLOC(buf, buflen); unsigned char* p = buf; int headlen = mqtt_head_pack(&head, p); p += headlen; PUSH16(p, topic_len); PUSH_N(p, msg->topic, topic_len); if (msg->qos) { mid = mqtt_next_mid(); PUSH16(p, mid); } hmutex_lock(&cli->mutex_); // send head + topic + mid int nwrite = hio_write(cli->io, buf, p - buf); HV_STACK_FREE(buf); if (nwrite < 0) { goto unlock; } // send payload nwrite = hio_write(cli->io, msg->payload, payload_len); unlock: hmutex_unlock(&cli->mutex_); return nwrite < 0 ? nwrite : mid; } int mqtt_client_subscribe(mqtt_client_t* cli, const char* topic, int qos) { if (!cli || !cli->io || !topic) return -1; if (!cli->connected) return -2; int topic_len = strlen(topic); int len = 2 + 2 + topic_len + 1; mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = MQTT_TYPE_SUBSCRIBE; head.qos = 1; head.length = len; int buflen = mqtt_estimate_length(&head); unsigned char* buf = NULL; HV_STACK_ALLOC(buf, buflen); unsigned char* p = buf; int headlen = mqtt_head_pack(&head, p); p += headlen; unsigned short mid = mqtt_next_mid(); PUSH16(p, mid); PUSH16(p, topic_len); PUSH_N(p, topic, topic_len); PUSH8(p, qos & 3); // send head + mid + topic + qos int nwrite = mqtt_client_send(cli, buf, p - buf); HV_STACK_FREE(buf); return nwrite < 0 ? nwrite : mid; } int mqtt_client_unsubscribe(mqtt_client_t* cli, const char* topic) { if (!cli || !cli->io || !topic) return -1; if (!cli->connected) return -2; int topic_len = strlen(topic); int len = 2 + 2 + topic_len; mqtt_head_t head; memset(&head, 0, sizeof(head)); head.type = MQTT_TYPE_UNSUBSCRIBE; head.qos = 1; head.length = len; int buflen = mqtt_estimate_length(&head); unsigned char* buf = NULL; HV_STACK_ALLOC(buf, buflen); unsigned char* p = buf; int headlen = mqtt_head_pack(&head, p); p += headlen; unsigned short mid = mqtt_next_mid(); PUSH16(p, mid); PUSH16(p, topic_len); PUSH_N(p, topic, topic_len); // send head + mid + topic int nwrite = mqtt_client_send(cli, buf, p - buf); HV_STACK_FREE(buf); return nwrite < 0 ? nwrite : mid; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/mqtt/mqtt_client.h000066400000000000000000000226631520575453600271370ustar00rootroot00000000000000#ifndef HV_MQTT_CLIENT_H_ #define HV_MQTT_CLIENT_H_ #include "mqtt_protocol.h" #include "hloop.h" #include "hssl.h" #include "hmutex.h" #define DEFAULT_MQTT_KEEPALIVE 60 // s typedef struct mqtt_client_s mqtt_client_t; // @type mqtt_type_e // @example examples/mqtt typedef void (*mqtt_client_cb)(mqtt_client_t* cli, int type); struct mqtt_client_s { // connect: host:port char host[256]; int port; int connect_timeout; // ms // reconnect reconn_setting_t* reconn_setting; // login: flags + keepalive + client_id + will + username + password // flags unsigned char protocol_version; // Default MQTT_PROTOCOL_V311 unsigned char clean_session: 1; unsigned char ssl: 1; // Read Only unsigned char alloced_ssl_ctx: 1; // intern unsigned char connected : 1; unsigned short keepalive; int ping_cnt; char client_id[64]; // will mqtt_message_t* will; // auth char username[64]; char password[64]; // message mqtt_head_t head; int error; // for MQTT_TYPE_CONNACK int mid; // for MQTT_TYPE_SUBACK, MQTT_TYPE_PUBACK mqtt_message_t message; // for MQTT_TYPE_PUBLISH // callback mqtt_client_cb cb; // userdata void* userdata; // privdata hloop_t* loop; hio_t* io; htimer_t* timer; // SSL/TLS hssl_ctx_t ssl_ctx; // thread-safe hmutex_t mutex_; }; BEGIN_EXTERN_C // hloop_new -> malloc(mqtt_client_t) HV_EXPORT mqtt_client_t* mqtt_client_new(hloop_t* loop DEFAULT(NULL)); // @see hloop_run HV_EXPORT void mqtt_client_run (mqtt_client_t* cli); // @see hloop_stop HV_EXPORT void mqtt_client_stop(mqtt_client_t* cli); // hloop_free -> free(mqtt_client_t) HV_EXPORT void mqtt_client_free(mqtt_client_t* cli); // id HV_EXPORT void mqtt_client_set_id(mqtt_client_t* cli, const char* id); // will HV_EXPORT void mqtt_client_set_will(mqtt_client_t* cli, mqtt_message_t* will); // auth HV_EXPORT void mqtt_client_set_auth(mqtt_client_t* cli, const char* username, const char* password); // callback HV_EXPORT void mqtt_client_set_callback(mqtt_client_t* cli, mqtt_client_cb cb); // userdata HV_EXPORT void mqtt_client_set_userdata(mqtt_client_t* cli, void* userdata); HV_EXPORT void* mqtt_client_get_userdata(mqtt_client_t* cli); // error HV_EXPORT int mqtt_client_get_last_error(mqtt_client_t* cli); // SSL/TLS HV_EXPORT int mqtt_client_set_ssl_ctx(mqtt_client_t* cli, hssl_ctx_t ssl_ctx); // hssl_ctx_new(opt) -> mqtt_client_set_ssl_ctx HV_EXPORT int mqtt_client_new_ssl_ctx(mqtt_client_t* cli, hssl_ctx_opt_t* opt); // reconnect HV_EXPORT int mqtt_client_set_reconnect(mqtt_client_t* cli, reconn_setting_t* reconn); HV_EXPORT int mqtt_client_reconnect(mqtt_client_t* cli); // connect // hio_create_socket -> hio_connect -> // on_connect -> mqtt_client_login -> // on_connack HV_EXPORT void mqtt_client_set_connect_timeout(mqtt_client_t* cli, int ms); HV_EXPORT void mqtt_client_set_host(mqtt_client_t* cli, const char* host, int port, int ssl); HV_EXPORT int mqtt_client_connect(mqtt_client_t* cli, const char* host, int port DEFAULT(DEFAULT_MQTT_PORT), int ssl DEFAULT(0)); HV_EXPORT bool mqtt_client_is_connected(mqtt_client_t* cli); // disconnect // @see hio_close HV_EXPORT int mqtt_client_disconnect(mqtt_client_t* cli); // publish HV_EXPORT int mqtt_client_publish(mqtt_client_t* cli, mqtt_message_t* msg); // subscribe HV_EXPORT int mqtt_client_subscribe(mqtt_client_t* cli, const char* topic, int qos DEFAULT(0)); // unsubscribe HV_EXPORT int mqtt_client_unsubscribe(mqtt_client_t* cli, const char* topic); END_EXTERN_C #ifdef __cplusplus #include #include #include #include namespace hv { // @usage examples/mqtt/mqtt_client_test.cpp class MqttClient { public: mqtt_client_t* client; // callbacks typedef std::function MqttCallback; typedef std::function MqttMessageCallback; MqttCallback onConnect; MqttCallback onClose; MqttMessageCallback onMessage; MqttClient(hloop_t* loop = NULL) { client = mqtt_client_new(loop); } ~MqttClient() { if (client) { mqtt_client_free(client); client = NULL; } } void run() { mqtt_client_set_callback(client, on_mqtt); mqtt_client_set_userdata(client, this); mqtt_client_run(client); } void stop() { mqtt_client_stop(client); } void setID(const char* id) { mqtt_client_set_id(client, id); } void setWill(mqtt_message_t* will) { mqtt_client_set_will(client, will); } void setAuth(const char* username, const char* password) { mqtt_client_set_auth(client, username, password); } void setPingInterval(int sec) { client->keepalive = sec; } int lastError() { return mqtt_client_get_last_error(client); } // SSL/TLS int setSslCtx(hssl_ctx_t ssl_ctx) { return mqtt_client_set_ssl_ctx(client, ssl_ctx); } int newSslCtx(hssl_ctx_opt_t* opt) { return mqtt_client_new_ssl_ctx(client, opt); } void setReconnect(reconn_setting_t* reconn) { mqtt_client_set_reconnect(client, reconn); } void setConnectTimeout(int ms) { mqtt_client_set_connect_timeout(client, ms); } void setHost(const char* host, int port = DEFAULT_MQTT_PORT, int ssl = 0) { mqtt_client_set_host(client, host, port, ssl); } int connect(const char* host, int port = DEFAULT_MQTT_PORT, int ssl = 0) { return mqtt_client_connect(client, host, port, ssl); } int reconnect() { return mqtt_client_reconnect(client); } int disconnect() { return mqtt_client_disconnect(client); } bool isConnected() { return mqtt_client_is_connected(client); } int publish(mqtt_message_t* msg, MqttCallback ack_cb = NULL) { int mid = mqtt_client_publish(client, msg); if (msg->qos > 0 && mid >= 0 && ack_cb) { setAckCallback(mid, ack_cb); } return mid; } int publish(const std::string& topic, const std::string& payload, int qos = 0, int retain = 0, MqttCallback ack_cb = NULL) { mqtt_message_t msg; memset(&msg, 0, sizeof(msg)); msg.topic_len = topic.size(); msg.topic = topic.c_str(); msg.payload_len = payload.size(); msg.payload = payload.c_str(); msg.qos = qos; msg.retain = retain; return publish(&msg, ack_cb); } int subscribe(const char* topic, int qos = 0, MqttCallback ack_cb = NULL) { int mid = mqtt_client_subscribe(client, topic, qos); if (qos > 0 && mid >= 0 && ack_cb) { setAckCallback(mid, ack_cb); } return mid; } int unsubscribe(const char* topic, MqttCallback ack_cb = NULL) { int mid = mqtt_client_unsubscribe(client, topic); if (mid >= 0 && ack_cb) { setAckCallback(mid, ack_cb); } return mid; } protected: void setAckCallback(int mid, MqttCallback cb) { ack_cbs_mutex.lock(); ack_cbs[mid] = std::move(cb); ack_cbs_mutex.unlock(); } void invokeAckCallback(int mid) { MqttCallback ack_cb = NULL; ack_cbs_mutex.lock(); auto iter = ack_cbs.find(mid); if (iter != ack_cbs.end()) { ack_cb = std::move(iter->second); ack_cbs.erase(iter); } ack_cbs_mutex.unlock(); if (ack_cb) ack_cb(this); } static void on_mqtt(mqtt_client_t* cli, int type) { MqttClient* client = (MqttClient*)mqtt_client_get_userdata(cli); // printf("on_mqtt type=%d\n", type); switch(type) { case MQTT_TYPE_CONNECT: // printf("mqtt connected!\n"); break; case MQTT_TYPE_DISCONNECT: // printf("mqtt disconnected!\n"); if (client->onClose) { client->onClose(client); } break; case MQTT_TYPE_CONNACK: // printf("mqtt connack!\n"); if (client->onConnect) { client->onConnect(client); } break; case MQTT_TYPE_PUBLISH: if (client->onMessage) { client->onMessage(client, &cli->message); } break; case MQTT_TYPE_PUBACK: /* qos = 1 */ // printf("mqtt puback mid=%d\n", cli->mid); client->invokeAckCallback(cli->mid); break; case MQTT_TYPE_PUBREC: /* qos = 2 */ // printf("mqtt pubrec mid=%d\n", cli->mid); // wait MQTT_TYPE_PUBCOMP break; case MQTT_TYPE_PUBCOMP: /* qos = 2 */ // printf("mqtt pubcomp mid=%d\n", cli->mid); client->invokeAckCallback(cli->mid); break; case MQTT_TYPE_SUBACK: // printf("mqtt suback mid=%d\n", cli->mid); client->invokeAckCallback(cli->mid); break; case MQTT_TYPE_UNSUBACK: // printf("mqtt unsuback mid=%d\n", cli->mid); client->invokeAckCallback(cli->mid); break; default: break; } } private: // mid => ack callback std::map ack_cbs; std::mutex ack_cbs_mutex; }; } #endif #endif // HV_MQTT_CLIENT_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/mqtt/mqtt_protocol.c000066400000000000000000000012541520575453600275060ustar00rootroot00000000000000#include "mqtt_protocol.h" #include "hmath.h" int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]) { buf[0] = (head->type << 4) | (head->dup << 3) | (head->qos << 1) | (head->retain); int bytes = varint_encode(head->length, buf + 1); return 1 + bytes; } int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len) { head->type = (buf[0] >> 4) & 0x0F; head->dup = (buf[0] >> 3) & 0x01; head->qos = (buf[0] >> 1) & 0x03; head->retain = buf[0] & 0x01; int bytes = len - 1; head->length = varint_decode(buf + 1, &bytes); if (bytes <= 0) return bytes; return 1 + bytes; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/mqtt/mqtt_protocol.h000066400000000000000000000044501520575453600275140ustar00rootroot00000000000000#ifndef HV_MQTT_PROTOCOL_H_ #define HV_MQTT_PROTOCOL_H_ #include "hexport.h" #define DEFAULT_MQTT_PORT 1883 #define MQTT_PROTOCOL_V31 3 #define MQTT_PROTOCOL_V311 4 #define MQTT_PROTOCOL_V5 5 // Not yet supproted #define MQTT_PROTOCOL_NAME "MQTT" #define MQTT_PROTOCOL_NAME_v31 "MQIsdp" /* * connect flags * 0 1 2 3-4 5 6 7 * reserved clean_session has_will will_qos will_retain has_password has_username */ #define MQTT_CONN_CLEAN_SESSION 0x02 #define MQTT_CONN_HAS_WILL 0x04 #define MQTT_CONN_WILL_RETAIN 0x20 #define MQTT_CONN_HAS_PASSWORD 0x40 #define MQTT_CONN_HAS_USERNAME 0x80 typedef enum { MQTT_TYPE_CONNECT = 1, MQTT_TYPE_CONNACK = 2, MQTT_TYPE_PUBLISH = 3, MQTT_TYPE_PUBACK = 4, MQTT_TYPE_PUBREC = 5, MQTT_TYPE_PUBREL = 6, MQTT_TYPE_PUBCOMP = 7, MQTT_TYPE_SUBSCRIBE = 8, MQTT_TYPE_SUBACK = 9, MQTT_TYPE_UNSUBSCRIBE = 10, MQTT_TYPE_UNSUBACK = 11, MQTT_TYPE_PINGREQ = 12, MQTT_TYPE_PINGRESP = 13, MQTT_TYPE_DISCONNECT = 14, } mqtt_type_e; typedef enum { MQTT_CONNACK_ACCEPTED = 0, MQTT_CONNACK_REFUSED_PROTOCOL_VERSION = 1, MQTT_CONNACK_REFUSED_IDENTIFIER_REJECTED = 2, MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE = 3, MQTT_CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4, MQTT_CONNACK_REFUSED_NOT_AUTHORIZED = 5, } mqtt_connack_e; typedef struct mqtt_head_s { unsigned char type: 4; unsigned char dup: 1; unsigned char qos: 2; unsigned char retain: 1; unsigned int length; } mqtt_head_t; typedef struct mqtt_message_s { unsigned int topic_len; const char* topic; unsigned int payload_len; const char* payload; unsigned char qos; unsigned char retain; } mqtt_message_t; BEGIN_EXTERN_C #define DEFAULT_MQTT_PACKAGE_MAX_LENGTH (1 << 28) // 256M HV_INLINE int mqtt_estimate_length(mqtt_head_t* head) { // 28 bits => 4*7 bits varint return 1 + 4 + head->length; } HV_EXPORT int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]); HV_EXPORT int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len); END_EXTERN_C #endif // HV_MQTT_PROTOCOL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/000077500000000000000000000000001520575453600253065ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/README.md000066400000000000000000000002161520575453600265640ustar00rootroot00000000000000## 目录结构 ``` . ├── dns.h DNS协议 ├── ftp.h FTP协议 ├── icmp.h ICMP协议 └── smtp.h SMTP协议 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/dns.c000066400000000000000000000217031520575453600262410ustar00rootroot00000000000000#include "dns.h" #include "hdef.h" #include "hsocket.h" #include "herr.h" void dns_free(dns_t* dns) { SAFE_FREE(dns->questions); SAFE_FREE(dns->answers); SAFE_FREE(dns->authorities); SAFE_FREE(dns->addtionals); } // www.example.com => 3www7example3com int dns_name_encode(const char* domain, char* buf) { const char* p = domain; char* plen = buf++; int buflen = 1; int len = 0; while (*p != '\0') { if (*p != '.') { ++len; *buf = *p; } else { *plen = len; //printf("len=%d\n", len); plen = buf; len = 0; } ++p; ++buf; ++buflen; } *plen = len; //printf("len=%d\n", len); *buf = '\0'; if (len != 0) { ++buflen; // include last '\0' } return buflen; } // 3www7example3com => www.example.com int dns_name_decode(const char* buf, char* domain) { const char* p = buf; int len = *p++; //printf("len=%d\n", len); int buflen = 1; while (*p != '\0') { if (len-- == 0) { len = *p; //printf("len=%d\n", len); *domain = '.'; } else { *domain = *p; } ++p; ++domain; ++buflen; } *domain = '\0'; ++buflen; // include last '\0' return buflen; } int dns_rr_pack(dns_rr_t* rr, char* buf, int len) { char* p = buf; char encoded_name[256]; int encoded_namelen = dns_name_encode(rr->name, encoded_name); int packetlen = encoded_namelen + 2 + 2 + (rr->data ? (4+2+rr->datalen) : 0); if (len < packetlen) { return -1; } memcpy(p, encoded_name, encoded_namelen); p += encoded_namelen; uint16_t* pushort = (uint16_t*)p; *pushort = htons(rr->rtype); p += 2; pushort = (uint16_t*)p; *pushort = htons(rr->rclass); p += 2; // ... if (rr->datalen && rr->data) { uint32_t* puint = (uint32_t*)p; *puint = htonl(rr->ttl); p += 4; pushort = (uint16_t*)p; *pushort = htons(rr->datalen); p += 2; memcpy(p, rr->data, rr->datalen); p += rr->datalen; } return packetlen; } int dns_rr_unpack(char* buf, int len, dns_rr_t* rr, int is_question) { char* p = buf; int off = 0; int namelen = 0; if (*(uint8_t*)p >= 192) { // name off, we ignore namelen = 2; //uint16_t nameoff = (*(uint8_t*)p - 192) * 256 + *(uint8_t*)(p+1); } else { namelen = dns_name_decode(buf, rr->name); } if (namelen < 0) return -1; p += namelen; off += namelen; if (len < off + 4) return -1; uint16_t* pushort = (uint16_t*)p; rr->rtype = ntohs(*pushort); p += 2; pushort = (uint16_t*)p; rr->rclass = ntohs(*pushort); p += 2; off += 4; if (!is_question) { if (len < off + 6) return -1; uint32_t* puint = (uint32_t*)p; rr->ttl = ntohl(*puint); p += 4; pushort = (uint16_t*)p; rr->datalen = ntohs(*pushort); p += 2; off += 6; if (len < off + rr->datalen) return -1; rr->data = p; p += rr->datalen; off += rr->datalen; } return off; } int dns_pack(dns_t* dns, char* buf, int len) { if (len < sizeof(dnshdr_t)) return -1; int off = 0; dnshdr_t* hdr = &dns->hdr; dnshdr_t htonhdr = dns->hdr; htonhdr.transaction_id = htons(hdr->transaction_id); htonhdr.nquestion = htons(hdr->nquestion); htonhdr.nanswer = htons(hdr->nanswer); htonhdr.nauthority = htons(hdr->nauthority); htonhdr.naddtional = htons(hdr->naddtional); memcpy(buf, &htonhdr, sizeof(dnshdr_t)); off += sizeof(dnshdr_t); int i; for (i = 0; i < hdr->nquestion; ++i) { int packetlen = dns_rr_pack(dns->questions+i, buf+off, len-off); if (packetlen < 0) return -1; off += packetlen; } for (i = 0; i < hdr->nanswer; ++i) { int packetlen = dns_rr_pack(dns->answers+i, buf+off, len-off); if (packetlen < 0) return -1; off += packetlen; } for (i = 0; i < hdr->nauthority; ++i) { int packetlen = dns_rr_pack(dns->authorities+i, buf+off, len-off); if (packetlen < 0) return -1; off += packetlen; } for (i = 0; i < hdr->naddtional; ++i) { int packetlen = dns_rr_pack(dns->addtionals+i, buf+off, len-off); if (packetlen < 0) return -1; off += packetlen; } return off; } int dns_unpack(char* buf, int len, dns_t* dns) { memset(dns, 0, sizeof(dns_t)); if (len < sizeof(dnshdr_t)) return -1; int off = 0; dnshdr_t* hdr = &dns->hdr; memcpy(hdr, buf, sizeof(dnshdr_t)); off += sizeof(dnshdr_t); hdr->transaction_id = ntohs(hdr->transaction_id); hdr->nquestion = ntohs(hdr->nquestion); hdr->nanswer = ntohs(hdr->nanswer); hdr->nauthority = ntohs(hdr->nauthority); hdr->naddtional = ntohs(hdr->naddtional); int i; if (hdr->nquestion) { int bytes = hdr->nquestion * sizeof(dns_rr_t); SAFE_ALLOC(dns->questions, bytes); for (i = 0; i < hdr->nquestion; ++i) { int packetlen = dns_rr_unpack(buf+off, len-off, dns->questions+i, 1); if (packetlen < 0) return -1; off += packetlen; } } if (hdr->nanswer) { int bytes = hdr->nanswer * sizeof(dns_rr_t); SAFE_ALLOC(dns->answers, bytes); for (i = 0; i < hdr->nanswer; ++i) { int packetlen = dns_rr_unpack(buf+off, len-off, dns->answers+i, 0); if (packetlen < 0) return -1; off += packetlen; } } if (hdr->nauthority) { int bytes = hdr->nauthority * sizeof(dns_rr_t); SAFE_ALLOC(dns->authorities, bytes); for (i = 0; i < hdr->nauthority; ++i) { int packetlen = dns_rr_unpack(buf+off, len-off, dns->authorities+i, 0); if (packetlen < 0) return -1; off += packetlen; } } if (hdr->naddtional) { int bytes = hdr->naddtional * sizeof(dns_rr_t); SAFE_ALLOC(dns->addtionals, bytes); for (i = 0; i < hdr->naddtional; ++i) { int packetlen = dns_rr_unpack(buf+off, len-off, dns->addtionals+i, 0); if (packetlen < 0) return -1; off += packetlen; } } return off; } // dns_pack -> sendto -> recvfrom -> dns_unpack int dns_query(dns_t* query, dns_t* response, const char* nameserver) { char buf[1024]; int buflen = sizeof(buf); buflen = dns_pack(query, buf, buflen); if (buflen < 0) { return buflen; } #ifdef OS_WIN WSAInit(); #endif int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket"); return ERR_SOCKET; } so_sndtimeo(sockfd, 5000); so_rcvtimeo(sockfd, 5000); int ret = 0; int nsend, nrecv; int nparse; struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); memset(&addr, 0, addrlen); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(nameserver); addr.sin_port = htons(DNS_PORT); nsend = sendto(sockfd, buf, buflen, 0, (struct sockaddr*)&addr, addrlen); if (nsend != buflen) { ret = ERR_SENDTO; goto error; } nrecv = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen); if (nrecv <= 0) { ret = ERR_RECVFROM; goto error; } nparse = dns_unpack(buf, nrecv, response); if (nparse != nrecv) { ret = -ERR_INVALID_PACKAGE; goto error; } error: if (sockfd != INVALID_SOCKET) { closesocket(sockfd); } return ret; } int nslookup(const char* domain, uint32_t* addrs, int naddr, const char* nameserver) { dns_t query; memset(&query, 0, sizeof(query)); query.hdr.transaction_id = getpid(); query.hdr.qr = DNS_QUERY; query.hdr.rd = 1; query.hdr.nquestion = 1; dns_rr_t question; memset(&question, 0, sizeof(question)); strncpy(question.name, domain, sizeof(question.name)); question.rtype = DNS_TYPE_A; question.rclass = DNS_CLASS_IN; query.questions = &question; dns_t resp; memset(&resp, 0, sizeof(resp)); int ret = dns_query(&query, &resp, nameserver); if (ret != 0) { return ret; } dns_rr_t* rr = resp.answers; int addr_cnt = 0; if (resp.hdr.transaction_id != query.hdr.transaction_id || resp.hdr.qr != DNS_RESPONSE || resp.hdr.rcode != 0) { ret = -ERR_MISMATCH; goto end; } if (resp.hdr.nanswer == 0) { ret = 0; goto end; } for (int i = 0; i < resp.hdr.nanswer; ++i, ++rr) { if (rr->rtype == DNS_TYPE_A) { if (addr_cnt < naddr && rr->datalen == 4) { memcpy(addrs+addr_cnt, rr->data, 4); } ++addr_cnt; } /* else if (rr->rtype == DNS_TYPE_CNAME) { char name[256]; dns_name_decode(rr->data, name); } */ } ret = addr_cnt; end: dns_free(&resp); return ret; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/dns.h000066400000000000000000000053631520575453600262520ustar00rootroot00000000000000#ifndef HV_DNS_H_ #define HV_DNS_H_ #include "hexport.h" #include "hplatform.h" #define DNS_PORT 53 #define DNS_QUERY 0 #define DNS_RESPONSE 1 #define DNS_TYPE_A 1 // ipv4 #define DNS_TYPE_NS 2 #define DNS_TYPE_CNAME 5 #define DNS_TYPE_SOA 6 #define DNS_TYPE_WKS 11 #define DNS_TYPE_PTR 12 #define DNS_TYPE_HINFO 13 #define DNS_TYPE_MX 15 #define DNS_TYPE_AAAA 28 // ipv6 #define DNS_TYPE_AXFR 252 #define DNS_TYPE_ANY 255 #define DNS_CLASS_IN 1 #define DNS_NAME_MAXLEN 256 // sizeof(dnshdr_t) = 12 typedef struct dnshdr_s { uint16_t transaction_id; // flags #if BYTE_ORDER == LITTLE_ENDIAN uint8_t rd:1; uint8_t tc:1; uint8_t aa:1; uint8_t opcode:4; uint8_t qr:1; uint8_t rcode:4; uint8_t cd:1; uint8_t ad:1; uint8_t res:1; uint8_t ra:1; #elif BYTE_ORDER == BIG_ENDIAN uint8_t qr:1; // DNS_QUERY or DNS_RESPONSE uint8_t opcode:4; uint8_t aa:1; // authoritative uint8_t tc:1; // truncated uint8_t rd:1; // recursion desired uint8_t ra:1; // recursion available uint8_t res:1; // reserved uint8_t ad:1; // authenticated data uint8_t cd:1; // checking disable uint8_t rcode:4; #else #error "BYTE_ORDER undefined!" #endif uint16_t nquestion; uint16_t nanswer; uint16_t nauthority; uint16_t naddtional; } dnshdr_t; typedef struct dns_rr_s { char name[DNS_NAME_MAXLEN]; // original domain, such as www.example.com uint16_t rtype; uint16_t rclass; uint32_t ttl; uint16_t datalen; char* data; } dns_rr_t; typedef struct dns_s { dnshdr_t hdr; dns_rr_t* questions; dns_rr_t* answers; dns_rr_t* authorities; dns_rr_t* addtionals; } dns_t; BEGIN_EXTERN_C // www.example.com => 3www7example3com HV_EXPORT int dns_name_encode(const char* domain, char* buf); // 3www7example3com => www.example.com HV_EXPORT int dns_name_decode(const char* buf, char* domain); HV_EXPORT int dns_rr_pack(dns_rr_t* rr, char* buf, int len); HV_EXPORT int dns_rr_unpack(char* buf, int len, dns_rr_t* rr, int is_question); HV_EXPORT int dns_pack(dns_t* dns, char* buf, int len); HV_EXPORT int dns_unpack(char* buf, int len, dns_t* dns); // NOTE: free dns->rrs HV_EXPORT void dns_free(dns_t* dns); // dns_pack -> sendto -> recvfrom -> dns_unpack HV_EXPORT int dns_query(dns_t* query, dns_t* response, const char* nameserver DEFAULT("127.0.1.1")); // domain -> dns_t query; -> dns_query -> dns_t response; -> addrs HV_EXPORT int nslookup(const char* domain, uint32_t* addrs, int naddr, const char* nameserver DEFAULT("127.0.1.1")); END_EXTERN_C #endif // HV_DNS_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/ftp.c000066400000000000000000000157001520575453600262460ustar00rootroot00000000000000#include "ftp.h" #include "hsocket.h" #include "herr.h" const char* ftp_command_str(enum ftp_command cmd) { switch (cmd) { #define X(name) case FTP_##name: return #name; FTP_COMMAND_MAP(X) #undef X default: return ""; } } const char* ftp_status_str(enum ftp_status status) { switch (status) { #define XXX(code, name, string) case FTP_STATUS_##name: return #string; FTP_STATUS_MAP(XXX) #undef XXX default: return ""; } } int ftp_connect(ftp_handle_t* hftp, const char* host, int port) { int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); if (sockfd < 0) { return sockfd; } so_sndtimeo(sockfd, 5000); so_rcvtimeo(sockfd, 5000); hftp->sockfd = sockfd; int ret = 0; int status_code = 0; memset(hftp->recvbuf, 0, FTP_RECV_BUFSIZE); int nrecv = recv(sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(hftp->recvbuf); if (status_code != FTP_STATUS_READY) { ret = status_code; goto error; } return 0; error: closesocket(sockfd); return ret; } int ftp_login(ftp_handle_t* hftp, const char* username, const char* password) { int status_code = ftp_exec(hftp, "USER", username); status_code = ftp_exec(hftp, "PASS", password); return status_code == FTP_STATUS_LOGIN_OK ? 0 : status_code; } int ftp_quit(ftp_handle_t* hftp) { ftp_exec(hftp, "QUIT", NULL); closesocket(hftp->sockfd); return 0; } int ftp_exec(ftp_handle_t* hftp, const char* cmd, const char* param) { char buf[1024]; int len = 0; if (param && *param) { len = snprintf(buf, sizeof(buf), "%s %s\r\n", cmd, param); } else { len = snprintf(buf, sizeof(buf), "%s\r\n", cmd); } int nsend, nrecv; int ret = 0; nsend = send(hftp->sockfd, buf, len, 0); if (nsend != len) { ret = ERR_SEND; goto error; } //printf("> %s", buf); memset(hftp->recvbuf, 0, FTP_RECV_BUFSIZE); nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } //printf("< %s", hftp->recvbuf); return atoi(hftp->recvbuf); error: closesocket(hftp->sockfd); return ret; } static int ftp_parse_pasv(const char* resp, char* host, int* port) { // 227 Entering Passive Mode (127,0,0,1,4,51) const char* str = strchr(resp, '('); if (str == NULL) { return ERR_RESPONSE; } int arr[6]; sscanf(str, "(%d,%d,%d,%d,%d,%d)", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5]); sprintf(host, "%d.%d.%d.%d", arr[0], arr[1], arr[2], arr[3]); *port = arr[4] << 8 | arr[5]; return 0; } int ftp_download_with_cb(ftp_handle_t* hftp, const char* filepath, ftp_download_cb cb) { int status_code = ftp_exec(hftp, "PASV", NULL); if (status_code != FTP_STATUS_PASV) { return status_code; } char host[64]; int port = 0; int ret = ftp_parse_pasv(hftp->recvbuf, host, &port); if (ret != 0) { return ret; } //ftp_exec(hftp, "RETR", filepath); char request[1024]; int len = snprintf(request, sizeof(request), "RETR %s\r\n", filepath); int nsend = send(hftp->sockfd, request, len, 0); if (nsend != len) { closesocket(hftp->sockfd); return ERR_SEND; } //printf("> %s", request); int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); if (sockfd < 0) { return sockfd; } int nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { closesocket(hftp->sockfd); return ERR_RECV; } //printf("< %s", hftp->recvbuf); { // you can create thread to recv data char recvbuf[1024]; int ntotal = 0; while (1) { nrecv = recv(sockfd, recvbuf, sizeof(recvbuf), 0); if (cb) { cb(hftp, recvbuf, nrecv); } if (nrecv <= 0) break; ntotal += nrecv; } } closesocket(sockfd); nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { closesocket(hftp->sockfd); return ERR_RECV; } //printf("< %s", hftp->recvbuf); status_code = atoi(hftp->recvbuf); return status_code == FTP_STATUS_TRANSFER_COMPLETE ? 0 : status_code; } // local => remote int ftp_upload(ftp_handle_t* hftp, const char* local_filepath, const char* remote_filepath) { int status_code = ftp_exec(hftp, "PASV", NULL); if (status_code != FTP_STATUS_PASV) { return status_code; } char host[64]; int port = 0; int ret = ftp_parse_pasv(hftp->recvbuf, host, &port); if (ret != 0) { return ret; } //ftp_exec(hftp, "STOR", remote_filepath); char request[1024]; int len = snprintf(request, sizeof(request), "STOR %s\r\n", remote_filepath); int nsend = send(hftp->sockfd, request, len, 0); if (nsend != len) { closesocket(hftp->sockfd); return ERR_SEND; } //printf("> %s", request); int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); if (sockfd < 0) { return sockfd; } int nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { closesocket(hftp->sockfd); return ERR_RECV; } //printf("< %s", hftp->recvbuf); { // you can create thread to send data FILE* fp = fopen(local_filepath, "rb"); if (fp == NULL) { closesocket(sockfd); return ERR_OPEN_FILE; } char sendbuf[1024]; int nread, nsend; int ntotal = 0; while (1) { nread = fread(sendbuf, 1, sizeof(sendbuf), fp); if (nread == 0) break; nsend = send(sockfd, sendbuf, nread, 0); if (nsend != nread) break; ntotal += nsend; } fclose(fp); } closesocket(sockfd); nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); if (nrecv <= 0) { closesocket(hftp->sockfd); return ERR_RECV; } //printf("< %s", hftp->recvbuf); status_code = atoi(hftp->recvbuf); return status_code == FTP_STATUS_TRANSFER_COMPLETE ? 0 : status_code; } static int s_ftp_download_cb(ftp_handle_t* hftp, char* buf, int len) { FILE* fp = (FILE*)hftp->userdata; if (fp == NULL) return -1; if (len <= 0) { fclose(fp); hftp->userdata = NULL; return 0; } return fwrite(buf, 1, len, fp); } // remote => local int ftp_download(ftp_handle_t* hftp, const char* remote_filepath, const char* local_filepath) { FILE* fp = fopen(local_filepath, "wb"); if (fp == NULL) { return ERR_OPEN_FILE; } hftp->userdata = (void*)fp; int ret = ftp_download_with_cb(hftp, remote_filepath, s_ftp_download_cb); // ensure fclose if (hftp->userdata != NULL) { fclose(fp); hftp->userdata = NULL; } return ret; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/ftp.h000066400000000000000000000047571520575453600262650ustar00rootroot00000000000000#ifndef HV_FTP_H_ #define HV_FTP_H_ #include "hexport.h" #define FTP_COMMAND_PORT 21 #define FTP_DATA_PORT 20 // ftp_command // X(name) #define FTP_COMMAND_MAP(X) \ X(HELP) \ X(USER) \ X(PASS) \ X(PWD) \ X(CWD) \ X(CDUP) \ X(MKD) \ X(RMD) \ X(STAT) \ X(SIZE) \ X(DELE) \ X(RNFR) \ X(RNTO) \ X(PORT) \ X(PASV) \ X(LIST) \ X(NLST) \ X(APPE) \ X(RETR) \ X(STOR) \ X(QUIT) \ enum ftp_command { #define X(name) FTP_##name, FTP_COMMAND_MAP(X) #undef X }; // ftp_status // XXX(code, name, string) #define FTP_STATUS_MAP(XXX) \ XXX(220, READY, Ready) \ XXX(221, BYE, Bye) \ XXX(226, TRANSFER_COMPLETE, Transfer complete) \ XXX(227, PASV, Entering Passive Mode) \ XXX(331, PASS, Password required) \ XXX(230, LOGIN_OK, Login OK) \ XXX(250, OK, OK) \ XXX(500, BAD_SYNTAX, Bad syntax) \ XXX(530, NOT_LOGIN, Not login) \ enum ftp_status { #define XXX(code, name, string) FTP_STATUS_##name = code, FTP_STATUS_MAP(XXX) #undef XXX }; // more friendly macros #define FTP_MKDIR FTP_MKD #define FTP_RMDIR FTP_RMD #define FTP_APPEND FTP_APPE #define FTP_REMOVE FTP_DELE #define FTP_DOWNLOAD FTP_RETR #define FTP_UPLOAD FTP_STOR #define FTP_RECV_BUFSIZE 8192 typedef struct ftp_handle_s { int sockfd; char recvbuf[FTP_RECV_BUFSIZE]; void* userdata; } ftp_handle_t; BEGIN_EXTERN_C HV_EXPORT const char* ftp_command_str(enum ftp_command cmd); HV_EXPORT const char* ftp_status_str(enum ftp_status status); HV_EXPORT int ftp_connect(ftp_handle_t* hftp, const char* host, int port); HV_EXPORT int ftp_login(ftp_handle_t* hftp, const char* username, const char* password); HV_EXPORT int ftp_quit(ftp_handle_t* hftp); HV_EXPORT int ftp_exec(ftp_handle_t* hftp, const char* cmd, const char* param); // local => remote HV_EXPORT int ftp_upload(ftp_handle_t* hftp, const char* local_filepath, const char* remote_filepath); // remote => local HV_EXPORT int ftp_download(ftp_handle_t* hftp, const char* remote_filepath, const char* local_filepath); typedef int (*ftp_download_cb)(ftp_handle_t* hftp, char* buf, int len); HV_EXPORT int ftp_download_with_cb(ftp_handle_t* hftp, const char* filepath, ftp_download_cb cb); END_EXTERN_C #endif // HV_FTP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/icmp.c000066400000000000000000000077701520575453600264150ustar00rootroot00000000000000#include "icmp.h" #include "netinet.h" #include "hdef.h" #include "hsocket.h" #include "htime.h" #define PING_TIMEOUT 1000 // ms int ping(const char* host, int cnt) { static uint16_t seq = 0; uint16_t pid16 = (uint16_t)getpid(); char ip[64] = {0}; uint32_t start_tick, end_tick; uint64_t start_hrtime, end_hrtime; int timeout = 0; int sendbytes = 64; char sendbuf[64]; char recvbuf[128]; // iphdr + icmp = 84 at least icmp_t* icmp_req = (icmp_t*)sendbuf; iphdr_t* ipheader = (iphdr_t*)recvbuf; icmp_t* icmp_res; // ping stat int send_cnt = 0; int recv_cnt = 0; int ok_cnt = 0; float rtt, min_rtt, max_rtt, total_rtt; rtt = max_rtt = total_rtt = 0.0f; min_rtt = 1000000.0f; //min_rtt = MIN(rtt, min_rtt); //max_rtt = MAX(rtt, max_rtt); // gethostbyname -> socket -> setsockopt -> sendto -> recvfrom -> closesocket sockaddr_u peeraddr; socklen_t addrlen = sizeof(peeraddr); memset(&peeraddr, 0, addrlen); int ret = ResolveAddr(host, &peeraddr); if (ret != 0) return ret; sockaddr_ip(&peeraddr, ip, sizeof(ip)); int sockfd = socket(peeraddr.sa.sa_family, SOCK_RAW, IPPROTO_ICMP); if (sockfd < 0) { perror("socket"); if (errno == EPERM) { fprintf(stderr, "please use root or sudo to create a raw socket.\n"); } return -socket_errno(); } timeout = PING_TIMEOUT; ret = so_sndtimeo(sockfd, timeout); if (ret < 0) { perror("setsockopt"); goto error; } timeout = PING_TIMEOUT; ret = so_rcvtimeo(sockfd, timeout); if (ret < 0) { perror("setsockopt"); goto error; } icmp_req->icmp_type = ICMP_ECHO; icmp_req->icmp_code = 0; icmp_req->icmp_id = pid16; for (int i = 0; i < sendbytes - sizeof(icmphdr_t); ++i) { icmp_req->icmp_data[i] = i; } start_tick = gettick_ms(); while (cnt-- > 0) { // NOTE: checksum icmp_req->icmp_seq = ++seq; icmp_req->icmp_cksum = 0; icmp_req->icmp_cksum = checksum((uint8_t*)icmp_req, sendbytes); start_hrtime = gethrtime_us(); addrlen = sockaddr_len(&peeraddr); int nsend = sendto(sockfd, sendbuf, sendbytes, 0, &peeraddr.sa, addrlen); if (nsend < 0) { perror("sendto"); continue; } ++send_cnt; addrlen = sizeof(peeraddr); int nrecv = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, &peeraddr.sa, &addrlen); if (nrecv < 0) { perror("recvfrom"); continue; } ++recv_cnt; end_hrtime = gethrtime_us(); // check valid bool valid = false; int iphdr_len = ipheader->ihl * 4; int icmp_len = nrecv - iphdr_len; if (icmp_len == sendbytes) { icmp_res = (icmp_t*)(recvbuf + ipheader->ihl*4); if (icmp_res->icmp_type == ICMP_ECHOREPLY && icmp_res->icmp_id == pid16 && icmp_res->icmp_seq == seq) { valid = true; } } if (valid == false) { printd("recv invalid icmp packet!\n"); continue; } rtt = (end_hrtime-start_hrtime) / 1000.0f; min_rtt = MIN(rtt, min_rtt); max_rtt = MAX(rtt, max_rtt); total_rtt += rtt; printd("%d bytes from %s: icmp_seq=%u ttl=%u time=%.1f ms\n", icmp_len, ip, seq, ipheader->ttl, rtt); fflush(stdout); ++ok_cnt; if (cnt > 0) hv_sleep(1); // sleep a while, then agian } end_tick = gettick_ms(); printd("--- %s ping statistics ---\n", host); printd("%d packets transmitted, %d received, %d%% packet loss, time %d ms\n", send_cnt, recv_cnt, (send_cnt-recv_cnt)*100/(send_cnt==0?1:send_cnt), end_tick-start_tick); printd("rtt min/avg/max = %.3f/%.3f/%.3f ms\n", min_rtt, total_rtt/(ok_cnt==0?1:ok_cnt), max_rtt); closesocket(sockfd); return ok_cnt; error: closesocket(sockfd); return socket_errno() > 0 ? -socket_errno() : -1; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/icmp.h000066400000000000000000000003751520575453600264140ustar00rootroot00000000000000#ifndef HV_ICMP_H_ #define HV_ICMP_H_ #include "hexport.h" BEGIN_EXTERN_C // @param cnt: ping count // @return: ok count // @note: printd $CC -DPRINT_DEBUG HV_EXPORT int ping(const char* host, int cnt DEFAULT(4)); END_EXTERN_C #endif // HV_ICMP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/smtp.c000066400000000000000000000150341520575453600264400ustar00rootroot00000000000000#include "smtp.h" #include "hsocket.h" #include "herr.h" #include "base64.h" const char* smtp_command_str(enum smtp_command cmd) { switch (cmd) { #define XX(name, string) case SMTP_##name: return #string; SMTP_COMMAND_MAP(XX) #undef XX default: return ""; } } const char* smtp_status_str(enum smtp_status status) { switch (status) { #define XXX(code, name, string) case SMTP_STATUS_##name: return #string; SMTP_STATUS_MAP(XXX) #undef XXX default: return ""; } } int smtp_build_command(enum smtp_command cmd, const char* param, char* buf, int buflen) { switch (cmd) { // unary case SMTP_DATA: case SMTP_QUIT: return snprintf(buf, buflen, "%s\r\n", smtp_command_str(cmd)); //
case SMTP_MAIL: case SMTP_RCPT: return snprintf(buf, buflen, "%s <%s>\r\n", smtp_command_str(cmd), param); default: return snprintf(buf, buflen, "%s %s\r\n", smtp_command_str(cmd), param); } } // EHLO => AUTH PLAIN => MAIL => RCPT => DATA => data => EOB => QUIT int sendmail(const char* smtp_server, const char* username, const char* password, mail_t* mail) { char buf[1024] = {0}; int buflen = sizeof(buf); int cmdlen = 0; int status_code = 0; char basic[256]; int basiclen; int sockfd = ConnectTimeout(smtp_server, SMTP_PORT, DEFAULT_CONNECT_TIMEOUT); if (sockfd < 0) { return sockfd; } so_sndtimeo(sockfd, 5000); so_rcvtimeo(sockfd, 5000); int ret, nsend, nrecv; nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_READY) { ret = status_code; goto error; } // EHLO smtp.xxx.com\r\n cmdlen = smtp_build_command(SMTP_EHLO, smtp_server, buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_OK) { ret = status_code; goto error; } // AUTH PLAIN\r\n cmdlen = smtp_build_command(SMTP_AUTH, "PLAIN", buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_AUTH) { ret = status_code; goto error; } { // BASE64 \0username\0password int usernamelen = strlen(username); int passwordlen = strlen(password); basic[0] = '\0'; memcpy(basic+1, username, usernamelen); basic[1+usernamelen] = '\0'; memcpy(basic+1+usernamelen+1, password, passwordlen); basiclen = 1 + usernamelen + 1 + passwordlen; } hv_base64_encode((unsigned char*)basic, basiclen, buf); cmdlen = BASE64_ENCODE_OUT_SIZE(basiclen); buf[cmdlen] = '\r'; buf[cmdlen+1] = '\n'; cmdlen += 2; nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_AUTH_SUCCESS) { ret = status_code; goto error; } // MAIL FROM: \r\n cmdlen = smtp_build_command(SMTP_MAIL, mail->from, buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_OK) { ret = status_code; goto error; } // RCPT TO: \r\n cmdlen = smtp_build_command(SMTP_RCPT, mail->to, buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_OK) { ret = status_code; goto error; } // DATA\r\n cmdlen = smtp_build_command(SMTP_DATA, NULL, buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } status_code = atoi(buf); // SMTP_STATUS_DATA if (status_code >= 400) { ret = status_code; goto error; } // From: cmdlen = snprintf(buf, buflen, "From:%s\r\n", mail->from); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } // To: cmdlen = snprintf(buf, buflen, "To:%s\r\n", mail->to); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } // Subject: cmdlen = snprintf(buf, buflen, "Subject:%s\r\n\r\n", mail->subject); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } // body cmdlen = strlen(mail->body); nsend = send(sockfd, mail->body, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } // EOB nsend = send(sockfd, SMTP_EOB, SMTP_EOB_LEN, 0); if (nsend != SMTP_EOB_LEN) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_SEND; goto error; } status_code = atoi(buf); if (status_code != SMTP_STATUS_OK) { ret = status_code; goto error; } // QUIT\r\n cmdlen = smtp_build_command(SMTP_QUIT, NULL, buf, buflen); nsend = send(sockfd, buf, cmdlen, 0); if (nsend != cmdlen) { ret = ERR_SEND; goto error; } nrecv = recv(sockfd, buf, buflen, 0); if (nrecv <= 0) { ret = ERR_RECV; goto error; } /* status_code = atoi(buf); if (status_code != SMTP_STATUS_BYE) { ret = status_code; goto error; } */ ret = SMTP_STATUS_OK; error: if (sockfd != INVALID_SOCKET) { closesocket(sockfd); } return ret; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/protocol/smtp.h000066400000000000000000000042371520575453600264500ustar00rootroot00000000000000#ifndef HV_SMTP_H_ #define HV_SMTP_H_ #include "hexport.h" #define SMTP_PORT 25 #define SMTPS_PORT 465 #define SMTP_EOB "\r\n.\r\n" #define SMTP_EOB_LEN 5 // smtp_command // XX(name, string) #define SMTP_COMMAND_MAP(XX)\ XX(HELO, HELO) \ XX(EHLO, EHLO) \ XX(AUTH, AUTH) \ XX(MAIL, MAIL FROM:) \ XX(RCPT, RCPT TO:) \ XX(DATA, DATA) \ XX(QUIT, QUIT) \ enum smtp_command { #define XX(name, string) SMTP_##name, SMTP_COMMAND_MAP(XX) #undef XX }; // smtp_status // XXX(code, name, string) #define SMTP_STATUS_MAP(XXX) \ XXX(220, READY, Ready) \ XXX(221, BYE, Bye) \ XXX(235, AUTH_SUCCESS, Authentication success) \ XXX(250, OK, OK) \ XXX(334, AUTH, Auth input) \ XXX(354, DATA, End with .) \ XXX(500, BAD_SYNTAX, Bad syntax) \ XXX(502, NOT_IMPLEMENTED,Command not implemented) \ XXX(503, BAD_SEQUENCE, Bad sequence of commands) \ XXX(504, UNRECOGNIZED_AUTH_TYPE, Unrecognized authentication type) \ XXX(535, AUTH_FAILED, Authentication failed) \ XXX(553, ERR_MAIL, Mailbox name not allowed) \ XXX(554, ERR_DATA, Transaction failed) \ enum smtp_status { #define XXX(code, name, string) SMTP_STATUS_##name = code, SMTP_STATUS_MAP(XXX) #undef XXX }; typedef struct mail_s { char* from; char* to; char* subject; char* body; } mail_t; BEGIN_EXTERN_C HV_EXPORT const char* smtp_command_str(enum smtp_command cmd); HV_EXPORT const char* smtp_status_str(enum smtp_status status); // cmd param\r\n HV_EXPORT int smtp_build_command(enum smtp_command cmd, const char* param, char* buf, int buflen); // status_code status_message\r\n HV_EXPORT int sendmail(const char* smtp_server, const char* username, const char* password, mail_t* mail); END_EXTERN_C #endif // HV_SMTP_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/000077500000000000000000000000001520575453600251345ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/check.sh000077500000000000000000000005651520575453600265560ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. cd ${ROOT_DIR} bin/httpd -c etc/httpd.conf -s restart -d ps aux | grep httpd HTTPS=`netstat -atn | grep 8443 | wc -l` bin/http_client_test bin/curl -v http://127.0.0.1:8080/ if [ $HTTPS -gt 0 ]; then bin/curl -v https://127.0.0.1:8443/ fi bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/ping kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/cmake_cross_compile.sh000077500000000000000000000012331520575453600314730ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. if [ $# -gt 0 ]; then CROSS_COMPILE=$1 else sudo apt install g++-arm-linux-gnueabi CROSS_COMPILE=arm-linux-gnueabi- fi echo CROSS_COMPILE=${CROSS_COMPILE} cd ${ROOT_DIR} . scripts/toolchain.sh export ${CROSS_COMPILE} BUILD_DIR=build/${HV_TARGET_OS}/${HV_TARGET_ARCH} echo BUILD_DIR=${BUILD_DIR} mkdir -p ${BUILD_DIR} cd ${BUILD_DIR} cmake ../../.. -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_SYSTEM_NAME=$HV_TARGET_OS -DCMAKE_SYSTEM_PROCESSOR=$HV_TARGET_ARCH make libhv libhv_static cd ${ROOT_DIR} . scripts/toolchain.sh unset ${CROSS_COMPILE} echo 'Completed => ${BUILD_DIR}' kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/consul.py000077500000000000000000000054711520575453600270230ustar00rootroot00000000000000#!/usr/bin/python3 import sys import json import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Cache-Control': 'no-cache', 'Accpet': '*/*', 'Content-Type': 'application/json'} _node = {'ip': '127.0.0.1', 'port': 8500} def gen_ServiceID(service_name, service_ip, service_port): return service_name + '-' + service_ip + ':' + str(service_port) def register_service(service_name, service_ip, service_port , node=_node): service = {} service['Name'] = service_name service['Address'] = service_ip service['Port'] = service_port service['ID'] = gen_ServiceID(service_name, service_ip, service_port) check = {} check['TCP'] = service['Address'] + ':' + str(service['Port']) check['Interval'] = '10s' check['DeregisterCriticalServiceAfter'] = '30s' service['Check'] = check data = json.dumps(service) url = 'http://' + node['ip'] + ':' + str(node['port']) url += '/v1/agent/service/register' try: res = requests.put(url=url, headers=headers, data=data) return res.status_code == 200 and len(res.content) == 0 except Exception as e: print(e) return False def deregister_service(ServiceID, node=_node): url = 'http://' + node['ip'] + ':' + str(node['port']) url += '/v1/agent/service/deregister/' url += ServiceID try: res = requests.put(url=url, headers=headers) return res.status_code == 200 and len(res.content) == 0 except Exception as e: print(e) return False def discover_service(service_name, node=_node): url = 'http://' + node['ip'] + ':' + str(node['port']) url += '/v1/catalog/service/' url += service_name try: res = requests.get(url=url, headers=headers) return res.content except Exception as e: print(e) return 'false' def main(): print(sys.argv) if len(sys.argv) < 4: print('Usage: cmd service_name service_ip service_port node_ip node_port') return service_name = sys.argv[1] service_ip = sys.argv[2] service_port = int(sys.argv[3]) if len(sys.argv) >= 5: _node['ip'] = sys.argv[4] _node['port'] = int(sys.argv[5]) ServiceID = gen_ServiceID(service_name, service_ip, service_port) if register_service(service_name, service_ip, service_port): print('register_service [%s] succeed!' % (ServiceID)) else: print('register_service failed!') print(discover_service(service_name)) ''' if deregister_service(ServiceID): print('deregister_service [%s] succeed!' % (ServiceID)) else: print('deregister_service failed') print(discover_service(service_name)) ''' if __name__ == '__main__': main() kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/consul_agent.sh000077500000000000000000000006601520575453600301560ustar00rootroot00000000000000#!/bin/bash rm -r consul rm nohup.out mkdir consul print_help() { cat < /proc/sys/kernel/core_uses_pid echo "/tmp/core-%e-%p-%t" > /proc/sys/kernel/core_pattern echo "1" > /proc/sys/fs/suid_dumpable print_conf ulimit -c unlimited ulimit -a kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/create_repo.sh000077500000000000000000000005571520575453600277720ustar00rootroot00000000000000#!/bin/bash mkdir -p include lib src bin doc etc 3rd/include 3rd/lib dist touch README.md BUILD.md RELEASE.md CHANGELOG.md Makefile .gitignore git init # personal git submodule add https://github.com/ithewei/libhv.git src/hv cp src/hv/.gitignore . cp src/hv/.clang-format . cp src/hv/Makefile . cp -r src/hv/etc/* etc cp src/hv/examples/hmain_test.cpp src/main.cpp kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/libhv.cmake000066400000000000000000000003061520575453600272410ustar00rootroot00000000000000set(CMAKE_C_COMPILER $CC) set(CMAKE_CXX_COMPILER $CXX) set(CMAKE_SYSTEM_NAME $HV_TARGET_OS) set(CMAKE_SYSTEM_PROCESSOR $HV_TARGET_ARCH) if(WIN32) add_definitions(-D_WIN32_WINNT=0x600) endif() kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/shini.sh000066400000000000000000000225551520575453600266130ustar00rootroot00000000000000# shini - compatible INI library for sh # # This code is released freely under the MIT license - see the shipped LICENSE document. # For the latest version etc, please see https://github.com/wallyhall/shini # # Solely for the purpose of portable performance, this script breaks good practice to # avoid forking subshells. One such good practice is avoiding global variables. # This variable is used to carry non-numeric results from functions to the caller. # Alternatively an echo and "$(...)" approach could be used, but is significantly slower. shini_setup() { if [ -n "$ZSH_VERSION" ]; then RESTORE_OPTS=$(set +o) # Enable BASH_REMATCH for zsh setopt KSH_ARRAYS BASH_REMATCH fi } shini_teardown() { [ -n "$ZSH_VERSION" ] && eval "$RESTORE_OPTS" } shini_function_exists() { type "$1" > /dev/null 2>&1 return $? } shini_regex_match() { # $KSH_VERSION (I'm told) only exists on ksh 93 and above, which supports regex matching. if [ -n "$BASH_VERSINFO" ] && [ "$BASH_VERSINFO" -ge 3 ] || \ [ -n "$ZSH_VERSION" ] || \ [ -n "$KSH_VERSION" ]; then [[ "$1" =~ $2 ]] && return 0 || return 1 fi printf '%s' "$1" | grep -qe "$2" return $? } shini_regex_replace() { if [ -n "$BASH_VERSINFO" ] && [ "${BASH_VERSINFO}" -ge 3 ] || \ [ -n "$ZSH_VERSION" ]; then [[ "$1" =~ $2 ]] && shini_retval=${BASH_REMATCH[1]} || shini_retval="$1" return 0 fi shini_retval="$(printf '%s' "$1" | sed -E "s/$2/\1/")" # If you have isses on older systems, # it may be the non-newer POSIX compliant sed. # -E should be enabling extended regex mode portably. } # @param inifile Filename of INI file to parse # @param postfix Function postfix for callbacks (optional) # @param extra Extra argument for callbacks (optional) shini_parse() { shini_parse_section "$1" '' "$2" "$3" "$4" "$5" } # @param inifile Filename of INI file to parse # @param section Section to parse (or empty string for entire file) # @param postfix Function postfix for callbacks (optional) # @param extra Extra argument for callbacks (optional) shini_parse_section() { shini_setup # ******** RX_KEY='[a-zA-Z0-9_\-\.]' RX_VALUE="[^;\"]" RX_SECTION='[a-zA-Z0-9_\-]' RX_WS='[ ]' RX_QUOTE='"' RX_HEX='[0-9A-F]' POSTFIX='' SKIP_TO_SECTION='' EXTRA1='' EXTRA2='' EXTRA3='' SECTION_FOUND=-1 if [ $# -ge 2 ] && [ ! -z "$2" ]; then SKIP_TO_SECTION="$2" fi if [ $# -ge 3 ] && [ ! -z "$3" ]; then POSTFIX="_$3" fi if [ $# -ge 4 ] && ! [ -z "$4" ]; then EXTRA1="$4" fi if [ $# -ge 5 ] && [ ! -z "$5" ]; then EXTRA2="$5" fi if [ $# -ge 6 ] && [ ! -z "$6" ]; then EXTRA3="$6" fi if ! shini_function_exists "__shini_parsed${POSTFIX}"; then printf 'shini: __shini_parsed%s function not declared.\n' "${POSTFIX}" 1>&2 exit 255 fi if [ $# -lt 1 ]; then if shini_function_exists "__shini_no_file_passed{$POSTFIX}"; then "__shini_no_file_passed${POSTFIX}" "$EXTRA1" "$EXTRA2" "$EXTRA3" else printf 'shini: Argument 1 needs to specify the INI file to parse.\n' 1>&2 exit 254 fi fi INI_FILE="$1" if [ ! -r "$INI_FILE" ]; then if shini_function_exists "__shini_file_unreadable${POSTFIX}"; then "__shini_file_unreadable${POSTFIX}" "$INI_FILE" "$EXTRA1" "$EXTRA2" "$EXTRA3" else printf 'shini: Unable to read INI file:\n `%s`\n' "$INI_FILE" 1>&2 exit 253 fi fi # Iterate INI file line by line LINE_NUM=0 SECTION='' while read LINE || [ -n "$LINE" ]; do # -n $LINE catches final line if not empty # Check for new sections if shini_regex_match "$LINE" "^${RX_WS}*\[${RX_SECTION}${RX_SECTION}*\]${RX_WS}*$"; then shini_regex_replace "$LINE" "^${RX_WS}*\[(${RX_SECTION}${RX_SECTION}*)\]${RX_WS}*$" "\1" SECTION=$shini_retval if [ "$SKIP_TO_SECTION" != '' ]; then # stop once specific section is finished [ $SECTION_FOUND -eq 0 ] && break; # mark the specified section as found [ "$SKIP_TO_SECTION" = "$SECTION" ] && SECTION_FOUND=0; fi if shini_function_exists "__shini_parsed_section${POSTFIX}"; then "__shini_parsed_section${POSTFIX}" "$SECTION" "$EXTRA1" "$EXTRA2" "$EXTRA3" fi LINE_NUM=$((LINE_NUM+1)) continue fi # Skip over sections we don't care about, if a specific section was specified [ "$SKIP_TO_SECTION" != '' ] && [ $SECTION_FOUND -ne 0 ] && LINE_NUM=$((LINE_NUM+1)) && continue; # Check for new values if shini_regex_match "$LINE" "^${RX_WS}*${RX_KEY}${RX_KEY}*${RX_WS}*="; then shini_regex_replace "$LINE" "^${RX_WS}*(${RX_KEY}${RX_KEY}*)${RX_WS}*=.*$" KEY=$shini_retval shini_regex_replace "$LINE" "^${RX_WS}*${RX_KEY}${RX_KEY}*${RX_WS}*=${RX_WS}*${RX_QUOTE}{0,1}(${RX_VALUE}*)${RX_QUOTE}{0,1}(${RX_WS}*\;.*)*$" VALUE=$shini_retval if shini_regex_match "$LINE" "^0x${RX_HEX}${RX_HEX}*$"; then VALUE=$(printf '%d' "$VALUE") fi "__shini_parsed${POSTFIX}" "$SECTION" "$KEY" "$VALUE" "$EXTRA1" "$EXTRA2" "$EXTRA3" if shini_function_exists "__shini_parsed_comment${POSTFIX}"; then if shini_regex_match "$LINE" ";"; then shini_regex_replace "$LINE" "^.*\;(.*)$" COMMENT=$shini_retval "__shini_parsed_comment${POSTFIX}" "$COMMENT" "$EXTRA1" "$EXTRA2" "$EXTRA3" fi fi LINE_NUM=$((LINE_NUM+1)) continue fi # Announce parse errors if [ "$LINE" != '' ] && ! shini_regex_match "$LINE" "^${RX_WS}*;.*$" && ! shini_regex_match "$LINE" "^${RX_WS}*$"; then if shini_function_exists "__shini_parse_error${POSTFIX}"; then "__shini_parse_error${POSTFIX}" $LINE_NUM "$LINE" "$EXTRA1" "$EXTRA2" "$EXTRA3" else printf 'shini: Unable to parse line %d:\n `%s`\n' $LINE_NUM "$LINE" fi fi LINE_NUM=$((LINE_NUM+1)) done < "$INI_FILE" # ******** shini_teardown } # @param inifile Filename of INI file to write to # @param section Section of INI file to write to # @param variable Variable name to add/update/delete # @param value Value to add/update, do not specify to delete shini_write() { shini_setup # ******** # This is not yet optimised (early write support only) - # We actually re-parse the entire file, looking for the location in which to # write the new value, writing out everything we parse as-is meanwhile. # Declare the following if you want particular behaviour (like skipping # broken INI file content or handling an unreadable file etc). # __shini_no_file_passed__writer() # __shini_file_unreadable__writer() # __shini_parse_error__writer() # Writer callbacks, used for writing the INI file content __shini_parsed_section__writer() { # Validate the last section wasn't the target section if [ "$LAST_SECTION" = "$WRITE_SECTION" ]; then # If it was, and the value wasn't written already, write it if [ $VALUE_WRITTEN -eq 0 ]; then printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" VALUE_WRITTEN=1 fi fi printf "\n[%s]" "$1" >> "$INI_FILE_TEMP" LAST_SECTION="$1" } __shini_parsed_comment__writer() { printf ";%s" "$1" >> "$INI_FILE_TEMP" } __shini_parsed__writer() { if [ "$1" = "$WRITE_SECTION" ]; then if [ "$2" = "$WRITE_KEY" ]; then if [ ! -z "$WRITE_VALUE" ]; then printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" fi VALUE_WRITTEN=1 return fi fi printf "\n%s=%s" "$2" "$3" >> "$INI_FILE_TEMP" } if [ $# -lt 3 ]; then if shini_function_exists "__shini_no_file_passed"; then __shini_no_file_passed else printf 'shini: Argument 1 needs to specify the INI file to write.\n' 1>&2 exit 254 fi fi INI_FILE="$1" INI_FILE_TEMP="$(mktemp -t shini_XXXXXX)" WRITE_SECTION="$2" WRITE_KEY="$3" WRITE_VALUE="$4" LAST_SECTION="" VALUE_WRITTEN=0 shini_parse "$1" "_writer" "$2" "$3" "$4" # Still not written out yet if [ $VALUE_WRITTEN -eq 0 ]; then # Check if final existing section was target one, add it if not if [ "$LAST_SECTION" != "$WRITE_SECTION" ]; then printf "\n[%s]" "$WRITE_SECTION" >> "$INI_FILE_TEMP" fi # Write value at end of file printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" fi mv "$INI_FILE_TEMP" "$INI_FILE" # ******** shini_teardown } # default usage __shini_parsed() { if [[ $2 != *\$* ]] && [[ $3 != *\$* ]]; then eval $2=$3 fi } __shini_parse_error() { error_line=$1 } __shini_parse_error__writer() { error_line=$1 } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/test-coverage.sh000077500000000000000000000024041520575453600302430ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. cd ${ROOT_DIR} bin/httpd -c etc/httpd.conf -s restart -d bin/ls bin/date bin/ifconfig bin/mkdir_p 123/456 bin/rmdir_p 123/456 bin/defer_test bin/hstring_test bin/hpath_test bin/hatomic_test bin/hatomic_cpp_test bin/hmutex_test bin/socketpair_test bin/threadpool_test bin/objectpool_test bin/curl -v localhost:8080 bin/curl -v localhost:8080/ping bin/curl -v localhost:8080/echo -d "hello,world!" bin/curl -v localhost:8080/query?page_no=1\&page_size=10 bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' bin/curl -v localhost:8080/form -F "user=admin pswd=123456" bin/curl -v localhost:8080/upload -F "file=@LICENSE" bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' bin/curl -v localhost:8080/test -F 'bool=1 int=123 float=3.14 string=hello' bin/curl -v -X DELETE localhost:8080/group/test/user/123 bin/httpd -s stop bin/htimer_test kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/toolchain.sh000077500000000000000000000045641520575453600274640ustar00rootroot00000000000000#!/bin/bash print_help() { cat <&1 | grep Target | sed 's/Target: //'` TARGET_ARCH=`echo $TARGET_PLATFORM | awk -F'-' '{print $1}'` case $TARGET_PLATFORM in *mingw*) TARGET_OS=Windows ;; *android*) TARGET_OS=Android ;; *darwin*) TARGET_OS=Darwin ;; *) TARGET_OS=Linux ;; esac # TARGET_OS,TARGET_ARCH used by make export HV_HOST_OS=$HOST_OS export HV_HOST_ARCH=$HOST_ARCH export HV_TARGET_OS=$TARGET_OS export HV_TARGET_ARCH=$TARGET_ARCH export HOST=$TARGET_PLATFORM elif [ $COMMAND = "unset" ]; then unset CROSS_COMPILE unset CC unset CXX unset AR unset AS unset LD unset STRIP unset RANLIB unset NM unset HOST_OS unset HOST_ARCH unset TARGET_OS unset TARGET_ARCH unset HOST else print_help return fi } main $@ echo "CC = $CC" echo "CXX = $CXX" if [ $CC ]; then CC_VERSION=`$CC --version 2>&1 | head -n 1` echo "$CC_VERSION" fi echo "AR = $AR" echo "AS = $AS" echo "LD = $LD" echo "STRIP = $STRIP" echo "RANLIB = $RANLIB" echo "NM = $NM" echo "HV_HOST_OS = $HOST_OS" echo "HV_HOST_ARCH = $HOST_ARCH" echo "HV_TARGET_OS = $TARGET_OS" echo "HV_TARGET_ARCH = $TARGET_ARCH" kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/unittest.sh000077500000000000000000000006701520575453600273550ustar00rootroot00000000000000#!/bin/bash SCRIPT_DIR=$(cd `dirname $0`; pwd) ROOT_DIR=${SCRIPT_DIR}/.. cd ${ROOT_DIR} bin/rbtree_test bin/hbase_test bin/date bin/ifconfig bin/mkdir_p 123/456 bin/ls bin/rmdir_p 123/456 bin/base64 bin/md5 bin/sha1 bin/defer_test bin/hstring_test bin/hpath_test bin/hurl_test # bin/hatomic_test # bin/hatomic_cpp_test # bin/hthread_test # bin/hmutex_test bin/socketpair_test # bin/threadpool_test # bin/objectpool_test bin/sizeof_test kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/scripts/websocket_server.py000077500000000000000000000005711520575453600310700ustar00rootroot00000000000000#!/usr/bin/env python3 # pip3 install websockets import asyncio import websockets async def echo(websocket): async for message in websocket: print(message) await websocket.send(message) async def serve(port): async with websockets.serve(echo, "0.0.0.0", port): await asyncio.Future() if __name__ == "__main__": asyncio.run(serve(9999)) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/000077500000000000000000000000001520575453600242465ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/appletls.c000066400000000000000000001352201520575453600262410ustar00rootroot00000000000000#include "hssl.h" #ifdef WITH_APPLETLS /* Disclaimer: excerpted from curl */ #include /* For some reason, when building for iOS, the omnibus header above does * not include SecureTransport.h as of iOS SDK 5.1. */ #include #include #include #include "hsocket.h" /* The Security framework has changed greatly between iOS and different macOS versions, and we will try to support as many of them as we can (back to Leopard and iOS 5) by using macros and weak-linking. In general, you want to build this using the most recent OS SDK, since some features require curl to be built against the latest SDK. TLS 1.1 and 1.2 support, for instance, require the macOS 10.8 SDK or later. TLS 1.3 requires the macOS 10.13 or iOS 11 SDK or later. */ #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) #if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 #error "The Secure Transport back-end requires Leopard or later." #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */ #define CURL_BUILD_IOS 0 #define CURL_BUILD_IOS_7 0 #define CURL_BUILD_IOS_9 0 #define CURL_BUILD_IOS_11 0 #define CURL_BUILD_IOS_13 0 #define CURL_BUILD_MAC 1 /* This is the maximum API level we are allowed to use when building: */ #define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 #define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 #define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 #define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 #define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 #define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 #define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 #define CURL_BUILD_MAC_10_15 MAC_OS_X_VERSION_MAX_ALLOWED >= 101500 /* These macros mean "the following code is present to allow runtime backward compatibility with at least this cat or earlier": (You set this at build-time using the compiler command line option "-mmacosx-version-min.") */ #define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 #define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060 #define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070 #define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 #define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090 #elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE #define CURL_BUILD_IOS 1 #define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 #define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000 #define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 #define CURL_BUILD_IOS_13 __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 #define CURL_BUILD_MAC 0 #define CURL_BUILD_MAC_10_5 0 #define CURL_BUILD_MAC_10_6 0 #define CURL_BUILD_MAC_10_7 0 #define CURL_BUILD_MAC_10_8 0 #define CURL_BUILD_MAC_10_9 0 #define CURL_BUILD_MAC_10_11 0 #define CURL_BUILD_MAC_10_13 0 #define CURL_BUILD_MAC_10_15 0 #define CURL_SUPPORT_MAC_10_5 0 #define CURL_SUPPORT_MAC_10_6 0 #define CURL_SUPPORT_MAC_10_7 0 #define CURL_SUPPORT_MAC_10_8 0 #define CURL_SUPPORT_MAC_10_9 0 #else #error "The Secure Transport back-end requires iOS or macOS." #endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */ #if !defined(__MAC_10_8) static const SSLProtocol kTLSProtocol11 = (SSLProtocol)7; static const SSLProtocol kTLSProtocol12 = (SSLProtocol)8; #endif #if !defined(__MAC_10_13) static const SSLProtocol kTLSProtocol13 = (SSLProtocol)10; #endif static inline const char* SSLProtocolToString(SSLProtocol proto) { switch(proto) { case kSSLProtocol2: return "SSLv2"; case kSSLProtocol3: return "SSLv3"; case kTLSProtocol1: return "TLSv1"; case kTLSProtocol11: return "TLSv1.1"; case kTLSProtocol12: return "TLSv1.2"; case kTLSProtocol13: return "TLSv1.3"; default: return "Unknown"; } } struct st_cipher { const char *name; /* Cipher suite IANA name. It starts with "TLS_" prefix */ const char *alias_name; /* Alias name is the same as OpenSSL cipher name */ SSLCipherSuite num; /* Cipher suite code/number defined in IANA registry */ bool weak; /* Flag to mark cipher as weak based on previous implementation of Secure Transport back-end by CURL */ }; /* Macro to initialize st_cipher data structure: stringify id to name, cipher number/id, 'weak' suite flag */ #define CIPHER_DEF(num, alias, weak) \ { #num, alias, num, weak } /* Macro to initialize st_cipher data structure with name, code (IANA cipher number/id value), and 'weak' suite flag. The first 28 cipher suite numbers have the same IANA code for both SSL and TLS standards: numbers 0x0000 to 0x001B. They have different names though. The first 4 letters of the cipher suite name are the protocol name: "SSL_" or "TLS_", rest of the IANA name is the same for both SSL and TLS cipher suite name. The second part of the problem is that macOS/iOS SDKs don't define all TLS codes but only 12 of them. The SDK defines all SSL codes though, i.e. SSL_NUM constant is always defined for those 28 ciphers while TLS_NUM is defined only for 12 of the first 28 ciphers. Those 12 TLS cipher codes match to corresponding SSL enum value and represent the same cipher suite. Therefore we'll use the SSL enum value for those cipher suites because it is defined for all 28 of them. We make internal data consistent and based on TLS names, i.e. all st_cipher item names start with the "TLS_" prefix. Summarizing all the above, those 28 first ciphers are presented in our table with both TLS and SSL names. Their cipher numbers are assigned based on the SDK enum value for the SSL cipher, which matches to IANA TLS number. */ #define CIPHER_DEF_SSLTLS(num_wo_prefix, alias, weak) \ { "TLS_" #num_wo_prefix, alias, SSL_##num_wo_prefix, weak } /* Cipher suites were marked as weak based on the following: RC4 encryption - rfc7465, the document contains a list of deprecated ciphers. Marked in the code below as weak. RC2 encryption - many mentions, was found vulnerable to a relatively easy attack https://link.springer.com/chapter/10.1007%2F3-540-69710-1_14 Marked in the code below as weak. DES and IDEA encryption - rfc5469, has a list of deprecated ciphers. Marked in the code below as weak. Anonymous Diffie-Hellman authentication and anonymous elliptic curve Diffie-Hellman - vulnerable to a man-in-the-middle attack. Deprecated by RFC 4346 aka TLS 1.1 (section A.5, page 60) Null bulk encryption suites - not encrypted communication Export ciphers, i.e. ciphers with restrictions to be used outside the US for software exported to some countries, they were excluded from TLS 1.1 version. More precisely, they were noted as ciphers which MUST NOT be negotiated in RFC 4346 aka TLS 1.1 (section A.5, pages 60 and 61). All of those filters were considered weak because they contain a weak algorithm like DES, RC2 or RC4, and already considered weak by other criteria. 3DES - NIST deprecated it and is going to retire it by 2023 https://csrc.nist.gov/News/2017/Update-to-Current-Use-and-Deprecation-of-TDEA OpenSSL https://www.openssl.org/blog/blog/2016/08/24/sweet32/ also deprecated those ciphers. Some other libraries also consider it vulnerable or at least not strong enough. CBC ciphers are vulnerable with SSL3.0 and TLS1.0: https://www.cisco.com/c/en/us/support/docs/security/email-security-appliance /118518-technote-esa-00.html We don't take care of this issue because it is resolved by later TLS versions and for us, it requires more complicated checks, we need to check a protocol version also. Vulnerability doesn't look very critical and we do not filter out those cipher suites. */ #define CIPHER_WEAK_NOT_ENCRYPTED TRUE #define CIPHER_WEAK_RC_ENCRYPTION TRUE #define CIPHER_WEAK_DES_ENCRYPTION TRUE #define CIPHER_WEAK_IDEA_ENCRYPTION TRUE #define CIPHER_WEAK_ANON_AUTH TRUE #define CIPHER_WEAK_3DES_ENCRYPTION TRUE #define CIPHER_STRONG_ENOUGH FALSE /* Please do not change the order of the first ciphers available for SSL. Do not insert and do not delete any of them. Code below depends on their order and continuity. If you add a new cipher, please maintain order by number, i.e. insert in between existing items to appropriate place based on cipher suite IANA number */ const static struct st_cipher ciphertable[] = { /* SSL version 3.0 and initial TLS 1.0 cipher suites. Defined since SDK 10.2.8 */ CIPHER_DEF_SSLTLS(NULL_WITH_NULL_NULL, /* 0x0000 */ NULL, CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF_SSLTLS(RSA_WITH_NULL_MD5, /* 0x0001 */ "NULL-MD5", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF_SSLTLS(RSA_WITH_NULL_SHA, /* 0x0002 */ "NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC4_40_MD5, /* 0x0003 */ "EXP-RC4-MD5", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_MD5, /* 0x0004 */ "RC4-MD5", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_SHA, /* 0x0005 */ "RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC2_CBC_40_MD5, /* 0x0006 */ "EXP-RC2-CBC-MD5", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_WITH_IDEA_CBC_SHA, /* 0x0007 */ "IDEA-CBC-SHA", CIPHER_WEAK_IDEA_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0008 */ "EXP-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_WITH_DES_CBC_SHA, /* 0x0009 */ "DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */ "DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x000B */ "EXP-DH-DSS-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_DSS_WITH_DES_CBC_SHA, /* 0x000C */ "DH-DSS-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x000D */ "DH-DSS-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x000E */ "EXP-DH-RSA-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_RSA_WITH_DES_CBC_SHA, /* 0x000F */ "DH-RSA-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0010 */ "DH-RSA-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x0011 */ "EXP-EDH-DSS-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_DSS_WITH_DES_CBC_SHA, /* 0x0012 */ "EDH-DSS-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x0013 */ "DHE-DSS-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0014 */ "EXP-EDH-RSA-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_RSA_WITH_DES_CBC_SHA, /* 0x0015 */ "EDH-RSA-DES-CBC-SHA", CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0016 */ "DHE-RSA-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_RC4_40_MD5, /* 0x0017 */ "EXP-ADH-RC4-MD5", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF_SSLTLS(DH_anon_WITH_RC4_128_MD5, /* 0x0018 */ "ADH-RC4-MD5", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_DES40_CBC_SHA, /* 0x0019 */ "EXP-ADH-DES-CBC-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF_SSLTLS(DH_anon_WITH_DES_CBC_SHA, /* 0x001A */ "ADH-DES-CBC-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF_SSLTLS(DH_anon_WITH_3DES_EDE_CBC_SHA, /* 0x001B */ "ADH-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_NULL_SHA, /* 0x001C */ NULL, CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, /* 0x001D */ NULL, CIPHER_STRONG_ENOUGH), #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 /* RFC 4785 - Pre-Shared Key (PSK) Ciphersuites with NULL Encryption */ CIPHER_DEF(TLS_PSK_WITH_NULL_SHA, /* 0x002C */ "PSK-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA, /* 0x002D */ "DHE-PSK-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA, /* 0x002E */ "RSA-PSK-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ /* TLS addenda using AES, per RFC 3268. Defined since SDK 10.4u */ CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */ "AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA, /* 0x0030 */ "DH-DSS-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA, /* 0x0031 */ "DH-RSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA, /* 0x0032 */ "DHE-DSS-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA, /* 0x0033 */ "DHE-RSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA, /* 0x0034 */ "ADH-AES128-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */ "AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA, /* 0x0036 */ "DH-DSS-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA, /* 0x0037 */ "DH-RSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA, /* 0x0038 */ "DHE-DSS-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA, /* 0x0039 */ "DHE-RSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA, /* 0x003A */ "ADH-AES256-SHA", CIPHER_WEAK_ANON_AUTH), #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS /* TLS 1.2 addenda, RFC 5246 */ /* Server provided RSA certificate for key exchange. */ CIPHER_DEF(TLS_RSA_WITH_NULL_SHA256, /* 0x003B */ "NULL-SHA256", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */ "AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */ "AES256-SHA256", CIPHER_STRONG_ENOUGH), /* Server-authenticated (and optionally client-authenticated) Diffie-Hellman. */ CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA256, /* 0x003E */ "DH-DSS-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA256, /* 0x003F */ "DH-RSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, /* 0x0040 */ "DHE-DSS-AES128-SHA256", CIPHER_STRONG_ENOUGH), /* TLS 1.2 addenda, RFC 5246 */ CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, /* 0x0067 */ "DHE-RSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA256, /* 0x0068 */ "DH-DSS-AES256-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA256, /* 0x0069 */ "DH-RSA-AES256-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, /* 0x006A */ "DHE-DSS-AES256-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, /* 0x006B */ "DHE-RSA-AES256-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA256, /* 0x006C */ "ADH-AES128-SHA256", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA256, /* 0x006D */ "ADH-AES256-SHA256", CIPHER_WEAK_ANON_AUTH), #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 /* Addendum from RFC 4279, TLS PSK */ CIPHER_DEF(TLS_PSK_WITH_RC4_128_SHA, /* 0x008A */ "PSK-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008B */ "PSK-3DES-EDE-CBC-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA, /* 0x008C */ "PSK-AES128-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA, /* 0x008D */ "PSK-AES256-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_RC4_128_SHA, /* 0x008E */ "DHE-PSK-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008F */ "DHE-PSK-3DES-EDE-CBC-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA, /* 0x0090 */ "DHE-PSK-AES128-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA, /* 0x0091 */ "DHE-PSK-AES256-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_RC4_128_SHA, /* 0x0092 */ "RSA-PSK-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x0093 */ "RSA-PSK-3DES-EDE-CBC-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA, /* 0x0094 */ "RSA-PSK-AES128-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA, /* 0x0095 */ "RSA-PSK-AES256-CBC-SHA", CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS /* Addenda from rfc 5288 AES Galois Counter Mode (GCM) Cipher Suites for TLS. */ CIPHER_DEF(TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */ "AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */ "AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* 0x009E */ "DHE-RSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, /* 0x009F */ "DHE-RSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_GCM_SHA256, /* 0x00A0 */ "DH-RSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_GCM_SHA384, /* 0x00A1 */ "DH-RSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A2 */ "DHE-DSS-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A3 */ "DHE-DSS-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A4 */ "DH-DSS-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A5 */ "DH-DSS-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DH_anon_WITH_AES_128_GCM_SHA256, /* 0x00A6 */ "ADH-AES128-GCM-SHA256", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_DH_anon_WITH_AES_256_GCM_SHA384, /* 0x00A7 */ "ADH-AES256-GCM-SHA384", CIPHER_WEAK_ANON_AUTH), #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 /* RFC 5487 - PSK with SHA-256/384 and AES GCM */ CIPHER_DEF(TLS_PSK_WITH_AES_128_GCM_SHA256, /* 0x00A8 */ "PSK-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_PSK_WITH_AES_256_GCM_SHA384, /* 0x00A9 */ "PSK-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AA */ "DHE-PSK-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AB */ "DHE-PSK-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AC */ "RSA-PSK-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AD */ "RSA-PSK-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA256, /* 0x00AE */ "PSK-AES128-CBC-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA384, /* 0x00AF */ "PSK-AES256-CBC-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_PSK_WITH_NULL_SHA256, /* 0x00B0 */ "PSK-NULL-SHA256", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_PSK_WITH_NULL_SHA384, /* 0x00B1 */ "PSK-NULL-SHA384", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B2 */ "DHE-PSK-AES128-CBC-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B3 */ "DHE-PSK-AES256-CBC-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA256, /* 0x00B4 */ "DHE-PSK-NULL-SHA256", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA384, /* 0x00B5 */ "DHE-PSK-NULL-SHA384", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B6 */ "RSA-PSK-AES128-CBC-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B7 */ "RSA-PSK-AES256-CBC-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA256, /* 0x00B8 */ "RSA-PSK-NULL-SHA256", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA384, /* 0x00B9 */ "RSA-PSK-NULL-SHA384", CIPHER_WEAK_NOT_ENCRYPTED), #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ /* RFC 5746 - Secure Renegotiation. This is not a real suite, it is a response to initiate negotiation again */ CIPHER_DEF(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, /* 0x00FF */ NULL, CIPHER_STRONG_ENOUGH), #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 /* TLS 1.3 standard cipher suites for ChaCha20+Poly1305. Note: TLS 1.3 ciphersuites do not specify the key exchange algorithm -- they only specify the symmetric ciphers. Cipher alias name matches to OpenSSL cipher name, and for TLS 1.3 ciphers */ CIPHER_DEF(TLS_AES_128_GCM_SHA256, /* 0x1301 */ NULL, /* The OpenSSL cipher name matches to the IANA name */ CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_AES_256_GCM_SHA384, /* 0x1302 */ NULL, /* The OpenSSL cipher name matches to the IANA name */ CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_CHACHA20_POLY1305_SHA256, /* 0x1303 */ NULL, /* The OpenSSL cipher name matches to the IANA name */ CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_AES_128_CCM_SHA256, /* 0x1304 */ NULL, /* The OpenSSL cipher name matches to the IANA name */ CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_AES_128_CCM_8_SHA256, /* 0x1305 */ NULL, /* The OpenSSL cipher name matches to the IANA name */ CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* ECDSA addenda, RFC 4492 */ CIPHER_DEF(TLS_ECDH_ECDSA_WITH_NULL_SHA, /* 0xC001 */ "ECDH-ECDSA-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_RC4_128_SHA, /* 0xC002 */ "ECDH-ECDSA-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC003 */ "ECDH-ECDSA-DES-CBC3-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC004 */ "ECDH-ECDSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC005 */ "ECDH-ECDSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_NULL_SHA, /* 0xC006 */ "ECDHE-ECDSA-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, /* 0xC007 */ "ECDHE-ECDSA-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC008 */ "ECDHE-ECDSA-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */ "ECDHE-ECDSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */ "ECDHE-ECDSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_NULL_SHA, /* 0xC00B */ "ECDH-RSA-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_ECDH_RSA_WITH_RC4_128_SHA, /* 0xC00C */ "ECDH-RSA-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC00D */ "ECDH-RSA-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, /* 0xC00E */ "ECDH-RSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, /* 0xC00F */ "ECDH-RSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_NULL_SHA, /* 0xC010 */ "ECDHE-RSA-NULL-SHA", CIPHER_WEAK_NOT_ENCRYPTED), CIPHER_DEF(TLS_ECDHE_RSA_WITH_RC4_128_SHA, /* 0xC011 */ "ECDHE-RSA-RC4-SHA", CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC012 */ "ECDHE-RSA-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */ "ECDHE-RSA-AES128-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */ "ECDHE-RSA-AES256-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_anon_WITH_NULL_SHA, /* 0xC015 */ "AECDH-NULL-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_ECDH_anon_WITH_RC4_128_SHA, /* 0xC016 */ "AECDH-RC4-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, /* 0xC017 */ "AECDH-DES-CBC3-SHA", CIPHER_WEAK_3DES_ENCRYPTION), CIPHER_DEF(TLS_ECDH_anon_WITH_AES_128_CBC_SHA, /* 0xC018 */ "AECDH-AES128-SHA", CIPHER_WEAK_ANON_AUTH), CIPHER_DEF(TLS_ECDH_anon_WITH_AES_256_CBC_SHA, /* 0xC019 */ "AECDH-AES256-SHA", CIPHER_WEAK_ANON_AUTH), #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with HMAC SHA-256/384. */ CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */ "ECDHE-ECDSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */ "ECDHE-ECDSA-AES256-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC025 */ "ECDH-ECDSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC026 */ "ECDH-ECDSA-AES256-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */ "ECDHE-RSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */ "ECDHE-RSA-AES256-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, /* 0xC029 */ "ECDH-RSA-AES128-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, /* 0xC02A */ "ECDH-RSA-AES256-SHA384", CIPHER_STRONG_ENOUGH), /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with SHA-256/384 and AES Galois Counter Mode (GCM) */ CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */ "ECDHE-ECDSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */ "ECDHE-ECDSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02D */ "ECDH-ECDSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02E */ "ECDH-ECDSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */ "ECDHE-RSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */ "ECDHE-RSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, /* 0xC031 */ "ECDH-RSA-AES128-GCM-SHA256", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, /* 0xC032 */ "ECDH-RSA-AES256-GCM-SHA384", CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 /* ECDHE_PSK Cipher Suites for Transport Layer Security (TLS), RFC 5489 */ CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, /* 0xC035 */ "ECDHE-PSK-AES128-CBC-SHA", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, /* 0xC036 */ "ECDHE-PSK-AES256-CBC-SHA", CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 /* Addenda from rfc 7905 ChaCha20-Poly1305 Cipher Suites for Transport Layer Security (TLS). */ CIPHER_DEF(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */ "ECDHE-RSA-CHACHA20-POLY1305", CIPHER_STRONG_ENOUGH), CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */ "ECDHE-ECDSA-CHACHA20-POLY1305", CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ #if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 /* ChaCha20-Poly1305 Cipher Suites for Transport Layer Security (TLS), RFC 7905 */ CIPHER_DEF(TLS_PSK_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCAB */ "PSK-CHACHA20-POLY1305", CIPHER_STRONG_ENOUGH), #endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ /* Tags for SSL 2 cipher kinds which are not specified for SSL 3. Defined since SDK 10.2.8 */ CIPHER_DEF(SSL_RSA_WITH_RC2_CBC_MD5, /* 0xFF80 */ NULL, CIPHER_WEAK_RC_ENCRYPTION), CIPHER_DEF(SSL_RSA_WITH_IDEA_CBC_MD5, /* 0xFF81 */ NULL, CIPHER_WEAK_IDEA_ENCRYPTION), CIPHER_DEF(SSL_RSA_WITH_DES_CBC_MD5, /* 0xFF82 */ NULL, CIPHER_WEAK_DES_ENCRYPTION), CIPHER_DEF(SSL_RSA_WITH_3DES_EDE_CBC_MD5, /* 0xFF83 */ NULL, CIPHER_WEAK_3DES_ENCRYPTION), }; #define NUM_OF_CIPHERS sizeof(ciphertable)/sizeof(ciphertable[0]) static const char* SSLCipherSuiteToString(SSLCipherSuite cipher) { /* The first ciphers in the ciphertable are continuos. Here we do small optimization and instead of loop directly get SSL name by cipher number. */ if(cipher <= SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA) { return ciphertable[cipher].name; } /* Iterate through the rest of the ciphers */ for(size_t i = SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA + 1; i < NUM_OF_CIPHERS; ++i) { if(ciphertable[i].num == cipher) { return ciphertable[i].name; } } return ciphertable[SSL_NULL_WITH_NULL_NULL].name; } static bool is_cipher_suite_strong(SSLCipherSuite suite_num) { for(size_t i = 0; i < NUM_OF_CIPHERS; ++i) { if(ciphertable[i].num == suite_num) { return !ciphertable[i].weak; } } /* If the cipher is not in our list, assume it is a new one and therefore strong. Previous implementation was the same, if cipher suite is not in the list, it was considered strong enough */ return true; } const char* hssl_backend() { return "appletls"; } typedef struct appletls_ctx { SecIdentityRef cert; hssl_ctx_opt_t* param; } appletls_ctx_t; hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { appletls_ctx_t* ctx = (appletls_ctx_t*)malloc(sizeof(appletls_ctx_t)); if (ctx == NULL) return NULL; ctx->cert = NULL; ctx->param = param; return ctx; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { if (ssl_ctx == NULL) return; appletls_ctx_t* ctx = (appletls_ctx_t*)ssl_ctx; if (ctx->cert) { CFRelease(ctx->cert); ctx->cert = NULL; } free(ctx); } typedef struct appletls_s { SSLContextRef session; appletls_ctx_t* ctx; int fd; } appletls_t; hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { if (ssl_ctx == NULL) return NULL; appletls_t* appletls = (appletls_t*)malloc(sizeof(appletls_t)); if (appletls == NULL) return NULL; appletls->session = NULL; appletls->ctx = (appletls_ctx_t*)ssl_ctx; appletls->fd = fd; return (hssl_t)appletls; } static OSStatus SocketRead(SSLConnectionRef conn, void* data, size_t* len) { // printf("SocketRead(%d)\n", (int)*len); appletls_t* appletls = (appletls_t*)conn; uint8_t* buffer = (uint8_t*)data; size_t remain = *len; *len = 0; int fd = appletls->fd; // int timeout = 1000; // struct timeval tv = { timeout / 1000, (timeout % 1000) * 1000 }; // fd_set readfds; while (remain) { /* FD_ZERO(&readfds); FD_SET(fd, &readfds); int nselect = select(fd + 1, &readfds, 0, 0, &tv); printf("nselect=%d\n", nselect); if (nselect < 0) { return errSSLClosedAbort; } if (nselect == 0) { return errSSLWouldBlock; } */ // printf("read(%d)\n", (int)remain); // NOTE: avoid blocking if (remain < 16) { so_rcvtimeo(fd, 1000); } ssize_t nread = read(fd, buffer, remain); // printf("nread=%d errno=%d\n", (int)nread, (int)errno); if (nread == 0) return errSSLClosedGraceful; if (nread < 0) { switch (errno) { case ENOENT: return errSSLClosedGraceful; case ECONNRESET:return errSSLClosedAbort; case EAGAIN: return errSSLWouldBlock; default: return errSSLClosedAbort; } } *len += nread; remain -= nread; buffer += nread; } return noErr; } static OSStatus SocketWrite(SSLConnectionRef conn, const void* data, size_t* len) { // printf("SocketWrite(%d)\n", (int)*len); appletls_t* appletls = (appletls_t*)conn; uint8_t* buffer = (uint8_t*)data; size_t remain = *len; *len = 0; int fd = appletls->fd; while (remain) { if (remain < 16) { so_sndtimeo(fd, 1000); } // printf("write(%d)\n", (int)remain); ssize_t nwrite = write(fd, buffer, remain); // printf("nwrite=%d errno=%d\n", (int)nwrite, (int)errno); if (nwrite <= 0) { switch (errno) { case EAGAIN: return errSSLWouldBlock; default: return errSSLClosedAbort; } } remain -= nwrite; buffer += nwrite; *len += nwrite; } return noErr; } static int hssl_init(hssl_t ssl, int endpoint) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; OSStatus ret = noErr; if (appletls->session == NULL) { #if defined(__MAC_10_8) appletls->session = SSLCreateContext(NULL, endpoint == HSSL_SERVER ? kSSLServerSide : kSSLClientSide, kSSLStreamType); #else SSLNewContext(endpoint == HSSL_SERVER, &(appletls->session)); #endif } if (appletls->session == NULL) { fprintf(stderr, "SSLCreateContext failed!\n"); return HSSL_ERROR; } // ret = SSLSetProtocolVersionEnabled(appletls->session, kSSLProtocolAll, true); ret = SSLSetProtocolVersionMin(appletls->session, kTLSProtocol12); if (ret != noErr) { fprintf(stderr, "SSLSetProtocolVersionMin failed!\n"); return HSSL_ERROR; } bool verify_peer = false; if (appletls->ctx->param && appletls->ctx->param->verify_peer) { verify_peer = true; } #if defined(__MAC_10_8) ret = SSLSetSessionOption(appletls->session, kSSLSessionOptionBreakOnServerAuth, !verify_peer); #else ret = SSLSetEnableCertVerify(appletls->session, verify_peer); #endif if (ret != noErr) { fprintf(stderr, "SSLSetEnableCertVerify failed!\n"); return HSSL_ERROR; } if (appletls->ctx->cert) { CFArrayRef certs = CFArrayCreate(NULL, (const void**)&appletls->ctx->cert, 1, NULL); if (!certs) { fprintf(stderr, "CFArrayCreate failed!\n"); return HSSL_ERROR; } ret = SSLSetCertificate(appletls->session, certs); CFRelease(certs); if (ret != noErr) { fprintf(stderr, "SSLSetCertificate failed!\n"); return HSSL_ERROR; } } size_t all_ciphers_count = 0, allowed_ciphers_count = 0; SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; ret = SSLGetNumberSupportedCiphers(appletls->session, &all_ciphers_count); if (ret != noErr) { fprintf(stderr, "SSLGetNumberSupportedCiphers failed!\n"); goto error; } all_ciphers = (SSLCipherSuite*)malloc(all_ciphers_count * sizeof(SSLCipherSuite)); allowed_ciphers = (SSLCipherSuite*)malloc(all_ciphers_count * sizeof(SSLCipherSuite)); if (all_ciphers == NULL || allowed_ciphers == NULL) { fprintf(stderr, "malloc failed!\n"); goto error; } ret = SSLGetSupportedCiphers(appletls->session, all_ciphers, &all_ciphers_count); if (ret != noErr) { fprintf(stderr, "SSLGetSupportedCiphers failed!\n"); goto error; } for (size_t i = 0; i < all_ciphers_count; ++i) { if (is_cipher_suite_strong(all_ciphers[i])) { allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i]; } } ret = SSLSetEnabledCiphers(appletls->session, allowed_ciphers, allowed_ciphers_count); if (ret != noErr) { fprintf(stderr, "SSLSetEnabledCiphers failed!\n"); goto error; } if (all_ciphers) { free(all_ciphers); all_ciphers = NULL; } if (allowed_ciphers) { free(allowed_ciphers); allowed_ciphers = NULL; } ret = SSLSetIOFuncs(appletls->session, SocketRead, SocketWrite); if (ret != noErr) { fprintf(stderr, "SSLSetIOFuncs failed!\n"); return HSSL_ERROR; } ret = SSLSetConnection(appletls->session, appletls); if (ret != noErr) { fprintf(stderr, "SSLSetConnection failed!\n"); return HSSL_ERROR; } /* char session_id[64] = {0}; int session_id_len = snprintf(session_id, sizeof(session_id), "libhv:appletls:%p", appletls->session); ret = SSLSetPeerID(appletls->session, session_id, session_id_len); if (ret != noErr) { fprintf(stderr, "SSLSetPeerID failed!\n"); return HSSL_ERROR; } */ return HSSL_OK; error: if (all_ciphers) { free(all_ciphers); } if (allowed_ciphers) { free(allowed_ciphers); } return HSSL_ERROR; } void hssl_free(hssl_t ssl) { if (ssl == NULL) return; appletls_t* appletls = (appletls_t*)ssl; if (appletls->session) { #if defined(__MAC_10_8) CFRelease(appletls->session); #else SSLDisposeContext(appletls->session); #endif appletls->session = NULL; } free(appletls); } static int hssl_handshake(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; OSStatus ret = SSLHandshake(appletls->session); // printf("SSLHandshake retval=%d\n", (int)ret); switch(ret) { case noErr: break; case errSSLWouldBlock: return HSSL_WANT_READ; case errSSLPeerAuthCompleted: /* peer cert is valid, or was ignored if verification disabled */ return hssl_handshake(ssl); case errSSLBadConfiguration: return HSSL_WANT_READ; default: return HSSL_ERROR; } /* SSLProtocol protocol = kSSLProtocolUnknown; SSLGetNegotiatedProtocolVersion(appletls->session, &protocol); SSLCipherSuite cipher = SSL_NO_SUCH_CIPHERSUITE; SSLGetNegotiatedCipher(appletls->session, &cipher); printf("* %s connection using %s\n", SSLProtocolToString(protocol), SSLCipherSuiteToString(cipher)); */ return HSSL_OK; } int hssl_accept(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; if (appletls->session == NULL) { hssl_init(ssl, HSSL_SERVER); } return hssl_handshake(ssl); } int hssl_connect(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; if (appletls->session == NULL) { hssl_init(ssl, HSSL_CLIENT); } return hssl_handshake(ssl); } int hssl_read(hssl_t ssl, void* buf, int len) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; size_t processed = 0; // printf("SSLRead(%d)\n", len); OSStatus ret = SSLRead(appletls->session, buf, len, &processed); // printf("SSLRead retval=%d processed=%d\n", (int)ret, (int)processed); switch (ret) { case noErr: return processed; case errSSLWouldBlock: return processed ? processed : HSSL_WOULD_BLOCK; case errSSLClosedGraceful: case errSSLClosedNoNotify: return 0; default: return HSSL_ERROR; } } int hssl_write(hssl_t ssl, const void* buf, int len) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; size_t processed = 0; // printf("SSLWrite(%d)\n", len); OSStatus ret = SSLWrite(appletls->session, buf, len, &processed); // printf("SSLWrite retval=%d processed=%d\n", (int)ret, (int)processed); switch (ret) { case noErr: return processed; case errSSLWouldBlock: return processed ? processed : HSSL_WOULD_BLOCK; case errSSLClosedGraceful: case errSSLClosedNoNotify: return 0; default: return HSSL_ERROR; } } int hssl_close(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; SSLClose(appletls->session); return 0; } int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { if (ssl == NULL) return HSSL_ERROR; appletls_t* appletls = (appletls_t*)ssl; if (appletls->session == NULL) { hssl_init(ssl, HSSL_CLIENT); } SSLSetPeerDomainName(appletls->session, hostname, strlen(hostname)); return 0; } #endif // WITH_APPLETLS kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/gnutls.c000066400000000000000000000131161520575453600257300ustar00rootroot00000000000000#include "hssl.h" #ifdef WITH_GNUTLS #include "gnutls/gnutls.h" const char* hssl_backend() { return "gnutls"; } typedef gnutls_certificate_credentials_t gnutls_ctx_t; hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { static int s_initialized = 0; if (s_initialized == 0) { gnutls_global_init(); s_initialized = 1; } gnutls_ctx_t ctx; const char* crt_file = NULL; const char* key_file = NULL; const char* ca_file = NULL; const char* ca_path = NULL; int ret = gnutls_certificate_allocate_credentials(&ctx); if (ret != GNUTLS_E_SUCCESS) { return NULL; } if (param) { if (param->crt_file && *param->crt_file) { crt_file = param->crt_file; } if (param->key_file && *param->key_file) { key_file = param->key_file; } if (param->ca_file && *param->ca_file) { ca_file = param->ca_file; } if (param->ca_path && *param->ca_path) { ca_path = param->ca_path; } if (ca_file) { ret = gnutls_certificate_set_x509_trust_file(ctx, ca_file, GNUTLS_X509_FMT_PEM); if (ret < 0) { fprintf(stderr, "ssl ca_file failed!\n"); goto error; } } if (ca_path) { ret = gnutls_certificate_set_x509_trust_dir(ctx, ca_path, GNUTLS_X509_FMT_PEM); if (ret < 0) { fprintf(stderr, "ssl ca_path failed!\n"); goto error; } } if (crt_file && key_file) { ret = gnutls_certificate_set_x509_key_file(ctx, crt_file, key_file, GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) { fprintf(stderr, "ssl crt_file/key_file error!\n"); goto error; } } if (param->verify_peer && !ca_file && !ca_path) { gnutls_certificate_set_x509_system_trust(ctx); } } return ctx; error: gnutls_certificate_free_credentials(ctx); return NULL; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { if (!ssl_ctx) return; gnutls_ctx_t ctx = (gnutls_ctx_t)ssl_ctx; gnutls_certificate_free_credentials(ctx); } typedef struct gnutls_s { gnutls_session_t session; gnutls_ctx_t ctx; int fd; } gnutls_t; hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { gnutls_t* gnutls = (gnutls_t*)malloc(sizeof(gnutls_t)); if (gnutls == NULL) return NULL; gnutls->session = NULL; gnutls->ctx = (gnutls_ctx_t)ssl_ctx; gnutls->fd = fd; return (hssl_t)gnutls; } static int hssl_init(hssl_t ssl, int endpoint) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) { gnutls_init(&gnutls->session, endpoint); gnutls_priority_set_direct(gnutls->session, "NORMAL", NULL); gnutls_credentials_set(gnutls->session, GNUTLS_CRD_CERTIFICATE, gnutls->ctx); gnutls_transport_set_ptr(gnutls->session, (gnutls_transport_ptr_t)(ptrdiff_t)gnutls->fd); } return HSSL_OK; } void hssl_free(hssl_t ssl) { if (ssl == NULL) return; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session) { gnutls_deinit(gnutls->session); gnutls->session = NULL; } free(gnutls); } static int hssl_handshake(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) return HSSL_ERROR; int ret = 0; while (1) { ret = gnutls_handshake(gnutls->session); if (ret == GNUTLS_E_SUCCESS) { return HSSL_OK; } else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { return gnutls_record_get_direction(gnutls->session) == 0 ? HSSL_WANT_READ : HSSL_WANT_WRITE; } else if (gnutls_error_is_fatal(ret)) { // fprintf(stderr, "gnutls_handshake failed: %s\n", gnutls_strerror(ret)); return HSSL_ERROR; } } return HSSL_OK; } int hssl_accept(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) { hssl_init(ssl, GNUTLS_SERVER); } return hssl_handshake(ssl); } int hssl_connect(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) { hssl_init(ssl, GNUTLS_CLIENT); } return hssl_handshake(ssl); } int hssl_read(hssl_t ssl, void* buf, int len) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) return HSSL_ERROR; int ret = 0; while ((ret = gnutls_record_recv(gnutls->session, buf, len)) == GNUTLS_E_INTERRUPTED); return ret; } int hssl_write(hssl_t ssl, const void* buf, int len) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) return HSSL_ERROR; int ret = 0; while ((ret = gnutls_record_send(gnutls->session, buf, len)) == GNUTLS_E_INTERRUPTED); return ret; } int hssl_close(hssl_t ssl) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) return HSSL_ERROR; gnutls_bye(gnutls->session, GNUTLS_SHUT_RDWR); return HSSL_OK; } int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { if (ssl == NULL) return HSSL_ERROR; gnutls_t* gnutls = (gnutls_t*)ssl; if (gnutls->session == NULL) { hssl_init(ssl, GNUTLS_CLIENT); } gnutls_server_name_set(gnutls->session, GNUTLS_NAME_DNS, hostname, strlen(hostname)); return 0; } #endif // WITH_GNUTLS kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/hssl.c000066400000000000000000000007361520575453600253710ustar00rootroot00000000000000#include "hssl.h" hssl_ctx_t g_ssl_ctx = NULL; hssl_ctx_t hssl_ctx_init(hssl_ctx_init_param_t* param) { if (g_ssl_ctx == NULL) { g_ssl_ctx = hssl_ctx_new(param); } return g_ssl_ctx; } void hssl_ctx_cleanup(hssl_ctx_t ssl_ctx) { hssl_ctx_free(ssl_ctx); if (g_ssl_ctx == ssl_ctx) { g_ssl_ctx = NULL; } } hssl_ctx_t hssl_ctx_instance() { if (g_ssl_ctx == NULL) { g_ssl_ctx = hssl_ctx_new(NULL); } return g_ssl_ctx; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/hssl.h000066400000000000000000000041461520575453600253750ustar00rootroot00000000000000#ifndef HV_SSL_H_ #define HV_SSL_H_ #include "hexport.h" #include "hplatform.h" #if !defined(WITH_OPENSSL) && \ !defined(WITH_GNUTLS) && \ !defined(WITH_MBEDTLS) #ifdef OS_WIN #define WITH_WINTLS #ifdef _MSC_VER #pragma comment(lib, "secur32.lib") #pragma comment(lib, "crypt32.lib") #endif #elif defined(OS_DARWIN) #define WITH_APPLETLS #else #define HV_WITHOUT_SSL #endif #endif typedef void* hssl_ctx_t; ///> SSL_CTX typedef void* hssl_t; ///> SSL enum { HSSL_SERVER = 0, HSSL_CLIENT = 1, }; enum { HSSL_OK = 0, HSSL_ERROR = -1, HSSL_WANT_READ = -2, HSSL_WANT_WRITE = -3, HSSL_WOULD_BLOCK = -4, }; typedef struct { const char* crt_file; const char* key_file; const char* ca_file; const char* ca_path; short verify_peer; short endpoint; // HSSL_SERVER / HSSL_CLIENT } hssl_ctx_opt_t, hssl_ctx_init_param_t; BEGIN_EXTERN_C /* const char* hssl_backend() { #ifdef WITH_OPENSSL return "openssl"; #elif defined(WITH_GNUTLS) return "gnutls"; #elif defined(WITH_MBEDTLS) return "mbedtls"; #else return "nossl"; #endif } */ HV_EXPORT const char* hssl_backend(); #define HV_WITH_SSL (strcmp(hssl_backend(), "nossl") != 0) HV_EXPORT extern hssl_ctx_t g_ssl_ctx; HV_EXPORT hssl_ctx_t hssl_ctx_init(hssl_ctx_init_param_t* param); HV_EXPORT void hssl_ctx_cleanup(hssl_ctx_t ssl_ctx); HV_EXPORT hssl_ctx_t hssl_ctx_instance(); HV_EXPORT hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt); HV_EXPORT void hssl_ctx_free(hssl_ctx_t ssl_ctx); HV_EXPORT hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd); HV_EXPORT void hssl_free(hssl_t ssl); HV_EXPORT int hssl_accept(hssl_t ssl); HV_EXPORT int hssl_connect(hssl_t ssl); HV_EXPORT int hssl_read(hssl_t ssl, void* buf, int len); HV_EXPORT int hssl_write(hssl_t ssl, const void* buf, int len); HV_EXPORT int hssl_close(hssl_t ssl); HV_EXPORT int hssl_set_sni_hostname(hssl_t ssl, const char* hostname); #ifdef WITH_OPENSSL HV_EXPORT int hssl_ctx_set_alpn_protos(hssl_ctx_t ssl_ctx, const unsigned char* protos, unsigned int protos_len); #endif END_EXTERN_C #endif // HV_SSL_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/mbedtls.c000066400000000000000000000130531520575453600260460ustar00rootroot00000000000000#include "hssl.h" #include "hsocket.h" #ifdef WITH_MBEDTLS #include "mbedtls/version.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/x509.h" #include "mbedtls/ssl.h" #include "mbedtls/net_sockets.h" #include "mbedtls/error.h" #include "mbedtls/debug.h" #if defined(MBEDTLS_SSL_CACHE_C) #include "mbedtls/ssl_cache.h" #endif #ifdef _MSC_VER //#pragma comment(lib, "libmbedtls.a") //#pragma comment(lib, "libmbedx509.a") //#pragma comment(lib, "libmbedcrypto.a") #endif const char* hssl_backend() { return "mbedtls"; } struct mbedtls_ctx { mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ssl_config conf; mbedtls_x509_crt cert; mbedtls_pk_context pkey; #if defined(MBEDTLS_SSL_CACHE_C) mbedtls_ssl_cache_context cache; #endif }; hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { struct mbedtls_ctx* ctx = (struct mbedtls_ctx*)malloc(sizeof(struct mbedtls_ctx)); if (ctx == NULL) return NULL; mbedtls_ssl_config_init(&ctx->conf); #if defined(MBEDTLS_SSL_CACHE_C) mbedtls_ssl_cache_init(&ctx->cache); #endif mbedtls_x509_crt_init(&ctx->cert); mbedtls_pk_init(&ctx->pkey); mbedtls_entropy_init(&ctx->entropy); mbedtls_ctr_drbg_init(&ctx->ctr_drbg); int mode = MBEDTLS_SSL_VERIFY_NONE; int endpoint = MBEDTLS_SSL_IS_CLIENT; bool check = false; if (param) { if (param->crt_file && *param->crt_file) { if (mbedtls_x509_crt_parse_file(&ctx->cert, param->crt_file) != 0) { fprintf(stderr, "ssl crt_file error!\n"); goto error; } } if (param->key_file && *param->key_file) { #if MBEDTLS_VERSION_MAJOR >= 3 if (mbedtls_pk_parse_keyfile(&ctx->pkey, param->key_file, NULL, NULL, NULL) != 0) { #else if (mbedtls_pk_parse_keyfile(&ctx->pkey, param->key_file, NULL) != 0) { #endif fprintf(stderr, "ssl key_file error!\n"); goto error; } check = true; } if (param->verify_peer) { mode = MBEDTLS_SSL_VERIFY_REQUIRED; } if (param->endpoint == HSSL_SERVER) { endpoint = MBEDTLS_SSL_IS_SERVER; } } mbedtls_ctr_drbg_seed(&ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy, NULL, 0); if (mbedtls_ssl_config_defaults(&ctx->conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { fprintf(stderr, "ssl config error!\n"); goto error; } mbedtls_ssl_conf_authmode(&ctx->conf, mode); mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg); #if defined(MBEDTLS_SSL_CACHE_C) mbedtls_ssl_conf_session_cache(&ctx->conf, &ctx->cache, mbedtls_ssl_cache_get, mbedtls_ssl_cache_set); #endif if (check) { mbedtls_ssl_conf_ca_chain(&ctx->conf, ctx->cert.next, NULL); if (mbedtls_ssl_conf_own_cert(&ctx->conf, &ctx->cert, &ctx->pkey) != 0) { fprintf(stderr, "ssl key_file check failed!\n"); goto error; } } return ctx; error: free(ctx); return NULL; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { if (!ssl_ctx) return; struct mbedtls_ctx *mctx = (struct mbedtls_ctx *)ssl_ctx; mbedtls_x509_crt_free(&mctx->cert); mbedtls_pk_free(&mctx->pkey); mbedtls_ssl_config_free(&mctx->conf); #if defined(MBEDTLS_SSL_CACHE_C) mbedtls_ssl_cache_free(&mctx->cache); #endif mbedtls_ctr_drbg_free(&mctx->ctr_drbg); mbedtls_entropy_free(&mctx->entropy); free(mctx); } static int __mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len) { int fd = (intptr_t)ctx; // int n = write(fd, buf, len); int n = send(fd, (char*)(buf), (int)(len), 0); if (n >= 0) return n; return ((socket_errno() == EAGAIN || socket_errno() == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1); } static int __mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len) { int fd = (intptr_t)ctx; // int n = read(fd, buf, len); int n = recv(fd, (char*)(buf), (int)(len), 0); if (n >= 0) return n; return ((socket_errno() == EAGAIN || socket_errno() == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1); } hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { struct mbedtls_ctx* mctx = (struct mbedtls_ctx*)ssl_ctx; mbedtls_ssl_context* ssl = (mbedtls_ssl_context*)malloc(sizeof(mbedtls_ssl_context)); if (ssl == NULL) return NULL; mbedtls_ssl_init(ssl); mbedtls_ssl_setup(ssl, &mctx->conf); mbedtls_ssl_set_bio(ssl, (void*)(intptr_t)fd, __mbedtls_net_send, __mbedtls_net_recv, NULL); return ssl; } void hssl_free(hssl_t ssl) { if (ssl) { mbedtls_ssl_free(ssl); ssl = NULL; } } static int hssl_handshake(hssl_t ssl) { int ret = mbedtls_ssl_handshake(ssl); if (ret != 0) { if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return HSSL_WANT_READ; } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return HSSL_WANT_WRITE; } } return ret; } int hssl_accept(hssl_t ssl) { return hssl_handshake(ssl); } int hssl_connect(hssl_t ssl) { return hssl_handshake(ssl); } int hssl_read(hssl_t ssl, void* buf, int len) { return mbedtls_ssl_read(ssl, buf, len); } int hssl_write(hssl_t ssl, const void* buf, int len) { return mbedtls_ssl_write(ssl, buf, len); } int hssl_close(hssl_t ssl) { return 0; } int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { #ifdef MBEDTLS_X509_CRT_PARSE_C mbedtls_ssl_set_hostname(ssl, hostname); #endif return 0; } #endif // WITH_MBEDTLS kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/nossl.c000066400000000000000000000015141520575453600255510ustar00rootroot00000000000000#include "hssl.h" #ifdef HV_WITHOUT_SSL const char* hssl_backend() { return "nossl"; } hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt) { fprintf(stderr, "Please recompile WITH_SSL.\n"); return NULL; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { } hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { return (void*)(intptr_t)fd; } void hssl_free(hssl_t ssl) { } int hssl_accept(hssl_t ssl) { return 0; } int hssl_connect(hssl_t ssl) { return 0; } int hssl_read(hssl_t ssl, void* buf, int len) { int fd = (intptr_t)ssl; return read(fd, buf, len); } int hssl_write(hssl_t ssl, const void* buf, int len) { int fd = (intptr_t)ssl; return write(fd, buf, len); } int hssl_close(hssl_t ssl) { return 0; } int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { return 0; } #endif // HV_WITHOUT_SSL kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/openssl.c000066400000000000000000000124211520575453600260750ustar00rootroot00000000000000#include "hssl.h" #ifdef WITH_OPENSSL #include "openssl/ssl.h" #include "openssl/err.h" #ifdef _MSC_VER //#pragma comment(lib, "libssl.a") //#pragma comment(lib, "libcrypto.a") #endif const char* hssl_backend() { return "openssl"; } hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { static int s_initialized = 0; if (s_initialized == 0) { #if OPENSSL_VERSION_NUMBER < 0x10100000L SSL_library_init(); SSL_load_error_strings(); #else OPENSSL_init_ssl(OPENSSL_INIT_SSL_DEFAULT, NULL); #endif s_initialized = 1; } #if OPENSSL_VERSION_NUMBER < 0x10100000L SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); #else SSL_CTX* ctx = SSL_CTX_new(TLS_method()); #endif if (ctx == NULL) return NULL; int mode = SSL_VERIFY_NONE; const char* ca_file = NULL; const char* ca_path = NULL; if (param) { if (param->ca_file && *param->ca_file) { ca_file = param->ca_file; } if (param->ca_path && *param->ca_path) { ca_path = param->ca_path; } if (ca_file || ca_path) { if (!SSL_CTX_load_verify_locations(ctx, ca_file, ca_path)) { fprintf(stderr, "ssl ca_file/ca_path failed!\n"); goto error; } } if (param->crt_file && *param->crt_file) { if (!SSL_CTX_use_certificate_file(ctx, param->crt_file, SSL_FILETYPE_PEM)) { fprintf(stderr, "ssl crt_file error!\n"); goto error; } } if (param->key_file && *param->key_file) { if (!SSL_CTX_use_PrivateKey_file(ctx, param->key_file, SSL_FILETYPE_PEM)) { fprintf(stderr, "ssl key_file error!\n"); goto error; } if (!SSL_CTX_check_private_key(ctx)) { fprintf(stderr, "ssl key_file check failed!\n"); goto error; } } if (param->verify_peer) { mode = SSL_VERIFY_PEER; if (param->endpoint == HSSL_SERVER) { mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; } } } if (mode == SSL_VERIFY_PEER && !ca_file && !ca_path) { SSL_CTX_set_default_verify_paths(ctx); } #ifdef SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER SSL_CTX_set_mode(ctx, SSL_CTX_get_mode(ctx) | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #endif SSL_CTX_set_verify(ctx, mode, NULL); return ctx; error: SSL_CTX_free(ctx); return NULL; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { if (!ssl_ctx) return; SSL_CTX_free((SSL_CTX*)ssl_ctx); } hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { SSL* ssl = SSL_new((SSL_CTX*)ssl_ctx); if (ssl == NULL) return NULL; SSL_set_fd(ssl, fd); return ssl; } void hssl_free(hssl_t ssl) { if (ssl) { SSL_free((SSL*)ssl); ssl = NULL; } } int hssl_accept(hssl_t ssl) { int ret = SSL_accept((SSL*)ssl); if (ret == 1) return 0; int err = SSL_get_error((SSL*)ssl, ret); if (err == SSL_ERROR_WANT_READ) { return HSSL_WANT_READ; } else if (err == SSL_ERROR_WANT_WRITE) { return HSSL_WANT_WRITE; } return err; } int hssl_connect(hssl_t ssl) { int ret = SSL_connect((SSL*)ssl); if (ret == 1) return 0; int err = SSL_get_error((SSL*)ssl, ret); if (err == SSL_ERROR_WANT_READ) { return HSSL_WANT_READ; } else if (err == SSL_ERROR_WANT_WRITE) { return HSSL_WANT_WRITE; } return err; } int hssl_read(hssl_t ssl, void* buf, int len) { return SSL_read((SSL*)ssl, buf, len); } int hssl_write(hssl_t ssl, const void* buf, int len) { return SSL_write((SSL*)ssl, buf, len); } int hssl_close(hssl_t ssl) { SSL_shutdown((SSL*)ssl); return 0; } int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME SSL_set_tlsext_host_name((SSL*)ssl, hostname); #endif return 0; } #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation static int hssl_ctx_alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { const unsigned char* protos = (unsigned char*)arg; unsigned int protos_len = strlen((char*)protos); // printf("hssl_ctx_alpn_select_cb(in=%*.s:%u out=%.*s:%u protos=%.*s:%u)\n", inlen, in, inlen, (int)*outlen, (char*)out, (int)*outlen, protos_len, protos, protos_len); if (SSL_select_next_proto((unsigned char **) out, outlen, protos, protos_len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { fprintf(stderr, "SSL_select_next_proto failed!\n"); return SSL_TLSEXT_ERR_ALERT_FATAL; } // printf("SSL_select_next_proto(out=%.*s:%u)\n", (int)*outlen, (char*)*out, (int)*outlen); return SSL_TLSEXT_ERR_OK; } #endif int hssl_ctx_set_alpn_protos(hssl_ctx_t ssl_ctx, const unsigned char* protos, unsigned int protos_len) { int ret = -1; // printf("hssl_ctx_set_alpn_protos(%.*s:%u)\n", protos_len, protos, protos_len); #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation // for HSSL_CLIENT // ret = SSL_CTX_set_alpn_protos((SSL_CTX*)ssl_ctx, (const unsigned char*)protos, protos_len); // for HSSL_SERVER SSL_CTX_set_alpn_select_cb((SSL_CTX*)ssl_ctx, hssl_ctx_alpn_select_cb, (void*)protos); ret = 0; #endif return ret; } #endif // WITH_OPENSSL kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/ssl/wintls.c000066400000000000000000000716561520575453600257510ustar00rootroot00000000000000#include "hssl.h" #ifdef WITH_WINTLS // #define PRINT_DEBUG // #define PRINT_ERROR #include "hdef.h" #include #include #include #include #define SECURITY_WIN32 #include #include #define TLS_SOCKET_BUFFER_SIZE 17000 #ifndef SP_PROT_SSL2_SERVER #define SP_PROT_SSL2_SERVER 0x00000004 #endif #ifndef SP_PROT_SSL2_CLIENT #define SP_PROT_SSL2_CLIENT 0x00000008 #endif #ifndef SP_PROT_SSL3_SERVER #define SP_PROT_SSL3_SERVER 0x00000010 #endif #ifndef SP_PROT_SSL3_CLIENT #define SP_PROT_SSL3_CLIENT 0x00000020 #endif #ifndef SP_PROT_TLS1_SERVER #define SP_PROT_TLS1_SERVER 0x00000040 #endif #ifndef SP_PROT_TLS1_CLIENT #define SP_PROT_TLS1_CLIENT 0x00000080 #endif #ifndef SP_PROT_TLS1_0_SERVER #define SP_PROT_TLS1_0_SERVER SP_PROT_TLS1_SERVER #endif #ifndef SP_PROT_TLS1_0_CLIENT #define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT #endif #ifndef SP_PROT_TLS1_1_SERVER #define SP_PROT_TLS1_1_SERVER 0x00000100 #endif #ifndef SP_PROT_TLS1_1_CLIENT #define SP_PROT_TLS1_1_CLIENT 0x00000200 #endif #ifndef SP_PROT_TLS1_2_SERVER #define SP_PROT_TLS1_2_SERVER 0x00000400 #endif #ifndef SP_PROT_TLS1_2_CLIENT #define SP_PROT_TLS1_2_CLIENT 0x00000800 #endif #ifndef SP_PROT_TLS1_3_SERVER #define SP_PROT_TLS1_3_SERVER 0x00001000 #endif #ifndef SP_PROT_TLS1_3_CLIENT #define SP_PROT_TLS1_3_CLIENT 0x00002000 #endif #ifndef SCH_USE_STRONG_CRYPTO #define SCH_USE_STRONG_CRYPTO 0x00400000 #endif #ifndef SECBUFFER_ALERT #define SECBUFFER_ALERT 17 #endif const char* hssl_backend() { return "schannel"; } static PCCERT_CONTEXT getservercert(const char* path) { /* According to the information I searched from the internet, it is not possible to specify an x509 private key and certificate using the CertCreateCertificateContext interface. We must first export them as a pkcs#12 formatted file, and then import them into the Windows certificate store. This is because the Windows certificate store is an integrated system location that does not support the direct use of separate private key files and certificate files. The pkcs#12 format is a complex format that can store and protect keys and certificates. You can use the OpenSSL tool to combine the private key file and certificate file into a pkcs#12 formatted file, For example: OpenSSL pkcs12 -export -out cert.pfx -inkey private.key -in cert.cer Then, you can use the certutil tool or a graphical interface to import this file into the personal store of your local computer. After importing, you can use the CertFindCertificateInStore interface to create and manipulate certificate contexts. */ return NULL; } hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt) { SECURITY_STATUS SecStatus; TimeStamp Lifetime; CredHandle* hCred = NULL; SCHANNEL_CRED credData = { 0 }; TCHAR unisp_name[] = UNISP_NAME; unsigned long credflag; if (opt && opt->endpoint == HSSL_SERVER) { PCCERT_CONTEXT serverCert = NULL; // server-side certificate #if 1 // create cert from store //------------------------------------------------------- // Get the server certificate. //------------------------------------------------------- // Open the My store(personal store). HCERTSTORE hMyCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"MY"); if (hMyCertStore == NULL) { printe("Error opening MY store for server.\n"); return NULL; } //------------------------------------------------------- // Search for a certificate match its subject string to opt->crt_file. serverCert = CertFindCertificateInStore(hMyCertStore, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_A, opt->crt_file, NULL); CertCloseStore(hMyCertStore, 0); if (serverCert == NULL) { printe("Error retrieving server certificate. %x\n", GetLastError()); return NULL; } #else serverCert = getservercert(opt->ca_file); #endif credData.cCreds = 1; // 数量 credData.paCred = &serverCert; // credData.dwCredFormat = SCH_CRED_FORMAT_CERT_HASH; credData.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_3_SERVER; credflag = SECPKG_CRED_INBOUND; } else { credData.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_3_CLIENT; credflag = SECPKG_CRED_OUTBOUND; } #if 0 // just use the system defalut algs ALG_ID rgbSupportedAlgs[4]; rgbSupportedAlgs[0] = CALG_DH_EPHEM; rgbSupportedAlgs[1] = CALG_RSA_KEYX; rgbSupportedAlgs[2] = CALG_AES_128; rgbSupportedAlgs[3] = CALG_SHA_256; credData.cSupportedAlgs = 4; credData.palgSupportedAlgs = rgbSupportedAlgs; #endif credData.dwVersion = SCHANNEL_CRED_VERSION; // credData.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_NO_SERVERNAME_CHECK | SCH_USE_STRONG_CRYPTO | SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_IGNORE_NO_REVOCATION_CHECK | SCH_CRED_IGNORE_REVOCATION_OFFLINE; // credData.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION | SCH_CRED_REVOCATION_CHECK_CHAIN | SCH_CRED_IGNORE_REVOCATION_OFFLINE; // credData.dwMinimumCipherStrength = -1; // credData.dwMaximumCipherStrength = -1; //------------------------------------------------------- hCred = (CredHandle*)malloc(sizeof(CredHandle)); if (hCred == NULL) { return NULL; } SecStatus = AcquireCredentialsHandle(NULL, unisp_name, credflag, NULL, &credData, NULL, NULL, hCred, &Lifetime); if (SecStatus == SEC_E_OK) { #ifndef NDEBUG SecPkgCred_SupportedAlgs algs; if (QueryCredentialsAttributesA(hCred, SECPKG_ATTR_SUPPORTED_ALGS, &algs) == SEC_E_OK) { for (int i = 0; i < algs.cSupportedAlgs; i++) { printd("alg: 0x%08x\n", algs.palgSupportedAlgs[i]); } } #endif } else { printe("ERROR: AcquireCredentialsHandle: 0x%x\n", SecStatus); free(hCred); hCred = NULL; } return hCred; } void hssl_ctx_free(hssl_ctx_t ssl_ctx) { SECURITY_STATUS sec_status = FreeCredentialsHandle(ssl_ctx); if (sec_status != SEC_E_OK) { printe("free_cred_handle FreeCredentialsHandle %d\n", sec_status); } } static void init_sec_buffer(SecBuffer* secure_buffer, unsigned long type, unsigned long len, void* buffer) { secure_buffer->BufferType = type; secure_buffer->cbBuffer = len; secure_buffer->pvBuffer = buffer; } static void init_sec_buffer_desc(SecBufferDesc* secure_buffer_desc, unsigned long version, unsigned long num_buffers, SecBuffer* buffers) { secure_buffer_desc->ulVersion = version; secure_buffer_desc->cBuffers = num_buffers; secure_buffer_desc->pBuffers = buffers; } /* enum for the nonblocking SSL connection state machine */ typedef enum { ssl_connect_1, ssl_connect_2, ssl_connect_2_reading, ssl_connect_2_writing, ssl_connect_3, ssl_connect_done } ssl_connect_state; struct wintls_s { hssl_ctx_t ssl_ctx; // CredHandle int fd; union { ssl_connect_state state2; ssl_connect_state connecting_state; }; SecHandle sechandle; SecPkgContext_StreamSizes stream_sizes_; size_t buffer_to_decrypt_offset_; size_t dec_len_; char encrypted_buffer_[TLS_SOCKET_BUFFER_SIZE]; char buffer_to_decrypt_[TLS_SOCKET_BUFFER_SIZE]; char decrypted_buffer_[TLS_SOCKET_BUFFER_SIZE + TLS_SOCKET_BUFFER_SIZE]; char* sni; }; hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { struct wintls_s* ret = malloc(sizeof(*ret)); if (ret) { memset(ret, 0, sizeof(*ret)); ret->ssl_ctx = ssl_ctx; ret->fd = fd; ret->sechandle.dwLower = 0; ret->sechandle.dwUpper = 0; } return ret; } void hssl_free(hssl_t _ssl) { struct wintls_s* ssl = _ssl; SECURITY_STATUS sec_status = DeleteSecurityContext(&ssl->sechandle); if (sec_status != SEC_E_OK) { printe("hssl_free DeleteSecurityContext %d", sec_status); } if (ssl->sni) { free(ssl->sni); } free(ssl); } static void free_all_buffers(SecBufferDesc* secure_buffer_desc) { for (unsigned long i = 0; i < secure_buffer_desc->cBuffers; ++i) { void* buffer = secure_buffer_desc->pBuffers[i].pvBuffer; if (buffer != NULL) { FreeContextBuffer(buffer); } } } static int __sendwrapper(SOCKET fd, const char* buf, size_t len, int flags) { int left = len; int offset = 0; while (left > 0) { int bytes_sent = send(fd, buf + offset, left, flags); if (bytes_sent == 0 || (bytes_sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK && WSAGetLastError() != WSAEINTR)) { break; } if (bytes_sent > 0) { offset += bytes_sent; left -= bytes_sent; } } return offset; } static int __recvwrapper(SOCKET fd, char* buf, int len, int flags) { int ret = 0; do { ret = recv(fd, buf, len, flags); } while (ret == SOCKET_ERROR && WSAGetLastError() == WSAEINTR); return ret; } int hssl_accept(hssl_t ssl) { int ret = HSSL_ERROR; struct wintls_s* winssl = ssl; bool authn_completed = false; // Input buffer char buffer_in[TLS_SOCKET_BUFFER_SIZE]; SecBuffer secure_buffer_in[2] = { 0 }; init_sec_buffer(&secure_buffer_in[0], SECBUFFER_TOKEN, TLS_SOCKET_BUFFER_SIZE, buffer_in); init_sec_buffer(&secure_buffer_in[1], SECBUFFER_EMPTY, 0, NULL); SecBufferDesc secure_buffer_desc_in = { 0 }; init_sec_buffer_desc(&secure_buffer_desc_in, SECBUFFER_VERSION, 2, secure_buffer_in); // Output buffer SecBuffer secure_buffer_out[3] = { 0 }; init_sec_buffer(&secure_buffer_out[0], SECBUFFER_TOKEN, 0, NULL); init_sec_buffer(&secure_buffer_out[1], SECBUFFER_ALERT, 0, NULL); init_sec_buffer(&secure_buffer_out[2], SECBUFFER_EMPTY, 0, NULL); SecBufferDesc secure_buffer_desc_out = { 0 }; init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 3, secure_buffer_out); unsigned long context_requirements = ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_CONFIDENTIALITY; // We use ASC_REQ_ALLOCATE_MEMORY which means the buffers will be allocated for us, we need to make sure we free them. ULONG context_attributes = 0; TimeStamp life_time = { 0 }; secure_buffer_in[0].cbBuffer = __recvwrapper(winssl->fd, (char*)secure_buffer_in[0].pvBuffer, TLS_SOCKET_BUFFER_SIZE, 0); // printd("%s recv %d %d\n", __func__, secure_buffer_in[0].cbBuffer, WSAGetLastError()); if (secure_buffer_in[0].cbBuffer == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) { ret = HSSL_WANT_READ; } else if (secure_buffer_in[0].cbBuffer > 0) { SECURITY_STATUS sec_status = AcceptSecurityContext(winssl->ssl_ctx, winssl->state2 == 0 ? NULL : &winssl->sechandle, &secure_buffer_desc_in, context_requirements, 0, &winssl->sechandle, &secure_buffer_desc_out, &context_attributes, &life_time); winssl->state2 = 1; // printd("establish_server_security_context AcceptSecurityContext %x\n", sec_status); if (secure_buffer_out[0].cbBuffer > 0) { int rc = __sendwrapper(winssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); if (rc != secure_buffer_out[0].cbBuffer) { goto END; } } switch (sec_status) { case SEC_E_OK: ret = HSSL_OK; authn_completed = true; break; case SEC_I_CONTINUE_NEEDED: ret = HSSL_WANT_READ; break; case SEC_I_COMPLETE_AND_CONTINUE: case SEC_I_COMPLETE_NEEDED: { SECURITY_STATUS complete_sec_status = SEC_E_OK; complete_sec_status = CompleteAuthToken(&winssl->sechandle, &secure_buffer_desc_out); if (complete_sec_status != SEC_E_OK) { printe("establish_server_security_context CompleteAuthToken %x\n", complete_sec_status); goto END; } if (sec_status == SEC_I_COMPLETE_NEEDED) { authn_completed = true; ret = HSSL_OK; } else { ret = HSSL_WANT_READ; } break; } default: break; } } END: free_all_buffers(&secure_buffer_desc_out); if (authn_completed) { SECURITY_STATUS sec_status = QueryContextAttributes(&winssl->sechandle, SECPKG_ATTR_STREAM_SIZES, &winssl->stream_sizes_); if (sec_status != SEC_E_OK) { printe("get_stream_sizes QueryContextAttributes %d\n", sec_status); } } return ret; } static int schannel_connect_step1(struct wintls_s* ssl) { int ret = 0; ULONG context_attributes = 0; unsigned long context_requirements = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; TimeStamp life_time = { 0 }; SecBuffer secure_buffer_out[1] = { 0 }; init_sec_buffer(&secure_buffer_out[0], SECBUFFER_EMPTY, 0, NULL); SecBufferDesc secure_buffer_desc_out = { 0 }; init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 1, secure_buffer_out); SECURITY_STATUS sec_status = InitializeSecurityContext(ssl->ssl_ctx, NULL, ssl->sni, context_requirements, 0, 0, NULL, 0, &ssl->sechandle, &secure_buffer_desc_out, &context_attributes, &life_time); if (sec_status != SEC_I_CONTINUE_NEEDED) { printe("1InitializeSecurityContext: %x\n", sec_status); } if (secure_buffer_out[0].cbBuffer > 0) { int rc = __sendwrapper(ssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); if (rc != secure_buffer_out[0].cbBuffer) { // TODO: Handle the error printe("%s :send failed\n", __func__); ret = -1; } else { printd("%s :send len=%d\n", __func__, rc); ssl->connecting_state = ssl_connect_2; } } free_all_buffers(&secure_buffer_desc_out); return ret; } static int schannel_connect_step2(struct wintls_s* ssl) { int ret = HSSL_ERROR; ULONG context_attributes = 0; bool verify_server_cert = 0; unsigned long context_requirements = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; if (!verify_server_cert) { context_requirements |= ISC_REQ_MANUAL_CRED_VALIDATION; } TimeStamp life_time = { 0 }; // Allocate a temporary buffer for input char* buffer_in = malloc(TLS_SOCKET_BUFFER_SIZE); if (buffer_in == NULL) { printe("schannel_connect_step2: Memory allocation failed\n"); return HSSL_ERROR; } int offset = 0; bool skip_recv = false; bool authn_complete = false; while (!authn_complete) { int in_buffer_size = 0; if (!skip_recv) { int received = __recvwrapper(ssl->fd, buffer_in + offset, TLS_SOCKET_BUFFER_SIZE, 0); if (received == SOCKET_ERROR) { if (WSAGetLastError() == WSAEWOULDBLOCK) { ret = HSSL_WANT_READ; } else { printe("schannel_connect_step2: Receive failed\n"); } break; } else if (received == 0) { printe("schannel_connect_step2: peer closed\n"); break; } in_buffer_size = received + offset; } else { in_buffer_size = offset; } skip_recv = false; offset = 0; // Input buffer SecBuffer secure_buffer_in[4] = { 0 }; init_sec_buffer(&secure_buffer_in[0], SECBUFFER_TOKEN, in_buffer_size, buffer_in); init_sec_buffer(&secure_buffer_in[1], SECBUFFER_EMPTY, 0, NULL); SecBufferDesc secure_buffer_desc_in = { 0 }; init_sec_buffer_desc(&secure_buffer_desc_in, SECBUFFER_VERSION, 2, secure_buffer_in); // Output buffer SecBuffer secure_buffer_out[3] = { 0 }; init_sec_buffer(&secure_buffer_out[0], SECBUFFER_TOKEN, 0, NULL); init_sec_buffer(&secure_buffer_out[1], SECBUFFER_ALERT, 0, NULL); init_sec_buffer(&secure_buffer_out[2], SECBUFFER_EMPTY, 0, NULL); SecBufferDesc secure_buffer_desc_out = { 0 }; init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 3, secure_buffer_out); printd("h2:%d\n", in_buffer_size); SECURITY_STATUS sec_status = InitializeSecurityContext(ssl->ssl_ctx, &ssl->sechandle, ssl->sni, context_requirements, 0, 0, &secure_buffer_desc_in, 0, &ssl->sechandle, &secure_buffer_desc_out, &context_attributes, &life_time); printd("h2 0x%x inbuf[1] type=%d %d inbuf[0]=%d\n", sec_status, secure_buffer_in[1].BufferType, secure_buffer_in[1].cbBuffer, secure_buffer_in[0].cbBuffer); if (sec_status == SEC_E_OK || sec_status == SEC_I_CONTINUE_NEEDED) { // for (size_t i = 0; i < 3; i++) { // printd("obuf[%zu] type=%d %d\n", i, secure_buffer_out[i].BufferType, secure_buffer_out[i].cbBuffer); // } if (secure_buffer_out[0].cbBuffer > 0) { int rc = __sendwrapper(ssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); if (rc != secure_buffer_out[0].cbBuffer) { printe("schannel_connect_step2: Send failed\n"); // TODO: Handle the error break; } // printd("%s :send ok\n", __func__); } if (sec_status == SEC_I_CONTINUE_NEEDED) { if (secure_buffer_in[1].BufferType == SECBUFFER_EXTRA && secure_buffer_in[1].cbBuffer > 0) { offset = secure_buffer_in[0].cbBuffer - secure_buffer_in[1].cbBuffer; memmove(buffer_in, buffer_in + offset, secure_buffer_in[1].cbBuffer); offset = secure_buffer_in[1].cbBuffer; skip_recv = true; } } else if (sec_status == SEC_E_OK) { authn_complete = true; ret = HSSL_OK; ssl->connecting_state = ssl_connect_3; } } else if (sec_status == SEC_E_INCOMPLETE_MESSAGE) { offset = secure_buffer_in[0].cbBuffer; } else { printe("2InitializeSecurityContext: 0x%x\n", sec_status); break; } free_all_buffers(&secure_buffer_desc_out); } // END: free(buffer_in); // Free the temporary buffer return ret; } static void dumpconninfo(SecHandle* sechandle) { SECURITY_STATUS Status; SecPkgContext_ConnectionInfo ConnectionInfo; Status = QueryContextAttributes(sechandle, SECPKG_ATTR_CONNECTION_INFO, (PVOID)&ConnectionInfo); if (Status != SEC_E_OK) { printe("Error 0x%x querying connection info\n", Status); return; } printd("\n"); switch (ConnectionInfo.dwProtocol) { case SP_PROT_TLS1_CLIENT: printd("Protocol: TLS1\n"); break; case SP_PROT_SSL3_CLIENT: printd("Protocol: SSL3\n"); break; case SP_PROT_SSL2_CLIENT: printd("Protocol: SSL2\n"); break; case SP_PROT_PCT1_CLIENT: printd("Protocol: PCT\n"); break; default: printd("Protocol: 0x%x\n", ConnectionInfo.dwProtocol); } switch (ConnectionInfo.aiCipher) { case CALG_RC4: printd("Cipher: RC4\n"); break; case CALG_3DES: printd("Cipher: Triple DES\n"); break; case CALG_RC2: printd("Cipher: RC2\n"); break; case CALG_DES: case CALG_CYLINK_MEK: printd("Cipher: DES\n"); break; case CALG_SKIPJACK: printd("Cipher: Skipjack\n"); break; case CALG_AES_128: printd("Cipher: aes128\n"); break; default: printd("Cipher: 0x%x\n", ConnectionInfo.aiCipher); } printd("Cipher strength: %d\n", ConnectionInfo.dwCipherStrength); switch (ConnectionInfo.aiHash) { case CALG_MD5: printd("Hash: MD5\n"); break; case CALG_SHA: printd("Hash: SHA\n"); break; default: printd("Hash: 0x%x\n", ConnectionInfo.aiHash); } printd("Hash strength: %d\n", ConnectionInfo.dwHashStrength); switch (ConnectionInfo.aiExch) { case CALG_RSA_KEYX: case CALG_RSA_SIGN: printd("Key exchange: RSA\n"); break; case CALG_KEA_KEYX: printd("Key exchange: KEA\n"); break; case CALG_DH_EPHEM: printd("Key exchange: DH Ephemeral\n"); break; default: printd("Key exchange: 0x%x\n", ConnectionInfo.aiExch); } printd("Key exchange strength: %d\n", ConnectionInfo.dwExchStrength); } int hssl_connect(hssl_t _ssl) { int ret = 0; struct wintls_s* ssl = _ssl; if (ssl->connecting_state == ssl_connect_1) { ret = schannel_connect_step1(ssl); } if (!ret && ssl->connecting_state == ssl_connect_2) { ret = schannel_connect_step2(ssl); } // printd("%s %x\n", __func__, ret); if (!ret) { if (ssl->connecting_state == ssl_connect_3) { // ret = schannel_connect_step3(ssl); } SECURITY_STATUS sec_status = QueryContextAttributes(&ssl->sechandle, SECPKG_ATTR_STREAM_SIZES, &ssl->stream_sizes_); if (sec_status != SEC_E_OK) { printe("get_stream_sizes QueryContextAttributes %d\n", sec_status); } else { printd("stream_sizes bs:%d h:%d t:%d max:%d bfs:%d\n", ssl->stream_sizes_.cbBlockSize, ssl->stream_sizes_.cbHeader, ssl->stream_sizes_.cbTrailer, ssl->stream_sizes_.cbMaximumMessage, ssl->stream_sizes_.cBuffers); } dumpconninfo(&ssl->sechandle); } return ret; } static int decrypt_message(SecHandle security_context, unsigned long* extra, char* in_buf, int in_len, char* out_buf, int out_len) { printd("%s: inlen=%d\n", __func__, in_len); // Initialize the secure buffers SecBuffer secure_buffers[4] = { 0 }; init_sec_buffer(&secure_buffers[0], SECBUFFER_DATA, in_len, in_buf); init_sec_buffer(&secure_buffers[1], SECBUFFER_EMPTY, 0, NULL); init_sec_buffer(&secure_buffers[2], SECBUFFER_EMPTY, 0, NULL); init_sec_buffer(&secure_buffers[3], SECBUFFER_EMPTY, 0, NULL); // Initialize the secure buffer descriptor SecBufferDesc secure_buffer_desc = { 0 }; init_sec_buffer_desc(&secure_buffer_desc, SECBUFFER_VERSION, 4, secure_buffers); // Decrypt the message using the security context SECURITY_STATUS sec_status = DecryptMessage(&security_context, &secure_buffer_desc, 0, NULL); for (size_t i = 1; i < 4; i++) { printd("%d: %u %u\n", i, secure_buffers[i].BufferType, secure_buffers[i].cbBuffer); } if (sec_status == SEC_E_INCOMPLETE_MESSAGE) { printe("decrypt_message SEC_E_INCOMPLETE_MESSAGE\n"); return -1; } else if (sec_status == SEC_E_DECRYPT_FAILURE) { printe("decrypt_message ignore SEC_E_DECRYPT_FAILURE\n"); return 0; } else if (sec_status == SEC_E_UNSUPPORTED_FUNCTION) { printe("decrypt_message ignore SEC_E_UNSUPPORTED_FUNCTION\n"); return 0; } if (sec_status != SEC_E_OK) { printe("decrypt_message DecryptMessage: 0x%x\n", sec_status); return -1; } if (secure_buffers[3].BufferType == SECBUFFER_EXTRA && secure_buffers[3].cbBuffer > 0) { *extra = secure_buffers[3].cbBuffer; } memcpy(out_buf, secure_buffers[1].pvBuffer, secure_buffers[1].cbBuffer); // printd("ob:%s\n", out_buf); return secure_buffers[1].cbBuffer; } int hssl_read(hssl_t _ssl, void* buf, int len) { struct wintls_s* ssl = _ssl; printd("%s: dec_len_= %zu\n", __func__, ssl->dec_len_); if (ssl->dec_len_ > 0) { if (buf == NULL) { return 0; } int decrypted = MIN(ssl->dec_len_, len); memcpy(buf, ssl->decrypted_buffer_, (size_t)decrypted); ssl->dec_len_ -= decrypted; if (ssl->dec_len_) { memmove(ssl->decrypted_buffer_, ssl->decrypted_buffer_ + decrypted, (size_t)ssl->dec_len_); } else { // hssl_read(_ssl, NULL, 0); } return decrypted; } // We might have leftovers, an incomplete message from a previous call. // Calculate the available buffer length for tcp recv. int recv_max_len = TLS_SOCKET_BUFFER_SIZE - ssl->buffer_to_decrypt_offset_; int bytes_received = __recvwrapper(ssl->fd, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, recv_max_len, 0); // printd("%s recv %d %d\n", __func__, bytes_received, WSAGetLastError()); if (bytes_received == SOCKET_ERROR) { if (WSAGetLastError() == WSAEWOULDBLOCK) { bytes_received = 0; return 0; } else { return -1; } } else if (bytes_received == 0) { return 0; } int encrypted_buffer_len = ssl->buffer_to_decrypt_offset_ + bytes_received; ssl->buffer_to_decrypt_offset_ = 0; while (true) { // printd("%s:buffer_to_decrypt_offset_ = %d , encrypted_buffer_len= %d\n", __func__, ssl->buffer_to_decrypt_offset_, encrypted_buffer_len); if (ssl->buffer_to_decrypt_offset_ >= encrypted_buffer_len) { // Reached the encrypted buffer length, we decrypted everything so we can stop. break; } unsigned long extra = 0; int decrypted_len = decrypt_message(ssl->sechandle, &extra, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, encrypted_buffer_len - ssl->buffer_to_decrypt_offset_, ssl->decrypted_buffer_ + ssl->dec_len_, TLS_SOCKET_BUFFER_SIZE + TLS_SOCKET_BUFFER_SIZE - ssl->dec_len_); if (decrypted_len == -1) { // Incomplete message, we shuold keep it so it will be decrypted on the next call to recv(). // Shift the remaining buffer to the beginning and break the loop. memmove(ssl->buffer_to_decrypt_, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, encrypted_buffer_len - ssl->buffer_to_decrypt_offset_); break; } ssl->dec_len_ += decrypted_len; ssl->buffer_to_decrypt_offset_ = encrypted_buffer_len - extra; } ssl->buffer_to_decrypt_offset_ = encrypted_buffer_len - ssl->buffer_to_decrypt_offset_; return hssl_read(_ssl, buf, len); } int hssl_write(hssl_t _ssl, const void* buf, int len) { struct wintls_s* ssl = _ssl; SecPkgContext_StreamSizes* stream_sizes = &ssl->stream_sizes_; if (len > (int)stream_sizes->cbMaximumMessage) { len = stream_sizes->cbMaximumMessage; } // Calculate the minimum output buffer length int min_out_len = stream_sizes->cbHeader + len + stream_sizes->cbTrailer; if (min_out_len > TLS_SOCKET_BUFFER_SIZE) { printe("encrypt_message: Output buffer is too small"); return -1; } // Initialize the secure buffers SecBuffer secure_buffers[4] = { 0 }; init_sec_buffer(&secure_buffers[0], SECBUFFER_STREAM_HEADER, stream_sizes->cbHeader, ssl->encrypted_buffer_); init_sec_buffer(&secure_buffers[1], SECBUFFER_DATA, len, ssl->encrypted_buffer_ + stream_sizes->cbHeader); init_sec_buffer(&secure_buffers[2], SECBUFFER_STREAM_TRAILER, stream_sizes->cbTrailer, ssl->encrypted_buffer_ + stream_sizes->cbHeader + len); init_sec_buffer(&secure_buffers[3], SECBUFFER_EMPTY, 0, NULL); // Initialize the secure buffer descriptor SecBufferDesc secure_buffer_desc = { 0 }; init_sec_buffer_desc(&secure_buffer_desc, SECBUFFER_VERSION, 4, secure_buffers); // Copy the input buffer to the data buffer memcpy(secure_buffers[1].pvBuffer, buf, len); // Encrypt the message using the security context SECURITY_STATUS sec_status = EncryptMessage(&ssl->sechandle, 0, &secure_buffer_desc, 0); // Check the encryption status and the data buffer length if (sec_status != SEC_E_OK) { printe("encrypt_message EncryptMessage %d\n", sec_status); return -1; } if (secure_buffers[1].cbBuffer > (unsigned int)len) { printe("encrypt_message: Data buffer is too large\n"); return -1; } // Adjust the minimum output buffer length min_out_len = secure_buffers[0].cbBuffer + secure_buffers[1].cbBuffer + secure_buffers[2].cbBuffer; printd("enc02: %d %d\n", secure_buffers[0].cbBuffer, secure_buffers[2].cbBuffer); // Send the encrypted message to the socket int offset = __sendwrapper(ssl->fd, ssl->encrypted_buffer_, min_out_len, 0); // Check the send result if (offset != min_out_len) { printe("hssl_write: Send failed\n"); return -1; } else { printd("hssl_write: Send %d\n", min_out_len); } // Return the number of bytes sent excluding the header and trailer return offset - secure_buffers[0].cbBuffer - secure_buffers[2].cbBuffer; } int hssl_close(hssl_t _ssl) { return 0; } int hssl_set_sni_hostname(hssl_t _ssl, const char* hostname) { struct wintls_s* ssl = _ssl; ssl->sni = strdup(hostname); return 0; } #endif // WITH_WINTLS kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/000077500000000000000000000000001520575453600253245ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/CMakeLists.txt000066400000000000000000000076111520575453600300710ustar00rootroot00000000000000add_definitions(-DHV_SOURCE=1) # ------base------ add_executable(hbase_test hbase_test.c ../base/hbase.c) target_include_directories(hbase_test PRIVATE .. ../base) add_executable(mkdir_p mkdir_test.c ../base/hbase.c) target_include_directories(mkdir_p PRIVATE .. ../base) add_executable(rmdir_p rmdir_test.c ../base/hbase.c) target_include_directories(rmdir_p PRIVATE .. ../base) add_executable(date date_test.c ../base/htime.c) target_include_directories(date PRIVATE .. ../base) add_executable(hatomic_test hatomic_test.c) target_include_directories(hatomic_test PRIVATE .. ../base) target_link_libraries(hatomic_test -lpthread) add_executable(hthread_test hthread_test.cpp) target_include_directories(hthread_test PRIVATE .. ../base) target_link_libraries(hthread_test -lpthread) add_executable(hmutex_test hmutex_test.c ../base/htime.c) target_include_directories(hmutex_test PRIVATE .. ../base) target_link_libraries(hmutex_test -lpthread) add_executable(connect_test connect_test.c ../base/hsocket.c ../base/htime.c) target_include_directories(connect_test PRIVATE .. ../base) add_executable(socketpair_test socketpair_test.c ../base/hsocket.c) target_include_directories(socketpair_test PRIVATE .. ../base) # ------util------ add_executable(base64 base64_test.c ../util/base64.c) target_include_directories(base64 PRIVATE .. ../util) add_executable(md5 md5_test.c ../util/md5.c) target_include_directories(md5 PRIVATE .. ../util) add_executable(sha1 sha1_test.c ../util/sha1.c) target_include_directories(sha1 PRIVATE .. ../util) # ------cpputil------ add_executable(hstring_test hstring_test.cpp ../cpputil/hstring.cpp) target_include_directories(hstring_test PRIVATE .. ../base ../cpputil) add_executable(hpath_test hpath_test.cpp ../cpputil/hpath.cpp) target_include_directories(hpath_test PRIVATE .. ../base ../cpputil) add_executable(hurl_test hurl_test.cpp ../cpputil/hurl.cpp ../base/hbase.c) target_include_directories(hurl_test PRIVATE .. ../base ../cpputil) add_executable(ls listdir_test.cpp ../cpputil/hdir.cpp) target_include_directories(ls PRIVATE .. ../base ../cpputil) add_executable(ifconfig ifconfig_test.cpp ../cpputil/ifconfig.cpp) target_include_directories(ifconfig PRIVATE .. ../base ../cpputil) add_executable(defer_test defer_test.cpp) target_include_directories(defer_test PRIVATE .. ../base ../cpputil) add_executable(synchronized_test synchronized_test.cpp) target_include_directories(synchronized_test PRIVATE .. ../base ../cpputil) target_link_libraries(synchronized_test -lpthread) add_executable(threadpool_test threadpool_test.cpp) target_include_directories(threadpool_test PRIVATE .. ../base ../cpputil) target_link_libraries(threadpool_test -lpthread) add_executable(objectpool_test objectpool_test.cpp) target_include_directories(objectpool_test PRIVATE .. ../base ../cpputil) target_link_libraries(objectpool_test -lpthread) # ------protocol------ add_executable(nslookup nslookup_test.c ../protocol/dns.c) target_include_directories(nslookup PRIVATE .. ../base ../protocol) add_executable(ping ping_test.c ../protocol/icmp.c ../base/hsocket.c ../base/htime.c) target_compile_definitions(ping PRIVATE -DPRINT_DEBUG) target_include_directories(ping PRIVATE .. ../base ../protocol) add_executable(ftp ftp_test.c ../protocol/ftp.c ../base/hsocket.c) target_include_directories(ftp PRIVATE .. ../base ../protocol) add_executable(sendmail sendmail_test.c ../protocol/smtp.c ../base/hsocket.c ../util/base64.c) target_include_directories(sendmail PRIVATE .. ../base ../protocol ../util) if(UNIX) add_executable(webbench webbench.c) endif() add_custom_target(unittest DEPENDS mkdir_p rmdir_p date hatomic_test hthread_test hmutex_test connect_test socketpair_test base64 md5 sha1 hstring_test hpath_test hurl_test ls ifconfig defer_test synchronized_test threadpool_test objectpool_test nslookup ping ftp sendmail ) kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/base64_test.c000066400000000000000000000072051520575453600276170ustar00rootroot00000000000000/* * @build: gcc -o bin/base64 unittest/base64_test.c util/base64.c -I. -Iutil * */ #include #include #include #include #include "base64.h" static void test() { unsigned char in[] = "0123456789"; // test encode int encoded_size = BASE64_ENCODE_OUT_SIZE(10); char* encoded = (char*)malloc(encoded_size + 1); encoded_size = hv_base64_encode(in, 10, encoded); encoded[encoded_size] = '\0'; assert(strcmp(encoded, "MDEyMzQ1Njc4OQ==") == 0); // test decode int decoded_size = BASE64_DECODE_OUT_SIZE(encoded_size); unsigned char* decoded = (unsigned char*)malloc(decoded_size); decoded_size = hv_base64_decode(encoded, encoded_size, decoded); assert(decoded_size == 10 && memcmp(in, decoded, decoded_size) == 0); free(encoded); free(decoded); } int main(int argc, char* argv[]) { test(); if (argc < 3) { printf("Usage: base64 infile outfile\n"); printf(" base64 -d infile outfile\n"); return -10; } else if (argc == 3) { // encode file const char* infile = argv[1]; const char* outfile = argv[2]; FILE* infp = fopen(infile, "rb"); if (infp == NULL) { printf("Open file '%s' failed!\n", infile); return -20; } fseek(infp, 0, SEEK_END); long filesize = ftell(infp); // printf("filesize=%ld\n", filesize); fseek(infp, 0, SEEK_SET); unsigned char* filebuf = (unsigned char*)malloc(filesize); size_t nread = fread(filebuf, 1, filesize, infp); assert(nread == filesize); int encoded_size = BASE64_ENCODE_OUT_SIZE(filesize); char* encoded = (char*)malloc(encoded_size + 1); encoded_size = hv_base64_encode(filebuf, filesize, encoded); encoded[encoded_size] = '\0'; FILE* outfp = fopen(outfile, "w"); if (outfp == NULL) { printf("Save file '%s' failed!\n", infile); return -20; } size_t nwrite = fwrite(encoded, 1, encoded_size, outfp); assert(nwrite == encoded_size); free(filebuf); free(encoded); fclose(infp); fclose(outfp); } else if (argc == 4) { const char* flags = argv[1]; if (flags[0] == '-' && flags[1] == 'd') { // decode file const char* infile = argv[2]; const char* outfile = argv[3]; FILE* infp = fopen(infile, "r"); if (infp == NULL) { printf("Open file '%s' failed!\n", infile); return -20; } fseek(infp, 0, SEEK_END); long filesize = ftell(infp); // printf("filesize=%ld\n", filesize); fseek(infp, 0, SEEK_SET); char* filebuf = (char*)malloc(filesize); size_t nread = fread(filebuf, 1, filesize, infp); assert(nread == filesize); int decoded_size = BASE64_DECODE_OUT_SIZE(filesize); unsigned char* decoded = (unsigned char*)malloc(decoded_size); decoded_size = hv_base64_decode(filebuf, filesize, decoded); FILE* outfp = fopen(outfile, "wb"); if (outfp == NULL) { printf("Save file '%s' failed!\n", infile); return -20; } size_t nwrite = fwrite(decoded, 1, decoded_size, outfp); assert(nwrite == decoded_size); free(filebuf); free(decoded); fclose(infp); fclose(outfp); } else { printf("Unrecognized flags '%s'\n", flags); return -40; } } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/connect_test.c000066400000000000000000000015201520575453600301560ustar00rootroot00000000000000#include "hsocket.h" #include "htime.h" int main(int argc, char* argv[]) { if (argc < 3) { printf("Usage: cmd ip port\n"); return -10; } const char* ip = argv[1]; int port = atoi(argv[2]); unsigned int start_time = gettick_ms(); int ret = ConnectNonblock(ip, port); unsigned int end_time = gettick_ms(); printf("ConnectNonblock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); start_time = gettick_ms(); ret = ConnectTimeout(ip, port, 3000); end_time = gettick_ms(); printf("ConnectTimeout[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); start_time = gettick_ms(); ret = Connect(ip, port, 0); end_time = gettick_ms(); printf("ConnectBlock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/date_test.c000066400000000000000000000005411520575453600274440ustar00rootroot00000000000000#include "htime.h" int main(int argc, char* argv[]) { datetime_t dt = datetime_now(); char buf1[DATETIME_FMT_BUFLEN]; datetime_fmt(&dt, buf1); puts(buf1); datetime_fmt_iso(&dt, buf1); puts(buf1); time_t ts = datetime_mktime(&dt); char buf2[GMTIME_FMT_BUFLEN]; gmtime_fmt(ts, buf2); puts(buf2); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/defer_test.cpp000066400000000000000000000003471520575453600301600ustar00rootroot00000000000000#include #include "hscope.h" int main() { defer ( printf("1\n"); printf("2\n"); ) defer ( printf("3\n"); printf("4\n"); ) defer(printf("hello\n");) return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/ftp_test.c000066400000000000000000000050111520575453600273150ustar00rootroot00000000000000#include #include #include #include "ftp.h" void print_help() { printf("Usage:\n\ help\n\ login \n\ download \n\ upload \n\ quit\n"); } int main(int argc, char** argv) { if (argc < 2) { printf("Usage: ftp host [port]\n"); return 0; } const char* host = argv[1]; int port = FTP_COMMAND_PORT; if (argc >= 3) { port = atoi(argv[2]); } int ret = 0; ftp_handle_t hftp; ret = ftp_connect(&hftp, host, port); if (ret != 0) { printf("ftp connect failed!\n"); return ret; } print_help(); char cmd[256] = {0}; char param1[256] = {0}; char param2[256] = {0}; while (1) { printf("> "); scanf("%s", cmd); if (strncmp(cmd, "help", 4) == 0) { print_help(); } else if (strncmp(cmd, "login", 5) == 0) { scanf("%s", param1); scanf("%s", param2); //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); const char* username = param1; const char* password = param2; ret = ftp_login(&hftp, username, password); printf("%s", hftp.recvbuf); if (ret != 0) break; } else if (strncmp(cmd, "upload", 6) == 0) { scanf("%s", param1); scanf("%s", param2); //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); const char* localfile = param1; const char* remotefile = param2; ret = ftp_upload(&hftp, localfile, remotefile); printf("%s", hftp.recvbuf); if (ret != 0) break; } else if (strncmp(cmd, "download", 8) == 0) { scanf("%s", param1); scanf("%s", param2); //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); const char* remotefile = param1; const char* localfile = param2; ret = ftp_download(&hftp, remotefile, localfile); printf("%s", hftp.recvbuf); if (ret != 0) break; } else if (strncmp(cmd, "quit", 4) == 0) { break; } else { scanf("%s", param1); //printf("cmd=%s param=%s\n", cmd, param1); ret = ftp_exec(&hftp, cmd, param1); printf("%s", hftp.recvbuf); } } printf("QUIT\n"); ftp_quit(&hftp); printf("%s", hftp.recvbuf); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hatomic_test.c000066400000000000000000000014271520575453600301570ustar00rootroot00000000000000#include #include "hatomic.h" #include "hthread.h" hatomic_flag_t flag = HATOMIC_FLAG_INIT; hatomic_t cnt = HATOMIC_VAR_INIT(0); HTHREAD_ROUTINE(test_hatomic_flag) { if (!hatomic_flag_test_and_set(&flag)) { printf("tid=%ld flag 0=>1\n", hv_gettid()); } else { printf("tid=%ld flag=1\n", hv_gettid()); } return 0; } HTHREAD_ROUTINE(test_hatomic) { for (int i = 0; i < 10; ++i) { long n = hatomic_inc(&cnt); printf("tid=%ld cnt=%ld\n", hv_gettid(), n); hv_delay(1); } return 0; } int main() { for (int i = 0; i < 10; ++i) { hthread_create(test_hatomic_flag, NULL); } for (int i = 0; i < 10; ++i) { hthread_create(test_hatomic, NULL); } hv_delay(1000); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hatomic_test.cpp000066400000000000000000000014271520575453600305170ustar00rootroot00000000000000#include #include "hatomic.h" #include "hthread.h" hatomic_flag_t flag = HATOMIC_FLAG_INIT; hatomic_t cnt = HATOMIC_VAR_INIT(0); HTHREAD_ROUTINE(test_hatomic_flag) { if (!hatomic_flag_test_and_set(&flag)) { printf("tid=%ld flag 0=>1\n", hv_gettid()); } else { printf("tid=%ld flag=1\n", hv_gettid()); } return 0; } HTHREAD_ROUTINE(test_hatomic) { for (int i = 0; i < 10; ++i) { long n = hatomic_inc(&cnt); printf("tid=%ld cnt=%ld\n", hv_gettid(), n); hv_delay(1); } return 0; } int main() { for (int i = 0; i < 10; ++i) { hthread_create(test_hatomic_flag, NULL); } for (int i = 0; i < 10; ++i) { hthread_create(test_hatomic, NULL); } hv_delay(1000); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hbase_test.c000066400000000000000000000105221520575453600276110ustar00rootroot00000000000000#include "hbase.h" int main(int argc, char* argv[]) { char buf[16] = {0}; printf("hv_rand(10, 99) -> %d\n", hv_rand(10, 99)); printf("hv_random_string(buf, 10) -> %s\n", hv_random_string(buf, 10)); assert(hv_getboolean("1")); assert(hv_getboolean("yes")); assert(hv_wildcard_match("www.example.com", "www.example.com")); assert(hv_wildcard_match("www.example.com", "*.example.com")); assert(hv_wildcard_match("www.example.com", "www.*.com")); assert(hv_wildcard_match("www.example.com", "www.example.*")); assert(hv_parse_size("256") == 256); assert(hv_parse_size("1K") == 1024); assert(hv_parse_size("1G2M3K4B") == 1 * 1024 * 1024 * 1024 + 2 * 1024 * 1024 + 3 * 1024 + 4); assert(hv_parse_time("30") == 30); assert(hv_parse_time("1m") == 60); assert(hv_parse_time("1d2h3m4s") == 1 * 24 * 60 * 60 + 2 * 60 * 60 + 3 * 60 + 4); const char* test_urls[] = { "http://user:pswd@[www.example.com]:80/path?query#fragment", "http://user:pswd@www.example.com:80/path?query#fragment", "http://user:pswd@www.example.com/path?query#fragment", "http://www.example.com/path?query#fragment", "http://www.example.com/path?query", "http://www.example.com/path", "www.example.com/path", "/path", }; hurl_t stURL; for (int i = 0; i < ARRAY_SIZE(test_urls); ++i) { const char* strURL = test_urls[i]; printf("%s =>\n", strURL); hv_parse_url(&stURL, strURL); assert(stURL.port == 80); // scheme:// if (stURL.fields[HV_URL_SCHEME].len > 0) { const char* scheme = strURL + stURL.fields[HV_URL_SCHEME].off; int len = stURL.fields[HV_URL_SCHEME].len; assert(len == 4); assert(strncmp(scheme, "http", len) == 0); printf("%.*s://", len, scheme); } // user:pswd@ if (stURL.fields[HV_URL_USERNAME].len > 0) { const char* user = strURL + stURL.fields[HV_URL_USERNAME].off; int len = stURL.fields[HV_URL_USERNAME].len; assert(len == 4); assert(strncmp(user, "user", len) == 0); printf("%.*s", len, user); if (stURL.fields[HV_URL_PASSWORD].len > 0) { const char* pswd = strURL + stURL.fields[HV_URL_PASSWORD].off; int len = stURL.fields[HV_URL_PASSWORD].len; assert(len == 4); assert(strncmp(pswd, "pswd", len) == 0); printf(":%.*s", len, pswd); } printf("@"); } // host:port if (stURL.fields[HV_URL_HOST].len > 0) { const char* host = strURL + stURL.fields[HV_URL_HOST].off; int len = stURL.fields[HV_URL_HOST].len; assert(len == strlen("www.example.com")); assert(strncmp(host, "www.example.com", len) == 0); printf("%.*s", len, host); if (stURL.fields[HV_URL_PORT].len > 0) { const char* port = strURL + stURL.fields[HV_URL_PORT].off; int len = stURL.fields[HV_URL_PORT].len; assert(len == 2); assert(strncmp(port, "80", len) == 0); printf(":%.*s", len, port); } } // /path if (stURL.fields[HV_URL_PATH].len > 0) { const char* path = strURL + stURL.fields[HV_URL_PATH].off; int len = stURL.fields[HV_URL_PATH].len; assert(len == 5); assert(strncmp(path, "/path", len) == 0); printf("%.*s", len, path); } // ?query if (stURL.fields[HV_URL_QUERY].len > 0) { const char* query = strURL + stURL.fields[HV_URL_QUERY].off; int len = stURL.fields[HV_URL_QUERY].len; assert(len == 5); assert(strncmp(query, "query", len) == 0); printf("?%.*s", len, query); } // #fragment if (stURL.fields[HV_URL_FRAGMENT].len > 0) { const char* fragment = strURL + stURL.fields[HV_URL_FRAGMENT].off; int len = stURL.fields[HV_URL_FRAGMENT].len; assert(len == 8); assert(strncmp(fragment, "fragment", len) == 0); printf("#%.*s", len, fragment); } printf("\n"); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hmutex_test.c000066400000000000000000000070341520575453600300450ustar00rootroot00000000000000#include "hthread.h" #include "hmutex.h" #include "htime.h" void once_print() { printf("exec once\n"); } HTHREAD_ROUTINE(test_once) { honce_t once = HONCE_INIT; for (int i = 0; i < 10; ++i) { honce(&once, once_print); } printf("honce test OK!\n"); return 0; } HTHREAD_ROUTINE(test_mutex) { hmutex_t mutex; hmutex_init(&mutex); hmutex_lock(&mutex); hmutex_unlock(&mutex); hmutex_destroy(&mutex); printf("hmutex test OK!\n"); return 0; } HTHREAD_ROUTINE(test_recursive_mutex) { hrecursive_mutex_t mutex; hrecursive_mutex_init(&mutex); hrecursive_mutex_lock(&mutex); hrecursive_mutex_lock(&mutex); hrecursive_mutex_unlock(&mutex); hrecursive_mutex_unlock(&mutex); hrecursive_mutex_destroy(&mutex); printf("hrecursive_mutex test OK!\n"); return 0; } HTHREAD_ROUTINE(test_spinlock) { hspinlock_t spin; hspinlock_init(&spin); hspinlock_lock(&spin); hspinlock_unlock(&spin); hspinlock_destroy(&spin); printf("hspinlock test OK!\n"); return 0; } HTHREAD_ROUTINE(test_rwlock) { hrwlock_t rwlock; hrwlock_init(&rwlock); hrwlock_rdlock(&rwlock); hrwlock_rdunlock(&rwlock); hrwlock_wrlock(&rwlock); hrwlock_wrunlock(&rwlock); hrwlock_destroy(&rwlock); printf("hrwlock test OK!\n"); return 0; } HTHREAD_ROUTINE(test_timed_mutex) { htimed_mutex_t mutex; htimed_mutex_init(&mutex); htimed_mutex_lock(&mutex); time_t start_time = gettick_ms(); htimed_mutex_lock_for(&mutex, 3000); time_t end_time = gettick_ms(); printf("htimed_mutex_lock_for %zdms\n", end_time - start_time); htimed_mutex_unlock(&mutex); htimed_mutex_destroy(&mutex); printf("htimed_mutex test OK!\n"); return 0; } HTHREAD_ROUTINE(test_condvar) { hmutex_t mutex; hmutex_init(&mutex); hcondvar_t cv; hcondvar_init(&cv); hmutex_lock(&mutex); hcondvar_signal(&cv); hcondvar_broadcast(&cv); time_t start_time = gettick_ms(); hcondvar_wait_for(&cv, &mutex, 3000); time_t end_time = gettick_ms(); printf("hcondvar_wait_for %zdms\n", end_time - start_time); hmutex_unlock(&mutex); hmutex_destroy(&mutex); hcondvar_destroy(&cv); printf("hcondvar test OK!\n"); return 0; } HTHREAD_ROUTINE(test_sem) { hsem_t sem; hsem_init(&sem, 10); for (int i = 0; i < 10; ++i) { hsem_wait(&sem); } hsem_post(&sem); hsem_wait(&sem); time_t start_time = gettick_ms(); hsem_wait_for(&sem, 3000); time_t end_time = gettick_ms(); printf("hsem_wait_for %zdms\n", end_time - start_time); hsem_destroy(&sem); printf("hsem test OK!\n"); return 0; } int main(int argc, char* argv[]) { hthread_t thread_once = hthread_create(test_once, NULL); hthread_t thread_mutex = hthread_create(test_mutex, NULL); hthread_t thread_recursive_mutex = hthread_create(test_recursive_mutex, NULL); hthread_t thread_spinlock = hthread_create(test_spinlock, NULL); hthread_t thread_rwlock = hthread_create(test_rwlock, NULL); hthread_t thread_timed_mutex = hthread_create(test_timed_mutex, NULL); hthread_t thread_condvar = hthread_create(test_condvar, NULL); hthread_t thread_sem = hthread_create(test_sem, NULL); hthread_join(thread_once); hthread_join(thread_mutex); hthread_join(thread_recursive_mutex); hthread_join(thread_spinlock); hthread_join(thread_rwlock); hthread_join(thread_timed_mutex); hthread_join(thread_condvar); hthread_join(thread_sem); printf("hthread test OK!\n"); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hpath_test.cpp000066400000000000000000000011401520575453600301670ustar00rootroot00000000000000#include "hpath.h" int main(int argc, char** argv) { std::string filepath = HPath::join("/mnt/share/image", "test.jpg"); std::string basename = HPath::basename(filepath); std::string dirname = HPath::dirname(filepath); std::string filename = HPath::filename(filepath); std::string suffixname = HPath::suffixname(filepath); printf("filepath = %s\n", filepath.c_str()); printf("basename = %s\n", basename.c_str()); printf("dirname = %s\n", dirname.c_str()); printf("filename = %s\n", filename.c_str()); printf("suffixname = %s\n", suffixname.c_str()); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hstring_test.cpp000066400000000000000000000026371520575453600305550ustar00rootroot00000000000000#include "hstring.h" using namespace hv; int main(int argc, char** argv) { std::string str1 = "a1B2*C3d4=="; std::string str2 = "a1B2*C3d4=="; println("toupper=" + toupper(str1)); println("tolower=" + tolower(str2)); std::string str3 = "abcdefg"; println("reverse=" + reverse(str3)); std::string str4 = "123456789"; printf("startswith=%d\nendswith=%d\ncontains=%d\n", (int)startswith(str4, "123"), (int)endswith(str4, "789"), (int)contains(str4, "456")); std::string str5 = asprintf("%s%d", "hello", 5); println("asprintf=" + str5); std::string str6("123,456,789"); StringList strlist = split(str6, ','); println("split " + str6); for (auto& str : strlist) { println(str); } std::string str7("user=admin&pswd=123456"); hv::KeyValue kv = splitKV(str7, '&', '='); for (auto& pair : kv) { printf("%s=%s\n", pair.first.c_str(), pair.second.c_str()); } std::string str8(""); std::string str9 = trim_pairs(str8); println("trim_pairs=" + str9); std::string str10("{{title}}"); std::string str11 = replace(str10, "{{title}}", "Home"); println("replace=" + str11); NetAddr addr1("0.0.0.0:8080"); println(addr1.to_string()); NetAddr addr2("[::0]:8080"); println(addr2.to_string()); NetAddr addr3(":8080"); println(addr3.to_string()); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hthread_test.cpp000066400000000000000000000024041520575453600305060ustar00rootroot00000000000000#include "hthread.h" #include "htime.h" HTHREAD_ROUTINE(test_thread1) { int cnt = 10; while (cnt-- > 0) { printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); hv_msleep(100); } return 0; } class TestThread2 : public HThread { protected: virtual void run() { int cnt = 10; while (cnt-- > 0) { printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); hv_msleep(100); } } }; class TestThread3 : public HThread { protected: virtual bool doPrepare() { printf("doPrepare\n"); return true; } virtual void doTask() { printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); } virtual bool doFinish() { printf("doFinish\n"); return true; } }; int main() { printf("c-style hthread_create\n"); hthread_t thread1 = hthread_create(test_thread1, NULL); hthread_join(thread1); printf("cpp-style override HThread::run\n"); TestThread2 thread2; thread2.start(); thread2.stop(); printf("cpp-style override HThread::doTask\n"); TestThread3 thread3; thread3.setSleepPolicy(HThread::SLEEP_UNTIL, 100); thread3.start(); hv_sleep(1); thread3.stop(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/hurl_test.cpp000066400000000000000000000011731520575453600300430ustar00rootroot00000000000000#include #include "hurl.h" int main(int argc, char** argv) { std::string strURL = "http://www.example.com/path?query#fragment"; HUrl url; if (!url.parse(strURL)) { printf("parse url %s error!\n", strURL.c_str()); return -1; } std::string dumpURL = url.dump(); printf("%s =>\n%s\n", strURL.c_str(), dumpURL.c_str()); assert(strURL == dumpURL); const char* str = "中 文"; std::string escaped = HUrl::escape(str); std::string unescaped = HUrl::unescape(escaped.c_str()); printf("%s => %s\n", str, escaped.c_str()); assert(str == unescaped); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/ifconfig_test.cpp000066400000000000000000000005571520575453600306620ustar00rootroot00000000000000#include #include "ifconfig.h" int main() { std::vector ifcs; ifconfig(ifcs); for (auto& item : ifcs) { printf("%s\nip: %s\nmask: %s\nbroadcast: %s\nmac: %s\n\n", item.name, item.ip, item.mask, item.broadcast, item.mac); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/listdir_test.cpp000066400000000000000000000025411520575453600305430ustar00rootroot00000000000000#include #include "hdir.h" int main(int argc, char* argv[]) { const char* dir = "."; if (argc > 1) { dir = argv[1]; } std::list dirs; listdir(dir, dirs); for (auto& item : dirs) { printf("%c%c%c%c%c%c%c%c%c%c\t", item.type, (item.mode & 0400) ? 'r' : '-', (item.mode & 0200) ? 'w' : '-', (item.mode & 0100) ? 'x' : '-', (item.mode & 0040) ? 'r' : '-', (item.mode & 0020) ? 'w' : '-', (item.mode & 0010) ? 'x' : '-', (item.mode & 0004) ? 'r' : '-', (item.mode & 0002) ? 'w' : '-', (item.mode & 0001) ? 'x' : '-'); float hsize; if (item.size < 1024) { printf("%lu\t", item.size); } else if ((hsize = item.size/1024.0f) < 1024.0f) { printf("%.1fK\t", hsize); } else if ((hsize /= 1024.0f) < 1024.0f) { printf("%.1fM\t", hsize); } else { hsize /= 1024.0f; printf("%.1fG\t", hsize); } struct tm* tm = localtime(&item.mtime); printf("%04d-%02d-%02d %02d:%02d:%02d\t", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); printf("%s%s\n", item.name, item.type == 'd' ? "/" : ""); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/md5_test.c000066400000000000000000000030071520575453600272140ustar00rootroot00000000000000/* * @build: gcc -o bin/md5 unittest/md5_test.c util/md5.c -I. -Iutil * */ #include #include #include #include #include "md5.h" static void test() { unsigned char ch = '1'; char md5[33] = {0}; hv_md5_hex(&ch, 1, md5, sizeof(md5)); assert(strcmp(md5, "c4ca4238a0b923820dcc509a6f75849b") == 0); } int main(int argc, char* argv[]) { test(); if (argc < 2) { printf("Usage: md5 file\n"); printf(" md5 -s string\n"); return -10; } char md5[33] = {0}; if (argc == 2) { const char* filepath = argv[1]; FILE* fp = fopen(filepath, "rb"); if (fp == NULL) { printf("Open file '%s' failed!\n", filepath); return -20; } fseek(fp, 0, SEEK_END); long filesize = ftell(fp); // printf("filesize=%ld\n", filesize); fseek(fp, 0, SEEK_SET); unsigned char* filebuf = (unsigned char*)malloc(filesize); size_t nread = fread(filebuf, 1, filesize, fp); assert(nread == filesize); hv_md5_hex(filebuf, filesize, md5, sizeof(md5)); free(filebuf); fclose(fp); } else if (argc == 3) { const char* flags = argv[1]; if (flags[0] == '-' && flags[1] == 's') { hv_md5_hex((unsigned char*)argv[2], strlen(argv[2]), md5, sizeof(md5)); } else { printf("Unrecognized flags '%s'\n", flags); return -40; } } puts(md5); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/mkdir_test.c000066400000000000000000000003111520575453600276300ustar00rootroot00000000000000#include "hbase.h" int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: mkdir_p dir\n"); return -1; } const char* dir = argv[1]; return hv_mkdir_p(dir); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/nslookup_test.c000066400000000000000000000013421520575453600304010ustar00rootroot00000000000000#include #include "hplatform.h" // inet_ntop #include "dns.h" // nslookup int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: nslookup domain [nameserver]\n"); return -1; } const char* domain = argv[1]; const char* nameserver = "127.0.1.1"; #ifndef OS_LINUX nameserver = "114.114.114.114"; // nameserver = "8.8.8.8"; #endif if (argc > 2) { nameserver = argv[2]; } uint32_t addrs[16]; int naddr = nslookup(domain, addrs, 16, nameserver); if (naddr < 0) { return naddr; } char ip[16]; for (int i = 0; i < naddr; ++i) { inet_ntop(AF_INET, (void*)&addrs[i], ip, 16); printf("%s\n", ip); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/objectpool_test.cpp000066400000000000000000000017331520575453600312330ustar00rootroot00000000000000#include #include #include "hobjectpool.h" #ifdef _WIN32 #include #else #include #endif void msleep(unsigned int ms) { #ifdef _WIN32 Sleep(ms); #else usleep(ms*1000); #endif } class Task { public: Task() {printf("Task()\n");} ~Task() {printf("~Task()\n");} void Do() { printf("%p start do...\n", this); msleep(4000); printf("%p end do\n", this); } }; HObjectPool task_pool(1, 5); void task_thread(int id) { printf("thread %d run...\n", id); HPoolObject pTask(task_pool); if (pTask) { pTask->Do(); } else { printf("No available task in pool\n"); } printf("thread %d exit\n", id); } int main(int argc, char** argv) { for (int i = 0; i < 10; ++i) { new std::thread(task_thread, i); } msleep(5000); for (int i = 10; i < 20; ++i) { new std::thread(task_thread, i); } msleep(10000); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/ping_test.c000066400000000000000000000005301520575453600274620ustar00rootroot00000000000000#include #include "icmp.h" #include "hplatform.h" int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: ping host|ip\n"); return -10; } char* host = argv[1]; int ping_cnt = 4; int ok_cnt = ping(host, ping_cnt); printf("ping %d count, %d ok.\n", ping_cnt, ok_cnt); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/rbtree_test.c000066400000000000000000000055211520575453600300150ustar00rootroot00000000000000#include #include #include "rbtree.h" typedef int rbtree_key_type; typedef int rbtree_val_type; struct rbtree_entry { struct rb_node rb_node; rbtree_key_type key; rbtree_val_type val; }; int rbtree_insert(struct rb_root* root, struct rbtree_entry* entry) { printf("insert %d\n", entry->key); struct rb_node** n = &root->rb_node; struct rb_node* parent = NULL; struct rbtree_entry* e = NULL; while (*n) { parent = *n; e = rb_entry(*n, struct rbtree_entry, rb_node); if (entry->key < e->key) { n = &(*n)->rb_left; } else if (entry->key > e->key) { n = &(*n)->rb_right; } else { return -1; } } rb_link_node(&entry->rb_node, parent, n); rb_insert_color(&entry->rb_node, root); return 0; } int rbtree_remove(struct rb_root* root, struct rbtree_entry* entry) { printf("remove %d\n", entry->key); rb_erase(&entry->rb_node, root); return 0; } struct rbtree_entry* rbtree_search(struct rb_root* root, const rbtree_key_type* key) { struct rb_node* n = root->rb_node; struct rbtree_entry* e = NULL; while (n) { e = rb_entry(n, struct rbtree_entry, rb_node); if (*key < e->key) { n = n->rb_left; } else if (*key > e->key) { n = n->rb_right; } else { return e; } } return NULL; } void rbtree_entry_print(struct rbtree_entry* entry) { if (entry == NULL) { printf("null\n"); return; } printf("%d:%d\n", entry->key, entry->val); } int main() { struct rb_root root = { NULL }; struct rbtree_entry* entry = NULL; struct rbtree_entry entries[10]; for (int i = 0; i < 10; ++i) { memset(&entries[i], 0, sizeof(struct rbtree_entry)); entries[i].key = i; entries[i].val = i; } rbtree_insert(&root, &entries[1]); rbtree_insert(&root, &entries[2]); rbtree_insert(&root, &entries[3]); rbtree_insert(&root, &entries[7]); rbtree_insert(&root, &entries[8]); rbtree_insert(&root, &entries[9]); rbtree_insert(&root, &entries[4]); rbtree_insert(&root, &entries[5]); rbtree_insert(&root, &entries[6]); rbtree_remove(&root, &entries[1]); rbtree_remove(&root, &entries[9]); rbtree_remove(&root, &entries[4]); rbtree_remove(&root, &entries[6]); int key = 5; entry = rbtree_search(&root, &key); rbtree_entry_print(entry); key = 4; entry = rbtree_search(&root, &key); rbtree_entry_print(entry); struct rb_node* node = NULL; // while((node = rb_first(&root))) { while((node = root.rb_node)) { entry = rb_entry(node, struct rbtree_entry, rb_node); rb_erase(node, &root); rbtree_entry_print(entry); memset(entry, 0, sizeof(struct rbtree_entry)); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/rmdir_test.c000066400000000000000000000003111520575453600276370ustar00rootroot00000000000000#include "hbase.h" int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: rmdir_p dir\n"); return -1; } const char* dir = argv[1]; return hv_rmdir_p(dir); } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/sendmail_test.c000066400000000000000000000012331520575453600303220ustar00rootroot00000000000000#include #include "smtp.h" int main(int argc, char** argv) { if (argc < 8) { printf("Usage: sendmail smtp_server username password from to subject body\n"); return -10; } const char* smtp_server = argv[1]; const char* username = argv[2]; const char* password = argv[3]; mail_t mail; mail.from = argv[4]; mail.to = argv[5]; mail.subject = argv[6]; mail.body = argv[7]; int status_code = sendmail(smtp_server, username, password, &mail); printf("sendmail: %d %s\n", status_code, smtp_status_str((enum smtp_status)status_code)); return status_code == SMTP_STATUS_OK ? 0 : status_code; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/sha1_test.c000066400000000000000000000030421520575453600273620ustar00rootroot00000000000000/* * @build: gcc -o bin/sha1 unittest/sha1_test.c util/sha1.c -I. -Iutil * */ #include #include #include #include #include "sha1.h" static void test() { unsigned char ch = '1'; char sha1[41] = {0}; hv_sha1_hex(&ch, 1, sha1, sizeof(sha1)); assert(strcmp(sha1, "356a192b7913b04c54574d18c28d46e6395428ab") == 0); } int main(int argc, char* argv[]) { test(); if (argc < 2) { printf("Usage: sha1 file\n"); printf(" sha1 -s string\n"); return -10; } char sha1[41] = {0}; if (argc == 2) { const char* filepath = argv[1]; FILE* fp = fopen(filepath, "rb"); if (fp == NULL) { printf("Open file '%s' failed!\n", filepath); return -20; } fseek(fp, 0, SEEK_END); long filesize = ftell(fp); // printf("filesize=%ld\n", filesize); fseek(fp, 0, SEEK_SET); unsigned char* filebuf = (unsigned char*)malloc(filesize); size_t nread = fread(filebuf, 1, filesize, fp); assert(nread == filesize); hv_sha1_hex(filebuf, filesize, sha1, sizeof(sha1)); free(filebuf); fclose(fp); } else if (argc == 3) { const char* flags = argv[1]; if (flags[0] == '-' && flags[1] == 's') { hv_sha1_hex((unsigned char*)argv[2], strlen(argv[2]), sha1, sizeof(sha1)); } else { printf("Unrecognized flags '%s'\n", flags); return -40; } } puts(sha1); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/sizeof_test.cpp000066400000000000000000000047431520575453600303760ustar00rootroot00000000000000#include #include "hloop.h" #include "hevent.h" #include "EventLoop.h" #include "EventLoopThread.h" #include "EventLoopThreadPool.h" #include "Channel.h" #include "TcpClient.h" #include "TcpServer.h" #include "UdpClient.h" #include "UdpServer.h" #include "HttpMessage.h" #include "Http1Parser.h" #include "HttpContext.h" #include "HttpServer.h" #include "HttpHandler.h" #include "HttpResponseWriter.h" #include "WebSocketChannel.h" #include "WebSocketParser.h" #include "WebSocketServer.h" #include "WebSocketClient.h" using namespace hv; int main() { // event printf("sizeof(struct hloop_s)=%lu\n", sizeof(struct hloop_s)); printf("sizeof(struct hevent_s)=%lu\n", sizeof(struct hevent_s)); printf("sizeof(struct hidle_s)=%lu\n", sizeof(struct hidle_s)); printf("sizeof(struct htimer_s)=%lu\n", sizeof(struct htimer_s)); printf("sizeof(struct htimeout_s)=%lu\n", sizeof(struct htimeout_s)); printf("sizeof(struct hperiod_s)=%lu\n", sizeof(struct hperiod_s)); printf("sizeof(struct hio_s)=%lu\n", sizeof(struct hio_s)); // evpp printf("sizeof(class EventLoop)=%lu\n", sizeof(EventLoop)); printf("sizeof(class EventLoopThread)=%lu\n", sizeof(EventLoopThread)); printf("sizeof(class EventLoopThreadPool)=%lu\n", sizeof(EventLoopThreadPool)); printf("sizeof(class Channel)=%lu\n", sizeof(Channel)); printf("sizeof(class SocketChannel)=%lu\n", sizeof(SocketChannel)); printf("sizeof(class TcpClient)=%lu\n", sizeof(TcpClient)); printf("sizeof(class TcpServer)=%lu\n", sizeof(TcpServer)); printf("sizeof(class UdpClient)=%lu\n", sizeof(UdpClient)); printf("sizeof(class UdpServer)=%lu\n", sizeof(UdpServer)); // http printf("sizeof(class HttpRequest)=%lu\n", sizeof(HttpRequest)); printf("sizeof(class HttpResponse)=%lu\n", sizeof(HttpResponse)); printf("sizeof(class Http1Parser)=%lu\n", sizeof(Http1Parser)); printf("sizeof(class HttpContext)=%lu\n", sizeof(HttpContext)); printf("sizeof(class HttpServer)=%lu\n", sizeof(HttpServer)); printf("sizeof(class HttpHandler)=%lu\n", sizeof(HttpHandler)); printf("sizeof(class HttpResponseWrite)=%lu\n", sizeof(HttpResponseWriter)); // websocket printf("sizeof(class WebSocketChannel)=%lu\n", sizeof(WebSocketChannel)); printf("sizeof(class WebSocketParser)=%lu\n", sizeof(WebSocketParser)); printf("sizeof(class WebSocketClient)=%lu\n", sizeof(WebSocketClient)); printf("sizeof(class WebSocketServer)=%lu\n", sizeof(WebSocketServer)); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/socketpair_test.c000066400000000000000000000013351520575453600306750ustar00rootroot00000000000000#include #include "hsocket.h" int main(int argc, char* argv[]) { int sockfds[2]; if (Socketpair(AF_INET, SOCK_STREAM, 0, sockfds) != 0) { printf("socketpair failed!\n"); return -1; } printf("Socketpair %d<=>%d\n", sockfds[0], sockfds[1]); char sendbuf[] = "hello,world!"; char recvbuf[1460]; int nsend = send(sockfds[0], sendbuf, strlen(sendbuf), 0); printf("sockfd:%d send %d bytes: %s\n", sockfds[0], nsend, sendbuf); memset(recvbuf, 0, sizeof(recvbuf)); int nrecv = recv(sockfds[1], recvbuf, sizeof(recvbuf), 0); printf("sockfd:%d recv %d bytes: %s\n", sockfds[1], nrecv, recvbuf); closesocket(sockfds[0]); closesocket(sockfds[1]); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/synchronized_test.cpp000066400000000000000000000010341520575453600316040ustar00rootroot00000000000000#include "hthread.h" #include "hmutex.h" #define THREAD_NUM 10 std::mutex g_mutex; HTHREAD_ROUTINE(test_synchronized) { synchronized(g_mutex) { hv_delay(1000); printf("tid=%ld time=%llus\n", hv_gettid(), (unsigned long long)time(NULL)); } return 0; } int main() { hthread_t threads[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; ++i) { threads[i] = hthread_create(test_synchronized, NULL); } for (int i = 0; i < THREAD_NUM; ++i) { hthread_join(threads[i]); } return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/threadpool_test.cpp000066400000000000000000000007141520575453600312320ustar00rootroot00000000000000#include #include "hthreadpool.h" #include "hthread.h" #include "htime.h" void print_task(int i) { printf("thread[%ld]: task[%d]\n", hv_gettid(), i); hv_sleep(1); } int main(int argc, char** argv) { HThreadPool tp(1, 4); tp.start(); int i = 0; for (; i < 10; ++i) { tp.commit(print_task, i); } tp.wait(); for (; i < 20; ++i) { tp.commit(print_task, i); } tp.wait(); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/unittest/webbench.c000066400000000000000000000235331520575453600272530ustar00rootroot00000000000000#include #include #include #include #include // for gethostbyname #include #include #include #include #include #include #include int Connect(const char* host, int port) { struct sockaddr_in addr; addr.sin_family = AF_INET; in_addr_t inaddr = inet_addr(host); if (inaddr != INADDR_NONE) { addr.sin_addr.s_addr = inaddr; } else { struct hostent* phe = gethostbyname(host); if (phe == NULL) { return -1; } memcpy(&addr.sin_addr, phe->h_addr_list[0], phe->h_length); } addr.sin_port = htons(port); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("socket"); return -2; } if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("connect"); return -3; } return sock; } #define METHOD_GET 0 #define METHOD_HEAD 1 #define METHOD_OPTIONS 2 #define METHOD_TRACE 3 #define VERSION "webbench/1.19.3.15" int verbose = 0; int quiet = 0; volatile int timerexpired = 0; // for timer int time = 30; int clients = 1; char host[64] = {0}; int port = 80; char* proxy_host = NULL; int proxy_port = 80; int method = METHOD_GET; int http = 1; // 1=HTTP/1.1 0=HTTP/1.0 int keepalive = 0; const char* url = NULL; #define REQUEST_SIZE 2048 char request[REQUEST_SIZE] = {0}; char buf[1460] = {0}; int mypipe[2]; // IPC static const char options[] = "?hVvq01kt:p:c:"; static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {"verbose", no_argument, NULL, 'v'}, {"quiet", no_argument, NULL, 'q'}, {"time", required_argument, NULL, 't'}, {"proxy", required_argument, NULL, 'p'}, {"clients", required_argument, NULL, 'c'}, {"http10", no_argument, NULL, '0'}, {"http11", no_argument, NULL, '1'}, {"keepalive", no_argument, NULL, 'k'}, {"get", no_argument, &method, METHOD_GET}, {"head", no_argument, &method, METHOD_HEAD}, {"options", no_argument, &method, METHOD_OPTIONS}, {"trace", no_argument, &method, METHOD_TRACE}, {NULL, 0, NULL, 0} }; void print_usage() { printf("Usage: webbench [%s] URL\n", options); puts("\n\ Options:\n\ -?|-h|--help Print this information.\n\ -V|--version Print version.\n\ -v|--verbose Print verbose.\n\ -q|--quiet Print quiet.\n\ -0|--http10 Use HTTP/1.0 protocol.\n\ -1|--http11 Use HTTP/1.1 protocol.\n\ -k|--keepalive Connection: keep-alive.\n\ -t|--time Run benchmark for seconds. Default 30.\n\ -p|--proxy Use proxy server for request.\n\ -c|--clients Run HTTP clients. Default one.\n\ --get Use GET request method.\n\ --head Use HEAD request method.\n\ --options Use OPTIONS request method.\n\ --trace Use TRACE request method.\n\ "); } int parse_cmdline(int argc, char** argv) { int opt = 0; int opt_idx = 0; while ((opt=getopt_long(argc, argv, options, long_options, &opt_idx)) != EOF) { switch (opt) { case '?': case 'h': print_usage(); exit(1); case 'V': puts(VERSION); exit(1); case 'v': verbose = 1; break; case 'q': quiet = 1; break; case '0': http = 0; break; case '1': http = 1; break; case 'k': keepalive = 1; break; case 't': time = atoi(optarg); break; case 'c': clients = atoi(optarg); break; case 'p': { // host:port char* pos = strrchr(optarg, ':'); proxy_host = optarg; if (pos == NULL) break; if (pos == optarg || pos == optarg + strlen(optarg) - 1) { printf("Error option --proxy\n"); return -2; } *pos = '\0'; proxy_port = atoi(pos+1); } break; } } if (optind == argc) { printf("Missing URL\n"); return -2; } url = argv[optind]; return 0; } static void alarm_handler(int singal) { timerexpired = 1; } int main(int argc, char** argv) { if (argc == 1) { print_usage(); return 2; } int ret = parse_cmdline(argc, argv); if (ret != 0) { return ret; } printf("%d clients, running %d sec\n", clients, time); // domain port url const char* req_url = "/"; if (proxy_host) { strncpy(host, proxy_host, sizeof(host)); port = proxy_port; } else { // http://host:port/path const char* pos1 = strstr(url, "http://"); if (pos1 == NULL) { pos1 = url; } else { pos1 += strlen("http://"); } const char* pos2 = strchr(pos1, '/'); if (pos2 == NULL) { pos2 = url + strlen(url); } else { req_url = pos2; } int len = pos2 - pos1; char* server = (char*)malloc(len+1); memcpy(server, pos1, len); server[len] = '\0'; char* pos3 = strrchr(server, ':'); if (pos3 == NULL) { port = 80; } else { *pos3 = '\0'; port = atoi(pos3+1); } strncpy(host, server, sizeof(host)); free(server); } char Host[256]; snprintf(Host, sizeof(Host), "Host: %s:%d\r\n", host, port); printf("%s", Host); // test connect int sock = Connect(host, port); if (sock < 0) { printf("Connect failed!\n"); return -20; } else { printf("Connect test OK!\n"); close(sock); } // build request switch (method) { case METHOD_GET: default: strcpy(request, "GET"); break; case METHOD_HEAD: strcpy(request, "HEAD"); break; case METHOD_OPTIONS: strcpy(request, "OPTIONS"); break; case METHOD_TRACE: strcpy(request, "TRACE"); break; } strcat(request, " "); strcat(request, req_url); strcat(request, " "); if (http == 0) { strcat(request, "HTTP/1.0"); } else if (http == 1) { strcat(request, "HTTP/1.1"); } strcat(request, "\r\n"); strcat(request, "User-Agent: webbench/1.18.3.15\r\n"); strcat(request, Host); strcat(request, "Cache-Control: no-cache\r\n"); if (keepalive) { strcat(request, "Connection: keep-alive\r\n"); } else { strcat(request, "Connection: close\r\n"); } strcat(request, "\r\n"); if (!quiet) { printf("%s", request); } // IPC if (pipe(mypipe) < 0) { perror("pipe"); exit(20); } // fork childs pid_t pid = 0; FILE* fp = NULL; long long succeed = 0, failed = 0, bytes = 0; int childs = clients; int i; for (i = 0; i < childs; ++i) { pid = fork(); if (pid < 0) { perror("fork"); exit(-10); } if (pid == 0) { // child //printf("child[%d] start\n", getpid()); signal(SIGALRM, alarm_handler); alarm(time); int sock = -1; int len = strlen(request); int wrbytes, rdbytes; while (1) { connect: if (timerexpired) break; if (sock == -1) { sock = Connect(host, port); } if (sock < 0) { ++failed; continue; } int total_rdbytes = 0; write: if (timerexpired) break; wrbytes = write(sock, request, len); if (verbose) { printf("write %d bytes\n", wrbytes); } if (wrbytes != len) { ++failed; goto close; } if (verbose) { printf("%s\n", request); } read: if (timerexpired) break; rdbytes = read(sock, buf, sizeof(buf)); if (verbose) { printf("read %d bytes\n", rdbytes); } if (rdbytes <= 0) { ++failed; goto close; } if (verbose) { printf("%.*s\n", rdbytes, buf); } static int s_rdbytes = 0; if (s_rdbytes == 0) { s_rdbytes = rdbytes; } bytes += rdbytes; total_rdbytes += rdbytes; if (total_rdbytes < s_rdbytes) { // NOTE: some http server head and body send not one packet. goto read; } ++succeed; close: if (!keepalive) { close(sock); sock = -1; } } fp = fdopen(mypipe[1], "w"); if (fp == NULL) { perror("fdopen"); return 30; } fprintf(fp, "%lld %lld %lld\n", succeed, failed, bytes); fclose(fp); //printf("child[%d] end\n", getpid()); return 0; } } fp = fdopen(mypipe[0], "r"); if (fp == NULL) { perror("fdopen"); return 30; } while (1) { long long i,j,k; fscanf(fp, "%lld %lld %lld", &i, &j, &k); succeed += i; failed += j; bytes += k; if (--childs==0) break; } fclose(fp); printf("recv %lld bytes/sec, %lld succeed, %lld failed\n", bytes/time, succeed, failed); return 0; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/000077500000000000000000000000001520575453600244225ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/README.md000066400000000000000000000002411520575453600256760ustar00rootroot00000000000000## 目录结构 ``` . ├── base64.h BASE64编解码 ├── md5.h MD5数字摘要 └── sha1.h SHA1安全散列算法 ``` kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/base64.c000066400000000000000000000070261520575453600256570ustar00rootroot00000000000000#include #include "base64.h" /* BASE 64 encode table */ static const char base64en[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; #define BASE64_PAD '=' #define BASE64DE_FIRST '+' #define BASE64DE_LAST 'z' /* ASCII order for BASE 64 decode, -1 in unused character */ static const signed char base64de[] = { /* '+', ',', '-', '.', '/', '0', '1', '2', */ 62, -1, -1, -1, 63, 52, 53, 54, /* '3', '4', '5', '6', '7', '8', '9', ':', */ 55, 56, 57, 58, 59, 60, 61, -1, /* ';', '<', '=', '>', '?', '@', 'A', 'B', */ -1, -1, -1, -1, -1, -1, 0, 1, /* 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', */ 2, 3, 4, 5, 6, 7, 8, 9, /* 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', */ 10, 11, 12, 13, 14, 15, 16, 17, /* 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', */ 18, 19, 20, 21, 22, 23, 24, 25, /* '[', '\', ']', '^', '_', '`', 'a', 'b', */ -1, -1, -1, -1, -1, -1, 26, 27, /* 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', */ 28, 29, 30, 31, 32, 33, 34, 35, /* 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', */ 36, 37, 38, 39, 40, 41, 42, 43, /* 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', */ 44, 45, 46, 47, 48, 49, 50, 51, }; int hv_base64_encode(const unsigned char *in, unsigned int inlen, char *out) { unsigned int i = 0, j = 0; for (; i < inlen; i++) { int s = i % 3; switch (s) { case 0: out[j++] = base64en[(in[i] >> 2) & 0x3F]; continue; case 1: out[j++] = base64en[((in[i-1] & 0x3) << 4) + ((in[i] >> 4) & 0xF)]; continue; case 2: out[j++] = base64en[((in[i-1] & 0xF) << 2) + ((in[i] >> 6) & 0x3)]; out[j++] = base64en[in[i] & 0x3F]; } } /* move back */ i -= 1; /* check the last and add padding */ if ((i % 3) == 0) { out[j++] = base64en[(in[i] & 0x3) << 4]; out[j++] = BASE64_PAD; out[j++] = BASE64_PAD; } else if ((i % 3) == 1) { out[j++] = base64en[(in[i] & 0xF) << 2]; out[j++] = BASE64_PAD; } return j; } int hv_base64_decode(const char *in, unsigned int inlen, unsigned char *out) { unsigned int i = 0, j = 0; for (; i < inlen; i++) { int c; int s = i % 4; if (in[i] == '=') return j; if (in[i] < BASE64DE_FIRST || in[i] > BASE64DE_LAST || (c = base64de[in[i] - BASE64DE_FIRST]) == -1) return -1; switch (s) { case 0: out[j] = ((unsigned int)c << 2) & 0xFF; continue; case 1: out[j++] += ((unsigned int)c >> 4) & 0x3; /* if not last char with padding */ if (i < (inlen - 3) || in[inlen - 2] != '=') out[j] = ((unsigned int)c & 0xF) << 4; continue; case 2: out[j++] += ((unsigned int)c >> 2) & 0xF; /* if not last char with padding */ if (i < (inlen - 2) || in[inlen - 1] != '=') out[j] = ((unsigned int)c & 0x3) << 6; continue; case 3: out[j++] += (unsigned char)c; } } return j; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/base64.h000066400000000000000000000024311520575453600256570ustar00rootroot00000000000000#ifndef HV_BASE64_H_ #define HV_BASE64_H_ #include "hexport.h" #define BASE64_ENCODE_OUT_SIZE(s) (((s) + 2) / 3 * 4) #define BASE64_DECODE_OUT_SIZE(s) (((s)) / 4 * 3) BEGIN_EXTERN_C // @return encoded size HV_EXPORT int hv_base64_encode(const unsigned char *in, unsigned int inlen, char *out); // @return decoded size HV_EXPORT int hv_base64_decode(const char *in, unsigned int inlen, unsigned char *out); END_EXTERN_C #ifdef __cplusplus #include #include namespace hv { HV_INLINE std::string Base64Encode(const unsigned char* data, unsigned int len) { int encoded_size = BASE64_ENCODE_OUT_SIZE(len); std::string encoded_str(encoded_size + 1, 0); encoded_size = hv_base64_encode(data, len, (char*)encoded_str.data()); encoded_str.resize(encoded_size); return encoded_str; } HV_INLINE std::string Base64Decode(const char* str, unsigned int len = 0) { if (len == 0) len = strlen(str); int decoded_size = BASE64_DECODE_OUT_SIZE(len); std::string decoded_buf(decoded_size + 1, 0); decoded_size = hv_base64_decode(str, len, (unsigned char*)decoded_buf.data()); if (decoded_size > 0) { decoded_buf.resize(decoded_size); } else { decoded_buf.clear(); } return decoded_buf; } } #endif #endif // HV_BASE64_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/md5.c000066400000000000000000000151761520575453600252650ustar00rootroot00000000000000#include #include "md5.h" #define F(x,y,z) ((x & y) | (~x & z)) #define G(x,y,z) ((x & z) | (y & ~z)) #define H(x,y,z) (x^y^z) #define I(x,y,z) (y ^ (x | ~z)) #define ROTATE_LEFT(x,n) ((x << n) | (x >> (32-n))) #define FF(a,b,c,d,x,s,ac) \ { \ a += F(b,c,d) + x + ac; \ a = ROTATE_LEFT(a,s); \ a += b; \ } #define GG(a,b,c,d,x,s,ac) \ { \ a += G(b,c,d) + x + ac; \ a = ROTATE_LEFT(a,s); \ a += b; \ } #define HH(a,b,c,d,x,s,ac) \ { \ a += H(b,c,d) + x + ac; \ a = ROTATE_LEFT(a,s); \ a += b; \ } #define II(a,b,c,d,x,s,ac) \ { \ a += I(b,c,d) + x + ac; \ a = ROTATE_LEFT(a,s); \ a += b; \ } static void HV_MD5Transform(unsigned int state[4],unsigned char block[64]); static void HV_MD5Encode(unsigned char *output,unsigned int *input,unsigned int len); static void HV_MD5Decode(unsigned int *output,unsigned char *input,unsigned int len); static unsigned char PADDING[] = { 0x80,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 }; void HV_MD5Init(HV_MD5_CTX *ctx) { ctx->count[0] = 0; ctx->count[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; } void HV_MD5Update(HV_MD5_CTX *ctx,unsigned char *input,unsigned int inputlen) { unsigned int i = 0,index = 0,partlen = 0; index = (ctx->count[0] >> 3) & 0x3F; partlen = 64 - index; ctx->count[0] += inputlen << 3; if(ctx->count[0] < (inputlen << 3)) { ctx->count[1]++; } ctx->count[1] += inputlen >> 29; if(inputlen >= partlen) { memcpy(&ctx->buffer[index],input,partlen); HV_MD5Transform(ctx->state,ctx->buffer); for(i = partlen;i+64 <= inputlen;i+=64) { HV_MD5Transform(ctx->state,&input[i]); } index = 0; } else { i = 0; } memcpy(&ctx->buffer[index],&input[i],inputlen-i); } void HV_MD5Final(HV_MD5_CTX *ctx,unsigned char digest[16]) { unsigned int index = 0,padlen = 0; unsigned char bits[8]; index = (ctx->count[0] >> 3) & 0x3F; padlen = (index < 56)?(56-index):(120-index); HV_MD5Encode(bits,ctx->count,8); HV_MD5Update(ctx,PADDING,padlen); HV_MD5Update(ctx,bits,8); HV_MD5Encode(digest,ctx->state,16); } void HV_MD5Encode(unsigned char *output,unsigned int *input,unsigned int len) { unsigned int i = 0,j = 0; while(j < len) { output[j] = input[i] & 0xFF; output[j+1] = (input[i] >> 8) & 0xFF; output[j+2] = (input[i] >> 16) & 0xFF; output[j+3] = (input[i] >> 24) & 0xFF; i++; j+=4; } } void HV_MD5Decode(unsigned int *output,unsigned char *input,unsigned int len) { unsigned int i = 0,j = 0; while(j < len) { output[i] = (input[j]) | (input[j+1] << 8) | (input[j+2] << 16) | (input[j+3] << 24); i++; j+=4; } } void HV_MD5Transform(unsigned int state[4],unsigned char block[64]) { unsigned int a = state[0]; unsigned int b = state[1]; unsigned int c = state[2]; unsigned int d = state[3]; unsigned int x[64]; HV_MD5Decode(x,block,64); FF(a, b, c, d, x[ 0], 7, 0xd76aa478); FF(d, a, b, c, x[ 1], 12, 0xe8c7b756); FF(c, d, a, b, x[ 2], 17, 0x242070db); FF(b, c, d, a, x[ 3], 22, 0xc1bdceee); FF(a, b, c, d, x[ 4], 7, 0xf57c0faf); FF(d, a, b, c, x[ 5], 12, 0x4787c62a); FF(c, d, a, b, x[ 6], 17, 0xa8304613); FF(b, c, d, a, x[ 7], 22, 0xfd469501); FF(a, b, c, d, x[ 8], 7, 0x698098d8); FF(d, a, b, c, x[ 9], 12, 0x8b44f7af); FF(c, d, a, b, x[10], 17, 0xffff5bb1); FF(b, c, d, a, x[11], 22, 0x895cd7be); FF(a, b, c, d, x[12], 7, 0x6b901122); FF(d, a, b, c, x[13], 12, 0xfd987193); FF(c, d, a, b, x[14], 17, 0xa679438e); FF(b, c, d, a, x[15], 22, 0x49b40821); GG(a, b, c, d, x[ 1], 5, 0xf61e2562); GG(d, a, b, c, x[ 6], 9, 0xc040b340); GG(c, d, a, b, x[11], 14, 0x265e5a51); GG(b, c, d, a, x[ 0], 20, 0xe9b6c7aa); GG(a, b, c, d, x[ 5], 5, 0xd62f105d); GG(d, a, b, c, x[10], 9, 0x2441453); GG(c, d, a, b, x[15], 14, 0xd8a1e681); GG(b, c, d, a, x[ 4], 20, 0xe7d3fbc8); GG(a, b, c, d, x[ 9], 5, 0x21e1cde6); GG(d, a, b, c, x[14], 9, 0xc33707d6); GG(c, d, a, b, x[ 3], 14, 0xf4d50d87); GG(b, c, d, a, x[ 8], 20, 0x455a14ed); GG(a, b, c, d, x[13], 5, 0xa9e3e905); GG(d, a, b, c, x[ 2], 9, 0xfcefa3f8); GG(c, d, a, b, x[ 7], 14, 0x676f02d9); GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); HH(a, b, c, d, x[ 5], 4, 0xfffa3942); HH(d, a, b, c, x[ 8], 11, 0x8771f681); HH(c, d, a, b, x[11], 16, 0x6d9d6122); HH(b, c, d, a, x[14], 23, 0xfde5380c); HH(a, b, c, d, x[ 1], 4, 0xa4beea44); HH(d, a, b, c, x[ 4], 11, 0x4bdecfa9); HH(c, d, a, b, x[ 7], 16, 0xf6bb4b60); HH(b, c, d, a, x[10], 23, 0xbebfbc70); HH(a, b, c, d, x[13], 4, 0x289b7ec6); HH(d, a, b, c, x[ 0], 11, 0xeaa127fa); HH(c, d, a, b, x[ 3], 16, 0xd4ef3085); HH(b, c, d, a, x[ 6], 23, 0x4881d05); HH(a, b, c, d, x[ 9], 4, 0xd9d4d039); HH(d, a, b, c, x[12], 11, 0xe6db99e5); HH(c, d, a, b, x[15], 16, 0x1fa27cf8); HH(b, c, d, a, x[ 2], 23, 0xc4ac5665); II(a, b, c, d, x[ 0], 6, 0xf4292244); II(d, a, b, c, x[ 7], 10, 0x432aff97); II(c, d, a, b, x[14], 15, 0xab9423a7); II(b, c, d, a, x[ 5], 21, 0xfc93a039); II(a, b, c, d, x[12], 6, 0x655b59c3); II(d, a, b, c, x[ 3], 10, 0x8f0ccc92); II(c, d, a, b, x[10], 15, 0xffeff47d); II(b, c, d, a, x[ 1], 21, 0x85845dd1); II(a, b, c, d, x[ 8], 6, 0x6fa87e4f); II(d, a, b, c, x[15], 10, 0xfe2ce6e0); II(c, d, a, b, x[ 6], 15, 0xa3014314); II(b, c, d, a, x[13], 21, 0x4e0811a1); II(a, b, c, d, x[ 4], 6, 0xf7537e82); II(d, a, b, c, x[11], 10, 0xbd3af235); II(c, d, a, b, x[ 2], 15, 0x2ad7d2bb); II(b, c, d, a, x[ 9], 21, 0xeb86d391); state[0] += a; state[1] += b; state[2] += c; state[3] += d; } void hv_md5(unsigned char* input, unsigned int inputlen, unsigned char digest[16]) { HV_MD5_CTX ctx; HV_MD5Init(&ctx); HV_MD5Update(&ctx, input, inputlen); HV_MD5Final(&ctx, digest); } static inline char i2hex(unsigned char i) { return i < 10 ? i + '0' : i - 10 + 'a'; } void hv_md5_hex(unsigned char* input, unsigned int inputlen, char* output, unsigned int outputlen) { int i; unsigned char digest[16]; if (outputlen < 32) return; hv_md5(input, inputlen, digest); for (i = 0; i < 16; ++i) { *output++ = i2hex(digest[i] >> 4); *output++ = i2hex(digest[i] & 0x0F); } if (outputlen > 32) *output = '\0'; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/md5.h000066400000000000000000000012641520575453600252630ustar00rootroot00000000000000#ifndef HV_MD5_H_ #define HV_MD5_H_ #include "hexport.h" typedef struct { unsigned int count[2]; unsigned int state[4]; unsigned char buffer[64]; } HV_MD5_CTX; BEGIN_EXTERN_C HV_EXPORT void HV_MD5Init(HV_MD5_CTX *ctx); HV_EXPORT void HV_MD5Update(HV_MD5_CTX *ctx, unsigned char *input, unsigned int inputlen); HV_EXPORT void HV_MD5Final(HV_MD5_CTX *ctx, unsigned char digest[16]); HV_EXPORT void hv_md5(unsigned char* input, unsigned int inputlen, unsigned char digest[16]); // NOTE: if outputlen > 32: output[32] = '\0' HV_EXPORT void hv_md5_hex(unsigned char* input, unsigned int inputlen, char* output, unsigned int outputlen); END_EXTERN_C #endif // HV_MD5_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/sha1.c000066400000000000000000000202111520575453600254160ustar00rootroot00000000000000/* SHA-1 in C By Steve Reid 100% Public Domain Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ /* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ /* #define SHA1HANDSOFF * Copies data before messing with it. */ #define SHA1HANDSOFF #include #include #include "sha1.h" #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ #if BYTE_ORDER == LITTLE_ENDIAN #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ |(rol(block->l[i],8)&0x00FF00FF)) #elif BYTE_ORDER == BIG_ENDIAN #define blk0(i) block->l[i] #else #error "Endianness not defined!" #endif #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); /* Hash a single 512-bit block. This is the core of the algorithm. */ void HV_SHA1Transform( uint32_t state[5], const unsigned char buffer[64] ) { uint32_t a, b, c, d, e; typedef union { unsigned char c[64]; uint32_t l[16]; } CHAR64LONG16; #ifdef SHA1HANDSOFF CHAR64LONG16 block[1]; /* use array to appear as a pointer */ memcpy(block, buffer, 64); #else /* The following had better never be used because it causes the * pointer-to-const buffer to be cast into a pointer to non-const. * And the result is written through. I threw a "const" in, hoping * this will cause a diagnostic. */ CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; #endif /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3); R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7); R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11); R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; #ifdef SHA1HANDSOFF memset(block, '\0', sizeof(block)); #endif } /* HV_SHA1Init - Initialize new context */ void HV_SHA1Init( HV_SHA1_CTX * context ) { /* SHA1 initialization constants */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } /* Run your data through this. */ void HV_SHA1Update( HV_SHA1_CTX * context, const unsigned char *data, uint32_t len ) { uint32_t i; uint32_t j; j = context->count[0]; if ((context->count[0] += len << 3) < j) context->count[1]++; context->count[1] += (len >> 29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64 - j)); HV_SHA1Transform(context->state, context->buffer); for (; i + 63 < len; i += 64) { HV_SHA1Transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } /* Add padding and return the message digest. */ void HV_SHA1Final( unsigned char digest[20], HV_SHA1_CTX * context ) { unsigned i; unsigned char finalcount[8]; unsigned char c; #if 0 /* untested "improvement" by DHR */ /* Convert context->count to a sequence of bytes * in finalcount. Second element first, but * big-endian order within element. * But we do it all backwards. */ unsigned char *fcp = &finalcount[8]; for (i = 0; i < 2; i++) { uint32_t t = context->count[i]; int j; for (j = 0; j < 4; t >>= 8, j++) *--fcp = (unsigned char) t} #else for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ } #endif c = 0200; HV_SHA1Update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; HV_SHA1Update(context, &c, 1); } HV_SHA1Update(context, finalcount, 8); /* Should cause a HV_SHA1Transform() */ for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } /* Wipe variables */ memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } void HV_SHA1( char *hash_out, const char *str, uint32_t len) { HV_SHA1_CTX ctx; unsigned int ii; HV_SHA1Init(&ctx); for (ii=0; ii> 4); *output++ = i2hex(digest[i] & 0x0F); } if (outputlen > 40) *output = '\0'; } kylin-cloud-ai-engine-plugin-1.1.0.1/third-party/libhv-v1.3.3/util/sha1.h000066400000000000000000000020131520575453600254230ustar00rootroot00000000000000#ifndef HV_SHA1_H_ #define HV_SHA1_H_ /* SHA-1 in C By Steve Reid 100% Public Domain */ /* for uint32_t */ #include #include "hexport.h" typedef struct { uint32_t state[5]; uint32_t count[2]; unsigned char buffer[64]; } HV_SHA1_CTX; BEGIN_EXTERN_C HV_EXPORT void HV_SHA1Transform( uint32_t state[5], const unsigned char buffer[64] ); HV_EXPORT void HV_SHA1Init( HV_SHA1_CTX * context ); HV_EXPORT void HV_SHA1Update( HV_SHA1_CTX * context, const unsigned char *data, uint32_t len ); HV_EXPORT void HV_SHA1Final( unsigned char digest[20], HV_SHA1_CTX * context ); HV_EXPORT void HV_SHA1( char *hash_out, const char *str, uint32_t len); HV_EXPORT void hv_sha1(unsigned char* input, uint32_t inputlen, unsigned char digest[20]); // NOTE: if outputlen > 40: output[40] = '\0' HV_EXPORT void hv_sha1_hex(unsigned char* input, uint32_t inputlen, char* output, uint32_t outputlen); END_EXTERN_C #endif // HV_SHA1_H_ kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/000077500000000000000000000000001520575453600205425ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/logger.cpp000066400000000000000000000032361520575453600225310ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "logger.h" #include #include void Logger::printLn() { std::cout << '\n'; } void Logger::printErrorLn() { std::cerr << '\n'; } std::string Logger::location(const char *fileName, int line, const char *funcName) { std::ostringstream oss; oss << '[' << fileName << ':' << line << ':' << funcName << ':' << gettid() << ']'; return oss.str(); } std::string Logger::currentTime() { struct timeval tv{}; struct tm *tm = nullptr; gettimeofday(&tv, nullptr); time_t tt = tv.tv_sec; tm = localtime(&tt); char buffer[32]{}; #ifdef RUN_IN_DEBUG snprintf(buffer, sizeof(buffer), "[%04d-%02d-%02d %02d:%02d:%02d.%03ld]", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec / 1000); #else snprintf(buffer, sizeof(buffer), "[%ld]", tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif return buffer; } Logger::Logger() { #ifdef RUN_IN_DEBUG level_ = LOG_LEVEL_DEBUG; #endif } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/logger.h000066400000000000000000000331101520575453600221700ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTILS_LOGGER_H #define UTILS_LOGGER_H #include #include #include #include #include #include #include #include // #define CLR_CLR "\033[0m" // 恢复颜色 // #define CLR_BLACK "\033[30m" // 黑色字 // #define CLR_RED "\033[31m" // 红色字 // #define CLR_GREEN "\033[32m" // 绿色字 // #define CLR_YELLOW "\033[33m" // 黄色字 // #define CLR_BLUE "\033[34m" // 蓝色字 // #define CLR_PURPLE "\033[35m" // 紫色字 // #define CLR_SKYBLUE "\033[36m" // 天蓝字 // #define CLR_WHITE "\033[37m" // 白色字 // // #define CLR_BLK_WHT "\033[40;37m" // 黑底白字 // #define CLR_RED_WHT "\033[41;37m" // 红底白字 // #define CLR_GREEN_WHT "\033[42;37m" // 绿底白字 // #define CLR_YELLOW_WHT "\033[43;37m" // 黄底白字 // #define CLR_BLUE_WHT "\033[44;37m" // 蓝底白字 // #define CLR_PURPLE_WHT "\033[45;37m" // 紫底白字 // #define CLR_SKYBLUE_WHT "\033[46;37m" // 天蓝底白字 // #define CLR_WHT_BLK "\033[47;30m" // 白底黑字 #ifndef __FILENAME__ #define __FILENAME__ (strrchr("/" __FILE__, '/') + 1) #endif inline pid_t gettid() { return static_cast(syscall(SYS_gettid)); } class Logger { public: enum Level { LOG_LEVEL_SILENT = 0, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, LOG_LEVEL_WARN, LOG_LEVEL_ERROR }; static void printLn(); template static void printLn(T t, Args... args) { std::cout << t << ' '; printLn(args...); } static void printErrorLn(); template static void printErrorLn(T t, Args... args) { std::cerr << t << ' '; printErrorLn(args...); } template static void printLnLevel(const Logger &logger, Level level, Args... args) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { printLn(currentTime(), "\033[36mdebug\033[0m", args...); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { printLn(currentTime(), "\033[32minfo \033[0m", args...); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { printLn(currentTime(), "\033[33mwarn \033[0m", args...); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { printLn(currentTime(), "\033[31merror\033[0m", args...); } #else // release 暂时往stderr输出 if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { printErrorLn(currentTime(), "\033[36mdebug\033[0m", args...); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { printErrorLn(currentTime(), "\033[32minfo \033[0m", args...); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { printErrorLn(currentTime(), "\033[33mwarn \033[0m", args...); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { printErrorLn(currentTime(), "\033[31merror\033[0m", args...); } #endif } static void printfLnLevel(const Logger &logger, Level level, const char *format) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG FILE *pFile = stdout; #else FILE *pFile = stderr; #endif if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[36mdebug\033[0m ", format); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[32minfo \033[0m", format); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[33mwarn \033[0m", format); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[31merror\033[0m", format); } } template static void printfLnLevel(const Logger &logger, Level level, const char *format, Args... args) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG FILE *pFile = stdout; #else FILE *pFile = stderr; #endif if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { std::fprintf(pFile, "%s %s", currentTime().c_str(), "\033[36mdebug\033[0m "); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[32minfo \033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[33mwarn \033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[31merror\033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } } static std::string location(const char *fileName, int line, const char *funcName); static std::string currentTime(); public: Logger(); private: mutable std::mutex mutex_; std::atomic level_{LOG_LEVEL_INFO}; }; static Logger g_Logger{}; #ifdef RUN_IN_DEBUG #define LOGD(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), ##__VA_ARGS__); \ } while (0) #define LOGDF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, "[%s:%d:%s:%d] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, gettid(), ##__VA_ARGS__); \ } while (0) #define LOGI(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGIF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, "[%s:%d:%s:%d] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, gettid(), ##__VA_ARGS__); \ } while (0) #define LOGW(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGWF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, "[%s:%d:%s:%d] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, gettid(), ##__VA_ARGS__); \ } while (0) #define LOGE(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), ##__VA_ARGS__); \ } while (0) #define LOGEF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, "[%s:%d:%s:%d] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, gettid(), ##__VA_ARGS__); \ } while (0) #else #define LOGD(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, ##__VA_ARGS__); \ } while (0) #define LOGDF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__); \ } while (0) #define LOGI(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, ##__VA_ARGS__); \ } while (0) #define LOGIF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, fmt, ##__VA_ARGS__); \ } while (0) #define LOGW(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, ##__VA_ARGS__); \ } while (0) #define LOGWF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, fmt, ##__VA_ARGS__); \ } while (0) #define LOGE(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, ##__VA_ARGS__); \ } while (0) #define LOGEF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, fmt, ##__VA_ARGS__); \ } while (0) #endif #endif // UTILS_LOGGER_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/000077500000000000000000000000001520575453600213335ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/servererror.cpp000066400000000000000000000061621520575453600244240ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map nlpChatErrorCodeMap = { {10000, ai_engine::NlpEngineErrorCode::FailedToAnswer}, {10001, ai_engine::NlpEngineErrorCode::NoServerService}, {10002, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {10003, ai_engine::NlpEngineErrorCode::InvalidParamType}, {10004, ai_engine::NlpEngineErrorCode::InvalidParamType}, {10005, ai_engine::NlpEngineErrorCode::InvalidParamType}, {10006, ai_engine::NlpEngineErrorCode::TooManyRequest}, {10007, ai_engine::NlpEngineErrorCode::TooFrequentRequest}, {10008, ai_engine::NlpEngineErrorCode::TooManyRequest}, {10009, ai_engine::NlpEngineErrorCode::FailedToConnectServer}, {10010, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {10011, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {10012, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {10013, ai_engine::NlpEngineErrorCode::InputTextBlocked}, {10014, ai_engine::NlpEngineErrorCode::OutputTextBlocked}, {10015, ai_engine::NlpEngineErrorCode::Unauthorized}, {10016, ai_engine::NlpEngineErrorCode::Unauthorized}, {10017, ai_engine::NlpEngineErrorCode::NoServerService}, {10019, ai_engine::NlpEngineErrorCode::InputTextBlocked}, {10021, ai_engine::NlpEngineErrorCode::InputTextBlocked}, {10110, ai_engine::NlpEngineErrorCode::NoServerService}, {10163, ai_engine::NlpEngineErrorCode::InvalidParamType}, {10222, ai_engine::NlpEngineErrorCode::ServerNoResponse}, {10907, ai_engine::NlpEngineErrorCode::TooManyData}, {11200, ai_engine::NlpEngineErrorCode::Unauthorized}, {11201, ai_engine::NlpEngineErrorCode::TooManyRequest}, {11202, ai_engine::NlpEngineErrorCode::TooFrequentRequest}, {11203, ai_engine::NlpEngineErrorCode::TooFrequentRequest}}; }; int xunfei_nlp_server_error::parseErrorCode(const std::string &result) { Json::Value obj = xunfei_nlp_util::stringToJson(result); if (!obj.isObject() || obj.isNull()) { return 0; } if (obj.isMember("header") && obj["header"].isMember("code") && obj["header"].isMember("message")) { return obj["header"]["code"].asInt(); } return 0; } ai_engine::NlpEngineErrorCode xunfei_nlp_server_error::errorCode2nlpResult(int errorCode) { if (nlpChatErrorCodeMap.count(errorCode) > 0) { return nlpChatErrorCodeMap.at(errorCode); } return ai_engine::NlpEngineErrorCode::UnknownError; } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/servererror.h000066400000000000000000000017531520575453600240720ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace xunfei_nlp_server_error { int parseErrorCode(const std::string &result); ai_engine::NlpEngineErrorCode errorCode2nlpResult(int errorCode); } // namespace xunfei_nlp_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/token.cpp000066400000000000000000000036341520575453600231650ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "token.h" #include #include "util.h" std::string xunfei_nlp_token::getAuthenticationUrl(const std::string &apiKey, const std::string &secretKey, const std::string &hostUrl) { auto urlData = xunfei_nlp_util::parseURL(hostUrl); std::string date = xunfei_nlp_util::getGmtTime(); std::string method{urlData["protocol"] == "https" ? "POST " : "GET "}; std::string originSignature{"host: " + urlData["Host"] + "\n" + "date: " + date + "\n" + method + urlData["Path"] + " HTTP/1.1"}; std::string shaSignature = xunfei_nlp_util::hmacSha256Encode(originSignature, secretKey); std::string authorization = "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", headers=\"host " "date request-line\", signature=\"" + shaSignature + "\""; authorization = xunfei_nlp_util::base64Encode(authorization); std::string callurl = hostUrl + "?" + "authorization=" + xunfei_nlp_util::urlEncode(authorization) + "&date=" + xunfei_nlp_util::urlEncode(date) + "&host=" + urlData["Host"]; return callurl; }kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/token.h000066400000000000000000000016641520575453600226330ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef TOKEN_H #define TOKEN_H #include #include namespace xunfei_nlp_token { std::string getAuthenticationUrl(const std::string &apiKey, const std::string &secretKey, const std::string &hostUrl); } #endif // TOKEN_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/util.cpp000066400000000000000000000212631520575453600230200ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "xunfei/logger.h" std::string xunfei_nlp_util::base64Encode(const std::string &input) { BIO *bio, *b64; BUF_MEM *bufferPtr; b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, input.c_str(), input.length()); BIO_flush(bio); BIO_get_mem_ptr(bio, &bufferPtr); std::string result(bufferPtr->data, bufferPtr->length); BIO_free_all(bio); return result; } std::string xunfei_nlp_util::urlEncode(const std::string &input) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto &&ch : input) { if (std::isalnum(ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~') { escaped << ch; continue; } escaped << std::uppercase; escaped << '%' << std::setw(2) << int((unsigned char)ch); escaped << std::nouppercase; } return escaped.str(); } std::unordered_map xunfei_nlp_util::parseURL(const std::string &url) { std::string protocol, host, port, path, query, fragment; // 解析协议部分 size_t protocolEnd = url.find("://"); if (protocolEnd != std::string::npos) { protocol = url.substr(0, protocolEnd); } // 解析主机和端口部分 size_t hostStart = protocolEnd != std::string::npos ? protocolEnd + 3 : 0; size_t hostEnd = url.find_first_of(":/", hostStart); if (hostEnd != std::string::npos) { size_t portStart = url[hostEnd] == ':' ? hostEnd + 1 : std::string::npos; size_t portEnd = url.find("/", hostEnd); host = url.substr(hostStart, hostEnd - hostStart); port = (portStart != std::string::npos && portEnd != std::string::npos) ? url.substr(portStart, portEnd - portStart) : ""; } // 解析路径、查询字符串和片段部分 size_t pathStart = url.find("/", hostEnd); size_t queryStart = url.find("?", pathStart); size_t fragmentStart = url.find("#", queryStart); path = url.substr(pathStart, queryStart - pathStart); query = queryStart != std::string::npos ? url.substr(queryStart + 1, fragmentStart - queryStart - 1) : ""; fragment = fragmentStart != std::string::npos ? url.substr(fragmentStart + 1) : ""; std::unordered_map urlParts = {{"Protocol", protocol}, {"Host", host}, {"Port", port}, {"Path", path}, {"Query", query}, {"Fragment", fragment}}; return urlParts; } std::string xunfei_nlp_util::hmacSha256Encode(const std::string &data, const std::string &key) { unsigned char digest[SHA256_DIGEST_LENGTH]; HMAC_CTX *ctx = HMAC_CTX_new(); HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha256(), NULL); HMAC_Update(ctx, reinterpret_cast(data.c_str()), data.length()); HMAC_Final(ctx, digest, NULL); HMAC_CTX_free(ctx); BIO *bio, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, digest, SHA256_DIGEST_LENGTH); BIO_flush(bio); BIO_get_mem_ptr(bio, &bptr); std::string result(bptr->data, bptr->length - 1); BIO_free_all(bio); return result; } namespace { #define NTP_PORT 123 #define NTP_TIMESTAMP_DELTA 2208988800ull // 1900-1970 年之间的秒数 #define TIME_SERVER "cn.pool.ntp.org" // 你可以换成其他国内NTP服务器 bool resolveHostname(const char *hostname, struct sockaddr_in *addr) { struct addrinfo hints{}; struct addrinfo *res{nullptr}; struct addrinfo *p{nullptr}; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; // IPv4 only if (getaddrinfo(hostname, nullptr, &hints, &res) != 0) { LOGE("DNS resolution failed!"); return false; } for (p = res; p != nullptr; p = p->ai_next) { if (p->ai_family == AF_INET) { memcpy(addr, p->ai_addr, sizeof(struct sockaddr_in)); freeaddrinfo(res); return true; } } freeaddrinfo(res); LOGE("No IPv4 address found for {}!", hostname); return false; } std::string getNtpServerGmtTime() { struct NtpPacket { uint8_t li_vn_mode; // 8 bits: LI, VN, Mode uint8_t stratum; // 8 bits: Stratum uint8_t poll; uint8_t precision; uint32_t rootDelay; uint32_t rootDispersion; uint32_t refId; uint32_t refTm_s; uint32_t refTm_f; uint32_t origTm_s; uint32_t origTm_f; uint32_t rxTm_s; uint32_t rxTm_f; uint32_t txTm_s; uint32_t txTm_f; }; int socketFd; struct sockaddr_in serverAddress{}; NtpPacket packet = {0}; // 设置 NTP 请求包 packet.li_vn_mode = 0x1B; // LI=0 (no warning), VN=4 (IPv4), Mode=3 (client) // 创建 UDP socket socketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (socketFd < 0) { LOGE("Socket creation error!"); return ""; } struct timeval timeout{}; timeout.tv_sec = 0; // 超时时间为 5 秒 timeout.tv_usec = 200 * 1000; if (setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) { LOGE("Failed to set timeout!"); close(socketFd); return ""; } // 解析域名 if (!resolveHostname(TIME_SERVER, &serverAddress)) { close(socketFd); return ""; } serverAddress.sin_port = htons(NTP_PORT); // 发送 NTP 请求 if (sendto(socketFd, (const char *)&packet, sizeof(NtpPacket), 0, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { LOGE("Send failed!"); close(socketFd); return ""; } // 接收响应 socklen_t len = sizeof(serverAddress); ssize_t n = recvfrom(socketFd, &packet, sizeof(NtpPacket), 0, (struct sockaddr *)&serverAddress, &len); if (n < 0) { LOGE("Receive failed!"); close(socketFd); return ""; } // 转换为 host 字节序 packet.txTm_s = ntohl(packet.txTm_s); packet.txTm_f = ntohl(packet.txTm_f); // 将 NTP 时间戳转换为 Unix 时间戳 time_t txTm = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA); struct tm *gmt = gmtime(&txTm); // UTC 时间 char buffer[80]; strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S GMT", gmt); LOGI("GMT time: ", std::string(buffer)); close(socketFd); return buffer; } std::string getLocalGmtTime() { setlocale(LC_TIME, "C"); time_t rawTime = time(0); tm *gmt = gmtime(&rawTime); const char *fmt = "%a, %d %b %Y %H:%M:%S GMT"; char tstr[30]; strftime(tstr, sizeof(tstr), fmt, gmt); return tstr; } } // namespace std::string xunfei_nlp_util::getGmtTime() { std::string gmtTime; for (int i = 0; i < 5; ++i) { gmtTime = getNtpServerGmtTime(); if (!gmtTime.empty()) { // 获取成功,退出循环 break; } // 获取失败,等待并重试 LOGW("Failed to get GMT time from NTP server, retrying..."); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (gmtTime.empty()) { return getLocalGmtTime(); } return gmtTime; } std::string xunfei_nlp_util::jsonToString(const Json::Value &value) { Json::StreamWriterBuilder builder; builder["emitUTF8"] = true; return Json::writeString(builder, value); } Json::Value xunfei_nlp_util::stringToJson(const std::string &string) { Json::Value value; if (Json::Reader reader; reader.parse(string, value)) { return value; } else { return Json::objectValue; } } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/util.h000066400000000000000000000030411520575453600224570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include #include namespace xunfei_nlp_util { std::string base64Encode(const std::string &input); std::string base64Decode(const std::string &input); std::string urlEncode(const std::string &input); std::unordered_map parseURL(const std::string &url); std::string hmacSha256Encode(const std::string &data, const std::string &key); std::string hmacSha1Encode(const std::string &data, const std::string &key); std::string getGmtTime(); std::string getCurrentUnixTimestamp(); std::string calculateMD5(const std::string &input); std::vector> splitData(const std::vector &audioData, size_t chunkSize); std::string jsonToString(const Json::Value &value); Json::Value stringToJson(const std::string &string); } // namespace xunfei_nlp_util #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/xunfeinlpengine.cpp000066400000000000000000000044641520575453600252450ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeinlpengine.h" #include "xunfeinlpengine_p.h" XunfeiNlpEngine::XunfeiNlpEngine() : d(new XunfeiNlpEnginePrivate()) {} XunfeiNlpEngine::~XunfeiNlpEngine() { delete d; } std::string XunfeiNlpEngine::engineName() const { return d->engineName(); } std::string XunfeiNlpEngine::currentModel() const { return d->currentModel(); } std::string XunfeiNlpEngine::currentModelName() const { return d->currentModelName(); } bool XunfeiNlpEngine::isCloud() const { return d->isCloud(); } bool XunfeiNlpEngine::isBuiltInEngine() const { return d->isBuiltInEngine(); } bool XunfeiNlpEngine::isCustomModelEngine() const { return d->isCustomModelEngine(); } void XunfeiNlpEngine::setConfig(const std::string &config) { d->setConfig(config); } bool XunfeiNlpEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } std::string XunfeiNlpEngine::modelInfo() const { return d->modelInfo(); } void XunfeiNlpEngine::setTextGenerationResultCallback(ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) { d->setTextGenerationResultCallback(callback); } ai_engine::result::AiEngineBaseResult XunfeiNlpEngine::init() { return d->init(); } ai_engine::result::AiEngineBaseResult XunfeiNlpEngine::chat(const std::string &message) { return d->chat(message); } ai_engine::result::AiEngineBaseResult XunfeiNlpEngine::generateContent(const std::string &input) { return d->generateContent(input); }; void XunfeiNlpEngine::stopChat() { d->stopChat(); } void XunfeiNlpEngine::stopGenerateContent() { d->stopGenerateContent(); } ai_engine::result::AiEngineBaseResult XunfeiNlpEngine::destroy() { return d->destroy(); } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/xunfeinlpengine.h000066400000000000000000000036651520575453600247140ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEINLPENGINE_H #define XUNFEINLPENGINE_H #include class XunfeiNlpEnginePrivate; class XunfeiNlpEngine : public ai_engine::gen_ai::nlp::AbstractTextGenerationEngine { public: XunfeiNlpEngine(); ~XunfeiNlpEngine() override; std::string engineName() const override; bool isCloud() const override; bool isBuiltInEngine() const override; bool isCustomModelEngine() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string currentModel() const override; std::string currentModelName() const override; std::string modelInfo() const override; void setTextGenerationResultCallback(ai_engine::gen_ai::nlp::TextGenerationResultCallback callback) override; ai_engine::result::AiEngineBaseResult generateContent(const std::string &input) override; ai_engine::result::AiEngineBaseResult chat(const std::string &message) override; void stopGenerateContent() override; void stopChat() override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; private: XunfeiNlpEnginePrivate *d; }; #endif // XUNFEINLPENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/xunfeinlpengine_p.cpp000066400000000000000000000440231520575453600255570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeinlpengine_p.h" #include #include #include #include "xunfei/logger.h" #include "servererror.h" #include "token.h" #include "util.h" bool XunfeiNlpEnginePrivate::connectWebsocket(const std::string &hostUrl) { std::string callurl = xunfei_nlp_token::getAuthenticationUrl(apiKey_, secretKey_, hostUrl); CURLcode res; if (currentCurl_) { curl_easy_setopt(currentCurl_, CURLOPT_URL, callurl.c_str()); curl_easy_setopt(currentCurl_, CURLOPT_CONNECT_ONLY, 2L); res = curl_easy_perform(currentCurl_); if (res == CURLE_HTTP_RETURNED_ERROR) { LOGE("xunfei authenticate failed:", curl_easy_strerror(res)); currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::Unauthorized, "Authentication failed"); return false; } if (res != CURLE_OK) { LOGE("net error:", res, curl_easy_strerror(res)); if (res == CURLE_PEER_FAILED_VERIFICATION) { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::SslCertificateError, curl_easy_strerror(res)); } else { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::NetworkDisconnected, curl_easy_strerror(res)); } return false; } return true; } currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::InvalidWords, "Failed to create resource"); return false; } void XunfeiNlpEnginePrivate::closeWebsocket() { size_t sent; if (currentCurl_) { curl_ws_send(currentCurl_, "", 0, &sent, 0, CURLWS_CLOSE); } } XunfeiNlpEnginePrivate::XunfeiNlpEnginePrivate() {} XunfeiNlpEnginePrivate::~XunfeiNlpEnginePrivate() { streamChatData_.clear(); } std::string XunfeiNlpEnginePrivate::engineName() const { return "xunfei"; } void XunfeiNlpEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = xunfei_nlp_util::stringToJson(config); if (configJson.isNull() || !configJson.isMember("apiKey") || !configJson.isMember("secretKey") || !configJson.isMember("appId") || !configJson["apiKey"].isString() || !configJson["secretKey"].isString() || !configJson["appId"].isString()) { LOGE("Invalid config for xunfei chat engine:", config); return; } appId_ = configJson["appId"].asString(); apiKey_ = configJson["apiKey"].asString(); secretKey_ = configJson["secretKey"].asString(); context_["header"]["app_id"] = appId_; } bool XunfeiNlpEnginePrivate::setCurrentModel(const std::string &model) { Json::Value modelInfoJson = xunfei_nlp_util::stringToJson(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { currentModel_ = model; return true; } } LOGE("Invalid current model name:", model); return false; } std::string XunfeiNlpEnginePrivate::modelInfo() const { LOGI("xunfei model info:", "xunfei"); const char *info = R"( { "vendor": "讯飞", "models": [ { "name": "讯飞-Spark Max", "model": "generalv3.5", "subConfig": [ { "name": "Spark Max", "config": [ { "friendlyName": "APPID", "configName": "appId" }, { "friendlyName": "APIKey", "configName": "apiKey" }, { "friendlyName": "APISecret", "configName": "secretKey" } ] } ], "maxTokens": 8192, "feedbackUrl": "https://console.xfyun.cn/workorder/commit" } ] } )"; return info; } void XunfeiNlpEnginePrivate::setTextGenerationResultCallback( const ai_engine::gen_ai::nlp::TextGenerationResultCallback &callback) { std::lock_guard locker(mutex_); textGenerationResultCallback_ = callback; } bool XunfeiNlpEnginePrivate::doSendData(const char *data, int dataLength, int type) { if (!isChatRunning()) { LOGI("XunfeiNlpEnginePrivate::chat: no chat is running, stop to send " "data"); return false; } size_t sent; CURLcode resultCode = curl_ws_send(currentCurl_, data, dataLength, &sent, 0, type); if (resultCode != CURLE_OK) { LOGE("send data to xunfei failed:", curl_easy_strerror(resultCode)); currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::NetworkDisconnected, curl_easy_strerror(resultCode)); return false; } return true; } CURLcode XunfeiNlpEnginePrivate::testConnectToServer() { std::string callurl = xunfei_nlp_token::getAuthenticationUrl(apiKey_, secretKey_, hostUrl_); CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, callurl.c_str()); curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */ /* Perform the request, res gets the return code */ CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); return res; } int XunfeiNlpEnginePrivate::getMaxTokens(const std::string &model) { Json::Value modelInfoJson = xunfei_nlp_util::stringToJson(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { maxTokens_ = item["maxTokens"].asInt(); return maxTokens_; } } return -1; } void XunfeiNlpEnginePrivate::clearContext() { if (context_["payload"].isMember("message")) { context_["payload"]["message"]["text"].clear(); } } void XunfeiNlpEnginePrivate::addContext(const std::string &role, const std::string &content) { if (role.empty() || content.empty()) { return; } if (role == "system") { context_["payload"]["message"]["text"][0]["role"] = role; context_["payload"]["message"]["text"][0]["content"] = content; } else { uint32_t size = context_["payload"]["message"]["text"].size(); context_["payload"]["message"]["text"][size]["role"] = role; context_["payload"]["message"]["text"][size]["content"] = content; } } ai_engine::result::AiEngineBaseResult XunfeiNlpEnginePrivate::buildChatMessage(const std::string &message) { Json::Value context = xunfei_nlp_util::stringToJson(message); ai_engine::result::AiEngineBaseResult result; if (!context.isMember("messages")) { result.success = false; result.error = {int(ai_engine::NlpEngineErrorCode::InvalidParamType), "The input information lacks messages content."}; return result; } if (!context["messages"].isArray()) { result.success = false; result.error = {int(ai_engine::NlpEngineErrorCode::InvalidParamType), "The messages is not array."}; return result; } uint32_t size = context["messages"].size(); for (uint32_t i = 0; i < size; ++i) { Json::Value item = context["messages"][i]; if ((!item.isMember("role")) || (!item["role"].isString())) { continue; } if ((!item.isMember("content")) || (!item["content"].isString())) { continue; } std::string role = item["role"].asString(); std::string content = item["content"].asString(); addContext(role, content); } if (context.isMember("top_k") && context["top_k"].isInt()) { context_["parameter"]["chat"]["top_k"] = context["top_k"].asInt(); } result.success = true; result.error = ai_engine::EngineError{}; return result; } void XunfeiNlpEnginePrivate::removeLastContext() { int size = context_["payload"]["message"]["text"].size(); if (size - 1 >= 0 && context_["payload"]["message"]["text"][size - 1]["role"].asString() == "user") { Json::Value removeValue; context_["payload"]["message"]["text"].removeIndex(size - 1, &removeValue); return; } if ((size - 1) >= 0 && (size - 2) >= 0 && context_["payload"]["message"]["text"][size - 1]["role"].asString() == "assistant" && context_["payload"]["message"]["text"][size - 2]["role"].asString() == "user") { Json::Value removeValue; context_["payload"]["message"]["text"].removeIndex(size - 1, &removeValue); context_["payload"]["message"]["text"].removeIndex(size - 2, &removeValue); return; } } ai_engine::result::AiEngineBaseResult XunfeiNlpEnginePrivate::init() { currentError_ = ai_engine::EngineError(); context_["parameter"]["chat"]["domain"] = "generalv3.5"; if (getMaxTokens(currentModel_) != -1) { context_["parameter"]["chat"]["max_tokens"] = maxTokens_; } return {true, ai_engine::EngineError()}; } ai_engine::result::AiEngineBaseResult XunfeiNlpEnginePrivate::generateContent(const std::string &input) { Json::Value inputJson = xunfei_nlp_util::stringToJson(input); if (input.empty() || inputJson.empty() || !inputJson.isMember("prompt")) { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } std::string promptContent = inputJson["prompt"].asString(); Json::Value messageJson; messageJson["messages"] = Json::Value(Json::arrayValue); Json::Value userMessage; userMessage["role"] = "user"; userMessage["content"] = promptContent; messageJson["messages"].append(userMessage); std::string message = messageJson.toStyledString(); return chat(message); } ai_engine::result::AiEngineBaseResult XunfeiNlpEnginePrivate::chat(const std::string &message) { currentError_ = ai_engine::EngineError(); { std::lock_guard locker(mutex_); if (textGenerationResultCallback_ == nullptr) { return {false, currentError_}; } } if (message.empty()) { currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::TooLittleData, "The message is empty"); return {false, currentError_}; } clearContext(); increaseChatCounter(); if (!waitForStopped()) { isStopped_ = false; } if (!isChatRunning()) { LOGI("XunfeiNlpEnginePrivate::chat: no chat is running"); return {true, currentError_}; } if (!initResources() || !connectWebsocket(hostUrl_)) { if (isStopped_) { return {true, ai_engine::EngineError()}; } decreaseChatCounter(); return {false, currentError_}; } ai_engine::result::AiEngineBaseResult result = buildChatMessage(message); if (!result.success) { return result; } std::string postString = xunfei_nlp_util::jsonToString(context_); LOGI(postString); if (!doSendData(postString.c_str(), postString.size(), CURLWS_TEXT)) { removeLastContext(); streamChatData_.clear(); closeWebsocket(); if (isStopped_) { return {true, ai_engine::EngineError()}; } decreaseChatCounter(); return {false, currentError_}; } handleReceiveData(); streamChatData_.clear(); closeWebsocket(); return {true, ai_engine::EngineError()}; } bool XunfeiNlpEnginePrivate::waitForStopped() { auto startTime = std::chrono::steady_clock::now(); while (isStopped_) { if (std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10)) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } void XunfeiNlpEnginePrivate::stopChat() { if (!isChatRunning()) { LOGI("XunfeiNlpEnginePrivate::stopChat: chat is not running"); return; } streamChatData_.clear(); decreaseChatCounter(); isStopped_ = true; ai_engine::gen_ai::nlp::TextGenerationResult result{true, currentError_, currentModelName_, std::string{R"({"result":"","is_end":true})"}}; { std::lock_guard locker(mutex_); if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } closeWebsocket(); releaseResources(); } void XunfeiNlpEnginePrivate::stopGenerateContent() { isStopped_ = true; } ai_engine::result::AiEngineBaseResult XunfeiNlpEnginePrivate::destroy() { stopChat(); return {true, ai_engine::EngineError()}; } void XunfeiNlpEnginePrivate::threadSafeCallChatResultCallback( const ai_engine::gen_ai::nlp::TextGenerationResult &result) const { std::lock_guard locker(mutex_); if (textGenerationResultCallback_ != nullptr) { textGenerationResultCallback_(result); } } void XunfeiNlpEnginePrivate::decreaseChatCounter() { if (chatCounter_ > 0) { --chatCounter_; } } void XunfeiNlpEnginePrivate::increaseChatCounter() { ++chatCounter_; } bool XunfeiNlpEnginePrivate::isChatRunning() const { return chatCounter_ > 0; } void XunfeiNlpEnginePrivate::handleReceiveData() { int retryCount = 0; while (!isStopped_) { int retCode; const std::string chatData = receiveChatData(&retCode); if (isNetworkError(retCode)) { handleNetworkError(retCode); break; } if (needReReceiveData(retCode)) { ++retryCount; if (retryCount > 1000 * 10) { auto ret = testConnectToServer(); if (ret != 0) { handleNetworkError(ret); break; } else { retryCount = 0; } } usleep(1000); continue; } if (int errorCode = xunfei_nlp_server_error::parseErrorCode(chatData); errorCode != 0) { handleServerError(errorCode, chatData); break; } if (isChatDataReady(retCode)) { bool isFinished = false; handleChatData(chatData, &isFinished); if (isFinished) { decreaseChatCounter(); break; } } retryCount = 0; usleep(1000); } if (isStopped_) { isStopped_ = false; } } std::string XunfeiNlpEnginePrivate::receiveChatData(int *retCode) const { size_t rlen; const curl_ws_frame *meta; char buffer[4100]{0}; CURLcode curlCode = curl_ws_recv(currentCurl_, buffer, sizeof(buffer), &rlen, &meta); *retCode = curlCode; return std::string(buffer, rlen); } bool XunfeiNlpEnginePrivate::isNetworkError(int retCode) const { return retCode != CURLE_OK && retCode != CURLE_AGAIN && retCode != CURLE_RECV_ERROR; } bool XunfeiNlpEnginePrivate::isChatDataReady(int retCode) const { return retCode == CURLE_OK; } bool XunfeiNlpEnginePrivate::needReReceiveData(int retCode) const { return retCode == CURLE_AGAIN || retCode == CURLE_RECV_ERROR; } void XunfeiNlpEnginePrivate::handleNetworkError(int retCode) { if (isStopped_) { isStopped_ = false; return; } LOGE("Net error:", curl_easy_strerror(CURLcode(retCode))); currentError_ = ai_engine::EngineError((int)ai_engine::NlpEngineErrorCode::NetworkDisconnected, curl_easy_strerror(CURLcode(retCode))); ai_engine::gen_ai::nlp::TextGenerationResult result{false, currentError_, currentModelName_, std::string{}}; threadSafeCallChatResultCallback(result); } void XunfeiNlpEnginePrivate::handleServerError(int errorCode, const std::string &errorMessage) { if (isStopped_) { isStopped_ = false; return; } LOGE("Xunfei chat failed", errorMessage); currentError_ = ai_engine::EngineError((int)xunfei_nlp_server_error::errorCode2nlpResult(errorCode), errorMessage); ai_engine::gen_ai::nlp::TextGenerationResult result{false, currentError_, currentModelName_, std::string{}}; threadSafeCallChatResultCallback(result); } void XunfeiNlpEnginePrivate::handleChatData(const std::string &chatData, bool *isFinished) { Json::Value obj = xunfei_nlp_util::stringToJson(chatData); Json::Value callbackObj; callbackObj["sentence_id"] = obj["payload"]["choices"]["seq"]; callbackObj["is_end"] = (obj["header"]["status"].asInt() == 2); callbackObj["result"] = obj["payload"]["choices"]["text"][0]["content"]; callbackObj["finish_reason"] = ""; streamChatData_.push_back(obj["payload"]["choices"]["text"][0]["content"]); ai_engine::gen_ai::nlp::TextGenerationResult result{ true, ai_engine::EngineError(), currentModelName_, callbackObj.toStyledString(), }; threadSafeCallChatResultCallback(result); *isFinished = (obj["header"]["status"].asInt() == 2); } bool XunfeiNlpEnginePrivate::initResources() { if (currentCurl_) { curl_easy_cleanup(currentCurl_); currentCurl_ = nullptr; } currentCurl_ = curl_easy_init(); return true; } void XunfeiNlpEnginePrivate::releaseResources() { if (currentCurl_) { curl_easy_cleanup(currentCurl_); currentCurl_ = nullptr; } } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/nlp/xunfeinlpengine_p.h000066400000000000000000000072731520575453600252320ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEINLPENGINE_P_H #define XUNFEINLPENGINE_P_H #include #include #include #include #include #include #include class XunfeiNlpEnginePrivate { public: XunfeiNlpEnginePrivate(); ~XunfeiNlpEnginePrivate(); std::string engineName() const; bool isCloud() const { return true; } bool isBuiltInEngine() const { return false; } bool isCustomModelEngine() const { return false; } void setConfig(const std::string &config); bool setCurrentModel(const std::string &model); std::string currentModel() const { return currentModel_; } std::string currentModelName() const { return currentModelName_; } std::string modelInfo() const; void setTextGenerationResultCallback(const ai_engine::gen_ai::nlp::TextGenerationResultCallback &callback); ai_engine::result::AiEngineBaseResult generateContent(const std::string &input); ai_engine::result::AiEngineBaseResult chat(const std::string &message); void stopGenerateContent(); void stopChat(); ai_engine::result::AiEngineBaseResult init(); ai_engine::result::AiEngineBaseResult destroy(); private: void threadSafeCallChatResultCallback(const ai_engine::gen_ai::nlp::TextGenerationResult &result) const; void handleReceiveData(); std::string receiveChatData(int *retCode) const; bool isNetworkError(int retCode) const; bool isChatDataReady(int retCode) const; bool needReReceiveData(int retCode) const; void handleNetworkError(int retCode); void handleServerError(int errorCode, const std::string &errorMessage); void handleChatData(const std::string &chatData, bool *isFinished); void decreaseChatCounter(); void increaseChatCounter(); bool isChatRunning() const; CURLcode testConnectToServer(); void addContext(const std::string &role, const std::string &content); ai_engine::result::AiEngineBaseResult buildChatMessage(const std::string &message); private: std::string appId_; std::string apiKey_; std::string secretKey_; std::string currentModel_{"generalv3.5"}; std::string currentModelName_{"讯飞-Spark Max"}; std::string hostUrl_{"wss://spark-api.xf-yun.com/v3.5/chat"}; int maxTokens_; mutable std::mutex mutex_; ai_engine::gen_ai::nlp::TextGenerationResultCallback textGenerationResultCallback_{nullptr}; Json::Value context_; void clearContext(); void removeLastContext(); std::vector streamChatData_; bool connectWebsocket(const std::string &hostUrl); void closeWebsocket(); CURL *currentCurl_{nullptr}; ai_engine::EngineError currentError_; bool initResources(); void releaseResources(); bool doSendData(const char *data, int dataLength, int type); int getMaxTokens(const std::string &model); bool waitForStopped(); std::atomic isStopped_{false}; std::atomic chatCounter_{0}; }; #endif // XUNFEINLPENGINE_P_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/000077500000000000000000000000001520575453600220115ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/servererror.cpp000066400000000000000000000224541520575453600251040ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map asrErrorCodeMap = {{10005, {ai_engine::EngineErrorCategory::Initialization, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10006, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooLittleParams}}, {10007, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10010, {ai_engine::EngineErrorCategory::Initialization, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10014, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::ServerNoResponse}}, {10019, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::ServerNoResponse}}, {10043, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10101, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooManyData}}, {10114, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooManyData}}, {10139, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10313, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10317, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {11200, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {11201, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooFrequentRequest}}, {10160, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10161, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10163, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10165, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooLittleParams}}, {10200, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::ServerNoResponse}}}; const std::map realtimeAsrErrorCodeMap = { {10105, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10106, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooLittleParams}}, {10107, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10110, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10700, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::NoServerService}}, {10202, {ai_engine::EngineErrorCategory::Initialization, ai_engine::SpeechEngineErrorCode::FailedToConnectServer}}, {10204, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::NoServerService}}, {10205, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::NoServerService}}, {16003, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::NoServerService}}, {10800, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooFrequentRequest}}, {37005, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooLittleData}}}; const std::map ttsErrorCodeMap = { {10005, {ai_engine::EngineErrorCategory::Initialization, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10006, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooLittleParams}}, {10007, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10010, {ai_engine::EngineErrorCategory::Initialization, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10109, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooManyData}}, {10019, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::ServerNoResponse}}, {10101, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooManyData}}, {10313, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {10317, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {11200, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::Unauthorized}}, {11201, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::TooFrequentRequest}}, {10160, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10161, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10163, {ai_engine::EngineErrorCategory::InputError, ai_engine::SpeechEngineErrorCode::InvalidParamType}}, {10200, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::ServerNoResponse}}, {10222, {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::NetworkLatencyTooLong}}}; }; // namespace int xunfei_speech_server_error::parseErrorCode(const std::string &result) { Json::Value obj = xunfei_speech_util::formatJsonFromString(result); if (!obj.isObject() || obj.isNull()) { return -1; } if (obj.isMember("code") && obj.isMember("message")) { return obj["code"].asInt(); } if (obj.isMember("code") && obj.isMember("action")) { return std::stoi(obj["code"].asString()); } return 0; } xunfei_speech_server_error::EngineErrorCode xunfei_speech_server_error::asrErrorCode2speechResult(int errorCode) { if (asrErrorCodeMap.count(errorCode) > 0) { return asrErrorCodeMap.at(errorCode); } return {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::UnsupportedScript}; } xunfei_speech_server_error::EngineErrorCode xunfei_speech_server_error::realtimeAsrErrorCode2speechResult(int errorCode) { if (realtimeAsrErrorCodeMap.count(errorCode) > 0) { return realtimeAsrErrorCodeMap.at(errorCode); } return {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::UnsupportedScript}; } xunfei_speech_server_error::EngineErrorCode xunfei_speech_server_error::ttsErrorCode2speechResult(int errorCode) { if (ttsErrorCodeMap.count(errorCode) > 0) { return ttsErrorCodeMap.at(errorCode); } return {ai_engine::EngineErrorCategory::OutputError, ai_engine::SpeechEngineErrorCode::UnsupportedScript}; } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/servererror.h000066400000000000000000000025211520575453600245420ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace xunfei_speech_server_error { int parseErrorCode(const std::string &result); struct EngineErrorCode { ai_engine::EngineErrorCategory category{ ai_engine::EngineErrorCategory::Invalid}; ai_engine::SpeechEngineErrorCode errorCode{ ai_engine::SpeechEngineErrorCode::UnsupportedScript}; }; EngineErrorCode asrErrorCode2speechResult(int errorCode); EngineErrorCode realtimeAsrErrorCode2speechResult(int errorCode); EngineErrorCode ttsErrorCode2speechResult(int errorCode); } // namespace xunfei_speech_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/util.cpp000066400000000000000000000320261520575453600234750ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "xunfei/logger.h" Json::Value xunfei_speech_util::formatJsonFromString(const std::string &stringJson) { Json::Value obj; std::string error; Json::CharReaderBuilder crbuilder; std::unique_ptr reader(crbuilder.newCharReader()); reader->parse(stringJson.c_str(), stringJson.c_str() + stringJson.size(), &obj, &error); return obj; } std::string xunfei_speech_util::base64Encode(const std::string &input) { BIO *bio, *b64; BUF_MEM *bufferPtr; b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, input.c_str(), input.length()); BIO_flush(bio); BIO_get_mem_ptr(bio, &bufferPtr); std::string result(bufferPtr->data, bufferPtr->length); BIO_free_all(bio); return result; } std::string xunfei_speech_util::base64Decode(const std::string &input) { // Base64 字符集 const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::vector decoded_data; // 解码 Base64 编码的字符串 size_t in_len = input.size(); size_t i = 0; unsigned char char_array_4[4], char_array_3[3]; int j = 0; while (in_len-- && (input[i] != '=') && (isalnum(input[i]) || (input[i] == '+') || (input[i] == '/'))) { char_array_4[j++] = static_cast(input[i]); ++i; if (j == 4) { for (j = 0; j < 4; ++j) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0x0F) << 4) + ((char_array_4[2] & 0x3C) >> 2); char_array_3[2] = ((char_array_4[2] & 0x03) << 6) + char_array_4[3]; for (j = 0; j < 3; ++j) decoded_data.push_back(char_array_3[j]); j = 0; } } if (j) { for (int k = j; k < 4; ++k) char_array_4[k] = 0; for (int k = 0; k < 4; ++k) char_array_4[k] = base64_chars.find(char_array_4[k]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0x0F) << 4) + ((char_array_4[2] & 0x3C) >> 2); char_array_3[2] = ((char_array_4[2] & 0x03) << 6) + char_array_4[3]; for (int k = 0; k < j - 1; ++k) decoded_data.push_back(char_array_3[k]); } // 转换解码后的数据为字符串 std::string decoded_string(decoded_data.begin(), decoded_data.end()); return decoded_string; } std::string xunfei_speech_util::urlEncode(const std::string &input) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto &&ch : input) { if (std::isalnum(ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~') { escaped << ch; continue; } escaped << std::uppercase; escaped << '%' << std::setw(2) << int((unsigned char)ch); escaped << std::nouppercase; } return escaped.str(); } std::unordered_map xunfei_speech_util::parseURL(const std::string &url) { std::string protocol, host, port, path, query, fragment; // 解析协议部分 size_t protocolEnd = url.find("://"); if (protocolEnd != std::string::npos) { protocol = url.substr(0, protocolEnd); } // 解析主机和端口部分 size_t hostStart = protocolEnd != std::string::npos ? protocolEnd + 3 : 0; size_t hostEnd = url.find_first_of(":/", hostStart); if (hostEnd != std::string::npos) { size_t portStart = url[hostEnd] == ':' ? hostEnd + 1 : std::string::npos; size_t portEnd = url.find("/", hostEnd); host = url.substr(hostStart, hostEnd - hostStart); port = (portStart != std::string::npos && portEnd != std::string::npos) ? url.substr(portStart, portEnd - portStart) : ""; } // 解析路径、查询字符串和片段部分 size_t pathStart = url.find("/", hostEnd); size_t queryStart = url.find("?", pathStart); size_t fragmentStart = url.find("#", queryStart); path = url.substr(pathStart, queryStart - pathStart); query = queryStart != std::string::npos ? url.substr(queryStart + 1, fragmentStart - queryStart - 1) : ""; fragment = fragmentStart != std::string::npos ? url.substr(fragmentStart + 1) : ""; std::unordered_map urlParts = { {"Protocol", protocol}, {"Host", host}, {"Port", port}, {"Path", path}, {"Query", query}, {"Fragment", fragment}}; return urlParts; } std::string xunfei_speech_util::hmacSha256Encode(const std::string &data, const std::string &key) { unsigned char digest[SHA256_DIGEST_LENGTH]; HMAC_CTX *ctx = HMAC_CTX_new(); HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha256(), NULL); HMAC_Update(ctx, reinterpret_cast(data.c_str()), data.length()); HMAC_Final(ctx, digest, NULL); HMAC_CTX_free(ctx); BIO *bio, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, digest, SHA256_DIGEST_LENGTH); BIO_flush(bio); BIO_get_mem_ptr(bio, &bptr); std::string result(bptr->data, bptr->length - 1); BIO_free_all(bio); return result; } std::string xunfei_speech_util::hmacSha1Encode(const std::string &data, const std::string &key) { unsigned char digest[SHA_DIGEST_LENGTH]; HMAC_CTX *ctx = HMAC_CTX_new(); HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha1(), NULL); HMAC_Update(ctx, reinterpret_cast(data.c_str()), data.length()); HMAC_Final(ctx, digest, NULL); HMAC_CTX_free(ctx); BIO *bio, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, digest, SHA_DIGEST_LENGTH); BIO_flush(bio); BIO_get_mem_ptr(bio, &bptr); std::string result(bptr->data, bptr->length - 1); BIO_free_all(bio); return result; } std::string xunfei_speech_util::getGmtTime() { setlocale(LC_TIME, "C"); time_t rawTime = time(0); tm *gmt = gmtime(&rawTime); const char *fmt = "%a, %d %b %Y %H:%M:%S GMT"; char tstr[30]; strftime(tstr, sizeof(tstr), fmt, gmt); return tstr; } #define NTP_PORT 123 #define NTP_TIMESTAMP_DELTA 2208988800ull // 1900-1970 年之间的秒数 #define TIME_SERVER "cn.pool.ntp.org" // 你可以换成其他国内NTP服务器 bool resolveHostname(const char *hostname, struct sockaddr_in *addr) { struct addrinfo hints{}; struct addrinfo *res{nullptr}; struct addrinfo *p{nullptr}; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; // IPv4 only if (getaddrinfo(hostname, nullptr, &hints, &res) != 0) { LOGE("DNS resolution failed!"); return false; } for (p = res; p != nullptr; p = p->ai_next) { if (p->ai_family == AF_INET) { memcpy(addr, p->ai_addr, sizeof(struct sockaddr_in)); freeaddrinfo(res); return true; } } freeaddrinfo(res); LOGE("No IPv4 address found for {}!", hostname); return false; } std::string getNtpServerGmtTime() { struct NtpPacket { uint8_t li_vn_mode; // 8 bits: LI, VN, Mode uint8_t stratum; // 8 bits: Stratum uint8_t poll; uint8_t precision; uint32_t rootDelay; uint32_t rootDispersion; uint32_t refId; uint32_t refTm_s; uint32_t refTm_f; uint32_t origTm_s; uint32_t origTm_f; uint32_t rxTm_s; uint32_t rxTm_f; uint32_t txTm_s; uint32_t txTm_f; }; struct sockaddr_in serverAddress{}; NtpPacket packet = {0}; // 设置 NTP 请求包 packet.li_vn_mode = 0x1B; // LI=0 (no warning), VN=4 (IPv4), Mode=3 (client) // 创建 UDP socket int socketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (socketFd < 0) { LOGE("Socket creation error!"); return std::string{}; } struct timeval timeout{}; timeout.tv_sec = 0; // 超时时间为 5 秒 timeout.tv_usec = 200 * 1000; if (setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) { LOGE("Failed to set timeout!"); close(socketFd); return std::string{}; } // 解析域名 if (!resolveHostname(TIME_SERVER, &serverAddress)) { close(socketFd); return std::string{}; } serverAddress.sin_port = htons(NTP_PORT); // 发送 NTP 请求 if (sendto(socketFd, (const char *)&packet, sizeof(NtpPacket), 0, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { LOGE("Send failed!"); close(socketFd); return std::string{}; } // 接收响应 socklen_t len = sizeof(serverAddress); ssize_t n = recvfrom(socketFd, &packet, sizeof(NtpPacket), 0, (struct sockaddr *)&serverAddress, &len); if (n < 0) { LOGE("Receive failed!"); close(socketFd); return std::string{}; } // 转换为 host 字节序 packet.txTm_s = ntohl(packet.txTm_s); packet.txTm_f = ntohl(packet.txTm_f); if (packet.txTm_s < NTP_TIMESTAMP_DELTA) { LOGE("Invalid NTP timestamp received:", packet.txTm_s, "(less than delta)"); close(socketFd); return std::string{}; } // 将 NTP 时间戳转换为 Unix 时间戳 time_t txTm = packet.txTm_s - NTP_TIMESTAMP_DELTA; // 添加时间戳有效性检测,最小有效时间为北京时间 2025-01-01 00:00:00 constexpr time_t minValidTimestamp = 1735660800; if (txTm < minValidTimestamp) { LOGE("Timestamp is invalid!"); return std::string{}; } return std::to_string(txTm); } std::string xunfei_speech_util::getCurrentUnixTimestamp() { std::string timestamp; for (int i = 0; i < 5; ++i) { // getNtpServerGmtTime易报错,多试几次 timestamp = getNtpServerGmtTime(); if (!timestamp.empty()) { break; } LOGW("Failed to get GMT time from NTP server, retrying..."); } if (timestamp.empty()) { timestamp = std::to_string(static_cast(time(nullptr))); LOGW("Using local Unix time for speech auth after NTP failure."); } return timestamp; } std::string xunfei_speech_util::calculateMD5(const std::string &input) { MD5_CTX context; MD5_Init(&context); MD5_Update(&context, input.c_str(), input.length()); unsigned char digest[MD5_DIGEST_LENGTH]; MD5_Final(digest, &context); char mdString[33]; for (int i = 0; i < 16; i++) sprintf(&mdString[i * 2], "%02x", (unsigned int)digest[i]); return std::string(mdString); } std::vector> xunfei_speech_util::splitData(const std::vector &audioData, size_t chunkSize) { std::vector> chunks; size_t dataSize = audioData.size(); size_t numChunks = dataSize / chunkSize; size_t remainder = dataSize % chunkSize; for (size_t i = 0; i < numChunks; ++i) { chunks.push_back( std::vector(audioData.begin() + i * chunkSize, audioData.begin() + (i + 1) * chunkSize)); } if (remainder != 0) { chunks.push_back( std::vector(audioData.end() - remainder, audioData.end())); } return chunks; } int64_t xunfei_speech_util::getTimestampMs() { struct timeval tv{}; gettimeofday(&tv, nullptr); return tv.tv_sec * 1000 + tv.tv_usec / 1000; }kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/util.h000066400000000000000000000035351520575453600231450ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include #include namespace xunfei_speech_util { inline std::string jsonToString(const Json::Value &value) { return value.toStyledString(); } inline Json::Value stringToJson(const std::string &string) { Json::Value value; if (Json::Reader reader; reader.parse(string, value)) { return value; } else { return Json::objectValue; } } Json::Value formatJsonFromString(const std::string &stringJson); std::string base64Encode(const std::string &input); std::string base64Decode(const std::string &input); std::string urlEncode(const std::string &input); std::unordered_map parseURL(const std::string &url); std::string hmacSha256Encode(const std::string &data, const std::string &key); std::string hmacSha1Encode(const std::string &data, const std::string &key); std::string getGmtTime(); std::string getCurrentUnixTimestamp(); std::string calculateMD5(const std::string &input); std::vector> splitData(const std::vector &audioData, size_t chunkSize); int64_t getTimestampMs(); } // namespace xunfei_speech_util #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/xunfeispeechengine.cpp000066400000000000000000000073221520575453600263750ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeispeechengine.h" #include "xunfeispeechengine_p.h" XunfeiSpeechEngine::XunfeiSpeechEngine() : d(new XunfeiSpeechEnginePrivate()) {} XunfeiSpeechEngine::~XunfeiSpeechEngine() { delete d; } std::string XunfeiSpeechEngine::engineName() const { return d->engineName(); } std::string XunfeiSpeechEngine::currentModel() const { return d->currentModel(); } std::string XunfeiSpeechEngine::currentModelName() const { return d->currentModelName(); } bool XunfeiSpeechEngine::isCloud() const { return d->isCloud(); } bool XunfeiSpeechEngine::isBuiltInEngine() const { return d->isBuiltInEngine(); } bool XunfeiSpeechEngine::isCustomModelEngine() const { return d->isCustomModelEngine(); } void XunfeiSpeechEngine::setConfig(const std::string &config) { d->setConfig(config); } bool XunfeiSpeechEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } std::string XunfeiSpeechEngine::modelInfo() const { return d->modelInfo(); } void XunfeiSpeechEngine::setRecognitionResultCallback( ai_engine::core_ai::speech::RecognitionResultCallback callback) { d->setRecognitionResultCallback(callback); } void XunfeiSpeechEngine::setSynthesisResultCallback( ai_engine::core_ai::speech::SynthesisResultCallback callback) { d->setSynthesisResultCallback(callback); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::initContinuousRecognitionModule() { return d->initContinuousRecognitionModule(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::startContinuousRecognition(const std::string ¶ms) { return d->startContinuousRecognition(params); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::writeContinuousRecognitionAudioData( const std::vector &audioData) { return d->writeContinuousRecognitionAudioData(audioData); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::stopContinuousRecognition() { return d->stopContinuousRecognition(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::destroyContinuousRecognitionModule() { return d->destroyContinuousRecognitionModule(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::initRecognizeOnceModule() { return d->initRecognizeOnceModule(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::recognizeOnce(const std::string ¶ms, const std::vector &audioData) { return d->recognizeOnce(params, audioData); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::destroyRecognizeOnceModule() { return d->destroyRecognizeOnceModule(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::initSynthesizeModule() { return d->initSynthesizeModule(); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::synthesizeText(const std::string ¶ms, const std::string &text) { return d->synthesizeText(params, text); } ai_engine::result::AiEngineBaseResult XunfeiSpeechEngine::destroySynthesizeModule() { return d->destroySynthesizeModule(); }kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/xunfeispeechengine.h000066400000000000000000000055351520575453600260460ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEISPEECHENGINE_H #define XUNFEISPEECHENGINE_H #include #include class XunfeiSpeechEnginePrivate; class XunfeiSpeechEngine : public ai_engine::core_ai::speech::AbstractSpeechEngine { public: XunfeiSpeechEngine(); ~XunfeiSpeechEngine() override; std::string engineName() const override; bool isCloud() const override; bool isBuiltInEngine() const override; bool isCustomModelEngine() const override; std::string currentModel() const override; std::string currentModelName() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string modelInfo() const override; void setRecognitionResultCallback( ai_engine::core_ai::speech::RecognitionResultCallback callback) override; void setSynthesisResultCallback( ai_engine::core_ai::speech::SynthesisResultCallback callback) override; // 语音识别 ai_engine::result::AiEngineBaseResult initContinuousRecognitionModule() override; ai_engine::result::AiEngineBaseResult startContinuousRecognition(const std::string ¶ms) override; ai_engine::result::AiEngineBaseResult writeContinuousRecognitionAudioData( const std::vector &audioData) override; ai_engine::result::AiEngineBaseResult stopContinuousRecognition() override; ai_engine::result::AiEngineBaseResult destroyContinuousRecognitionModule() override; ai_engine::result::AiEngineBaseResult initRecognizeOnceModule() override; ai_engine::result::AiEngineBaseResult recognizeOnce(const std::string ¶ms, const std::vector &audioData) override; ai_engine::result::AiEngineBaseResult destroyRecognizeOnceModule() override; // 语音合成 ai_engine::result::AiEngineBaseResult initSynthesizeModule() override; ai_engine::result::AiEngineBaseResult synthesizeText(const std::string ¶ms, const std::string &text) override; ai_engine::result::AiEngineBaseResult destroySynthesizeModule() override; private: XunfeiSpeechEnginePrivate *d; }; #endif // XUNFEISPEECHENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/xunfeispeechengine_p.cpp000066400000000000000000001160631520575453600267170ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeispeechengine_p.h" #include #include #include #include "xunfei/logger.h" #include "servererror.h" #include "util.h" XunfeiSpeechEnginePrivate::XunfeiSpeechEnginePrivate() { hlog_set_level(LOG_LEVEL_SILENT); } XunfeiSpeechEnginePrivate::~XunfeiSpeechEnginePrivate() {} std::string XunfeiSpeechEnginePrivate::engineName() const { return "xunfei"; } std::string XunfeiSpeechEnginePrivate::currentModel() const { return currentModel_; } std::string XunfeiSpeechEnginePrivate::currentModelName() const { return currentModelName_; } void XunfeiSpeechEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = xunfei_speech_util::formatJsonFromString(config); if (!configJson.isNull() && configJson.isMember("apiKeyRealTime") && configJson.isMember("appIdRealTime") && configJson["appIdRealTime"].isString() && configJson["apiKeyRealTime"].isString()) { appIdRealTime_ = configJson["appIdRealTime"].asString(); apiKeyRealTime_ = configJson["apiKeyRealTime"].asString(); } else { LOGE("Invalid config for xunfei realtime asr engine:", config, "."); } if (!configJson.isNull() && configJson.isMember("apiKeyContinuous") && configJson.isMember("secretKeyContinuous") && configJson.isMember("appIdContinuous") && configJson["apiKeyContinuous"].isString() && configJson["secretKeyContinuous"].isString() && configJson["appIdContinuous"].isString()) { appIdContinuous_ = configJson["appIdContinuous"].asString(); apiKeyContinuous_ = configJson["apiKeyContinuous"].asString(); secretKeyContinuous_ = configJson["secretKeyContinuous"].asString(); } else { LOGE("Invalid config for xunfei iat&tts engine:", config, "."); } } bool XunfeiSpeechEnginePrivate::setCurrentModel(const std::string &model) { Json::Value modelInfoJson = xunfei_speech_util::formatJsonFromString(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { currentModel_ = model; return true; } } LOGE("Invalid current model name:", model, "."); return false; } std::string XunfeiSpeechEnginePrivate::modelInfo() const { const char *info = R"( { "vendor": "讯飞", "models": [ { "name": "讯飞-语音大模型", "model": "讯飞-语音大模型", "subConfig": [ { "name": "语音听写&语音合成", "config": [ { "friendlyName": "APPID", "configName": "appIdContinuous" }, { "friendlyName": "APIKey", "configName": "apiKeyContinuous" }, { "friendlyName": "APISecret", "configName": "secretKeyContinuous" } ] }, { "name": "实时语音转写", "config": [ { "friendlyName": "APPID", "configName": "appIdRealTime" }, { "friendlyName": "APIKey", "configName": "apiKeyRealTime" } ] } ], "is3rdModel": true } ] } )"; return info; } void XunfeiSpeechEnginePrivate::setRecognitionResultCallback( ai_engine::core_ai::speech::RecognitionResultCallback callback) { recognitionCallback_ = callback; } void XunfeiSpeechEnginePrivate::setSynthesisResultCallback( ai_engine::core_ai::speech::SynthesisResultCallback callback) { synthesisCallback_ = callback; } void XunfeiSpeechEnginePrivate::setRecognitionParams( const std::string ¶ms) { Json::Value paramsJson = xunfei_speech_util::formatJsonFromString(params); format_ = paramsJson["format"].asString(); rate_ = paramsJson["rate"].asInt(); channel_ = paramsJson["channel"].asInt(); if (format_.empty()) { format_ = "pcm"; } if (rate_ == 0) { rate_ = 16000; } if (channel_ == 0) { channel_ = 1; } } void XunfeiSpeechEnginePrivate::setSynthesisParams(const std::string ¶ms) { Json::Value paramsJson = xunfei_speech_util::formatJsonFromString(params); if (paramsJson.isMember("speed") && paramsJson["speed"].isInt()) { speed_ = paramsJson["speed"].asInt(); } if (paramsJson.isMember("volume") && paramsJson["volume"].isInt()) { volume_ = paramsJson["volume"].asInt(); } if (paramsJson.isMember("pitch") && paramsJson["pitch"].isInt()) { pitch_ = paramsJson["pitch"].asInt(); } if (speed_ < 0 || speed_ > 100) { speed_ = 50; } if (volume_ < 0 || volume_ > 100) { volume_ = 50; } if (pitch_ < 0 || pitch_ > 100) { pitch_ = 50; } } std::string XunfeiSpeechEnginePrivate::continuousAsrBuildUrl() { const std::string ts = xunfei_speech_util::getCurrentUnixTimestamp(); if (ts.empty()) { return std::string{}; } std::string signInput = appIdRealTime_ + ts; signInput = xunfei_speech_util::calculateMD5(signInput); signInput = xunfei_speech_util::hmacSha1Encode(signInput, apiKeyRealTime_); return std::string(realtimeAsrHostUrl_) + "?" + "appid=" + appIdRealTime_ + "&ts=" + xunfei_speech_util::urlEncode(ts) + "&signa=" + xunfei_speech_util::urlEncode(signInput) + "&roleType=2"; } void XunfeiSpeechEnginePrivate::handleRecognitionResult( const Json::Value &jsonData) { RecognitionResultList resultList = getContinuousRecognitionResult(jsonData); if (recognitionCallback_) { for (const auto &result : resultList) { recognitionCallback_(result); } } } bool XunfeiSpeechEnginePrivate::isRecognizingResult( const Json::Value &jsonData) { return jsonData["cn"]["st"]["type"].asString() == "1"; } XunfeiSpeechEnginePrivate::RecognitionResultList XunfeiSpeechEnginePrivate::getContinuousRecognitionResult( const Json::Value &jsonData) { RecognitionResultList resultList; for (int k = 0; k < jsonData["cn"]["st"]["rt"].size(); k++) { for (int i = 0; i < jsonData["cn"]["st"]["rt"][k]["ws"].size(); i++) { for (int j = 0; j < jsonData["cn"]["st"]["rt"][k]["ws"][i]["cw"].size(); j++) { const std::string resultText = jsonData["cn"]["st"]["rt"][k]["ws"][i]["cw"][j]["w"] .asString(); // 该值只有角色切换时才会变化,其余时值为0。例如角色A开始说话 // rl=1,后面角色A说话rl都是0,等到角色B开始说话时,rl=2,角色 // B继续说话rl又变回0。 const std::string roleText = jsonData["cn"]["st"]["rt"][k]["ws"][i]["cw"][j]["rl"] .asString(); ai_engine::core_ai::speech::RecognitionResult result{}; result.success = true; result.error = EngineError{}; result.modelName = currentModelName_; result.text = resultText; result.speakerId = 1; if (isRecognizingResult(jsonData)) { result.reason = ai_engine::core_ai::speech:: SpeechResultReason::SpeechRecognizing; } else { result.reason = ai_engine::core_ai::speech:: SpeechResultReason::SpeechRecognized; } int role = atoi(roleText.c_str()); if (role != currentRole_ && role != 0) { result.speakerId = role; currentRole_ = role; resultList.push_back(result); continue; } if (resultList.empty()) { resultList.push_back(result); } else { resultList.back().text += resultText; } } } } return resultList; } void XunfeiSpeechEnginePrivate::handleMessage(const std::string &message) { LOGI("Continuous asr: on message", message); if (message.empty()) { return; } int code = xunfei_speech_server_error::parseErrorCode(message); if (code == -1) { // 回复消息体不完整,不是json结构 ai_engine::core_ai::speech::RecognitionResult result{}; result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Continuous asr: on message: message is incomplete."); result.modelName = currentModelName_; result.text = ""; result.speakerId = -1; result.reason = ai_engine::core_ai::speech::SpeechResultReason::SpeechErrorOccurred; if (recognitionCallback_) { recognitionCallback_(result); } } else if (code == 0) { Json::Value resultJson = xunfei_speech_util::stringToJson(message); if (resultJson.isMember("action") && resultJson["action"].isString()) { std::string action = resultJson["action"].asString(); if (action == "started") { LOGI("started"); } else if (action == "result") { Json::Value dataJson = xunfei_speech_util::formatJsonFromString( resultJson["data"].asString()); handleRecognitionResult(dataJson); } } } else { ai_engine::core_ai::speech::RecognitionResult result{}; result.success = false; int errorCode = int( xunfei_speech_server_error::realtimeAsrErrorCode2speechResult(code) .errorCode); Json::Value value = xunfei_speech_util::stringToJson(message); std::string errorMessage; if (value.isMember("desc") && value["desc"].isString()) { errorMessage = value["desc"].asString(); } // 返回10700错误码(引擎错误)时包含'超过15秒没有向服务端发送音频数据'的情况 // 会在报错信息中显示, 所以需要单独判断一下,返回正确的错误码 if (errorMessage.find("37005") != std::string::npos) { errorCode = (int)ai_engine::SpeechEngineErrorCode::TooLittleData; } result.error = EngineError(errorCode, errorMessage); result.modelName = currentModelName_; result.text = ""; result.speakerId = -1; result.reason = ai_engine::core_ai::speech::SpeechResultReason::SpeechErrorOccurred; if (recognitionCallback_) { recognitionCallback_(result); } } } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::initContinuousRecognitionModule() { ai_engine::result::AiEngineBaseResult result{false, EngineError{}}; std::atomic_bool isOpen{false}; std::atomic_bool isMessaged{false}; XunfeiWebSocketClient client{}; client.onopen = [&isOpen]() { LOGI("Init continuous asr: on open."); isOpen = true; }; client.onmessage = [&isMessaged, &result](const std::string &message) { LOGI("Init continuous asr: on message:", message, "."); // { // "action":"started", // "code":"0", // "data":"", // "desc":"success", // "sid":"rta13b4a589@dx2f5f1b49a270000100" // } int code = xunfei_speech_server_error::parseErrorCode(message); if (code == -1) { // 回复消息体不完整 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init continuous asr on message error"); } else if (code == 0) { result.success = true; } else { result.success = false; int errorCode = int( xunfei_speech_server_error::realtimeAsrErrorCode2speechResult( code) .errorCode); Json::Value value = xunfei_speech_util::stringToJson(message); std::string errorMessage; if (value.isMember("desc") && value["desc"].isString()) { errorMessage = value["desc"].asString(); } result.error = EngineError(errorCode, errorMessage); } isMessaged = true; }; client.onclose = []() { LOGI("Init continuous asr: on close."); }; client.setPingInterval(10000); std::string url = continuousAsrBuildUrl(); if (url.empty()) { // url为空,是由于时间服务器连不上,所以获取不到,报网络断开错误 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Get NTP server error."); return result; } int ret = client.open(url.c_str()); if (ret != 0) { LOGI("Init continuous asr: open failed."); result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init continuous asr: open failed."); return result; } client.setSendTimeoutSec(5); client.setRecvTimeoutSec(5); for (int i = 0; i < 50; ++i) { // 100ms usleep(100 * 1000); if (isOpen && isMessaged) { break; } } if (!result.success && result.error.getCode() == -1) { // 不成功且错误码为默认值时 result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init continuous asr: time out."); } return result; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::startContinuousRecognition( const std::string ¶ms) { std::lock_guard locker(mutex_); LOGD("Continuous asr: start."); ai_engine::result::AiEngineBaseResult result{false, EngineError{}}; setRecognitionParams(params); wssClient_.onopen = [this]() { LOGI("Continuous asr: on open."); continuousAsrOpened_ = true; }; wssClient_.onmessage = [this](const std::string &message) { handleMessage(message); }; wssClient_.onclose = [this]() { LOGI("Continuous asr: on close."); }; wssClient_.setPingInterval(10000); std::string url = continuousAsrBuildUrl(); LOGD(url); if (url.empty()) { // url为空,是由于时间服务器连不上,所以获取不到,报网络断开错误 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Get NTP server error."); return result; } continuousAsrOpened_ = false; int ret = wssClient_.open(url.c_str()); if (ret != 0) { LOGI("Continuous asr: open failed."); result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Continuous asr: open failed."); return result; } wssClient_.setSendTimeoutSec(15); wssClient_.setRecvTimeoutSec(15); // 需求要求5秒 for (int i = 0; i < 50; ++i) { // 100ms usleep(100 * 1000); if (continuousAsrOpened_) { break; } } result.success = true; continuousAsrFinished_ = false; ai_engine::core_ai::speech::RecognitionResult recognitionResult{}; recognitionResult.success = true; recognitionResult.error = {}; recognitionResult.modelName = currentModelName_; recognitionResult.text = ""; recognitionResult.speakerId = 0; recognitionResult.reason = ai_engine::core_ai::speech::SpeechResultReason:: SpeechRecognitionStarted; recognitionCallback_(recognitionResult); return result; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::writeContinuousRecognitionAudioData( const std::vector &audioData) { std::lock_guard locker(mutex_); ai_engine::result::AiEngineBaseResult result{false, EngineError{}}; if (continuousAsrFinished_) { // 主动关闭 result.success = true; return result; } if (!continuousAsrOpened_) { result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Continuous asr: wss client is not inited."); return result; } if (audioData.empty()) { result.success = false; result.error = ai_engine::EngineError( int(ai_engine::SpeechEngineErrorCode::TooLittleData), "Continuous asr: audio data is empty."); return result; } int sent = wssClient_.send(reinterpret_cast(audioData.data()), int(audioData.size()), ws_opcode::WS_OPCODE_BINARY); if (sent < 0) { LOGI("Continuous asr: send failed."); result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Continuous asr: send failed."); return result; } result.success = true; return result; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::stopContinuousRecognition() { std::lock_guard locker(mutex_); wssClient_.send(R"({"end": true})"); continuousAsrFinished_ = true; return {true, EngineError{}}; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::destroyContinuousRecognitionModule() { wssClient_.close(); return {true, EngineError{}}; } // 开始 - 一次语音识别私有函数 bool XunfeiSpeechEnginePrivate::onceAsrParamsCheck( const std::vector &audioData, EngineError &error) { if (!recognitionCallback_) { error = EngineError(int(ai_engine::SpeechEngineErrorCode::TooLittleParams), "Once Asr: callback is nullptr."); return false; } if (audioData.empty()) { // 此处不用调用回调函数通知 error = EngineError(int(ai_engine::SpeechEngineErrorCode::TooLittleData), "Once Asr: the audio data is empty."); return false; } return true; } std::string XunfeiSpeechEnginePrivate::onceAsrBuildData( const std::string ¶ms, const std::vector &audioData) { setRecognitionParams(params); Json::Value bodyJson; bodyJson["common"]["app_id"] = appIdContinuous_; bodyJson["business"]["language"] = "zh_cn"; bodyJson["business"]["domain"] = "iat"; bodyJson["business"]["accent"] = "mandarin"; bodyJson["data"]["status"] = 2; bodyJson["data"]["format"] = "audio/L16;rate=" + std::to_string(rate_); bodyJson["data"]["encoding"] = "raw"; bodyJson["data"]["audio"] = xunfei_speech_util::base64Encode( std::string(audioData.begin(), audioData.end())); return bodyJson.toStyledString(); } std::string XunfeiSpeechEnginePrivate::onceAsrBuildUrl() { auto urlData = xunfei_speech_util::parseURL(asrHostUrl_); std::string date = xunfei_speech_util::getGmtTime(); std::string originSignature; originSignature += "host: " + urlData["Host"] + "\n"; originSignature += "date: " + date + "\n"; originSignature += "GET " + urlData["Path"] + " HTTP/1.1"; std::string shaSignature = xunfei_speech_util::hmacSha256Encode( originSignature, secretKeyContinuous_); std::string authorization; authorization += R"(hmac username=")" + apiKeyContinuous_ + R"(", )"; authorization += R"(algorithm="hmac-sha256", )"; authorization += R"(headers="host date request-line", )"; authorization += R"(signature=")" + shaSignature + R"(")"; authorization = xunfei_speech_util::base64Encode(authorization); std::string url; url += std::string(asrHostUrl_); url += "?"; url += "authorization=" + xunfei_speech_util::urlEncode(authorization); url += "&"; url += "date=" + xunfei_speech_util::urlEncode(date); url += "&"; url += "host=" + urlData["Host"]; return url; } bool XunfeiSpeechEnginePrivate::onceAsrOnMessageCheck( const std::string &message) { if (int errorCode = xunfei_speech_server_error::parseErrorCode(message)) { LOGE("Once asr: xunfei recognize failed", message); int theErrorCode = int(xunfei_speech_server_error::asrErrorCode2speechResult(errorCode) .errorCode); EngineError error(theErrorCode, message); ai_engine::core_ai::speech::RecognitionResult result{ false, error, currentModelName_, {}, 0, ai_engine::core_ai::speech::SpeechResultReason:: SpeechErrorOccurred}; if (recognitionCallback_) { recognitionCallback_(result); } return false; } return true; } void XunfeiSpeechEnginePrivate::onceAsrOnMessage(const std::string &message, std::atomic_bool &isFinish) { if (!onceAsrOnMessageCheck(message)) { return; } Json::Value recognitionJson = xunfei_speech_util::formatJsonFromString(message); EngineError error{}; ai_engine::core_ai::speech::RecognitionResult result; result.success = true; result.error = error; result.modelName = currentModelName_; result.speakerId = 0; for (int i = 0; i < recognitionJson["data"]["result"]["ws"].size(); i++) { for (int j = 0; j < recognitionJson["data"]["result"]["ws"][i]["cw"].size(); j++) { result.text += recognitionJson["data"]["result"]["ws"][i]["cw"][j]["w"] .asString(); } } result.reason = ai_engine::core_ai::speech::SpeechResultReason:: SpeechRecognitionCompleted; if (recognitionCallback_) { recognitionCallback_(result); } isFinish = true; } // 结束 - 一次语音识别私有函数 ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::initRecognizeOnceModule() { ai_engine::result::AiEngineBaseResult result{false, EngineError{}}; std::atomic_bool isOpen{false}; std::atomic_bool isClose{false}; XunfeiWebSocketClient client{}; client.onopen = [&isOpen]() { LOGI("Init once asr: on open."); isOpen = true; }; client.onmessage = [](const std::string &message) { LOGI("Init once asr: on message:", message, "."); }; client.onclose = [&isClose]() { LOGI("Init once asr: on close."); isClose = true; }; client.setPingInterval(10000); std::string url = onceAsrBuildUrl(); int ret = client.open(url.c_str()); if (ret != 0) { LOGI("Init once asr: open failed."); result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init once asr: open failed."); return result; } client.setSendTimeoutSec(15); client.setRecvTimeoutSec(15); // 最多等待100次100毫秒(10秒),之后,如果还没有打开,则认为失败。 for (int i = 0; i < 100; ++i) { // 100ms usleep(100 * 1000); if (isOpen || isClose) { auto response = client.getHttpResponse(); LOGI(response->status_code, response->status_message()); // 401 缺少authorization参数 // {"message": "Unauthorized"} // 401 签名参数解析失败 // {"message": "HMAC signature cannot be verified"} // 401 签名校验失败 // {"message": "HMAC signature does not match"} // 403 时钟偏移校验失败 // {"message": "HMAC signature cannot be verified, a valid // date or x-date header is required for HMAC Authentication"} // 403 IP白名单校验失败 // {"message" : "Your IP address is not allowed"} if (response->status_code == 101) { // 说明服务端接收到请求,并把协议切换成为websocket协议 result.success = true; } else if (response->status_code == 400) { result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init once asr: NetworkDisconnected."); } else if (response->status_code == 403) { result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::SslCertificateError), "Init once asr: SslCertificateError."); } else { // TODO 先报鉴权错误,后续再进行区分 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::Unauthorized), "Init once asr: unauthorized."); } break; } } if (!result.success && result.error.getCode() == -1) { // 不成功且错误码为默认值时 result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init once asr: time out."); } return result; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::recognizeOnce( const std::string ¶ms, const std::vector &audioData) { EngineError engineError{}; if (!onceAsrParamsCheck(audioData, engineError)) { return {false, engineError}; } std::string data = onceAsrBuildData(params, audioData); std::string url = onceAsrBuildUrl(); // 开始 - libhv websocket client准备 std::atomic_bool isOpen{false}; onceAsrFinished_ = false; XunfeiWebSocketClient client{}; client.onopen = [&isOpen]() { LOGI("Once asr: on open."); isOpen = true; }; client.onmessage = [this](const std::string &message) { LOGI("Once asr: on message:", message); onceAsrOnMessage(message, onceAsrFinished_); }; client.onclose = [&isOpen, this]() { LOGI("Once asr: on close."); isOpen = true; onceAsrFinished_ = true; }; client.setPingInterval(10000); // 结束 - libhv websocket client准备 // 开始 - 发送代码 int ret = client.open(url.c_str()); if (ret != 0) { engineError = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Once asr: open failed."); return {false, engineError}; } client.setSendTimeoutSec(15); client.setRecvTimeoutSec(15); // 最多等待100次100毫秒(10秒),之后,如果还没有打开,则认为失败。 for (int i = 0; i < 100; ++i) { // 100ms usleep(100 * 1000); if (isOpen) { break; } } ret = client.send(data.data(), data.size()); if (ret == -1) { engineError = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Once asr: send failed."); return {false, engineError}; } while (!onceAsrFinished_) { usleep(100 * 1000); } client.close(); return {true, EngineError{}}; // 结束 - 发送代码 } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::destroyRecognizeOnceModule() { onceAsrFinished_ = true; return {true, EngineError{}}; } // 开始 - 一次语音合成私有函数 bool XunfeiSpeechEnginePrivate::onceTtsParamsCheck(const std::string &text, EngineError &engineError) { if (!synthesisCallback_) { engineError = EngineError(int(ai_engine::SpeechEngineErrorCode::TooLittleParams), "Once tts: callback is nullptr."); return false; } if (text.empty()) { // 此处不用调用回调函数通知 engineError = EngineError(int(ai_engine::SpeechEngineErrorCode::TooLittleData), "Once tts: text is empty."); return false; } return true; } std::string XunfeiSpeechEnginePrivate::onceTtsBuildData(const std::string ¶ms, const std::string &text) { setSynthesisParams(params); Json::Value bodyJson; bodyJson["common"]["app_id"] = appIdContinuous_; bodyJson["business"]["aue"] = "raw"; bodyJson["business"]["sfl"] = 1; bodyJson["business"]["vcn"] = "xiaoyan"; bodyJson["business"]["speed"] = speed_; bodyJson["business"]["volume"] = volume_; bodyJson["business"]["pitch"] = pitch_; bodyJson["business"]["tte"] = "UTF8"; bodyJson["data"]["status"] = 2; bodyJson["data"]["text"] = xunfei_speech_util::base64Encode(text); return bodyJson.toStyledString(); } std::string XunfeiSpeechEnginePrivate::onceTtsBuildUrl() { auto urlData = xunfei_speech_util::parseURL(ttsHostUrl_); std::string date = xunfei_speech_util::getGmtTime(); std::string originSignature; originSignature += "host: " + urlData["Host"] + "\n"; originSignature += "date: " + date + "\n"; originSignature += "GET " + urlData["Path"] + " HTTP/1.1"; std::string shaSignature = xunfei_speech_util::hmacSha256Encode( originSignature, secretKeyContinuous_); std::string authorization; authorization += R"(hmac username=")" + apiKeyContinuous_ + R"(", )"; authorization += R"(algorithm="hmac-sha256", )"; authorization += R"(headers="host date request-line", )"; authorization += R"(signature=")" + shaSignature + R"(")"; authorization = xunfei_speech_util::base64Encode(authorization); std::string url; url += std::string(ttsHostUrl_); url += "?"; url += "authorization=" + xunfei_speech_util::urlEncode(authorization); url += "&"; url += "date=" + xunfei_speech_util::urlEncode(date); url += "&"; url += "host=" + urlData["Host"]; return url; } bool XunfeiSpeechEnginePrivate::onceTtsOnMessageCheck( const std::string &message) { if (int errorCode = xunfei_speech_server_error::parseErrorCode(message)) { LOGE("Xunfei synthesize failed", message, "."); int theErrorCode = int(xunfei_speech_server_error::ttsErrorCode2speechResult(errorCode) .errorCode); EngineError error(theErrorCode, message); ai_engine::core_ai::speech::SynthesisResult result{ false, error, currentModelName_, {}, {}, {}, {}, ai_engine::core_ai::speech::SpeechResultReason:: SpeechErrorOccurred}; if (synthesisCallback_) { synthesisCallback_(result); } return false; } return true; } void XunfeiSpeechEnginePrivate::onceTtsOnMessage(const std::string &message, std::atomic_bool &isFinish) { if (!onceTtsOnMessageCheck(message)) { return; } Json::Value synthesisJson = xunfei_speech_util::formatJsonFromString(message); ai_engine::core_ai::speech::SynthesisResult result; result.success = true; result.error = EngineError{}; result.modelName = currentModelName_; result.audioFormat = "pcm"; result.audioRate = 16000; result.audioChannel = 1; result.base64AudioData = synthesisJson["data"]["audio"].asCString(); result.reason = ai_engine::core_ai::speech::SpeechResultReason::SpeechSynthesizing; if (synthesisJson["data"]["status"].asInt() == 2) { result.reason = ai_engine::core_ai::speech::SpeechResultReason:: SpeechSynthesisCompleted; isFinish = true; } if (synthesisCallback_) { synthesisCallback_(result); } } // 结束 - 一次语音合成私有函数 ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::initSynthesizeModule() { ai_engine::result::AiEngineBaseResult result{false, EngineError{}}; std::atomic_bool isOpen{false}; std::atomic_bool isClose{false}; XunfeiWebSocketClient client{}; client.onopen = [&isOpen]() { LOGI("Init once tts: on open."); isOpen = true; }; client.onmessage = [](const std::string &message) { LOGI("Init once tts: on message:", message, "."); }; client.onclose = [&isClose]() { LOGI("Init once tts: on close."); isClose = true; }; client.setPingInterval(10000); std::string url = onceTtsBuildUrl(); int ret = client.open(url.c_str()); if (ret != 0) { LOGI("Init once tts: open failed."); result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init once tts: open failed."); return result; } client.setSendTimeoutSec(15); client.setRecvTimeoutSec(15); // 最多等待100次100毫秒(10秒),之后,如果还没有打开,则认为失败。 for (int i = 0; i < 100; ++i) { // 100ms usleep(100 * 1000); if (isOpen || isClose) { auto response = client.getHttpResponse(); LOGI(response->status_code, response->status_message()); // 401 缺少authorization参数 // {"message": "Unauthorized"} // 401 签名参数解析失败 // {"message": "HMAC signature cannot be verified"} // 401 签名校验失败 // {"message": "HMAC signature does not match"} // 403 时钟偏移校验失败 // {"message": "HMAC signature cannot be verified, a valid // date or x-date header is required for HMAC Authentication"} // 403 IP白名单校验失败 // {"message" : "Your IP address is not allowed"} if (response->status_code == 101) { // 说明服务端接收到请求,并把协议切换成为websocket协议 result.success = true; } else if (response->status_code == 400) { // TODO 临时映射到SslCertificateError错误,后续完善 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::SslCertificateError), "Init once tts: SslCertificateError."); } else if (response->status_code == 403) { result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::SslCertificateError), "Init once tts: SslCertificateError."); } else { // TODO 先报鉴权错误,后续再进行区分 result.success = false; result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::Unauthorized), "Init once tts: unauthorized"); } break; } } if (!result.success && result.error.getCode() == -1) { // 不成功且错误码为默认值时 result.error = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Init once tts: time out."); } return result; } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::synthesizeText(const std::string ¶ms, const std::string &text) { EngineError engineError{}; if (!onceTtsParamsCheck(text, engineError)) { return {false, engineError}; } std::string data = onceTtsBuildData(params, text); std::string url = onceTtsBuildUrl(); // 开始 - libhv websocket client准备 std::atomic_bool isOpen{false}; std::atomic_bool isClose{false}; onceTtsFinished_ = false; XunfeiWebSocketClient client{}; client.onopen = [&isOpen]() { LOGI("Once tts: on open."); isOpen = true; }; client.onmessage = [this](const std::string &message) { // LOGI("Once tts: on message:", message, "."); onceTtsOnMessage(message, onceTtsFinished_); }; client.onclose = [&isClose, this]() { LOGI("Once tts: on close."); isClose = true; onceTtsFinished_ = true; }; client.setPingInterval(10000); // 结束 - libhv websocket client准备 ai_engine::core_ai::speech::SynthesisResult result{ true, EngineError{}, currentModelName_, {}, {}, {}, {}, ai_engine::core_ai::speech::SpeechResultReason::SpeechSynthesisStarted}; if (synthesisCallback_) { synthesisCallback_(result); } // 开始 - 发送代码 int ret = client.open(url.c_str()); LOGD("Once tts: open status:", ret); if (ret != 0) { engineError = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Once tts: open failed."); return {false, engineError}; } client.setSendTimeoutSec(15); client.setRecvTimeoutSec(15); // 等待打开后再发送数据 for (int i = 0; i < 100; ++i) { // 100ms usleep(100 * 1000); if (isOpen || isClose) { break; } } // 如果关闭了,说明打开失败 if (isClose) { HttpResponsePtr response = client.getHttpResponse(); LOGD(response->status_code, response->body); if (response != nullptr && response->status_code == 400) { engineError = EngineError( int(ai_engine::SpeechEngineErrorCode::SslCertificateError), "Once tts: open failed."); return {false, engineError}; } } ret = client.send(data); if (ret == -1) { engineError = EngineError( int(ai_engine::SpeechEngineErrorCode::NetworkDisconnected), "Once tts: send failed."); return {false, engineError}; } while (!onceTtsFinished_) { usleep(100 * 1000); } client.close(); return {true, EngineError{}}; // 结束 - 发送代码 } ai_engine::result::AiEngineBaseResult XunfeiSpeechEnginePrivate::destroySynthesizeModule() { onceTtsFinished_ = true; return {true, EngineError{}}; } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/speech/xunfeispeechengine_p.h000066400000000000000000000150331520575453600263570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEISPEECHENGINE_P_H #define XUNFEISPEECHENGINE_P_H #include #include #include #include "WebSocketClient.h" // 开始:XunfeiWebSocketClient class XunfeiWebSocketClient : public hv::WebSocketClient { public: XunfeiWebSocketClient(hv::EventLoopPtr loop = nullptr) : hv::WebSocketClient(loop) {} ~XunfeiWebSocketClient() override = default; void setConnectTimeoutSec(int sec) const { if (channel) { channel->setConnectTimeout(sec * 1000); } } void setSendTimeoutSec(int sec) const { if (channel) { channel->setWriteTimeout(sec * 1000); } } void setRecvTimeoutSec(int sec) const { if (channel) { channel->setReadTimeout(sec * 1000); } } void setCloseTimeoutSec(int sec) const { if (channel) { channel->setCloseTimeout(sec * 1000); } } private: hv::EventLoopPtr loop_{nullptr}; }; // 结束:XunfeiWebSocketClient class XunfeiSpeechEnginePrivate : public ai_engine::core_ai::speech::AbstractSpeechEngine { public: XunfeiSpeechEnginePrivate(); ~XunfeiSpeechEnginePrivate() override; std::string engineName() const override; bool isCloud() const override { return true; } bool isBuiltInEngine() const override { return false; } bool isCustomModelEngine() const override { return false; } std::string currentModel() const override; std::string currentModelName() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string modelInfo() const override; void setRecognitionResultCallback( ai_engine::core_ai::speech::RecognitionResultCallback callback) override; void setSynthesisResultCallback( ai_engine::core_ai::speech::SynthesisResultCallback callback) override; // 流式语音识别 ai_engine::result::AiEngineBaseResult initContinuousRecognitionModule() override; ai_engine::result::AiEngineBaseResult startContinuousRecognition(const std::string ¶ms) override; ai_engine::result::AiEngineBaseResult writeContinuousRecognitionAudioData( const std::vector &audioData) override; ai_engine::result::AiEngineBaseResult stopContinuousRecognition() override; ai_engine::result::AiEngineBaseResult destroyContinuousRecognitionModule() override; // 非流式语音识别 ai_engine::result::AiEngineBaseResult initRecognizeOnceModule() override; ai_engine::result::AiEngineBaseResult recognizeOnce(const std::string ¶ms, const std::vector &audioData) override; ai_engine::result::AiEngineBaseResult destroyRecognizeOnceModule() override; // 一次语音合成 ai_engine::result::AiEngineBaseResult initSynthesizeModule() override; ai_engine::result::AiEngineBaseResult synthesizeText(const std::string ¶ms, const std::string &text) override; ai_engine::result::AiEngineBaseResult destroySynthesizeModule() override; private: using EngineError = ai_engine::EngineError; void setRecognitionParams(const std::string ¶ms); void setSynthesisParams(const std::string ¶ms); // 开始 - 流式语音识别私有函数 std::string continuousAsrBuildUrl(); void handleRecognitionResult(const Json::Value &jsonData); bool isRecognizingResult(const Json::Value &jsonData); using RecognitionResultList = std::vector; RecognitionResultList getContinuousRecognitionResult(const Json::Value &jsonData); void handleMessage(const std::string &message); // 结束 - 流式语音识别私有函数 // 开始 - 一次语音识别私有函数 bool onceAsrParamsCheck(const std::vector &audioData, EngineError &error); std::string onceAsrBuildData(const std::string ¶ms, const std::vector &audioData); std::string onceAsrBuildUrl(); bool onceAsrOnMessageCheck(const std::string &message); void onceAsrOnMessage(const std::string &message, std::atomic_bool &isFinish); // 结束 - 一次语音识别私有函数 // 开始 - 一次语音合成私有函数 bool onceTtsParamsCheck(const std::string &text, EngineError &error); std::string onceTtsBuildData(const std::string ¶ms, const std::string &text); std::string onceTtsBuildUrl(); bool onceTtsOnMessageCheck(const std::string &message); void onceTtsOnMessage(const std::string &message, std::atomic_bool &isFinish); // 结束 - 一次语音合成私有函数 private: std::string realtimeAsrHostUrl_{"wss://rtasr.xfyun.cn/v1/ws"}; std::string asrHostUrl_{"wss://iat-api.xfyun.cn/v2/iat"}; std::string ttsHostUrl_{"wss://tts-api.xfyun.cn/v2/tts"}; std::string apiKeyRealTime_; std::string appIdRealTime_; std::string apiKeyContinuous_; std::string secretKeyContinuous_; std::string appIdContinuous_; std::string currentModel_{"讯飞-语音大模型"}; std::string currentModelName_{"讯飞-语音大模型"}; ai_engine::core_ai::speech::RecognitionResultCallback recognitionCallback_; ai_engine::core_ai::speech::SynthesisResultCallback synthesisCallback_; std::string format_; int rate_{16000}; int channel_{1}; int speed_{50}; int volume_{50}; int pitch_{50}; // 流式语音识别私有变量 int currentRole_{1}; std::atomic_bool continuousAsrOpened_{false}; std::atomic_bool continuousAsrFinished_{false}; XunfeiWebSocketClient wssClient_{}; std::mutex mutex_; std::atomic_bool onceAsrFinished_{false}; std::atomic_bool onceTtsFinished_{false}; }; #endif kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/000077500000000000000000000000001520575453600220515ustar00rootroot00000000000000kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/imageloader.cpp000066400000000000000000000034521520575453600250320ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "imageloader.h" #include #include #include "cpr/api.h" #include "cpr/callback.h" const std::map formatToString = { {FIF_UNKNOWN, "unknown"}, {FIF_JPEG, "jpeg"}, {FIF_PNG, "png"}, {FIF_WEBP, "webp"}}; vision::image_loader::ImageBaseInfo vision::image_loader::getImageInfoFromData(unsigned char *data, unsigned int length) { FIMEMORY *memory = FreeImage_OpenMemory(data, length); FREE_IMAGE_FORMAT format = FreeImage_GetFileTypeFromMemory(memory); FIBITMAP *bits = FreeImage_LoadFromMemory(format, memory); int width = FreeImage_GetWidth(bits); int height = FreeImage_GetHeight(bits); FreeImage_CloseMemory(memory); return image_loader::ImageBaseInfo{freeImageFormatToString(format), width, height}; } std::string vision::image_loader::freeImageFormatToString(FREE_IMAGE_FORMAT format) { auto it = formatToString.find(format); if (it != formatToString.end()) { return it->second; } else { return "unknown"; } } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/imageloader.h000066400000000000000000000021711520575453600244740ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef IMAGELOADER_H #define IMAGELOADER_H #include #include #include namespace vision { namespace image_loader { struct ImageBaseInfo { std::string format; int width; int height; }; ImageBaseInfo getImageInfoFromData(unsigned char *data, unsigned int length); std::string freeImageFormatToString(FREE_IMAGE_FORMAT format); } // namespace image_loader } // namespace vision #endif // IMAGELOADER_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/servererror.cpp000066400000000000000000000052611520575453600251410ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "servererror.h" #include "util.h" namespace { const std::map> visionPrompt2ImageErrorCodeMap = { {10003, {ai_engine::EngineErrorCategory::InputError, ai_engine::VisionEngineErrorCode::InvalidParamType}}, {10004, {ai_engine::EngineErrorCategory::InputError, ai_engine::VisionEngineErrorCode::InvalidParamType}}, {10005, {ai_engine::EngineErrorCategory::InputError, ai_engine::VisionEngineErrorCode::InvalidParamType}}, {10008, {ai_engine::EngineErrorCategory::InputError, ai_engine::VisionEngineErrorCode::TooManyRequest}}, {10110, {ai_engine::EngineErrorCategory::OutputError, ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}}, {10021, {ai_engine::EngineErrorCategory::InputError, ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}}, {10022, {ai_engine::EngineErrorCategory::OutputError, ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}}, {11202, {ai_engine::EngineErrorCategory::OutputError, ai_engine::VisionEngineErrorCode::TooFrequentRequest}} }; }; int xunfei_vision_server_error::parseErrorCode(const std::string &result) { Json::Value obj = xunfei_vision_util::formatJsonFromString(result); if (!obj.isObject() || obj.isNull()) { return 0; } if (obj.isMember("header") && obj["header"].isMember("code") && obj["header"].isMember("message")) { return obj["header"]["code"].asInt(); } return 0; } std::tuple xunfei_vision_server_error::errorCode2visionResult(int errorCode) { if (visionPrompt2ImageErrorCodeMap.count(errorCode) > 0) { return visionPrompt2ImageErrorCodeMap.at(errorCode); } return std::make_tuple( ai_engine::EngineErrorCategory::OutputError, ai_engine::VisionEngineErrorCode::ImageGenerationFailed); } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/servererror.h000066400000000000000000000020551520575453600246040ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVERERROR_H #define SERVERERROR_H #include #include namespace xunfei_vision_server_error { int parseErrorCode(const std::string &result); std::tuple errorCode2visionResult(int errorCode); } // namespace xunfei_vision_server_error #endif kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/token.cpp000066400000000000000000000037711520575453600237050ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "token.h" #include #include "cpr/api.h" #include "util.h" std::string xunfei_vision_token::getAuthenticationUrl(const std::string &apiKey, const std::string &secretKey, const std::string &hostUrl) { auto urlData = xunfei_vision_util::parseURL(hostUrl); std::string date = xunfei_vision_util::getGmtTime(); std::string originSignature{"host: " + urlData["Host"] + "\n" + "date: " + date + "\n" + "POST " + urlData["Path"] + " HTTP/1.1"}; std::string shaSignature = xunfei_vision_util::hmacSha256Encode(originSignature, secretKey); std::string authorization = "api_key=\"" + apiKey + "\", algorithm=\"hmac-sha256\", headers=\"host " "date request-line\", signature=\"" + shaSignature + "\""; authorization = xunfei_vision_util::base64Encode(authorization); std::string callurl = hostUrl + "?" + "authorization=" + xunfei_vision_util::urlEncode(authorization) + "&date=" + xunfei_vision_util::urlEncode(date) + "&host=" + urlData["Host"]; return callurl; }kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/token.h000066400000000000000000000017711520575453600233500ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef TOKEN_H #define TOKEN_H #include #include namespace xunfei_vision_token { std::string getAuthenticationUrl(const std::string &apiKey, const std::string &secretKey, const std::string &hostUrl); } #endif // TOKEN_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/util.cpp000066400000000000000000000252421520575453600235370ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "util.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "xunfei/logger.h" namespace { constexpr uint16_t NTP_PORT = 123; constexpr time_t NTP_TIMESTAMP_DELTA = 2208988800ull; // 1900-1970 年之间的秒数 constexpr const char *TIME_SERVER = "cn.pool.ntp.org"; // 你可以换成其他国内NTP服务器 bool resolveHostname(const char *hostname, struct sockaddr_in *addr) { struct addrinfo hints{}; struct addrinfo *res{nullptr}; struct addrinfo *p{nullptr}; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; // IPv4 only if (getaddrinfo(hostname, nullptr, &hints, &res) != 0) { LOGE("DNS resolution failed!"); return false; } for (p = res; p != nullptr; p = p->ai_next) { if (p->ai_family == AF_INET) { memcpy(addr, p->ai_addr, sizeof(struct sockaddr_in)); freeaddrinfo(res); return true; } } freeaddrinfo(res); LOGE("No IPv4 address found for {}!", hostname); return false; } std::string getNtpServerGmtTime() { struct NtpPacket { uint8_t li_vn_mode; // 8 bits: LI, VN, Mode uint8_t stratum; // 8 bits: Stratum uint8_t poll; uint8_t precision; uint32_t rootDelay; uint32_t rootDispersion; uint32_t refId; uint32_t refTm_s; uint32_t refTm_f; uint32_t origTm_s; uint32_t origTm_f; uint32_t rxTm_s; uint32_t rxTm_f; uint32_t txTm_s; uint32_t txTm_f; }; int socketFd; struct sockaddr_in serverAddress{}; NtpPacket packet = {0}; // 设置 NTP 请求包 packet.li_vn_mode = 0x1B; // LI=0 (no warning), VN=4 (IPv4), Mode=3 (client) // 创建 UDP socket socketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (socketFd < 0) { LOGE("Socket creation error!"); return ""; } struct timeval timeout{}; timeout.tv_sec = 0; timeout.tv_usec = 200 * 1000; if (setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) { LOGE("Failed to set timeout!"); close(socketFd); return ""; } // 解析域名 if (!resolveHostname(TIME_SERVER, &serverAddress)) { close(socketFd); return ""; } serverAddress.sin_port = htons(NTP_PORT); // 发送 NTP 请求 if (sendto(socketFd, (const char *)&packet, sizeof(NtpPacket), 0, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { LOGE("Send failed!"); close(socketFd); return ""; } // 接收响应 socklen_t len = sizeof(serverAddress); ssize_t n = recvfrom(socketFd, &packet, sizeof(NtpPacket), 0, (struct sockaddr *)&serverAddress, &len); if (n < 0) { LOGE("Receive failed!"); close(socketFd); return ""; } // 转换为 host 字节序 packet.txTm_s = ntohl(packet.txTm_s); packet.txTm_f = ntohl(packet.txTm_f); // 将 NTP 时间戳转换为 Unix 时间戳 time_t txTm = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA); struct tm *gmt = gmtime(&txTm); // UTC 时间 char buffer[80]; strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S GMT", gmt); LOGI("GMT time: ", std::string(buffer)); close(socketFd); return buffer; } std::string getLocalGmtTime() { setlocale(LC_TIME, "C"); time_t rawTime = time(0); tm *gmt = gmtime(&rawTime); const char *fmt = "%a, %d %b %Y %H:%M:%S GMT"; char tstr[30]; strftime(tstr, sizeof(tstr), fmt, gmt); return tstr; } } // namespace Json::Value xunfei_vision_util::formatJsonFromString(const std::string &stringJson) { Json::Value obj; std::string error; Json::CharReaderBuilder crbuilder; std::unique_ptr reader(crbuilder.newCharReader()); reader->parse(stringJson.c_str(), stringJson.c_str() + stringJson.size(), &obj, &error); return obj; } std::string xunfei_vision_util::base64Encode(const std::string &input) { BIO *bio, *b64; BUF_MEM *bufferPtr; b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, input.c_str(), input.length()); BIO_flush(bio); BIO_get_mem_ptr(bio, &bufferPtr); std::string result(bufferPtr->data, bufferPtr->length); BIO_free_all(bio); return result; } std::string xunfei_vision_util::base64Decode(const std::string &input) { // Base64 字符集 const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::vector decoded_data; // 解码 Base64 编码的字符串 size_t in_len = input.size(); size_t i = 0; unsigned char char_array_4[4], char_array_3[3]; int j = 0; while (in_len-- && (input[i] != '=') && (isalnum(input[i]) || (input[i] == '+') || (input[i] == '/'))) { char_array_4[j++] = static_cast(input[i]); ++i; if (j == 4) { for (j = 0; j < 4; ++j) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0x0F) << 4) + ((char_array_4[2] & 0x3C) >> 2); char_array_3[2] = ((char_array_4[2] & 0x03) << 6) + char_array_4[3]; for (j = 0; j < 3; ++j) decoded_data.push_back(char_array_3[j]); j = 0; } } if (j) { for (int k = j; k < 4; ++k) char_array_4[k] = 0; for (int k = 0; k < 4; ++k) char_array_4[k] = base64_chars.find(char_array_4[k]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0x0F) << 4) + ((char_array_4[2] & 0x3C) >> 2); char_array_3[2] = ((char_array_4[2] & 0x03) << 6) + char_array_4[3]; for (int k = 0; k < j - 1; ++k) decoded_data.push_back(char_array_3[k]); } // 转换解码后的数据为字符串 std::string decoded_string(decoded_data.begin(), decoded_data.end()); return decoded_string; } std::string xunfei_vision_util::urlEncode(const std::string &input) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; for (auto &&ch : input) { if (std::isalnum(ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~') { escaped << ch; continue; } escaped << std::uppercase; escaped << '%' << std::setw(2) << int((unsigned char)ch); escaped << std::nouppercase; } return escaped.str(); } std::unordered_map xunfei_vision_util::parseURL(const std::string &url) { std::string protocol, host, port, path, query, fragment; // 解析协议部分 size_t protocolEnd = url.find("://"); if (protocolEnd != std::string::npos) { protocol = url.substr(0, protocolEnd); } // 解析主机和端口部分 size_t hostStart = protocolEnd != std::string::npos ? protocolEnd + 3 : 0; size_t hostEnd = url.find_first_of(":/", hostStart); if (hostEnd != std::string::npos) { size_t portStart = url[hostEnd] == ':' ? hostEnd + 1 : std::string::npos; size_t portEnd = url.find("/", hostEnd); host = url.substr(hostStart, hostEnd - hostStart); port = (portStart != std::string::npos && portEnd != std::string::npos) ? url.substr(portStart, portEnd - portStart) : ""; } // 解析路径、查询字符串和片段部分 size_t pathStart = url.find("/", hostEnd); size_t queryStart = url.find("?", pathStart); size_t fragmentStart = url.find("#", queryStart); path = url.substr(pathStart, queryStart - pathStart); query = queryStart != std::string::npos ? url.substr(queryStart + 1, fragmentStart - queryStart - 1) : ""; fragment = fragmentStart != std::string::npos ? url.substr(fragmentStart + 1) : ""; std::unordered_map urlParts = { {"Protocol", protocol}, {"Host", host}, {"Port", port}, {"Path", path}, {"Query", query}, {"Fragment", fragment}}; return urlParts; } std::string xunfei_vision_util::hmacSha256Encode(const std::string &data, const std::string &key) { unsigned char digest[SHA256_DIGEST_LENGTH]; HMAC_CTX *ctx = HMAC_CTX_new(); HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha256(), NULL); HMAC_Update(ctx, reinterpret_cast(data.c_str()), data.length()); HMAC_Final(ctx, digest, NULL); HMAC_CTX_free(ctx); BIO *bio, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); bio = BIO_new(BIO_s_mem()); bio = BIO_push(b64, bio); BIO_write(bio, digest, SHA256_DIGEST_LENGTH); BIO_flush(bio); BIO_get_mem_ptr(bio, &bptr); std::string result(bptr->data, bptr->length - 1); BIO_free_all(bio); return result; } std::string xunfei_vision_util::getGmtTime() { std::string gmtTime; for (int i = 0; i < 5; ++i) { gmtTime = getNtpServerGmtTime(); if (!gmtTime.empty()) { // 获取成功,退出循环 break; } // 获取失败,等待并重试 LOGW("Failed to get GMT time from NTP server, retrying..."); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (gmtTime.empty()) { return getLocalGmtTime(); } return gmtTime; } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/util.h000066400000000000000000000025021520575453600231760ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTIL_H #define UTIL_H #include #include namespace xunfei_vision_util { Json::Value formatJsonFromString(const std::string &stringJson); std::string base64Encode(const std::string &input); std::string base64Decode(const std::string &input); std::string urlEncode(const std::string &input); std::unordered_map parseURL(const std::string &url); std::string hmacSha256Encode(const std::string &data, const std::string &key); std::string hmacSha1Encode(const std::string &data, const std::string &key); std::string getGmtTime(); } // namespace xunfei_vision_util #endif // UTIL_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/xunfeivisionengine.cpp000066400000000000000000000055301520575453600264740ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeivisionengine.h" #include "xunfeivisionengine_p.h" XunfeiVisionEngine::XunfeiVisionEngine() : d(new XunfeiVisionEnginePrivate()) {} XunfeiVisionEngine::~XunfeiVisionEngine() { delete d; } std::string XunfeiVisionEngine::engineName() const { return d->engineName(); } std::string XunfeiVisionEngine::currentModel() const { return d->currentModel(); } std::string XunfeiVisionEngine::currentModelName() const { return d->currentModelName(); } bool XunfeiVisionEngine::isCloud() const { return d->isCloud(); } bool XunfeiVisionEngine::isBuiltInEngine() const { return d->isBuiltInEngine(); } bool XunfeiVisionEngine::isCustomModelEngine() const { return d->isCustomModelEngine(); } void XunfeiVisionEngine::setConfig(const std::string &config) { d->setConfig(config); } bool XunfeiVisionEngine::setCurrentModel(const std::string &model) { return d->setCurrentModel(model); } std::string XunfeiVisionEngine::modelInfo() const { return d->modelInfo(); } void XunfeiVisionEngine::setGenerationResultCallback( ai_engine::gen_ai::vision::ImageGenerationCallback callback) { d->setGenerationResultCallback(callback); } ai_engine::result::AiEngineBaseResult XunfeiVisionEngine::init() { return d->init(); } ai_engine::result::AiEngineBaseResult XunfeiVisionEngine::destroy() { return d->destroy(); } void XunfeiVisionEngine::setImageSize(int width, int height) { d->setImageSize(width, height); } void XunfeiVisionEngine::setImageNumber(int number) { d->setImageNumber(number); } void XunfeiVisionEngine::setImageStyle(const std::string &style) { d->setImageStyle(style); } std::vector XunfeiVisionEngine::supportedImageStyles() const { return d->supportedImageStyles(); } int XunfeiVisionEngine::supportedImageNumber() const { return d->supportedImageNumber(); } std::vector> XunfeiVisionEngine::supportedImageSizes() const { return d->supportedImageSizes(); } ai_engine::result::AiEngineBaseResult XunfeiVisionEngine::generateImage(const std::string &prompt) { return d->generateImage(prompt); } void XunfeiVisionEngine::stopImageGeneration() { return d->stopImageGeneration(); } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/xunfeivisionengine.h000066400000000000000000000042761520575453600261470ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEIVISIONENGINE_H #define XUNFEIVISIONENGINE_H #include class XunfeiVisionEnginePrivate; class XunfeiVisionEngine : public ai_engine::gen_ai::vision::AbstractImageGenerationEngine { public: XunfeiVisionEngine(); ~XunfeiVisionEngine() override; std::string engineName() const override; std::string currentModel() const override; std::string currentModelName() const override; bool isCloud() const override; bool isBuiltInEngine() const override; bool isCustomModelEngine() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string modelInfo() const override; void setGenerationResultCallback( ai_engine::gen_ai::vision::ImageGenerationCallback) override; ai_engine::result::AiEngineBaseResult init() override; ai_engine::result::AiEngineBaseResult destroy() override; void setImageSize(int width, int height) override; void setImageNumber(int number) override; void setImageStyle(const std::string &style) override; std::vector supportedImageStyles() const override; int supportedImageNumber() const override; std::vector> supportedImageSizes() const override; ai_engine::result::AiEngineBaseResult generateImage(const std::string &prompt) override; void stopImageGeneration() override; private: XunfeiVisionEnginePrivate *d; }; #endif // XUNFEIVISIONENGINE_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/xunfeivisionengine_p.cpp000066400000000000000000000343261520575453600270200ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeivisionengine_p.h" #include #include #include "imageloader.h" #include "servererror.h" #include "token.h" #include "util.h" namespace { std::map imageStyleMap = { {0, "探索无限"}, {1, "古风"}, {2, "二次元"}, {3, "写实风格"}, {4, "浮世绘"}, {5, "low poly"}, {6, "未来主义"}, {7, "像素风格"}, {8, "概念艺术"}, {9, "赛博朋克"}, {10, "洛丽塔风格"}, {11, "巴洛克风格"}, {12, "超现实主义"}, {13, "水彩画"}, {14, "蒸汽波艺术"}, {15, "油画"}, {16, "卡通画"}, }; } XunfeiVisionEnginePrivate::XunfeiVisionEnginePrivate() {} XunfeiVisionEnginePrivate::~XunfeiVisionEnginePrivate() {} std::string XunfeiVisionEnginePrivate::engineName() const { return std::string("xunfei"); } std::string XunfeiVisionEnginePrivate::currentModel() const { return currentModel_; } std::string XunfeiVisionEnginePrivate::currentModelName() const { return currentModelName_; } bool XunfeiVisionEnginePrivate::setCurrentModel(const std::string &model) { Json::Value modelInfoJson = xunfei_vision_util::formatJsonFromString(modelInfo()); for (auto &item : modelInfoJson["models"]) { if (item["model"].asString() == model) { currentModel_ = model; return true; } } fprintf(stderr, "Invalid current model name: %s\n", model.c_str()); return false; } void XunfeiVisionEnginePrivate::setConfig(const std::string &config) { Json::Value configJson = xunfei_vision_util::formatJsonFromString(config); if (configJson.isNull() || !configJson.isMember("apiKey") || !configJson.isMember("secretKey") || !configJson.isMember("appId") || !configJson["apiKey"].isString() || !configJson["secretKey"].isString() || !configJson["appId"].isString()) { std::fprintf(stderr, "Invalid config for xunfei vision engine: %s\n", config.c_str()); return; } appId_ = configJson["appId"].asString(); apiKey_ = configJson["apiKey"].asString(); secretKey_ = configJson["secretKey"].asString(); } std::string XunfeiVisionEnginePrivate::modelInfo() const { const char *info = R"( { "vendor": "讯飞", "models": [ { "name": "讯飞-图片生成", "model": "讯飞-图片生成", "subConfig": [ { "name": "图片生成", "config": [ { "friendlyName": "APPID", "configName": "appId" }, { "friendlyName": "APIKey", "configName": "apiKey" }, { "friendlyName": "APISecret", "configName": "secretKey" } ] } ], "is3rdModel": true, "feedbackUrl": "https://console.xfyun.cn/workorder/commit" } ] } )"; return info; } void XunfeiVisionEnginePrivate::setGenerationResultCallback( ai_engine::gen_ai::vision::ImageGenerationCallback callback) { imageGenerationResultCallback_ = callback; } void XunfeiVisionEnginePrivate::setImageSize(int width, int height) { auto isSupportedSize = [this](const int inputWidth, const int inputHeight) -> bool { for (const auto &item : supportedImageSizes()) { if (item.first == inputWidth && item.second == inputHeight) { return true; } } return false; }; if (width <= 0 || height <= 0 || !isSupportedSize(width, height)) { currentError_ = ai_engine::EngineError( static_cast( ai_engine::VisionEngineErrorCode::ImageSizeInvalid), "Unsupported size of images"); imageWidth_ = -1; imageHeight_ = -1; return; } imageWidth_ = width; imageHeight_ = height; } void XunfeiVisionEnginePrivate::setImageNumber(int number) { if (number > supportedImageNumber() || number <= 0) { currentError_ = ai_engine::EngineError( static_cast( ai_engine::VisionEngineErrorCode::ImageNumberInvalid), "Unsupported number of images"); imageNumber_ = -1; return; } imageNumber_ = number; } void XunfeiVisionEnginePrivate::setImageStyle(const std::string &style) { imageStyle_ = style; } std::vector XunfeiVisionEnginePrivate::supportedImageStyles() const { return {"探索无限", "古风", "二次元", "写实风格", "浮世绘", "low poly", "未来主义", "像素风格", "概念艺术", "赛博朋克", "洛丽塔风格", "巴洛克风格", "超现实主义", "水彩画", "蒸汽波艺术", "油画", "卡通画"}; } int XunfeiVisionEnginePrivate::supportedImageNumber() const { return 1; } std::vector> XunfeiVisionEnginePrivate::supportedImageSizes() const { std::vector> result{ {512, 512}, {640, 360}, {640, 480}, {640, 640}, {680, 512}, {512, 680}, {768, 768}, {720, 1280}, {1280, 720}, {1024, 1024}}; return result; } void XunfeiVisionEnginePrivate::decreaseGenerationCounter() { if (generationCounter_ > 0) { --generationCounter_; } } void XunfeiVisionEnginePrivate::increaseGenerationCounter() { ++generationCounter_; } bool XunfeiVisionEnginePrivate::isGenerating() const { return generationCounter_ > 0; } void XunfeiVisionEnginePrivate::stopImageGeneration() { printf("XunfeiVisionEnginePrivate::stopImageGeneration\n"); if (!isGenerating()) { printf( "XunfeiVisionEnginePrivate::stopImageGeneration: imageGeneration " "is not running\n"); return; } decreaseGenerationCounter(); isStopped_ = true; ai_engine::gen_ai::vision::ImageGenerationResult data{ true, ai_engine::EngineError{}, currentModelName_, 0, 0, 1, 1, "", ""}; imageGenerationResultCallback_(data); } bool writePrompt2ImageResult(std::string data, intptr_t userData) { XunfeiVisionEnginePrivate *self = (XunfeiVisionEnginePrivate *)userData; if (self->isStopped_) { return false; } std::string resultString = self->incompleteResult_.data() + data; Json::Value resultJson = xunfei_vision_util::formatJsonFromString(resultString); if (resultJson.isNull() || !resultJson.isObject()) { self->incompleteResult_ += data; return true; } if (int errorCode = xunfei_vision_server_error::parseErrorCode(data)) { fprintf(stderr, "xunfei text2image failed: %s\n", data.c_str()); auto errorTuple = xunfei_vision_server_error::errorCode2visionResult(errorCode); self->currentError_ = ai_engine::EngineError((int)std::get<1>(errorTuple), data); self->runCallbackWithError(self->currentError_, self->imageNumber_, self->imageNumber_); self->isCallbackCalled_ = true; return false; } if (resultJson.isMember("message")) { self->currentError_ = ai_engine::EngineError( (int)ai_engine::VisionEngineErrorCode::Unauthorized, resultJson["message"].asString()); fprintf(stderr, "xunfei authentication failed: %s\n", resultJson["message"].asString().c_str()); return false; } if (resultString.substr(resultString.length() - 3) != "}}}") { self->incompleteResult_ += data; self->currentError_ = ai_engine::EngineError( (int)ai_engine::VisionEngineErrorCode::ImageGenerationFailed, "Incomplete image data"); return true; } self->incompleteResult_.clear(); ai_engine::gen_ai::vision::ImageGenerationResult imageData; for (int i = 0; i < resultJson["payload"]["choices"]["text"].size(); i++) { auto imageDataString = xunfei_vision_util::base64Decode( resultJson["payload"]["choices"]["text"][i]["content"].asString()); auto imageInfo = vision::image_loader::getImageInfoFromData( reinterpret_cast(imageDataString.data()), imageDataString.size()); ai_engine::EngineError error; imageData.success = true; imageData.error = error; imageData.modelName = self->currentModelName_; imageData.width = imageInfo.width; imageData.height = imageInfo.height; imageData.index = i; imageData.total = resultJson["payload"]["choices"]["text"].size(); imageData.format = imageInfo.format; imageData.imageBase64Data = xunfei_vision_util::base64Encode(imageDataString); } self->imageGenerationResultCallback_(imageData); self->currentError_ = ai_engine::EngineError(); return true; } ai_engine::result::AiEngineBaseResult XunfeiVisionEnginePrivate::generateImage(const std::string &prompt) { printf("XunfeiVisionEnginePrivate::generateImage\n"); incompleteResult_.clear(); isCallbackCalled_ = false; if (!imageGenerationResultCallback_) { return {false, currentError_}; } if (imageNumber_ == -1 || imageHeight_ == -1 || imageWidth_ == -1) { return {false, currentError_}; } if (prompt.empty()) { currentError_ = ai_engine::EngineError( (int)ai_engine::VisionEngineErrorCode::TooLittleData, "The prompt is empty"); return {false, currentError_}; } increaseGenerationCounter(); if (!waitForStopped()) { isStopped_ = false; } if (!isGenerating()) { printf("XunfeiVisionEnginePrivate::generateImage: no generation is " "running\n"); return {true, ai_engine::EngineError{}}; } Json::Value bodyJson; bodyJson["header"]["app_id"] = appId_; bodyJson["parameter"]["chat"]["domain"] = "general"; bodyJson["parameter"]["chat"]["width"] = imageWidth_; bodyJson["parameter"]["chat"]["height"] = imageHeight_; bodyJson["payload"]["message"]["text"][0]["role"] = "user"; if (imageStyle_.empty()) { bodyJson["payload"]["message"]["text"][0]["content"] = std::string(prompt); } else if (imageStyle_ == "low poly") { bodyJson["payload"]["message"]["text"][0]["content"] = std::string(prompt) + "," + "低多边形"; } else { bodyJson["payload"]["message"]["text"][0]["content"] = std::string(prompt) + "," + imageStyle_; } std::string bodyString = bodyJson.toStyledString(); cpr::Url url{xunfei_vision_token::getAuthenticationUrl(apiKey_, secretKey_, hostUrl_)}; cpr::Header header{cpr::Header{{"Content-Type", "application/json"}, {"charset", "UTF-8"}}}; cpr::Body body{cpr::Body{{bodyString}}}; cpr::LowSpeed lowSpeed{1, 10}; cpr::Response response = cpr::Post(url, header, body, lowSpeed, cpr::ConnectTimeout{10000}, cpr::WriteCallback{writePrompt2ImageResult, (intptr_t)this}); return processPrompt2ImageResult(response); } bool XunfeiVisionEnginePrivate::waitForStopped() { auto startTime = std::chrono::steady_clock::now(); while (isStopped_) { if (std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10)) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } ai_engine::result::AiEngineBaseResult XunfeiVisionEnginePrivate::processPrompt2ImageResult(cpr::Response &response) { if (isStopped_ || isCallbackCalled_) { isStopped_ = false; isCallbackCalled_ = false; return {true, ai_engine::EngineError{}}; } decreaseGenerationCounter(); if (response.error.code == cpr::ErrorCode::REQUEST_CANCELLED || !currentStatus()) { return {false, currentError_}; } if (response.error) { if (response.error.code == cpr::ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR) { currentError_ = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::SslCertificateError), response.error.message); } else { currentError_ = ai_engine::EngineError( int(ai_engine::NlpEngineErrorCode::NetworkDisconnected), response.error.message); } return {false, currentError_}; } return {true, ai_engine::EngineError{}}; } void XunfeiVisionEnginePrivate::runCallbackWithError( const ai_engine::EngineError &error, const int &index, const int &total) { int errorValue = 0; if (index == total) { for (int i = 0; i < total; i++) { ai_engine::gen_ai::vision::ImageGenerationResult data{ false, error, currentModelName_, errorValue, errorValue, i, total, "", ""}; imageGenerationResultCallback_(data); } } else { ai_engine::gen_ai::vision::ImageGenerationResult data{ false, error, currentModelName_, errorValue, errorValue, index, total, "", ""}; imageGenerationResultCallback_(data); } } bool XunfeiVisionEnginePrivate::currentStatus() { return (currentError_.getCode() == -1); } kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/vision/xunfeivisionengine_p.h000066400000000000000000000067451520575453600264710ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef XUNFEIVISIONENGINE_P_H #define XUNFEIVISIONENGINE_P_H #include #include #include #include #include #include class XunfeiVisionEnginePrivate : public ai_engine::gen_ai::vision::AbstractImageGenerationEngine { public: XunfeiVisionEnginePrivate(); ~XunfeiVisionEnginePrivate(); std::string engineName() const override; bool isCloud() const override { return true; } bool isBuiltInEngine() const override { return false; } bool isCustomModelEngine() const override { return false; } std::string currentModel() const override; std::string currentModelName() const override; void setConfig(const std::string &config) override; bool setCurrentModel(const std::string &model) override; std::string modelInfo() const override; void setGenerationResultCallback( ai_engine::gen_ai::vision::ImageGenerationCallback callback) override; ai_engine::result::AiEngineBaseResult init() override { return {true}; }; ai_engine::result::AiEngineBaseResult destroy() override { return {true}; }; void setImageSize(int width, int height) override; void setImageNumber(int number) override; void setImageStyle(const std::string &style) override; std::vector supportedImageStyles() const override; int supportedImageNumber() const override; std::vector> supportedImageSizes() const override; ai_engine::result::AiEngineBaseResult generateImage(const std::string &prompt) override; void stopImageGeneration() override; private: std::string appId_; std::string apiKey_; std::string secretKey_; std::string currentModel_{"讯飞-图片生成"}; std::string currentModelName_{"讯飞-图片生成"}; std::string hostUrl_{"https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti"}; ai_engine::gen_ai::vision::ImageGenerationCallback imageGenerationResultCallback_; friend bool writePrompt2ImageResult(std::string data, intptr_t userData); ai_engine::result::AiEngineBaseResult processPrompt2ImageResult(cpr::Response &response); void decreaseGenerationCounter(); void increaseGenerationCounter(); bool isGenerating() const; bool waitForStopped(); int imageWidth_{1024}; int imageHeight_{1024}; int imageNumber_{1}; std::string imageStyle_; std::atomic isStopped_{false}; std::atomic generationCounter_{0}; bool isCallbackCalled_{false}; std::string incompleteResult_; ai_engine::EngineError currentError_; bool currentStatus(); void runCallbackWithError(const ai_engine::EngineError &error, const int &index, const int &total); }; #endif // XUNFEIVISIONENGINE_P_H kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/xunfeiengine.cpp000066400000000000000000000026641520575453600237420ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "xunfeiengine.h" #include "xunfei/speech/xunfeispeechengine.h" #include "xunfei/nlp/xunfeinlpengine.h" #include "xunfei/vision/xunfeivisionengine.h" std::string XunfeiAiEngine::name() const { return "xunfei"; } std::unique_ptr XunfeiAiEngine::createSpeechEngine() { return std::make_unique(); } std::unique_ptr XunfeiAiEngine::createTextGenerationEngine() { return std::make_unique(); } std::unique_ptr XunfeiAiEngine::createImageGenerationEngine() { return std::make_unique(); } AI_ENGINE_PLUGIN_FACTORY(XunfeiAiEngine); kylin-cloud-ai-engine-plugin-1.1.0.1/xunfei/xunfeiengine.h000066400000000000000000000025331520575453600234020ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef KYLIN_XUNFEI_AI_ENGINE_PLUGIN_XUNFEI_ENGINE_H #define KYLIN_XUNFEI_AI_ENGINE_PLUGIN_XUNFEI_ENGINE_H #include class XunfeiAiEngine : public ai_engine::AbstractAiEnginePluginFactory { public: ~XunfeiAiEngine() override = default; std::string name() const override; std::unique_ptr createTextGenerationEngine() override; std::unique_ptr createSpeechEngine() override; std::unique_ptr createImageGenerationEngine() override; }; #endif