├── .gitattributes ├── .github └── workflows │ └── main.yml ├── API.md ├── CMakeLists.txt ├── COPYING ├── MANIFEST.XML ├── README.md ├── conanfile.py ├── include ├── AddInDefBase.h ├── ComponentBase.h ├── IMemoryManager.h ├── com.h └── types.h └── src ├── Component.cpp ├── Component.h ├── ForwardingServer.cpp ├── ForwardingServer.h ├── ForwardingSession.cpp ├── ForwardingSession.h ├── SshAddIn.cpp ├── SshAddIn.h ├── SshChannel.h ├── SshSession.h ├── addin.def ├── dllmain.cpp ├── exports.cpp └── stdafx.h /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sh eol=lf -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | # Conan-center does not provide x86 packages and I'm too lazy to maintain them myself 11 | # so there will be only x64 builds here 12 | os: [windows-latest, ubuntu-18.04] 13 | include: 14 | - os: windows-latest 15 | generator: VS16Win64 16 | - os: ubuntu-18.04 17 | generator: Ninja 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | 22 | - uses: actions/setup-python@v2 23 | with: 24 | python-version: '3.x' 25 | 26 | - run: | 27 | pip install wheel 28 | pip install conan 29 | conan profile new default --detect 30 | 31 | - run: conan profile update settings.compiler.libcxx=libstdc++11 default 32 | if: runner.os == 'Linux' 33 | 34 | - run: | 35 | mkdir ${{ github.workspace }}/build && cd ${{ github.workspace }}/build 36 | conan remote add bintray/infactum https://api.bintray.com/conan/infactum/public-conan 37 | conan install ${{ github.workspace }} 38 | 39 | - uses: lukka/run-cmake@v2 40 | id: runcmake_cmd 41 | with: 42 | buildDirectory: ${{ github.workspace }}/build 43 | cmakeGenerator: ${{ matrix.generator }} 44 | cmakeBuildType: Release 45 | 46 | - uses: actions/upload-artifact@v2 47 | with: 48 | name: windows-x64 49 | path: ${{ github.workspace }}/build/bin/ssh_native.dll 50 | if: runner.os == 'Windows' 51 | 52 | - uses: actions/upload-artifact@v2 53 | with: 54 | name: linux-x64 55 | path: ${{ github.workspace }}/build/lib/libssh_native.so 56 | if: runner.os == 'Linux' 57 | -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | # SSH Native # 2 | 3 | ## Свойства ## 4 | 5 | ### АдресСервера / Host ### 6 | **Использование:** 7 | Чтение и запись 8 | **Описание:** 9 | Тип: *Строка* 10 | Имя или IP-адрес сервера. 11 | 12 | ### Пользователь / User ### 13 | **Использование:** 14 | Чтение и запись 15 | **Описание:** 16 | Тип: *Строка* 17 | Имя пользователя для подключения к серверу. 18 | 19 | ### Порт / Port ### 20 | **Использование:** 21 | Чтение и запись 22 | **Описание:** 23 | Тип: *Число* 24 | Порт для подключения к серверу. 25 | Значение по умолчанию: 22 26 | 27 | ### Пароль / Password ### 28 | **Использование:** 29 | Только запись 30 | **Описание:** 31 | Тип: *Строка* 32 | Пароль пользователя. 33 | 34 | ## Методы ## 35 | 36 | ### ОписаниеОшибки / ErrorDesc ### 37 | **Синтаксис:** 38 | ОписаниеОшибки() 39 | **Возвращаемое значение:** 40 | Тип: *Строка*, *Неопределено* 41 | **Описание:** 42 | Содержит текст последней ошибки выполнения метода. 43 | 44 | ### Подключиться / Connect ### 45 | **Синтаксис:** 46 | Подключиться() 47 | **Описание:** 48 | Выполняет подключение и аутентификацию к серверу SSH. 49 | В первую очередь производится попытка аутентификации на основании ключа. 50 | Поиск ключей осуществляется в каталоге *<каталог пользователя>/.ssh*. 51 | В случае, если аутентификация по ключу не удалась и пароль пользователя заполнен, будет выполнена попытка парольной аутентификации. 52 | 53 | ### Выполнить / Exec ### 54 | **Синтаксис:** 55 | Выполнить(<СтрокаКоманды>, <СтандартныйВывод>, <СтандартныйВыводОшибок>) 56 | **Параметры:** 57 | * <СтрокаКоманды> (обязательный) 58 | Тип: *Строка* 59 | Команда для выполнения на удаленном сервере. 60 | * [out] <СтандартныйВывод> (необязательный) 61 | Тип: *Строка* 62 | Содержит результат стаднартного потока вывода (stdout) результата команды. 63 | * [out] <СтандартныйВыводОшибок> (необязательный) 64 | Тип: *Строка* 65 | Содержит результат стаднартного потока вывода ошибок (stderr) результата команды. 66 | 67 | **Возвращаемое значение:** 68 | Тип: *Булево* 69 | Успех выполнения метода. В случае возврата значения Ложь, описание ошибки может быть получено через одноименное свойство компоненты. 70 | **Описание:** 71 | Закрывает соединение с сервером SSH. 72 | 73 | ### Прочитать / Read ### 74 | **Синтаксис:** 75 | Прочитать(<Путь>, <Результат>) 76 | **Параметры:** 77 | * <Путь> (обязательный) 78 | Тип: *Строка* 79 | Путь к файлу на удаленном сервере. 80 | * [out] <Результат> (обязательный) 81 | Тип: *Двоичные данные* 82 | Двоичные данные файла, полученного с удаленного сервера. 83 | 84 | **Возвращаемое значение:** 85 | Тип: *Булево* 86 | Успех выполнения метода. В случае возврата значения Ложь, описание ошибки может быть получено через одноименное свойство компоненты. 87 | **Описание:** 88 | Выполняет получение файла с удаленного сервера по протоколу SCP. 89 | 90 | ### Записать / Write ### 91 | **Синтаксис:** 92 | Записать(<Путь>, <Данные>, <Режим>) 93 | **Параметры:** 94 | * <Путь> (обязательный) 95 | Тип: *Строка* 96 | Путь к файлу на удаленном сервере. 97 | * <Данные> (обязательный) 98 | Тип: *Двоичные данные* 99 | Двоичные данные файла, передаваемые на удаленный сервер. 100 | * <Режим> (необязательный) 101 | Тип: *Число*, *Строка* 102 | Определяет режим доступа к файлу, на удаленном сервере. Задается в виде строки с восьмеричным представлением или аналогичного числа в десятичной форме. Например, для режима r--r--r-- следует указывать "0444" или 292, а для rwxrwxrwx - "0777" или 511. 103 | Значение по умолчанию: 0644 (rw-r--r--) 104 | 105 | **Возвращаемое значение:** 106 | Тип: *Булево* 107 | Успех выполнения метода. В случае возврата значения Ложь, описание ошибки может быть получено через одноименное свойство компоненты. 108 | **Описание:** 109 | Выполняет отправку файла на удаленный сервер по протоколу SCP. 110 | 111 | ### ВключитьПеренаправлениеПорта / EnablePortForwarding ### 112 | **Синтаксис:** 113 | ВключитьПеренаправлениеПорта(<АдресСервера>, <Порт>, <ЛокальныйПорт>) 114 | **Параметры:** 115 | * <АдресСервера> (обязательный) 116 | Тип: *Строка* 117 | Адрес удаленного сервера 118 | * <Порт> (обязательный) 119 | Тип: *Число* 120 | Порт удаленного сервера 121 | * [in/out] <ЛокальныйПорт> (обязательный) 122 | Тип: *Число* 123 | Локальный порт для приема подключений. В случае, если передано значение 0, или тип значения переменной не число, 124 | будет выбран свободный локальный порт и его значение будет записано в данный параметр. 125 | 126 | **Возвращаемое значение:** 127 | Тип: *Булево* 128 | Успех выполнения метода. В случае возврата значения Ложь, описание ошибки может быть получено через одноименное свойство компоненты. 129 | **Описание:** 130 | Включает режим перенаправления TCP порта. В этом режиме все соединения, поступающие на локальный порт, будут через 131 | SSH соединение перенаправлены на указанный порт удаленного сервера. 132 | Метод может быть вызван многократно для перенаправления нескольких портов. 133 | 134 | ### ОтключитьПеренаправлениеПортов / DisablePortForwarding ### 135 | **Синтаксис:** 136 | ОтключитьПеренаправлениеПортов() 137 | **Описание:** 138 | Отключает перенаправоение портов, зарегистрированных методом *ВключитьПеренаправлениеПорта*. 139 | 140 | ### ВключитьЖурнал / EnableLog ### 141 | **Синтаксис:** 142 | ВключитьЖурнал(<Уровень>) 143 | **Параметры:** 144 | * <Уровень> (необязательный) 145 | Тип: *Число* 146 | Уровень детализации отладочной информации. 147 | Значение по умолчанию: 3 (DEBUG) 148 | 149 | **Описание:** 150 | Включает запись отладочных сообщений компоненты. В связи с тем, что данные хранятся в памяти приложения, нужно понимать, что длительное использование экземпляра компоненты с включенным журналом (без его принудительной очистки) может приводить к аварийному завершению процесса 1С:Предприятия. 151 | 152 | ### ПолучитьЖурнал / GetLog ### 153 | **Синтаксис:** 154 | ПолучитьЖурнал() 155 | **Возвращаемое значение:** 156 | Тип: *Строка* 157 | Содержимое отладочного журнала. 158 | **Описание:** 159 | Выполняет получение накопленных данных отладочного журнала. Получение журнала НЕ вызывает его очистку. 160 | 161 | ### ОчиститьЖурнал / ClearLog ### 162 | **Синтаксис:** 163 | ОчиститьЖурнал() 164 | **Описание:** 165 | Выполняет очистку отладочного журнала. 166 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(SSH_NATIVE) 3 | 4 | set(CMAKE_CXX_STANDARD 17) 5 | set(TARGET ssh_native) 6 | 7 | if (EXISTS ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) 8 | include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) 9 | conan_basic_setup() 10 | else () 11 | message(WARNING "The file conanbuildinfo.cmake doesn't exist, you have to run conan install first") 12 | endif () 13 | 14 | option(CASE_INSENSITIVE "Case insensitive method names" OFF) 15 | 16 | add_library(${TARGET} SHARED 17 | src/Component.cpp 18 | src/Component.h 19 | src/ForwardingServer.cpp 20 | src/ForwardingServer.h 21 | src/ForwardingSession.cpp 22 | src/ForwardingSession.h 23 | src/SshAddIn.cpp 24 | src/SshAddIn.h 25 | src/SshChannel.h 26 | src/SshSession.h 27 | src/addin.def 28 | src/dllmain.cpp 29 | src/exports.cpp 30 | src/stdafx.h) 31 | 32 | target_compile_definitions(${TARGET} PRIVATE 33 | UNICODE 34 | _UNICODE 35 | OUT_PARAMS 36 | WIN32_LEAN_AND_MEAN) 37 | 38 | if (CASE_INSENSITIVE) 39 | target_compile_definitions(${TARGET} PRIVATE CASE_INSENSITIVE) 40 | endif () 41 | 42 | target_include_directories(${TARGET} PRIVATE 43 | include) 44 | 45 | target_link_libraries(${TARGET} PRIVATE 46 | ${CONAN_LIBS}) 47 | 48 | if (WIN32 AND NOT MSVC) 49 | message(FATAL_ERROR "Must be compiled with MSVC on Windows") 50 | endif () 51 | 52 | if (WIN32) 53 | target_compile_definitions(${TARGET} PRIVATE 54 | _WINDOWS 55 | _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING) 56 | target_link_libraries(${TARGET} PRIVATE 57 | wsock32 58 | ws2_32) 59 | target_compile_options(${TARGET} PRIVATE /utf-8) 60 | endif () 61 | 62 | if (UNIX) 63 | if (TARGET_ARCH STREQUAL "x86") 64 | set(CMAKE_C_FLAGS "-m32 ${CMAKE_C_FLAGS}") 65 | set(CMAKE_CXX_FLAGS "-m32 ${CMAKE_CXX_FLAGS}") 66 | endif () 67 | endif () -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /MANIFEST.XML: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![CI](https://github.com/Infactum/ssh-native/workflows/CI/badge.svg) 2 | 3 | # SSH support for 1C:Enterprise 4 | 5 | Made with [modern template](https://github.com/Infactum/addin-template). 6 | See API docs [here](API.md). 7 | 8 | ⚠ Refactor required. Use with care. 9 | 10 | ## License exclusions 11 | In case of embedding this add-in inside 1C:Enterprise configuations, external processors, configuration extensions etc, it's allowed not to apply AGPL terms to whole application part, but only add-in itself. 12 | -------------------------------------------------------------------------------- /conanfile.py: -------------------------------------------------------------------------------- 1 | from conans import ConanFile 2 | 3 | 4 | class Pkg(ConanFile): 5 | settings = "os", "compiler", "build_type", "arch" 6 | generators = "cmake" 7 | requires = ( 8 | "boost/1.70.0", 9 | "libssh/0.9.4@infactum/stable", 10 | ) 11 | 12 | def configure(self): 13 | self.options["boost"].shared = False 14 | self.options["libssh"].shared = False 15 | 16 | def requirements(self): 17 | if self.settings.os == "Linux": 18 | self.requires("libuuid/1.0.3") 19 | -------------------------------------------------------------------------------- /include/AddInDefBase.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Warning!!! 3 | * DO NOT ALTER THIS FILE! 4 | */ 5 | 6 | #ifndef __ADAPTER_DEF_H__ 7 | #define __ADAPTER_DEF_H__ 8 | #include "types.h" 9 | 10 | struct IInterface 11 | { 12 | }; 13 | 14 | 15 | enum Interfaces 16 | { 17 | eIMsgBox = 0, 18 | eIPlatformInfo, 19 | 20 | #if defined(__ANDROID__) 21 | 22 | eIAndroidComponentHelper, 23 | 24 | #endif 25 | 26 | }; 27 | 28 | //////////////////////////////////////////////////////////////////////////////// 29 | /** 30 | * This class serves as representation of a platform for external 31 | * components External components use it to communicate with a platform. 32 | * 33 | */ 34 | /// Base interface for object components. 35 | class IAddInDefBase 36 | { 37 | public: 38 | virtual ~IAddInDefBase() {} 39 | /// Adds the error message 40 | /** 41 | * @param wcode - error code 42 | * @param source - source of error 43 | * @param descr - description of error 44 | * @param scode - error code (HRESULT) 45 | * @return the result of 46 | */ 47 | virtual bool ADDIN_API AddError(unsigned short wcode, const WCHAR_T* source, 48 | const WCHAR_T* descr, long scode) = 0; 49 | 50 | /// Reads a property value 51 | /** 52 | * @param wszPropName -property name 53 | * @param pVal - value being returned 54 | * @param pErrCode - error code (if any error occured) 55 | * @param errDescriptor - error description (if any error occured) 56 | * @return the result of read. 57 | */ 58 | virtual bool ADDIN_API Read(WCHAR_T* wszPropName, 59 | tVariant* pVal, 60 | long *pErrCode, 61 | WCHAR_T** errDescriptor) = 0; 62 | /// Writes a property value 63 | /** 64 | * @param wszPropName - property name 65 | * @param pVar - new property value 66 | * @return the result of write. 67 | */ 68 | virtual bool ADDIN_API Write(WCHAR_T* wszPropName, 69 | tVariant *pVar) = 0; 70 | 71 | ///Registers profile components 72 | /** 73 | * @param wszProfileName - profile name 74 | * @return the result of 75 | */ 76 | virtual bool ADDIN_API RegisterProfileAs(WCHAR_T* wszProfileName) = 0; 77 | 78 | /// Changes the depth of event buffer 79 | /** 80 | * @param lDepth - new depth of event buffer 81 | * @return the result of 82 | */ 83 | virtual bool ADDIN_API SetEventBufferDepth(long lDepth) = 0; 84 | /// Returns the depth of event buffer 85 | /** 86 | * @return the depth of event buffer 87 | */ 88 | virtual long ADDIN_API GetEventBufferDepth() = 0; 89 | /// Registers external event 90 | /** 91 | * @param wszSource - source of event 92 | * @param wszMessage - event message 93 | * @param wszData - message parameters 94 | * @return the result of 95 | */ 96 | virtual bool ADDIN_API ExternalEvent(WCHAR_T* wszSource, 97 | WCHAR_T* wszMessage, 98 | WCHAR_T* wszData) = 0; 99 | /// Clears event buffer 100 | /** 101 | */ 102 | virtual void ADDIN_API CleanEventBuffer() = 0; 103 | 104 | /// Sets status line contents 105 | /** 106 | * @param wszStatusLine - new status line contents 107 | * @return the result of 108 | */ 109 | virtual bool ADDIN_API SetStatusLine(WCHAR_T* wszStatusLine) = 0; 110 | /// Resets the status line contents 111 | /** 112 | * @return the result of 113 | */ 114 | virtual void ADDIN_API ResetStatusLine() = 0; 115 | }; 116 | 117 | class IAddInDefBaseEx : 118 | public IAddInDefBase 119 | { 120 | public: 121 | virtual ~IAddInDefBaseEx() {} 122 | 123 | virtual IInterface* ADDIN_API GetInterface(Interfaces iface) = 0; 124 | }; 125 | 126 | struct IMsgBox : 127 | public IInterface 128 | { 129 | virtual bool ADDIN_API Confirm(const WCHAR_T* queryText, tVariant* retVal) = 0; 130 | 131 | virtual bool ADDIN_API Alert(const WCHAR_T* text) = 0; 132 | }; 133 | 134 | struct IPlatformInfo : 135 | public IInterface 136 | { 137 | enum AppType 138 | { 139 | eAppUnknown = -1, 140 | eAppThinClient = 0, 141 | eAppThickClient, 142 | eAppWebClient, 143 | eAppServer, 144 | eAppExtConn, 145 | eAppMobileClient, 146 | eAppMobileServer, 147 | }; 148 | 149 | struct AppInfo 150 | { 151 | const WCHAR_T* AppVersion; 152 | const WCHAR_T* UserAgentInformation; 153 | AppType Application; 154 | }; 155 | 156 | virtual const AppInfo* ADDIN_API GetPlatformInfo() = 0; 157 | }; 158 | 159 | #endif //__ADAPTER_DEF_H__ 160 | -------------------------------------------------------------------------------- /include/ComponentBase.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Warning!!! 3 | * DO NOT ALTER THIS FILE! 4 | */ 5 | 6 | 7 | #ifndef __COMPONENT_BASE_H__ 8 | #define __COMPONENT_BASE_H__ 9 | 10 | #include "types.h" 11 | //////////////////////////////////////////////////////////////////////////////// 12 | /** 13 | * The given interface is intended for initialization and 14 | * uninitialization of component and its adjustments 15 | */ 16 | /// Interface of component initialization. 17 | class IInitDoneBase 18 | { 19 | public: 20 | virtual ~IInitDoneBase() {} 21 | /// Initializes component 22 | /** 23 | * @param disp - 1C:Enterpise interface 24 | * @return the result of 25 | */ 26 | virtual bool ADDIN_API Init(void* disp) = 0; 27 | /// Sets the memory manager 28 | /* 29 | * @param mem - pointer to memory manager interface. 30 | * @return the result of 31 | */ 32 | virtual bool ADDIN_API setMemManager(void* mem) = 0; 33 | 34 | /// Returns component version 35 | /** 36 | * @return - component version (2000 - version 2) 37 | */ 38 | virtual long ADDIN_API GetInfo() = 0; 39 | 40 | /// Uninitializes component 41 | /** 42 | * Component here should release all consumed resources. 43 | */ 44 | virtual void ADDIN_API Done() = 0; 45 | 46 | }; 47 | /////////////////////////////////////////////////////////////////////////// 48 | /** 49 | * The given interface defines methods that are intented to be used by the Platform 50 | */ 51 | /// Interface describing extension of language. 52 | class ILanguageExtenderBase 53 | { 54 | public: 55 | virtual ~ILanguageExtenderBase(){} 56 | /// Registers language extension 57 | /** 58 | * @param wsExtensionName - extension name 59 | * @return the result of 60 | */ 61 | virtual bool ADDIN_API RegisterExtensionAs(WCHAR_T** wsExtensionName) = 0; 62 | 63 | /// Returns number of component properties 64 | /** 65 | * @return number of properties 66 | */ 67 | virtual long ADDIN_API GetNProps() = 0; 68 | 69 | /// Finds property by name 70 | /** 71 | * @param wsPropName - property name 72 | * @return property index or -1, if it is not found 73 | */ 74 | virtual long ADDIN_API FindProp(const WCHAR_T* wsPropName) = 0; 75 | 76 | /// Returns property name 77 | /** 78 | * @param lPropNum - property index (starting with 0) 79 | * @param lPropAlias - 0 - international alias, 80 | * 1 - russian alias. (International alias is required) 81 | * @return proeprty name or 0 if it is not found 82 | */ 83 | virtual const WCHAR_T* ADDIN_API GetPropName(long lPropNum, 84 | long lPropAlias) = 0; 85 | 86 | /// Returns property value 87 | /** 88 | * @param lPropNum - property index (starting with 0) 89 | * @param pvarPropVal - the pointer to a variable for property value 90 | * @return the result of 91 | */ 92 | virtual bool ADDIN_API GetPropVal(const long lPropNum, 93 | tVariant* pvarPropVal) = 0; 94 | 95 | /// Sets the property value 96 | /** 97 | * @param lPropNum - property index (starting with 0) 98 | * @param varPropVal - the pointer to a variable for property value 99 | * @return the result of 100 | */ 101 | virtual bool ADDIN_API SetPropVal(const long lPropNum, 102 | tVariant* varPropVal) = 0; 103 | 104 | /// Is property readable? 105 | /** 106 | * @param lPropNum - property index (starting with 0) 107 | * @return true if property is readable 108 | */ 109 | virtual bool ADDIN_API IsPropReadable(const long lPropNum) = 0; 110 | 111 | /// Is property writable? 112 | /** 113 | * @param lPropNum - property index (starting with 0) 114 | * @return true if property is writable 115 | */ 116 | virtual bool ADDIN_API IsPropWritable(const long lPropNum) = 0; 117 | 118 | /// Returns number of component methods 119 | /** 120 | * @return number of component methods 121 | */ 122 | virtual long ADDIN_API GetNMethods() = 0; 123 | 124 | /// Finds a method by name 125 | /** 126 | * @param wsMethodName - method name 127 | * @return - method index 128 | */ 129 | virtual long ADDIN_API FindMethod(const WCHAR_T* wsMethodName) = 0; 130 | 131 | /// Returns method name 132 | /** 133 | * @param lMethodNum - method index(starting with 0) 134 | * @param lMethodAlias - 0 - international alias, 135 | * 1 - russian alias. (International alias is required) 136 | * @return method name or 0 if method is not found 137 | */ 138 | virtual const WCHAR_T* ADDIN_API GetMethodName(const long lMethodNum, 139 | const long lMethodAlias) = 0; 140 | 141 | /// Returns number of method parameters 142 | /** 143 | * @param lMethodNum - method index (starting with 0) 144 | * @return number of parameters 145 | */ 146 | virtual long ADDIN_API GetNParams(const long lMethodNum) = 0; 147 | 148 | /// Returns default value of method parameter 149 | /** 150 | * @param lMethodNum - method index(starting with 0) 151 | * @param lParamNum - parameter index (starting with 0) 152 | * @param pvarParamDefValue - the pointer to a variable for default value 153 | * @return the result of 154 | */ 155 | virtual bool ADDIN_API GetParamDefValue(const long lMethodNum, 156 | const long lParamNum, 157 | tVariant *pvarParamDefValue) = 0; 158 | 159 | /// Does the method have a return value? 160 | /** 161 | * @param lMethodNum - method index (starting with 0) 162 | * @return true if the method has a return value 163 | */ 164 | virtual bool ADDIN_API HasRetVal(const long lMethodNum) = 0; 165 | 166 | /// Calls the method as a procedure 167 | /** 168 | * @param lMethodNum - method index (starting with 0) 169 | * @param paParams - the pointer to array of method parameters 170 | * @param lSizeArray - the size of array 171 | * @return the result of 172 | */ 173 | virtual bool ADDIN_API CallAsProc(const long lMethodNum, 174 | tVariant* paParams, 175 | const long lSizeArray) = 0; 176 | 177 | /// Calls the method as a function 178 | /** 179 | * @param lMethodNum - method index (starting with 0) 180 | * @param pvarRetValue - the pointer to returned value 181 | * @param paParams - the pointer to array of method parameters 182 | * @param lSizeArray - the size of array 183 | * @return the result of 184 | */ 185 | virtual bool ADDIN_API CallAsFunc(const long lMethodNum, 186 | tVariant* pvarRetValue, 187 | tVariant* paParams, 188 | const long lSizeArray) = 0; 189 | }; 190 | /////////////////////////////////////////////////////////////////////////// 191 | /** 192 | * This interface is used to change component locale 193 | */ 194 | /// Base interface for component localization. 195 | class LocaleBase 196 | { 197 | public: 198 | virtual ~LocaleBase(){} 199 | /// Changes component locale 200 | /** 201 | * @param loc - new locale (for Windows - rus_RUS, 202 | * for Linux - ru_RU, etc...) 203 | */ 204 | virtual void ADDIN_API SetLocale(const WCHAR_T* loc) = 0; 205 | }; 206 | 207 | /////////////////////////////////////////////////////////////////////////// 208 | /** 209 | * The given interface is generalized, for its obligatory inheritance 210 | * in implementing components. 211 | */ 212 | /// Base interface describing object as a set of properties and methods. 213 | class IComponentBase : 214 | public IInitDoneBase, 215 | public ILanguageExtenderBase, 216 | public LocaleBase 217 | { 218 | public: 219 | virtual ~IComponentBase(){} 220 | }; 221 | 222 | enum AppCapabilities 223 | { 224 | eAppCapabilitiesInvalid = -1, 225 | eAppCapabilities1 = 1, 226 | eAppCapabilitiesLast = eAppCapabilities1, 227 | }; 228 | 229 | /// Announcements of exported functions 230 | /** 231 | * These functions should be implemented that component can be loaded and created. 232 | */ 233 | extern "C" long GetClassObject(const WCHAR_T*, IComponentBase** pIntf); 234 | extern "C" long DestroyObject(IComponentBase** pIntf); 235 | extern "C" const WCHAR_T* GetClassNames(); 236 | extern "C" AppCapabilities SetPlatformCapabilities(const AppCapabilities capabilities); 237 | 238 | typedef long (*GetClassObjectPtr)(const WCHAR_T* wsName, IComponentBase** pIntf); 239 | typedef long (*DestroyObjectPtr)(IComponentBase** pIntf); 240 | typedef const WCHAR_T* (*GetClassNamesPtr)(); 241 | typedef AppCapabilities (*SetPlatformCapabilitiesPtr)(const AppCapabilities capabilities); 242 | 243 | #endif //__COMPONENT_BASE_H__ 244 | -------------------------------------------------------------------------------- /include/IMemoryManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Warning!!! 3 | * DO NOT ALTER THIS FILE! 4 | */ 5 | 6 | 7 | #ifndef __IMEMORY_MANAGER_H__ 8 | #define __IMEMORY_MANAGER_H__ 9 | 10 | /////////////////////////////////////////////////////////////////////////////// 11 | /** 12 | * The given class allocates and releases memory for a component 13 | */ 14 | /// Interface representing memory manager. 15 | class IMemoryManager 16 | { 17 | public: 18 | virtual ~IMemoryManager() {} 19 | /// Allocates memory of specified size 20 | /** 21 | * @param pMemory - the double pointer to variable, that will hold newly 22 | * allocated block of memory of NULL if allocation fails. 23 | * @param ulCountByte - memory size 24 | * @return the result of 25 | */ 26 | virtual bool ADDIN_API AllocMemory (void** pMemory, unsigned long ulCountByte) = 0; 27 | /// Releases memory 28 | /** 29 | * @param pMemory - The double pointer to the memory block being released 30 | */ 31 | virtual void ADDIN_API FreeMemory (void** pMemory) = 0; 32 | }; 33 | 34 | #endif //__IMEMORY_MANAGER_H__ 35 | -------------------------------------------------------------------------------- /include/com.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __COM_H__ 3 | #define __COM_H__ 4 | 5 | #if defined(__linux__) || defined(__APPLE__) || defined(__ANDROID__) 6 | 7 | #ifdef __ANDROID__ 8 | 9 | typedef struct { 10 | unsigned int Data1; 11 | unsigned short Data2; 12 | unsigned short Data3; 13 | unsigned char Data4[ 8 ]; 14 | } uuid_t; 15 | 16 | #else 17 | #include 18 | #endif //__ANDROID__ 19 | 20 | #ifndef __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ // iOS 21 | #include 22 | #endif //!__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ 23 | 24 | #pragma GCC system_header 25 | 26 | typedef long HRESULT; 27 | 28 | #ifdef __GNUC__ 29 | #define STDMETHODCALLTYPE __attribute__ ((__stdcall__)) 30 | #define DECLSPEC_NOTHROW __attribute__ ((nothrow)) 31 | #define STDMETHOD(method) virtual DECLSPEC_NOTHROW HRESULT STDMETHODCALLTYPE method 32 | #else 33 | #define STDMETHODCALLTYPE 34 | #endif 35 | 36 | #define __stdcall STDMETHODCALLTYPE 37 | #define near 38 | #define far 39 | #define CONST const 40 | #define FAR far 41 | 42 | typedef unsigned long DWORD; 43 | #ifndef __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ // iOS 44 | typedef int BOOL; 45 | #elif defined(__LP64__) 46 | typedef bool BOOL; 47 | #else 48 | typedef signed char BOOL; 49 | #endif //!__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ 50 | 51 | typedef void VOID; 52 | typedef short SHORT; 53 | typedef unsigned char BYTE; 54 | typedef unsigned short WORD; 55 | typedef float FLOAT; 56 | typedef FLOAT *PFLOAT; 57 | typedef BOOL near *PBOOL; 58 | typedef BOOL far *LPBOOL; 59 | typedef BYTE near *PBYTE; 60 | typedef BYTE far *LPBYTE; 61 | typedef int near *PINT; 62 | typedef int far *LPINT; 63 | typedef WORD near *PWORD; 64 | typedef WORD far *LPWORD; 65 | typedef long far *LPLONG; 66 | typedef DWORD near *PDWORD; 67 | typedef DWORD far *LPDWORD; 68 | typedef void far *LPVOID; 69 | typedef CONST void far *LPCVOID; 70 | typedef wchar_t *BSTR; 71 | typedef long SCODE; 72 | typedef int INT; 73 | typedef unsigned int UINT; 74 | typedef unsigned int *PUINT; 75 | typedef wchar_t WCHAR; 76 | typedef wchar_t OLECHAR; 77 | typedef wchar_t *LPOLESTR; 78 | typedef const wchar_t *LPCOLESTR; 79 | typedef DWORD LCID; 80 | typedef PDWORD PLCID; 81 | typedef long LONG; 82 | typedef unsigned long ULONG; 83 | typedef long long LONGLONG; 84 | typedef unsigned long long ULONGLONG; 85 | typedef LONG DISPID; 86 | typedef double DOUBLE; 87 | typedef double DATE; 88 | typedef short VARIANT_BOOL; 89 | typedef void *PVOID; 90 | typedef char CHAR; 91 | typedef CONST CHAR *LPCSTR; 92 | typedef unsigned short USHORT; 93 | typedef void *HMODULE; 94 | #define OLESTR(str) L##str 95 | 96 | typedef uuid_t GUID; 97 | typedef uuid_t IID; 98 | typedef uuid_t UUID; 99 | #define REFIID const IID & 100 | #define MAX_PATH 260 101 | 102 | #define IsEqualIID(x,y) uuid_compare((x),(y)) 103 | #ifdef __GNUC__ 104 | #define LoadLibraryA(x) dlopen((x), RTLD_LAZY) 105 | #define FreeLibrary(x) dlclose((x)) 106 | #define GetProcAddress(x, y) dlsym((x), (y)) 107 | #endif //__GNUC__ 108 | 109 | #define E_FAIL 0x80004005L 110 | #define S_OK 0L 111 | #define S_FALSE 1L 112 | #define E_NOINTERFACE 0x80004002L 113 | #define E_NOTIMPL 0x80004001L 114 | #define E_INVALIDARG 0x80070057L 115 | #define E_UNEXPECTED 0x8000FFFFL 116 | #define E_OUTOFMEMORY 0x8007000EL 117 | #define DISP_E_UNKNOWNNAME 0x80020006L 118 | #define DISPID_UNKNOWN ( -1 ) 119 | #define TRUE 1 120 | #define FALSE 0 121 | 122 | typedef long ITypeInfo; 123 | 124 | #if defined (__GNUC__) && !defined (NONAMELESSUNION) 125 | __extension__ /* no named members */ 126 | #endif 127 | union tCY { 128 | __extension__ struct 129 | { 130 | unsigned long Lo; 131 | long Hi; 132 | }; 133 | long long int64; 134 | }; 135 | typedef union tagCY CY; 136 | #define CLSIDFromString(x,y) uuid_parse((x),(unsigned char*)(y)) 137 | 138 | #endif //defined(__linux__) || defined(__APPLE__) 139 | 140 | #endif //__COM_H__ 141 | -------------------------------------------------------------------------------- /include/types.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __CON_TYPES_H__ 3 | #define __CON_TYPES_H__ 4 | 5 | #if defined(_WINDOWS) || defined(WINAPI_FAMILY) 6 | #include 7 | #endif 8 | 9 | #if defined(WINAPI_FAMILY) 10 | #include 11 | #endif 12 | 13 | #if __GNUC__ >=3 14 | #pragma GCC system_header 15 | #endif 16 | 17 | #include "com.h" 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #define EXTERN_C extern "C" 24 | 25 | #ifdef __GNUC__ 26 | #define _ANONYMOUS_UNION __extension__ 27 | #define _ANONYMOUS_STRUCT __extension__ 28 | #else 29 | #define _ANONYMOUS_UNION 30 | #define _ANONYMOUS_STRUCT 31 | #endif //__GNUC__ 32 | 33 | #ifdef NONAMELESSUNION 34 | #define __VARIANT_NAME_1 u 35 | #define __VARIANT_NAME_2 iface 36 | #define __VARIANT_NAME_3 str 37 | #define __VARIANT_NAME_4 wstr 38 | #else 39 | #define __VARIANT_NAME_1 40 | #define __VARIANT_NAME_2 41 | #define __VARIANT_NAME_3 42 | #define __VARIANT_NAME_4 43 | #endif //NONAMELESSUNION 44 | 45 | #define RESULT_FROM_ERRNO(x) ((long)(x) <= 0 ? ((long)(x)) \ 46 | : ((long) (((x) & 0x0000FFFF) | (BASE_ERRNO << 16) | 0x80000000))) 47 | 48 | #define ADDIN_E_NONE 1000 49 | #define ADDIN_E_ORDINARY 1001 50 | #define ADDIN_E_ATTENTION 1002 51 | #define ADDIN_E_IMPORTANT 1003 52 | #define ADDIN_E_VERY_IMPORTANT 1004 53 | #define ADDIN_E_INFO 1005 54 | #define ADDIN_E_FAIL 1006 55 | #define ADDIN_E_MSGBOX_ATTENTION 1007 56 | #define ADDIN_E_MSGBOX_INFO 1008 57 | #define ADDIN_E_MSGBOX_FAIL 1009 58 | 59 | #ifndef ADDIN_API 60 | #ifdef _WINDOWS 61 | #define ADDIN_API __stdcall 62 | #else 63 | //#define ADDIN_API __attribute__ ((__stdcall__)) 64 | #define ADDIN_API 65 | #endif //_WINDOWS 66 | #endif //ADDIN_API 67 | 68 | #include 69 | 70 | #ifdef _WINDOWS 71 | #define WCHAR_T wchar_t 72 | #else 73 | #define WCHAR_T uint16_t 74 | #endif //_WINDOWS 75 | typedef unsigned short TYPEVAR; 76 | enum ENUMVAR 77 | { 78 | VTYPE_EMPTY = 0, 79 | VTYPE_NULL, 80 | VTYPE_I2, //int16_t 81 | VTYPE_I4, //int32_t 82 | VTYPE_R4, //float 83 | VTYPE_R8, //double 84 | VTYPE_DATE, //DATE (double) 85 | VTYPE_TM, //struct tm 86 | VTYPE_PSTR, //struct str string 87 | VTYPE_INTERFACE, //struct iface 88 | VTYPE_ERROR, //int32_t errCode 89 | VTYPE_BOOL, //bool 90 | VTYPE_VARIANT, //struct _tVariant * 91 | VTYPE_I1, //int8_t 92 | VTYPE_UI1, //uint8_t 93 | VTYPE_UI2, //uint16_t 94 | VTYPE_UI4, //uint32_t 95 | VTYPE_I8, //int64_t 96 | VTYPE_UI8, //uint64_t 97 | VTYPE_INT, //int Depends on architecture 98 | VTYPE_UINT, //unsigned int Depends on architecture 99 | VTYPE_HRESULT, //long hRes 100 | VTYPE_PWSTR, //struct wstr 101 | VTYPE_BLOB, //means in struct str binary data contain 102 | VTYPE_CLSID, //UUID 103 | VTYPE_STR_BLOB = 0xfff, 104 | VTYPE_VECTOR = 0x1000, 105 | VTYPE_ARRAY = 0x2000, 106 | VTYPE_BYREF = 0x4000, //Only with struct _tVariant * 107 | VTYPE_RESERVED = 0x8000, 108 | VTYPE_ILLEGAL = 0xffff, 109 | VTYPE_ILLEGALMASKED = 0xfff, 110 | VTYPE_TYPEMASK = 0xfff 111 | } ; 112 | #if defined (__GNUC__) && !defined (NONAMELESSUNION) 113 | __extension__ /* no named members */ 114 | #endif 115 | struct _tVariant 116 | { 117 | _ANONYMOUS_UNION union 118 | { 119 | int8_t i8Val; 120 | int16_t shortVal; 121 | int32_t lVal; 122 | int intVal; 123 | unsigned int uintVal; 124 | int64_t llVal; 125 | uint8_t ui8Val; 126 | uint16_t ushortVal; 127 | uint32_t ulVal; 128 | uint64_t ullVal; 129 | int32_t errCode; 130 | long hRes; 131 | float fltVal; 132 | double dblVal; 133 | bool bVal; 134 | char chVal; 135 | wchar_t wchVal; 136 | DATE date; 137 | IID IDVal; 138 | struct _tVariant *pvarVal; 139 | struct tm tmVal; 140 | _ANONYMOUS_STRUCT struct 141 | { 142 | void* pInterfaceVal; 143 | IID InterfaceID; 144 | } __VARIANT_NAME_2/*iface*/; 145 | _ANONYMOUS_STRUCT struct 146 | { 147 | char* pstrVal; 148 | uint32_t strLen; //count of bytes 149 | } __VARIANT_NAME_3/*str*/; 150 | _ANONYMOUS_STRUCT struct 151 | { 152 | WCHAR_T* pwstrVal; 153 | uint32_t wstrLen; //count of symbol 154 | } __VARIANT_NAME_4/*wstr*/; 155 | } __VARIANT_NAME_1; 156 | uint32_t cbElements; //Dimension for an one-dimensional array in pvarVal 157 | TYPEVAR vt; 158 | }; 159 | typedef struct _tVariant tVariant; 160 | typedef tVariant tVariantArg; 161 | 162 | 163 | #if defined(NONAMELESSUNION) 164 | #define TV_JOIN(X, Y) ((X)->u.Y) 165 | #else 166 | #define TV_JOIN(X, Y) ((X)->Y) 167 | #endif 168 | 169 | #define TV_VT(X) ((X)->vt) 170 | #define TV_ISBYREF(X) (TV_VT(X)&VT_BYREF) 171 | #define TV_ISARRAY(X) (TV_VT(X)&VT_ARRAY) 172 | #define TV_ISVECTOR(X) (TV_VT(X)&VT_VECTOR) 173 | #define TV_NONE(X) TV_I2(X) 174 | 175 | #define TV_UI1(X) TV_JOIN(X, ui8Val) 176 | #define TV_I2(X) TV_JOIN(X, shortVal) 177 | #define TV_I4(X) TV_JOIN(X, lVal) 178 | #define TV_I8(X) TV_JOIN(X, llVal) 179 | #define TV_R4(X) TV_JOIN(X, fltVal) 180 | #define TV_R8(X) TV_JOIN(X, dblVal) 181 | #define TV_I1(X) TV_JOIN(X, i8Val) 182 | #define TV_UI2(X) TV_JOIN(X, ushortVal) 183 | #define TV_UI4(X) TV_JOIN(X, ulVal) 184 | #define TV_UI8(X) TV_JOIN(X, ullVal) 185 | #define TV_INT(X) TV_JOIN(X, intVal) 186 | #define TV_UINT(X) TV_JOIN(X, uintVal) 187 | 188 | #ifdef _WIN64 189 | #define TV_INT_PTR(X) TV_JOIN(X, llVal) 190 | #define TV_UINT_PTR(X) TV_JOIN(X, ullVal) 191 | #else 192 | #define TV_INT_PTR(X) TV_JOIN(X, lVal) 193 | #define TV_UINT_PTR(X) TV_JOIN(X, ulVal) 194 | #endif 195 | 196 | 197 | #define TV_DATE(X) TV_JOIN(X, date) 198 | #define TV_STR(X) TV_JOIN(X, pstrVal) 199 | #define TV_WSTR(X) TV_JOIN(X, pwstrVal) 200 | #define TV_BOOL(X) TV_JOIN(X, bVal) 201 | #define TV_UNKNOWN(X) TV_JOIN(X, pInterfaceVal) 202 | #define TV_VARIANTREF(X) TV_JOIN(X, pvarVal) 203 | 204 | void tVarInit(tVariant* tvar); 205 | 206 | inline 207 | void tVarInit(tVariant* tvar) 208 | { 209 | assert(tvar != NULL); 210 | memset(tvar, 0, sizeof(tVariant)); 211 | TV_VT(tvar) = VTYPE_EMPTY; 212 | } 213 | //----------------------------------------------------------------------------// 214 | // static setter functions... 215 | 216 | #define DATA_SET_BEGIN(data_) \ 217 | tVarInit(data_); 218 | 219 | #define DATA_SET_END(data_, type_) \ 220 | TV_VT(data_) = type_; 221 | 222 | 223 | #define DATA_SET(data_, type_, member_, value_) \ 224 | DATA_SET_BEGIN(data_) \ 225 | TV_JOIN(data_, member_) = value_; \ 226 | DATA_SET_END(data_, type_) 227 | 228 | #define DATA_SET_WITH_CAST(data_, type_, member_, cast_, value_) \ 229 | DATA_SET_BEGIN(data_) \ 230 | TV_JOIN(data_, member_) = cast_ value_; \ 231 | DATA_SET_END(data_, type_) 232 | 233 | #endif //__CON_TYPES_H__ 234 | -------------------------------------------------------------------------------- /src/Component.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Modern Native AddIn 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "Component.h" 26 | 27 | #ifdef _WINDOWS 28 | #pragma warning (disable : 4267) 29 | #endif 30 | 31 | bool Component::Init(void *connection_) { 32 | connection = static_cast(connection_); 33 | return connection != nullptr; 34 | } 35 | 36 | bool Component::setMemManager(void *memory_manager_) { 37 | memory_manager = static_cast(memory_manager_); 38 | return memory_manager != nullptr; 39 | } 40 | 41 | void Component::SetLocale(const WCHAR_T *locale) { 42 | #ifdef CASE_INSENSITIVE 43 | try { 44 | std::locale::global(std::locale{toUTF8String(locale)}); 45 | } catch (std::runtime_error &) { 46 | std::locale::global(std::locale{""}); 47 | } 48 | #endif 49 | } 50 | 51 | bool Component::RegisterExtensionAs(WCHAR_T **ext_name) { 52 | auto name = extensionName(); 53 | 54 | try { 55 | storeVariable(name, ext_name); 56 | } catch (const std::bad_alloc &) { 57 | return false; 58 | } 59 | 60 | return true; 61 | } 62 | 63 | long Component::GetNProps() { 64 | return properties_meta.size(); 65 | } 66 | 67 | long Component::FindProp(const WCHAR_T *prop_name) { 68 | 69 | std::wstring lookup_name = toWstring(prop_name); 70 | 71 | #ifdef CASE_INSENSITIVE 72 | lookup_name = toUpper(lookup_name); 73 | 74 | for (auto i = 0u; i < properties_meta.size(); ++i) { 75 | if (toUpper(properties_meta[i].alias) == lookup_name 76 | || toUpper(properties_meta[i].alias_ru) == lookup_name) { 77 | return static_cast(i); 78 | } 79 | } 80 | #else 81 | for (auto i = 0u; i < properties_meta.size(); ++i) { 82 | if (properties_meta[i].alias == lookup_name 83 | || properties_meta[i].alias_ru == lookup_name) { 84 | return static_cast(i); 85 | } 86 | } 87 | #endif 88 | return -1; 89 | 90 | } 91 | 92 | const WCHAR_T *Component::GetPropName(long num, long lang_alias) { 93 | 94 | std::wstring *name; 95 | if (lang_alias == 0) { 96 | name = &(properties_meta[num].alias); 97 | } else { 98 | name = &(properties_meta[num].alias_ru); 99 | } 100 | 101 | WCHAR_T *result = nullptr; 102 | storeVariable(std::u16string(reinterpret_cast(name->c_str())), &result); 103 | 104 | return result; 105 | } 106 | 107 | bool Component::GetPropVal(const long num, tVariant *value) { 108 | 109 | try { 110 | auto tmp = properties_meta[num].getter(); 111 | storeVariable(*tmp, *value); 112 | } catch (const std::exception &e) { 113 | AddError(ADDIN_E_FAIL, extensionName(), e.what(), true); 114 | return false; 115 | } catch (...) { 116 | AddError(ADDIN_E_FAIL, extensionName(), UNKNOWN_EXCP, true); 117 | return false; 118 | } 119 | 120 | return true; 121 | } 122 | 123 | bool Component::SetPropVal(const long num, tVariant *value) { 124 | 125 | try { 126 | auto tmp = toStlVariant(*value); 127 | properties_meta[num].setter(std::move(tmp)); 128 | } catch (const std::exception &e) { 129 | AddError(ADDIN_E_FAIL, extensionName(), e.what(), true); 130 | return false; 131 | } catch (...) { 132 | AddError(ADDIN_E_FAIL, extensionName(), UNKNOWN_EXCP, true); 133 | return false; 134 | } 135 | 136 | return true; 137 | } 138 | 139 | bool Component::IsPropReadable(const long lPropNum) { 140 | return static_cast(properties_meta[lPropNum].getter); 141 | } 142 | 143 | bool Component::IsPropWritable(const long lPropNum) { 144 | return static_cast(properties_meta[lPropNum].setter); 145 | } 146 | 147 | long Component::GetNMethods() { 148 | return methods_meta.size(); 149 | } 150 | 151 | long Component::FindMethod(const WCHAR_T *method_name) { 152 | 153 | std::wstring lookup_name = toWstring(method_name); 154 | 155 | #ifdef CASE_INSENSITIVE 156 | lookup_name = toUpper(lookup_name); 157 | 158 | for (auto i = 0u; i < methods_meta.size(); ++i) { 159 | if (toUpper(methods_meta[i].alias) == lookup_name 160 | || toUpper(methods_meta[i].alias_ru) == lookup_name) { 161 | return static_cast(i); 162 | } 163 | } 164 | #else 165 | for (auto i = 0u; i < methods_meta.size(); ++i) { 166 | if (methods_meta[i].alias == lookup_name 167 | || methods_meta[i].alias_ru == lookup_name) { 168 | return static_cast(i); 169 | } 170 | } 171 | #endif 172 | 173 | return -1; 174 | } 175 | 176 | const WCHAR_T *Component::GetMethodName(const long num, const long lang_alias) { 177 | 178 | std::wstring *name; 179 | if (lang_alias == 0) { 180 | name = &(methods_meta[num].alias); 181 | } else { 182 | name = &(methods_meta[num].alias_ru); 183 | } 184 | 185 | WCHAR_T *result = nullptr; 186 | storeVariable(std::u16string(reinterpret_cast(name->c_str())), &result); 187 | 188 | return result; 189 | 190 | } 191 | 192 | long Component::GetNParams(const long method_num) { 193 | return methods_meta[method_num].params_count; 194 | } 195 | 196 | bool Component::GetParamDefValue(const long method_num, const long param_num, tVariant *def_value) { 197 | 198 | auto &def_args = methods_meta[method_num].default_args; 199 | 200 | auto it = def_args.find(param_num); 201 | if (it == def_args.end()) { 202 | return false; 203 | } 204 | 205 | storeVariable(it->second, *def_value); 206 | return true; 207 | } 208 | 209 | bool Component::HasRetVal(const long method_num) { 210 | return methods_meta[method_num].returns_value; 211 | } 212 | 213 | bool Component::CallAsProc(const long method_num, tVariant *params, const long array_size) { 214 | 215 | try { 216 | auto args = parseParams(params, array_size); 217 | methods_meta[method_num].call(args); 218 | #ifdef OUT_PARAMS 219 | storeParams(args, params); 220 | #endif 221 | } catch (const std::exception &e) { 222 | AddError(ADDIN_E_FAIL, extensionName(), e.what(), true); 223 | return false; 224 | } catch (...) { 225 | AddError(ADDIN_E_FAIL, extensionName(), UNKNOWN_EXCP, true); 226 | return false; 227 | } 228 | 229 | return true; 230 | } 231 | 232 | bool Component::CallAsFunc(const long method_num, tVariant *ret_value, tVariant *params, const long array_size) { 233 | 234 | try { 235 | auto args = parseParams(params, array_size); 236 | variant_t result = methods_meta[method_num].call(args); 237 | storeVariable(result, *ret_value); 238 | #ifdef OUT_PARAMS 239 | storeParams(args, params); 240 | #endif 241 | } catch (const std::exception &e) { 242 | AddError(ADDIN_E_FAIL, extensionName(), e.what(), true); 243 | return false; 244 | } catch (...) { 245 | AddError(ADDIN_E_FAIL, extensionName(), UNKNOWN_EXCP, true); 246 | return false; 247 | } 248 | 249 | return true; 250 | 251 | } 252 | 253 | void Component::AddError(unsigned short code, const std::string &src, const std::string &msg, bool throw_excp) { 254 | WCHAR_T *source = nullptr; 255 | WCHAR_T *descr = nullptr; 256 | 257 | storeVariable(src, &source); 258 | storeVariable(msg, &descr); 259 | 260 | connection->AddError(code, source, descr, throw_excp); 261 | 262 | memory_manager->FreeMemory(reinterpret_cast(&source)); 263 | memory_manager->FreeMemory(reinterpret_cast(&descr)); 264 | } 265 | 266 | void Component::AddProperty(const std::wstring &alias, const std::wstring &alias_ru, 267 | std::function(void)> getter, 268 | std::function setter) { 269 | 270 | PropertyMeta meta{alias, alias_ru, std::move(getter), std::move(setter)}; 271 | properties_meta.push_back(std::move(meta)); 272 | 273 | } 274 | 275 | void Component::AddProperty(const std::wstring &alias, const std::wstring &alias_ru, 276 | std::shared_ptr storage) { 277 | 278 | if (!storage) { 279 | return; 280 | } 281 | 282 | AddProperty(alias, alias_ru, 283 | [storage]() { // getter 284 | return storage; 285 | }, 286 | [storage](variant_t &&v) -> void { //setter 287 | *storage = std::move(v); 288 | }); 289 | 290 | } 291 | 292 | variant_t Component::toStlVariant(tVariant src) { 293 | switch (src.vt) { 294 | case VTYPE_EMPTY: 295 | return UNDEFINED; 296 | case VTYPE_I4: //int32_t 297 | return src.lVal; 298 | case VTYPE_R8: //double 299 | return src.dblVal; 300 | case VTYPE_PWSTR: { //std::string 301 | return toUTF8String(std::basic_string_view(src.pwstrVal, src.wstrLen)); 302 | } 303 | case VTYPE_BOOL: 304 | return src.bVal; 305 | case VTYPE_BLOB: 306 | return std::vector(src.pstrVal, src.pstrVal + src.strLen); 307 | default: 308 | throw std::bad_cast(); 309 | } 310 | } 311 | 312 | void Component::storeVariable(const variant_t &src, tVariant &dst) { 313 | 314 | if (dst.vt == VTYPE_PWSTR && dst.pwstrVal != nullptr) { 315 | memory_manager->FreeMemory(reinterpret_cast(&dst.pwstrVal)); 316 | } 317 | 318 | if ((dst.vt == VTYPE_PSTR || dst.vt == VTYPE_BLOB) && dst.pstrVal != nullptr) { 319 | memory_manager->FreeMemory(reinterpret_cast(&dst.pstrVal)); 320 | } 321 | 322 | std::visit(overloaded{ 323 | [&](std::monostate) { dst.vt = VTYPE_EMPTY; }, 324 | [&](const int32_t &v) { 325 | dst.vt = VTYPE_I4; 326 | dst.lVal = v; 327 | }, 328 | [&](const double &v) { 329 | dst.vt = VTYPE_R8; 330 | dst.dblVal = v; 331 | }, 332 | [&](const bool v) { 333 | dst.vt = VTYPE_BOOL; 334 | dst.bVal = v; 335 | }, 336 | [&](const std::string &v) { storeVariable(v, dst); }, 337 | [&](const std::vector &v) { storeVariable(v, dst); } 338 | }, src); 339 | 340 | } 341 | 342 | void Component::storeVariable(const std::string &src, tVariant &dst) { 343 | 344 | std::u16string tmp = toUTF16String(src); 345 | 346 | dst.vt = VTYPE_PWSTR; 347 | storeVariable(tmp, &dst.pwstrVal); 348 | dst.wstrLen = static_cast(tmp.length()); 349 | } 350 | 351 | void Component::storeVariable(const std::string &src, WCHAR_T **dst) { 352 | std::u16string tmp = toUTF16String(src); 353 | storeVariable(tmp, dst); 354 | } 355 | 356 | void Component::storeVariable(const std::u16string &src, WCHAR_T **dst) { 357 | 358 | size_t c_size = (src.size() + 1) * sizeof(char16_t); 359 | 360 | if (!memory_manager || !memory_manager->AllocMemory(reinterpret_cast(dst), c_size)) { 361 | throw std::bad_alloc(); 362 | }; 363 | 364 | memcpy(*dst, src.c_str(), c_size); 365 | } 366 | 367 | void Component::storeVariable(const std::vector &src, tVariant &dst) { 368 | 369 | dst.vt = VTYPE_BLOB; 370 | dst.strLen = src.size(); 371 | 372 | if (!memory_manager || !memory_manager->AllocMemory(reinterpret_cast(&dst.pstrVal), src.size())) { 373 | throw std::bad_alloc(); 374 | }; 375 | 376 | memcpy(dst.pstrVal, src.data(), src.size()); 377 | } 378 | 379 | std::vector Component::parseParams(tVariant *params, long array_size) { 380 | std::vector result; 381 | 382 | auto size = static_cast(array_size); 383 | result.reserve(size); 384 | for (size_t i = 0; i < size; i++) { 385 | result.emplace_back(toStlVariant(params[i])); 386 | } 387 | 388 | return result; 389 | } 390 | 391 | void Component::storeParams(const std::vector &src, tVariant *dest) { 392 | for (size_t i = 0; i < src.size(); i++) { 393 | storeVariable(src[i], dest[i]); 394 | } 395 | } 396 | 397 | std::wstring Component::toUpper(std::wstring str) { 398 | std::transform(str.begin(), str.end(), str.begin(), std::towupper); 399 | return str; 400 | } 401 | 402 | std::string Component::toUTF8String(std::basic_string_view src) { 403 | #ifdef _WINDOWS 404 | // VS bug 405 | // https://social.msdn.microsoft.com/Forums/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral 406 | static std::wstring_convert> cvt_utf8_utf16; 407 | return cvt_utf8_utf16.to_bytes(src.data(), src.data() + src.size()); 408 | #else 409 | static std::wstring_convert, char16_t> cvt_utf8_utf16; 410 | return cvt_utf8_utf16.to_bytes(reinterpret_cast(src.data()), 411 | reinterpret_cast(src.data() + src.size())); 412 | #endif 413 | } 414 | 415 | std::wstring Component::toWstring(std::basic_string_view src) { 416 | #ifdef _WINDOWS 417 | return std::wstring(src); 418 | #else 419 | std::wstring_convert> conv; 420 | return conv.from_bytes(reinterpret_cast(src.data()), 421 | reinterpret_cast(src.data() + src.size())); 422 | #endif 423 | } 424 | 425 | std::u16string Component::toUTF16String(std::string_view src) { 426 | #ifdef _WINDOWS 427 | static std::wstring_convert> cvt_utf8_utf16; 428 | std::wstring tmp = cvt_utf8_utf16.from_bytes(src.data(), src.data() + src.size()); 429 | return std::u16string(reinterpret_cast(tmp.data()), tmp.size()); 430 | #else 431 | static std::wstring_convert, char16_t> cvt_utf8_utf16; 432 | return cvt_utf8_utf16.from_bytes(src.data(), src.data() + src.size()); 433 | #endif 434 | } 435 | -------------------------------------------------------------------------------- /src/Component.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Modern Native AddIn 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef COMPONENT_H 21 | #define COMPONENT_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | template 36 | struct overloaded : Ts ... { 37 | using Ts::operator()...; 38 | }; 39 | template overloaded(Ts...) -> overloaded; 40 | 41 | #define UNDEFINED std::monostate() 42 | 43 | typedef std::variant< 44 | std::monostate, 45 | int32_t, 46 | double, 47 | bool, 48 | std::string, 49 | std::vector 50 | > variant_t; 51 | 52 | class Component : public IComponentBase { 53 | public: 54 | 55 | bool ADDIN_API Init(void *connection_) final; 56 | 57 | bool ADDIN_API setMemManager(void *memory_manager_) final; 58 | 59 | long ADDIN_API GetInfo() final { return 2100; }; 60 | 61 | void ADDIN_API Done() final {}; 62 | 63 | void ADDIN_API SetLocale(const WCHAR_T *locale) final; 64 | 65 | bool ADDIN_API RegisterExtensionAs(WCHAR_T **ext_name) final; 66 | 67 | long ADDIN_API GetNProps() final; 68 | 69 | long ADDIN_API FindProp(const WCHAR_T *prop_name) final; 70 | 71 | const WCHAR_T *ADDIN_API GetPropName(long num, long lang_alias) final; 72 | 73 | bool ADDIN_API GetPropVal(const long num, tVariant *value) final; 74 | 75 | bool ADDIN_API SetPropVal(const long num, tVariant *value) final; 76 | 77 | bool ADDIN_API IsPropReadable(const long lPropNum) final; 78 | 79 | bool ADDIN_API IsPropWritable(const long lPropNum) final; 80 | 81 | long ADDIN_API GetNMethods() final; 82 | 83 | long ADDIN_API FindMethod(const WCHAR_T *method_name) final; 84 | 85 | const WCHAR_T *ADDIN_API GetMethodName(const long num, const long lang_alias) final; 86 | 87 | long ADDIN_API GetNParams(const long method_num) final; 88 | 89 | bool ADDIN_API GetParamDefValue(const long method_num, const long param_num, tVariant *def_value) final; 90 | 91 | bool ADDIN_API HasRetVal(const long method_num) final; 92 | 93 | bool ADDIN_API CallAsProc(const long method_num, tVariant *params, const long array_size) final; 94 | 95 | bool ADDIN_API CallAsFunc(const long method_num, tVariant *ret_value, tVariant *params, 96 | const long array_size) final; 97 | 98 | protected: 99 | virtual std::string extensionName() = 0; 100 | 101 | void AddError(unsigned short code, const std::string &src, const std::string &msg, bool throw_excp); 102 | 103 | void AddProperty(const std::wstring &alias, const std::wstring &alias_ru, 104 | std::function(void)> getter = nullptr, 105 | std::function setter = nullptr); 106 | 107 | void AddProperty(const std::wstring &alias, const std::wstring &alias_ru, 108 | std::shared_ptr storage); 109 | 110 | template 111 | void AddMethod(const std::wstring &alias, const std::wstring &alias_ru, C *c, T(C::*f)(Ts ...), 112 | std::map &&def_args = {}); 113 | 114 | private: 115 | class PropertyMeta; 116 | 117 | class MethodMeta; 118 | 119 | template 120 | static auto refTupleGen(std::vector &v, std::index_sequence); 121 | 122 | static variant_t toStlVariant(tVariant src); 123 | 124 | static std::string toUTF8String(std::basic_string_view src); 125 | 126 | static std::wstring toWstring(std::basic_string_view src); 127 | 128 | static std::u16string toUTF16String(std::string_view src); 129 | 130 | void storeVariable(const std::string &src, tVariant &dst); 131 | 132 | void storeVariable(const std::string &src, WCHAR_T **dst); 133 | 134 | void storeVariable(const std::u16string &src, WCHAR_T **dst); 135 | 136 | void storeVariable(const std::vector &src, tVariant &dst); 137 | 138 | void storeVariable(const variant_t &src, tVariant &dst); 139 | 140 | static std::vector parseParams(tVariant *params, long array_size); 141 | 142 | void storeParams(const std::vector &src, tVariant *dest); 143 | 144 | static std::wstring toUpper(std::wstring str); 145 | 146 | IAddInDefBase *connection; 147 | IMemoryManager *memory_manager; 148 | std::vector properties_meta; 149 | std::vector methods_meta; 150 | static constexpr char UNKNOWN_EXCP[] = u8"Unknown unhandled exception"; 151 | 152 | }; 153 | 154 | class Component::PropertyMeta { 155 | public: 156 | PropertyMeta &operator=(const PropertyMeta &) = delete; 157 | 158 | PropertyMeta(const PropertyMeta &) = delete; 159 | 160 | PropertyMeta(PropertyMeta &&) = default; 161 | 162 | PropertyMeta &operator=(PropertyMeta &&) = default; 163 | 164 | std::wstring alias; 165 | std::wstring alias_ru; 166 | std::function(void)> getter; 167 | std::function setter; 168 | }; 169 | 170 | class Component::MethodMeta { 171 | public: 172 | MethodMeta &operator=(const MethodMeta &) = delete; 173 | 174 | MethodMeta(const MethodMeta &) = delete; 175 | 176 | MethodMeta(MethodMeta &&) = default; 177 | 178 | MethodMeta &operator=(MethodMeta &&) = default; 179 | 180 | std::wstring alias; 181 | std::wstring alias_ru; 182 | long params_count; 183 | bool returns_value; 184 | std::map default_args; 185 | std::function ¶ms)> call; 186 | }; 187 | 188 | template 189 | auto Component::refTupleGen(std::vector &v, std::index_sequence) { 190 | return std::forward_as_tuple(v[Indices]...); 191 | } 192 | 193 | template 194 | void Component::AddMethod(const std::wstring &alias, const std::wstring &alias_ru, C *c, T(C::*f)(Ts ...), 195 | std::map &&def_args) { 196 | 197 | MethodMeta meta{alias, alias_ru, sizeof...(Ts), !std::is_same::value, std::move(def_args), 198 | [f, c](std::vector ¶ms) -> variant_t { 199 | auto args = refTupleGen(params, std::make_index_sequence()); 200 | if constexpr (std::is_same::value) { 201 | std::apply(f, std::tuple_cat(std::make_tuple(c), args)); 202 | return UNDEFINED; 203 | } else { 204 | return std::apply(f, std::tuple_cat(std::make_tuple(c), args)); 205 | } 206 | } 207 | }; 208 | 209 | methods_meta.push_back(std::move(meta)); 210 | }; 211 | 212 | #endif //COMPONENT_H 213 | -------------------------------------------------------------------------------- /src/ForwardingServer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #include 21 | #include "ForwardingServer.h" 22 | 23 | ForwardingServer::ForwardingServer(asio::io_context &io_context, 24 | std::shared_ptr session_, 25 | std::string dest_, unsigned short dest_port_, 26 | unsigned short port) : 27 | acceptor(io_context, tcp::endpoint(asio::ip::address::from_string("0.0.0.0"), port)), 28 | session(std::move(session_)), 29 | dest(std::move(dest_)), 30 | dest_port(dest_port_) { 31 | doAccept(); 32 | } 33 | 34 | void ForwardingServer::doAccept() { 35 | acceptor.async_accept([this](boost::system::error_code error, tcp::socket socket) { 36 | if (!error) { 37 | std::shared_ptr s; 38 | try { 39 | s = createSession(std::move(socket)); 40 | } catch (const std::runtime_error &) { 41 | // Failed to create channel or start forwarding 42 | // Just ignore since I don't know where to send this error. 43 | } 44 | s->start(); 45 | } 46 | doAccept(); 47 | }); 48 | } 49 | 50 | unsigned short ForwardingServer::GetPort() { 51 | return acceptor.local_endpoint().port(); 52 | } 53 | 54 | std::shared_ptr ForwardingServer::createSession(tcp::socket socket) { 55 | 56 | auto forwarding_channel = std::make_shared(session); 57 | auto rc = ssh_channel_open_forward(forwarding_channel->c_channel(), 58 | dest.data(), dest_port, 59 | "localhost", GetPort()); 60 | if (rc != SSH_OK) { 61 | throw std::runtime_error(ssh_get_error(session->c_session())); 62 | } 63 | 64 | return std::make_shared(std::move(socket), std::move(forwarding_channel)); 65 | } 66 | -------------------------------------------------------------------------------- /src/ForwardingServer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef FORWARDINGSERVER_H 21 | #define FORWARDINGSERVER_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include "ForwardingSession.h" 27 | 28 | namespace asio = boost::asio; 29 | using asio::ip::tcp; 30 | 31 | class ForwardingServer { 32 | public: 33 | ForwardingServer(asio::io_context &io_context, 34 | std::shared_ptr session_, 35 | std::string dest_, unsigned short dest_port_, 36 | unsigned short port); 37 | 38 | unsigned short GetPort(); 39 | 40 | private: 41 | void doAccept(); 42 | 43 | std::shared_ptr createSession(tcp::socket socket); 44 | 45 | std::shared_ptr session; 46 | tcp::acceptor acceptor; 47 | const std::string dest; 48 | const unsigned short dest_port; 49 | }; 50 | 51 | 52 | #endif //FORWARDINGSERVER_H 53 | -------------------------------------------------------------------------------- /src/ForwardingSession.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #include "ForwardingSession.h" 21 | 22 | void ForwardingSession::start() { 23 | doRead(); 24 | doWrite(); 25 | } 26 | 27 | void ForwardingSession::stop() { 28 | if (socket.is_open()) { 29 | socket.close(); 30 | } 31 | } 32 | 33 | void ForwardingSession::doRead() { 34 | // Keep this object alive 35 | auto self = shared_from_this(); 36 | asio::post(socket.get_executor(), [this, self]() { handleRead(); }); 37 | } 38 | 39 | void ForwardingSession::handleRead() { 40 | auto c_channel = channel->c_channel(); 41 | 42 | if (ssh_channel_is_eof(c_channel)) { 43 | return; 44 | } 45 | 46 | if (!socket.is_open()) { 47 | return; 48 | } 49 | 50 | int len = ssh_channel_read_nonblocking(c_channel, read_buffer, BUFFER_SIZE, false); 51 | 52 | if (len == SSH_ERROR) { 53 | return; 54 | } 55 | 56 | auto self = shared_from_this(); 57 | asio::async_write(socket, asio::buffer(read_buffer, len), 58 | [this, self, len](const boost::system::error_code &error, std::size_t size) { 59 | if (!error && size == len) { 60 | doRead(); 61 | } 62 | }); 63 | } 64 | 65 | void ForwardingSession::doWrite() { 66 | auto self = shared_from_this(); 67 | 68 | if (!socket.is_open()) { 69 | return; 70 | } 71 | 72 | socket.async_read_some(write_mb, [this, self](const boost::system::error_code &error, std::size_t size) { 73 | if (error) { 74 | return; 75 | } 76 | auto c_channel = channel->c_channel(); 77 | 78 | if (!ssh_channel_is_open(c_channel)) { 79 | return; 80 | } 81 | 82 | auto rc = ssh_channel_write(c_channel, write_buffer, size); 83 | 84 | if (rc == SSH_ERROR || rc != size) { 85 | return; 86 | } 87 | 88 | doWrite(); 89 | }); 90 | } 91 | 92 | ForwardingSession::~ForwardingSession() { 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/ForwardingSession.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef FORWARDINGSESSION_H 21 | #define FORWARDINGSESSION_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include "SshChannel.h" 27 | 28 | namespace asio = boost::asio; 29 | using asio::ip::tcp; 30 | 31 | class ForwardingSession : public std::enable_shared_from_this { 32 | public: 33 | ForwardingSession(tcp::socket socket_, std::shared_ptr channel_) : 34 | socket(std::move(socket_)), 35 | channel(std::move(channel_)) {}; 36 | 37 | void start(); 38 | 39 | void stop(); 40 | 41 | // Read from SSH channel and pass to socket 42 | void doRead(); 43 | 44 | void handleRead(); 45 | 46 | // Read from socket and forward to SSH channel 47 | void doWrite(); 48 | 49 | virtual ~ForwardingSession(); 50 | 51 | private: 52 | std::shared_ptr channel; 53 | tcp::socket socket; 54 | static constexpr int BUFFER_SIZE = 1024; 55 | char read_buffer[BUFFER_SIZE] = {0}; 56 | char write_buffer[BUFFER_SIZE] = {0}; 57 | asio::mutable_buffer write_mb = {write_buffer, BUFFER_SIZE}; 58 | }; 59 | 60 | 61 | #endif //FORWARDINGSESSION_H 62 | -------------------------------------------------------------------------------- /src/SshAddIn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include "SshAddIn.h" 24 | 25 | std::string SshAddIn::extensionName() { 26 | return EXT_NAME; 27 | } 28 | 29 | SshAddIn::SshAddIn() { 30 | addMethods(); 31 | addProperties(); 32 | 33 | ssh_set_log_level(SSH_LOG_NOLOG); 34 | session = SshSession::Create(); 35 | } 36 | 37 | SshAddIn::~SshAddIn() { 38 | DisablePortForwarding(); 39 | 40 | ssh_set_log_callback([](int, const char *, const char *, void *) {}); 41 | ssh_set_log_userdata(nullptr); 42 | } 43 | 44 | variant_t SshAddIn::Connect() { 45 | error_desc.clear(); 46 | 47 | auto c_session = session->c_session(); 48 | 49 | if (ssh_is_connected(c_session)) { 50 | error_desc = ALREADY_CONNECTED; 51 | return false; 52 | } 53 | 54 | if (ssh_connect(c_session) != SSH_OK) { 55 | error_desc = ssh_get_error(c_session); 56 | return false; 57 | } 58 | 59 | return authenticate(); 60 | } 61 | 62 | void SshAddIn::addMethods() { 63 | AddMethod(L"Connect", L"Подключиться", this, &SshAddIn::Connect); 64 | AddMethod(L"Exec", L"Выполнить", this, &SshAddIn::Exec, {{1, ""}, 65 | {2, ""}}); 66 | AddMethod(L"Read", L"Прочитать", this, &SshAddIn::Read); 67 | AddMethod(L"Write", L"Записать", this, &SshAddIn::Write, {{2, "0644"}}); 68 | 69 | AddMethod(L"EnableLog", L"ВключитьЖурнал", this, &SshAddIn::EnableLog, {{0, SSH_LOG_DEBUG}}); 70 | AddMethod(L"GetLog", L"ПолучитьЖурнал", this, &SshAddIn::GetLog); 71 | AddMethod(L"ClearLog", L"ОчиститьЖурнал", this, &SshAddIn::ClearLog); 72 | 73 | AddMethod(L"EnablePortForwarding", L"ВключитьПеренаправлениеПорта", this, &SshAddIn::EnablePortForwarding); 74 | AddMethod(L"DisablePortForwarding", L"ОтключитьПеренаправлениеПортов", this, &SshAddIn::DisablePortForwarding); 75 | 76 | AddMethod(L"EnableLog", L"ВключитьЖурнал", this, &SshAddIn::EnableLog, {{0, SSH_LOG_DEBUG}}); 77 | AddMethod(L"GetLog", L"ПолучитьЖурнал", this, &SshAddIn::GetLog); 78 | AddMethod(L"ClearLog", L"ОчиститьЖурнал", this, &SshAddIn::ClearLog); 79 | 80 | AddMethod(L"ErrorDesc", L"ОписаниеОшибки", this, &SshAddIn::ErrorDesc); 81 | } 82 | 83 | void SshAddIn::addProperties() { 84 | using namespace std::placeholders; 85 | AddProperty(L"Host", L"АдресСервера", 86 | std::bind(&SshAddIn::getOption, this, SSH_OPTIONS_HOST), 87 | std::bind(&SshAddIn::setOption, this, SSH_OPTIONS_HOST, _1)); 88 | AddProperty(L"User", L"Пользователь", 89 | std::bind(&SshAddIn::getOption, this, SSH_OPTIONS_USER), 90 | std::bind(&SshAddIn::setOption, this, SSH_OPTIONS_USER, _1)); 91 | AddProperty(L"Port", L"Порт", 92 | std::bind(&SshAddIn::getPort, this), 93 | std::bind(&SshAddIn::setOption, this, SSH_OPTIONS_PORT, _1)); 94 | 95 | AddProperty(L"Password", L"Пароль", nullptr, [&](variant_t value) { 96 | std::visit(overloaded{ 97 | [&](const std::string &v) { password = v; }, 98 | [&](const int32_t &v) { password = std::to_string(v); }, 99 | [&](const auto &) { 100 | error_desc = TYPE_ERR; 101 | throw std::runtime_error(TYPE_ERR); 102 | } 103 | }, value); 104 | }); 105 | } 106 | 107 | void SshAddIn::setOption(ssh_options_e type, const variant_t &value) { 108 | error_desc.clear(); 109 | 110 | int result{SSH_ERROR}; 111 | std::visit(overloaded{ 112 | [&](const std::string &v) { result = ssh_options_set(session->c_session(), type, v.c_str()); }, 113 | [&](const int32_t &v) { result = ssh_options_set(session->c_session(), type, &v); }, 114 | [&](const auto &) {} 115 | }, value); 116 | 117 | if (result != SSH_OK) { 118 | error_desc = ssh_get_error(session->c_session()); 119 | AddError(ADDIN_E_FAIL, EXT_NAME, error_desc, true); 120 | } 121 | } 122 | 123 | std::shared_ptr SshAddIn::getOption(ssh_options_e type) { 124 | error_desc.clear(); 125 | char *pValue; 126 | 127 | if (ssh_options_get(session->c_session(), type, &pValue) == SSH_OK) { 128 | std::string value{pValue}; 129 | ssh_string_free_char(pValue); 130 | return std::make_shared(value); 131 | } else { 132 | error_desc = ssh_get_error(session->c_session()); 133 | AddError(ADDIN_E_FAIL, EXT_NAME, error_desc, true); 134 | ssh_string_free_char(pValue); 135 | return std::make_shared(UNDEFINED); 136 | } 137 | } 138 | 139 | std::shared_ptr SshAddIn::getPort() { 140 | error_desc.clear(); 141 | 142 | unsigned int port; 143 | if (ssh_options_get_port(session->c_session(), &port) == SSH_OK) { 144 | return std::make_shared(static_cast(port)); 145 | } else { 146 | error_desc = ssh_get_error(session->c_session()); 147 | AddError(ADDIN_E_FAIL, EXT_NAME, error_desc, true); 148 | return std::make_shared(UNDEFINED); 149 | } 150 | } 151 | 152 | variant_t SshAddIn::authenticate() { 153 | error_desc.clear(); 154 | 155 | auto c_session = session->c_session(); 156 | if (!ssh_is_connected(c_session)) { 157 | error_desc = NOT_CONNECTED; 158 | return false; 159 | } 160 | 161 | int rc; 162 | 163 | if (password.empty()) { 164 | rc = ssh_userauth_publickey_auto(c_session, nullptr, nullptr); 165 | } else { 166 | rc = ssh_userauth_password(c_session, nullptr, password.c_str()); 167 | } 168 | 169 | if (rc != SSH_AUTH_SUCCESS) { 170 | error_desc = ssh_get_error(c_session); 171 | return false; 172 | } 173 | 174 | return true; 175 | } 176 | 177 | variant_t SshAddIn::Exec(const variant_t &command, variant_t &res_stdout, variant_t &res_stderr) { 178 | 179 | error_desc.clear(); 180 | if (!(std::holds_alternative(command))) { 181 | error_desc = TYPE_ERR; 182 | throw std::runtime_error(TYPE_ERR); 183 | } 184 | 185 | std::string cmd = std::get(command); 186 | auto c_session = session->c_session(); 187 | 188 | if (!ssh_is_connected(c_session)) { 189 | error_desc = NOT_CONNECTED; 190 | return false; 191 | } 192 | 193 | std::shared_ptr channel; 194 | try { 195 | channel = std::make_shared(session); 196 | } catch (const std::runtime_error &error) { 197 | error_desc = error.what(); 198 | return false; 199 | } 200 | ssh_channel c_channel = channel->c_channel(); 201 | 202 | if (ssh_channel_open_session(c_channel) != SSH_OK) { 203 | error_desc = ssh_get_error(c_session); 204 | return false; 205 | } 206 | 207 | if (ssh_channel_request_exec(c_channel, cmd.c_str()) != SSH_OK) { 208 | error_desc = ssh_get_error(c_session); 209 | return false; 210 | } 211 | 212 | std::vector stdout_chunks; 213 | std::vector stderr_chunks; 214 | 215 | while (!ssh_channel_is_eof(c_channel)) { 216 | bool success = readChannel(stdout_chunks, c_channel, false) && 217 | readChannel(stderr_chunks, c_channel, true); 218 | 219 | if (!success) { 220 | error_desc = ssh_get_error(c_session); 221 | return false; 222 | } 223 | } 224 | 225 | res_stdout = boost::algorithm::join(stdout_chunks, ""); 226 | res_stderr = boost::algorithm::join(stderr_chunks, ""); 227 | 228 | ssh_channel_send_eof(c_channel); 229 | 230 | return true; 231 | } 232 | 233 | bool SshAddIn::readChannel(std::vector &chunks, ssh_channel channel, bool is_stderr) { 234 | 235 | char buffer[256]; 236 | 237 | for (;;) { 238 | int num_bytes = ssh_channel_read(channel, buffer, sizeof(buffer), is_stderr); 239 | if (num_bytes > 0) { 240 | chunks.emplace_back(buffer, num_bytes); 241 | } else if (num_bytes == 0) { 242 | break; 243 | } else { 244 | return false; 245 | } 246 | } 247 | 248 | return true; 249 | } 250 | 251 | void SshAddIn::EnableLog(const variant_t &level) { 252 | error_desc.clear(); 253 | 254 | if (!(std::holds_alternative(level))) { 255 | error_desc = TYPE_ERR; 256 | throw std::runtime_error(TYPE_ERR); 257 | } 258 | 259 | ssh_set_log_level(std::get(level)); 260 | ssh_set_log_userdata(this); 261 | ssh_set_log_callback([](int priority, const char *function, const char *buffer, void *userdata) { 262 | reinterpret_cast(userdata)->log.emplace_back(std::string(function) + ": " + std::string(buffer)); 263 | }); 264 | } 265 | 266 | variant_t SshAddIn::GetLog() { 267 | error_desc.clear(); 268 | std::string result = boost::algorithm::join(log, "\n"); 269 | return result; 270 | } 271 | 272 | void SshAddIn::ClearLog() { 273 | error_desc.clear(); 274 | log = std::vector(); 275 | } 276 | 277 | variant_t SshAddIn::Read(const variant_t &path, variant_t &dst) { 278 | 279 | error_desc.clear(); 280 | if (!(std::holds_alternative(path))) { 281 | error_desc = TYPE_ERR; 282 | throw std::runtime_error(TYPE_ERR); 283 | } 284 | 285 | boost::filesystem::path p{std::get(path)}; 286 | ssh_scp scp; 287 | auto c_session = session->c_session(); 288 | 289 | if (!ssh_is_connected(c_session)) { 290 | error_desc = NOT_CONNECTED; 291 | return false; 292 | } 293 | 294 | scp = ssh_scp_new(c_session, SSH_SCP_READ, p.generic_string().c_str()); 295 | if (scp == nullptr) { 296 | error_desc = ssh_get_error(c_session); 297 | return false; 298 | } 299 | 300 | if (ssh_scp_init(scp) != SSH_OK) { 301 | error_desc = ssh_get_error(c_session); 302 | ssh_scp_free(scp); 303 | return false; 304 | } 305 | 306 | auto result = receive(scp, dst); 307 | 308 | ssh_scp_close(scp); 309 | ssh_scp_free(scp); 310 | return result; 311 | } 312 | 313 | bool SshAddIn::receive(ssh_scp scp, variant_t &dst) { 314 | 315 | if (ssh_scp_pull_request(scp) != SSH_SCP_REQUEST_NEWFILE) { 316 | error_desc = ssh_get_error(session->c_session()); 317 | return false; 318 | } 319 | 320 | int size = ssh_scp_request_get_size(scp); 321 | std::vector buffer(size); 322 | 323 | ssh_scp_accept_request(scp); 324 | if (ssh_scp_read(scp, buffer.data(), size) == SSH_ERROR) { 325 | error_desc = ssh_get_error(session->c_session()); 326 | return false; 327 | } 328 | 329 | if (ssh_scp_pull_request(scp) != SSH_SCP_REQUEST_EOF) { 330 | error_desc = ssh_get_error(session->c_session()); 331 | return false; 332 | } 333 | 334 | dst = std::move(buffer); 335 | return true; 336 | } 337 | 338 | variant_t SshAddIn::Write(const variant_t &path, const variant_t &src, const variant_t &mode) { 339 | 340 | error_desc.clear(); 341 | 342 | if (!(std::holds_alternative(path)) 343 | || !(std::holds_alternative>(src))) { 344 | error_desc = TYPE_ERR; 345 | throw std::runtime_error(TYPE_ERR); 346 | } 347 | 348 | ssh_scp scp; 349 | auto c_session = session->c_session(); 350 | boost::filesystem::path p{std::get(path)}; 351 | std::vector buffer = std::get>(src); 352 | 353 | if (!ssh_is_connected(c_session)) { 354 | error_desc = NOT_CONNECTED; 355 | return false; 356 | } 357 | 358 | if (!p.has_filename()) { 359 | error_desc = "path doesn't contain filename"; 360 | return false; 361 | } 362 | 363 | scp = ssh_scp_new(c_session, SSH_SCP_WRITE, p.generic_string().c_str()); 364 | if (scp == nullptr) { 365 | error_desc = ssh_get_error(c_session); 366 | return false; 367 | } 368 | 369 | if (ssh_scp_init(scp) != SSH_OK) { 370 | error_desc = ssh_get_error(c_session); 371 | ssh_scp_free(scp); 372 | return false; 373 | } 374 | 375 | auto result = send(scp, p.filename().generic_string(), buffer, mode); 376 | 377 | ssh_scp_close(scp); 378 | ssh_scp_free(scp); 379 | return true; 380 | } 381 | 382 | bool SshAddIn::send(ssh_scp scp, const std::string &filename, const std::vector &buffer, const variant_t &mode) { 383 | 384 | int raw_mode; 385 | 386 | std::visit(overloaded{ 387 | [&](const std::string &v) { 388 | // см. ssh_scp_integer_mode 389 | raw_mode = std::strtoul(v.c_str(), nullptr, 8) & 0xffff; 390 | }, 391 | [&](const int32_t &v) { raw_mode = v; }, 392 | [&](const auto &) { 393 | error_desc = TYPE_ERR; 394 | throw std::runtime_error(TYPE_ERR); 395 | } 396 | }, mode); 397 | 398 | if (ssh_scp_push_file(scp, filename.c_str(), buffer.size(), raw_mode) != SSH_OK) { 399 | error_desc = ssh_get_error(session->c_session()); 400 | return false; 401 | } 402 | 403 | if (ssh_scp_write(scp, buffer.data(), buffer.size()) != SSH_OK) { 404 | error_desc = ssh_get_error(session->c_session()); 405 | return false; 406 | } 407 | 408 | return true; 409 | } 410 | 411 | variant_t SshAddIn::ErrorDesc() { 412 | if (error_desc.empty()) { 413 | return UNDEFINED; 414 | } 415 | return error_desc; 416 | } 417 | 418 | variant_t SshAddIn::EnablePortForwarding(const variant_t &dest_, const variant_t &dest_port_, variant_t &port_) { 419 | error_desc.clear(); 420 | 421 | if (!std::holds_alternative(dest_) 422 | || !std::holds_alternative(dest_port_)) { 423 | error_desc = TYPE_ERR; 424 | throw std::runtime_error(TYPE_ERR); 425 | } 426 | 427 | std::string dest = std::get(dest_); 428 | unsigned short dest_port = std::get(dest_port_); 429 | 430 | unsigned short port = 0; 431 | if (std::holds_alternative(port_)) { 432 | port = std::get(port_); 433 | } 434 | 435 | if (!ssh_is_connected(session->c_session())) { 436 | error_desc = NOT_CONNECTED; 437 | return false; 438 | } 439 | 440 | auto server = std::make_shared(io_context, session, dest, dest_port, port); 441 | port_ = server->GetPort(); 442 | forwarding_servers.emplace_back(std::move(server)); 443 | 444 | if (forwarding_servers.size() == 1) { 445 | port_forwarding_thread = std::thread([&io = io_context]() { io.run(); }); 446 | } 447 | 448 | return true; 449 | } 450 | 451 | void SshAddIn::DisablePortForwarding() { 452 | error_desc.clear(); 453 | 454 | io_context.stop(); 455 | if (port_forwarding_thread.joinable()) { 456 | port_forwarding_thread.join(); 457 | } 458 | 459 | forwarding_servers.clear(); 460 | } -------------------------------------------------------------------------------- /src/SshAddIn.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef SSHADDIN_H 21 | #define SSHADDIN_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include "Component.h" 27 | #include "SshSession.h" 28 | #include "SshChannel.h" 29 | #include "ForwardingServer.h" 30 | 31 | namespace asio = boost::asio; 32 | 33 | class SshAddIn final : public Component { 34 | public: 35 | SshAddIn(); 36 | 37 | ~SshAddIn() override; 38 | 39 | private: 40 | /* Exposed methods */ 41 | variant_t Connect(); 42 | 43 | variant_t Exec(const variant_t &command, variant_t &res_stdout, variant_t &res_stderr); 44 | 45 | variant_t Read(const variant_t &path, variant_t &dst); 46 | 47 | variant_t Write(const variant_t &path, const variant_t &src, const variant_t &mode); 48 | 49 | variant_t ErrorDesc(); 50 | 51 | variant_t EnablePortForwarding(const variant_t &dest_, const variant_t &dest_port_, variant_t &port_); 52 | 53 | void DisablePortForwarding(); 54 | 55 | void EnableLog(const variant_t &level); 56 | 57 | variant_t GetLog(); 58 | 59 | void ClearLog(); 60 | 61 | /* Exposed properties */ 62 | std::string password; 63 | 64 | /* Service API */ 65 | std::string extensionName() override; 66 | 67 | void addMethods(); 68 | 69 | void addProperties(); 70 | 71 | variant_t authenticate(); 72 | 73 | void setOption(ssh_options_e type, const variant_t &value); 74 | 75 | std::shared_ptr getOption(ssh_options_e type); 76 | 77 | std::shared_ptr getPort(); 78 | 79 | static bool readChannel(std::vector &chunks, ssh_channel channel, bool is_stderr); 80 | 81 | bool receive(ssh_scp scp, variant_t &dst); 82 | 83 | bool send(ssh_scp scp, const std::string &filename, const std::vector &buffer, const variant_t &mode); 84 | 85 | static constexpr char EXT_NAME[] = u8"SSH"; 86 | static constexpr char NOT_CONNECTED[] = u8"not connected"; 87 | static constexpr char ALREADY_CONNECTED[] = u8"already connected"; 88 | static constexpr char TYPE_ERR[] = u8"Неверный тип значения входного параметра"; 89 | 90 | std::shared_ptr session; 91 | std::vector log; 92 | std::string error_desc; 93 | 94 | std::thread port_forwarding_thread; 95 | asio::io_context io_context; 96 | std::vector> forwarding_servers; 97 | }; 98 | 99 | #endif //SSHADDIN_H 100 | -------------------------------------------------------------------------------- /src/SshChannel.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef SSHCHANNEL_H 21 | #define SSHCHANNEL_H 22 | 23 | #include 24 | #include 25 | #include "SshSession.h" 26 | 27 | class SshChannel { 28 | public: 29 | explicit SshChannel(std::shared_ptr session_) : 30 | session(std::move(session_)) { 31 | channel = ssh_channel_new(session->c_session()); 32 | if (channel == nullptr) { 33 | throw std::runtime_error(ssh_get_error(session->c_session())); 34 | } 35 | }; 36 | 37 | virtual ~SshChannel() { 38 | if (ssh_channel_is_open(channel)) { 39 | ssh_channel_close(channel); 40 | } 41 | ssh_channel_free(channel); 42 | } 43 | 44 | ssh_channel c_channel() { 45 | return channel; 46 | } 47 | 48 | private: 49 | std::shared_ptr session; 50 | ssh_channel channel; 51 | }; 52 | 53 | #endif //SSHCHANNEL_H 54 | -------------------------------------------------------------------------------- /src/SshSession.h: -------------------------------------------------------------------------------- 1 | /* 2 | * SSH Native 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #ifndef SSHSESSION_H 21 | #define SSHSESSION_H 22 | 23 | #include 24 | #include 25 | 26 | // Not a full-featured libssh wrapper, but a Boost.Asio helper 27 | class SshSession { 28 | public: 29 | static std::shared_ptr Create() { 30 | struct enable_shared_ptr : public SshSession { 31 | }; 32 | return std::make_shared(); 33 | } 34 | 35 | ssh_session c_session() { 36 | return session; 37 | } 38 | 39 | virtual ~SshSession() { 40 | // Disconnect will invalidate all ssh channels 41 | // Use with care and don't bind to 1C API 42 | if (ssh_is_connected(session)) { 43 | ssh_disconnect(session); 44 | } 45 | ssh_free(session); 46 | } 47 | 48 | private: 49 | // Prey that we don't get memory error here 50 | SshSession() : session(ssh_new()) {}; 51 | 52 | ssh_session session; 53 | }; 54 | 55 | #endif //SSHSESSION_H 56 | -------------------------------------------------------------------------------- /src/addin.def: -------------------------------------------------------------------------------- 1 | LIBRARY "ssh_native" 2 | 3 | EXPORTS 4 | GetClassObject 5 | DestroyObject 6 | GetClassNames 7 | SetPlatformCapabilities 8 | -------------------------------------------------------------------------------- /src/dllmain.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | 3 | #ifdef _WINDOWS 4 | 5 | BOOL APIENTRY DllMain(HMODULE hModule, 6 | DWORD ul_reason_for_call, 7 | LPVOID lpReserved 8 | ) { 9 | switch (ul_reason_for_call) { 10 | case DLL_PROCESS_ATTACH: 11 | case DLL_THREAD_ATTACH: 12 | case DLL_THREAD_DETACH: 13 | case DLL_PROCESS_DETACH: 14 | default: 15 | break; 16 | } 17 | return TRUE; 18 | } 19 | 20 | #endif //_WINDOWS 21 | -------------------------------------------------------------------------------- /src/exports.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Modern Native AddIn 3 | * Copyright (C) 2018 Infactum 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as 7 | * published by the Free Software Foundation, either version 3 of the 8 | * License, or (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | #include "SshAddIn.h" 24 | 25 | #ifdef _WINDOWS 26 | #pragma warning (disable : 4311 4302) 27 | #endif 28 | 29 | const WCHAR_T *GetClassNames() { 30 | #if defined(_DEBUG) && defined(_WINDOWS) 31 | MessageBox(0, L"Attach Debugger", L"GetClassNames", MB_OK); 32 | #endif 33 | static char16_t cls_names[] = u"SSH"; 34 | return reinterpret_cast(cls_names); 35 | } 36 | 37 | long GetClassObject(const WCHAR_T *clsName, IComponentBase **pInterface) { 38 | if (!*pInterface) { 39 | auto cls_name = std::u16string(reinterpret_cast(clsName)); 40 | if (cls_name == u"SSH") { 41 | *pInterface = new SshAddIn; 42 | } 43 | return (long) *pInterface; 44 | } 45 | return 0; 46 | } 47 | 48 | long DestroyObject(IComponentBase **pInterface) { 49 | if (!*pInterface) { 50 | return -1; 51 | } 52 | 53 | delete *pInterface; 54 | *pInterface = nullptr; 55 | return 0; 56 | } 57 | 58 | AppCapabilities SetPlatformCapabilities(const AppCapabilities capabilities) { 59 | return eAppCapabilitiesLast; 60 | } 61 | -------------------------------------------------------------------------------- /src/stdafx.h: -------------------------------------------------------------------------------- 1 | #ifndef STDAFX_H 2 | #define STDAFX_H 3 | 4 | #ifdef _WINDOWS 5 | 6 | #include 7 | 8 | #endif //_WINDOWS 9 | 10 | #endif //STDAFX_H 11 | --------------------------------------------------------------------------------