Merge remote-tracking branch 'remotes/origin/dev'

# Conflicts:
#	build/builder/build-external.py
#	build/builder/build-server.py
#	server/.idea/server.iml
pull/32/merge
apexliu 2017-04-05 03:44:11 +08:00
commit 2f315c558b
272 changed files with 8106 additions and 60461 deletions

38
.gitignore vendored
View File

@ -14,6 +14,7 @@ CMakeFiles
cmake_install.cmake cmake_install.cmake
Makefile Makefile
cmake-build cmake-build
cmake-build-debug
# for Python # for Python
__pycache__ __pycache__
@ -28,6 +29,7 @@ __pycache__
**/.idea/watcherTasks.xml **/.idea/watcherTasks.xml
**/.idea/codeStyleSettings.xml **/.idea/codeStyleSettings.xml
**/.idea/inspectionProfiles **/.idea/inspectionProfiles
**/.idea/vcs.xml
# for tmp folder or files. # for tmp folder or files.
/out /out
@ -37,29 +39,33 @@ __pycache__
/external/mongoose /external/mongoose
/external/openssl /external/openssl
/external/python /external/python
/external/libssh-win-static/include/libssh
/external/libssh-win-static/src
/external/libssh-win-static/lib
/external/mbedtls
/external/sqlite
/client/tools/putty
/client/tools/winscp
# for dist folder # for dist folder
/dist/*.zip
/dist/*.tar.gz
/dist/installer/linux/server/_tmp_
**/_tmp_ **/_tmp_
/dist/server/data
/dist/client/windows/assist/apps
/dist/client/windows/assist/cfg
/server/share/data/ts_db.db /server/share/etc/core.ini
/server/share/data/replay /server/share/etc/web.ini
/server/share/data
/server/share/log
/server/www/teleport/.idea/vcs.xml /server/www/teleport/.idea/vcs.xml
/server/www/teleport/static/js/var.js
/server/www/packages/packages-windows/x64 /server/www/packages/packages-windows/x64
# for generated files.
/config.ini
/build.bat
# for not finished code # for not finished code
/common/libex/test /common/libex/test
/external/mbedtls
/external/sqlite
/server/share/etc/core.ini
/server/share/etc/web.ini
/client/tp_rdp /client/tp_rdp
/external/libssh-win-static/lib
/server/share/log
/config.ini
/build.bat
/dist/windows/client/assist/apps
/dist/windows/client/assist/cfg

View File

@ -2,7 +2,7 @@
<module type="PYTHON_MODULE" version="4"> <module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$/builder" /> <content url="file://$MODULE_DIR$/builder" />
<orderEntry type="jdk" jdkName="py34-x86" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="py" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
<component name="TestRunnerService"> <component name="TestRunnerService">

View File

@ -6,7 +6,7 @@
VER_PYTHON="3.4.4" VER_PYTHON="3.4.4"
VER_PYTHON_SHORT="3.4" VER_PYTHON_SHORT="3.4"
VER_OPENSSL="1.0.2h" VER_OPENSSL="1.0.2h"
VER_SQLITE="3160200" VER_SQLITE="3170000"
VER_PSUTIL="4.2.0" VER_PSUTIL="4.2.0"
VER_PYTHON_LIB="${VER_PYTHON_SHORT}m" VER_PYTHON_LIB="${VER_PYTHON_SHORT}m"

View File

@ -1,4 +1,3 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import getopt import getopt
@ -7,47 +6,27 @@ import os
import platform import platform
import sys import sys
THIS_PATH = os.path.abspath(os.path.dirname(__file__)) from builder.core.env import env
ROOT_PATH = os.path.abspath(os.path.join(THIS_PATH, '..')) import builder.core.colorconsole as cc
BUILDER_PATH = os.path.join(THIS_PATH, 'builder') import builder.core.utils as utils
from builder.core.context import *
sys.path.append(os.path.join(BUILDER_PATH)) if env.is_py2:
try:
import core.colorconsole as cc
except ImportError:
print('can not import color console module.')
sys.exit(1)
import core.utils as utils
try:
from core.context import *
except ImportError:
cc.e('can not import core context module.')
sys.exit(1)
ctx = BuildContext()
if ctx.is_py2:
_input = raw_input _input = raw_input
else: else:
_input = input _input = input
if ctx.host_os == 'windows':
try:
import win32api, win32con
except:
cc.e('can not import module `win32api`.')
sys.exit(1)
options = list() options = list()
options_idx = 0 options_idx = 0
ctx = BuildContext()
def main(): def main():
cc.set_default(sep='', end='\n') cc.set_default(sep='', end='\n')
if not env.init(warn_miss_tool=True):
return
action = None action = None
argv = sys.argv[1:] argv = sys.argv[1:]
if len(argv) >= 1: if len(argv) >= 1:
@ -111,8 +90,8 @@ def main():
def clean_all(): def clean_all():
cc.v('remove compiler out path...') cc.e('sorry, clean not implemented yet.')
utils.remove(os.path.join(ROOT_PATH, 'out')) # utils.remove(os.path.join(env.root_path, 'out'))
def do_opt(opt): def do_opt(opt):
@ -151,7 +130,7 @@ def do_opt(opt):
return return
# cmd = '"%s" -B "%s" %s' % (utils.cfg.py_exec, os.path.join(BUILDER_PATH, script), arg) # cmd = '"%s" -B "%s" %s' % (utils.cfg.py_exec, os.path.join(BUILDER_PATH, script), arg)
cmd = '%s -B %s %s' % (utils.cfg.py_exec, os.path.join(BUILDER_PATH, script), arg) cmd = '%s -B %s %s' % (env.py_exec, os.path.join(env.builder_path, script), arg)
os.system(cmd) os.system(cmd)
@ -193,14 +172,15 @@ def add_split():
def make_options(): def make_options():
global options, options_idx, cfg # global options, options_idx
#
options = list() # options = list()
options_idx = 0 # options_idx = 0
if ctx.host_os == 'windows': if ctx.host_os == 'windows':
add_option('x86', 'ver', 'Update version setting') add_option('x86', 'ver', 'Update version setting')
add_option('x86', 'pysrt', 'Make Python-Runtime for python%s-x86' % (utils.cfg.py_ver_str)) add_option('x86', 'pysrt', 'Make Python-Runtime for python%s-x86' % env.py_ver_str)
add_option('x64', 'external', 'Build external dependency')
add_split() add_split()
add_option('x86', 'assist-exe', 'Assist Execute [%s]' % ctx.target_path) add_option('x86', 'assist-exe', 'Assist Execute [%s]' % ctx.target_path)
# add_option('x86', 'assist-rdp', 'Teleport RDP [%s]' % ctx.target_path) # add_option('x86', 'assist-rdp', 'Teleport RDP [%s]' % ctx.target_path)
@ -211,8 +191,8 @@ def make_options():
add_option('x86', 'installer', 'Teleport Installer for %s' % ctx.host_os) add_option('x86', 'installer', 'Teleport Installer for %s' % ctx.host_os)
else: else:
add_option('x64', 'ver', 'Update version setting') add_option('x64', 'ver', 'Update version setting')
add_option('x64', 'pysrt', 'Make Python-Runtime for python%s-x64' % (utils.cfg.py_ver_str)) add_option('x64', 'pysrt', 'Make Python-Runtime for python%s-x64' % env.py_ver_str)
add_option('x64', 'external', 'Build external for Teleport-Server') add_option('x64', 'external', 'Build external dependency')
add_split() add_split()
add_option('x64', 'server', 'Build server app [%s]' % ctx.target_path) add_option('x64', 'server', 'Build server app [%s]' % ctx.target_path)
add_split() add_split()

View File

@ -1,15 +1,13 @@
#!/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from core import colorconsole as cc from core import colorconsole as cc
from core import utils from core import utils
from core.context import * from core.context import *
from core.ver import * from core.ver import *
from core.env import env
ctx = BuildContext() ctx = BuildContext()
ROOT_PATH = utils.cfg.ROOT_PATH
class BuilderBase: class BuilderBase:
def __init__(self): def __init__(self):
@ -31,8 +29,8 @@ class BuilderWin(BuilderBase):
def build_exe(self): def build_exe(self):
cc.i('build tp_assist...') cc.i('build tp_assist...')
sln_file = os.path.join(ROOT_PATH, 'client', 'tp_assist', 'tp_assist.vs2015.sln') sln_file = os.path.join(env.root_path, 'client', 'tp_assist', 'tp_assist.vs2015.sln')
out_file = os.path.join(ROOT_PATH, 'out', 'client', ctx.bits_path, ctx.target_path, 'tp_assist.exe') out_file = os.path.join(env.root_path, 'out', 'client', ctx.bits_path, ctx.target_path, 'tp_assist.exe')
if os.path.exists(out_file): if os.path.exists(out_file):
utils.remove(out_file) utils.remove(out_file)
utils.msvc_build(sln_file, 'tp_assist', ctx.target_path, ctx.bits_path, False) utils.msvc_build(sln_file, 'tp_assist', ctx.target_path, ctx.bits_path, False)
@ -52,7 +50,7 @@ class BuilderWin(BuilderBase):
name = 'teleport-assist-{}'.format(VER_TELEPORT_ASSIST) name = 'teleport-assist-{}'.format(VER_TELEPORT_ASSIST)
out_path = os.path.join(ROOT_PATH, 'out', 'installer') out_path = os.path.join(env.root_path, 'out', 'installer')
utils.makedirs(out_path) utils.makedirs(out_path)
out_file = os.path.join(out_path, '{}.exe'.format(name)) out_file = os.path.join(out_path, '{}.exe'.format(name))
@ -113,12 +111,9 @@ class BuilderWin(BuilderBase):
@staticmethod @staticmethod
def _build_installer(): def _build_installer():
# base_path = os.path.join(ROOT_PATH, 'out', 'client') tmp_path = os.path.join(env.root_path, 'dist', 'client', 'windows', 'assist')
# base_tmp = os.path.join(base_path, '_tmp_')
tmp_path = os.path.join(ROOT_PATH, 'dist', 'windows', 'client', 'assist')
tmp_app_path = os.path.join(tmp_path, 'apps') tmp_app_path = os.path.join(tmp_path, 'apps')
tmp_cfg_path = os.path.join(tmp_path, 'cfg') tmp_cfg_path = os.path.join(tmp_path, 'cfg')
# E:\work\eomsoft\teleport - github\dist\windows\client\assist\apps
if os.path.exists(tmp_app_path): if os.path.exists(tmp_app_path):
utils.remove(tmp_app_path) utils.remove(tmp_app_path)
@ -128,31 +123,21 @@ class BuilderWin(BuilderBase):
utils.makedirs(tmp_app_path) utils.makedirs(tmp_app_path)
utils.makedirs(tmp_cfg_path) utils.makedirs(tmp_cfg_path)
utils.copy_file(os.path.join(ROOT_PATH, 'out', 'client', ctx.bits_path, ctx.target_path), tmp_app_path, 'tp_assist.exe') utils.copy_file(os.path.join(env.root_path, 'out', 'client', ctx.bits_path, ctx.target_path), tmp_app_path, 'tp_assist.exe')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'ssh.ini') utils.copy_file(os.path.join(env.root_path, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'ssh.ini')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'scp.ini') utils.copy_file(os.path.join(env.root_path, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'scp.ini')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'telnet.ini') utils.copy_file(os.path.join(env.root_path, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'telnet.ini')
utils.copy_ex(os.path.join(ROOT_PATH, 'client', 'tp_assist'), tmp_app_path, 'site') utils.copy_ex(os.path.join(env.root_path, 'client', 'tp_assist'), tmp_app_path, 'site')
# utils.makedirs(os.path.join(tmp_app_path, 'tools', 'tprdp'))
utils.makedirs(os.path.join(tmp_app_path, 'tools', 'putty')) utils.makedirs(os.path.join(tmp_app_path, 'tools', 'putty'))
utils.makedirs(os.path.join(tmp_app_path, 'tools', 'winscp')) utils.makedirs(os.path.join(tmp_app_path, 'tools', 'winscp'))
# utils.copy_file(os.path.join(ROOT_PATH, 'out', 'tp_rdp', ctx.bits_path, ctx.target_path), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'tp_rdp.exe') utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'putty'), os.path.join(tmp_app_path, 'tools', 'putty'), 'putty.exe')
# utils.copy_file(os.path.join(ROOT_PATH, 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'tprdp-client.exe') utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'winscp'), os.path.join(tmp_app_path, 'tools', 'winscp'), 'WinSCP.exe')
# utils.copy_file(os.path.join(ROOT_PATH, 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'tprdp-replay.exe') utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'winscp'), os.path.join(tmp_app_path, 'tools', 'winscp'), 'license.txt')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'putty'), os.path.join(tmp_app_path, 'tools', 'putty'), 'putty.exe') utils.copy_file(os.path.join(env.root_path, 'client', 'tools'), os.path.join(tmp_app_path, 'tools'), 'securecrt-telnet.vbs')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'winscp'), os.path.join(tmp_app_path, 'tools', 'winscp'), 'WinSCP.exe')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'winscp'), os.path.join(tmp_app_path, 'tools', 'winscp'), 'license.txt')
utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools'), os.path.join(tmp_app_path, 'tools'), 'securecrt-telnet.vbs')
# utils.makedirs(os.path.join(tmp_path, 'data')) utils.nsis_build(os.path.join(env.root_path, 'dist', 'client', 'windows', 'assist', 'installer.nsi'))
# utils.copy_file(os.path.join(ROOT_PATH, 'tp_assist'), os.path.join(tmp_path, 'data'), 'ssl.cert')
# out_file = os.path.join(ROOT_PATH, 'dist', '{}.zip'.format(name))
# utils.make_zip(base_tmp, out_file)
# E:\work\eomsoft\teleport - github\dist\windows\client\assist
utils.nsis_build(os.path.join(ROOT_PATH, 'dist', 'windows', 'client', 'assist', 'installer.nsi'))
class BuilderLinux(BuilderBase): class BuilderLinux(BuilderBase):
@ -182,6 +167,9 @@ def gen_builder(dist):
def main(): def main():
if not env.init():
return
builder = None builder = None
argv = sys.argv[1:] argv = sys.argv[1:]

View File

@ -1,26 +1,18 @@
#!/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import codecs
import shutil
import time
from core import colorconsole as cc from core import colorconsole as cc
from core import utils from core import utils
from core.context import * from core.context import *
from core.env import env
ctx = BuildContext() ctx = BuildContext()
ROOT_PATH = utils.cfg.ROOT_PATH PATH_EXTERNAL = os.path.join(env.root_path, 'external')
PATH_EXTERNAL = os.path.join(ROOT_PATH, 'external')
PATH_DOWNLOAD = os.path.join(PATH_EXTERNAL, '_download_') PATH_DOWNLOAD = os.path.join(PATH_EXTERNAL, '_download_')
OPENSSL_VER = utils.cfg.ver.openssl
LIBUV_VER = utils.cfg.ver.libuv
MBEDTLS_VER = utils.cfg.ver.mbedtls
SQLITE_VER = utils.cfg.ver.sqlite
LIBSSH_VER = utils.cfg.ver.libssh LIBSSH_VER = utils.cfg.ver.libssh
class BuilderBase: class BuilderBase:
def __init__(self): def __init__(self):
self.out_dir = '' self.out_dir = ''
@ -32,9 +24,28 @@ class BuilderBase:
def _init_path(self): def _init_path(self):
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def build_jsoncpp(self):
file_name = 'jsoncpp-{}.zip'.format(env.ver_jsoncpp)
if not utils.download_file('jsoncpp source tarball', 'https://github.com/open-source-parsers/jsoncpp/archive/{}.zip'.format(env.ver_jsoncpp), PATH_DOWNLOAD, file_name):
return
self._build_jsoncpp(file_name)
def _build_jsoncpp(self, file_name):
cc.e("this is a pure-virtual function.")
def build_mongoose(self):
file_name = 'mongoose-{}.zip'.format(env.ver_mongoose)
if not utils.download_file('mongoose source tarball', 'https://github.com/cesanta/mongoose/archive/{}.zip'.format(env.ver_mongoose), PATH_DOWNLOAD, file_name):
return
self._build_mongoose(file_name)
def _build_mongoose(self, file_name):
cc.e("this is a pure-virtual function.")
def build_openssl(self): def build_openssl(self):
file_name = 'openssl-{}.tar.gz'.format(OPENSSL_VER) file_name = 'openssl-{}.zip'.format(env.ver_openssl)
if not self._download_file('openssl source tarball', 'https://www.openssl.org/source/{}'.format(file_name), file_name): _alt_ver = '_'.join(env.ver_openssl.split('.'))
if not utils.download_file('openssl source tarball', 'https://github.com/openssl/openssl/archive/OpenSSL_{}.zip'.format(_alt_ver), PATH_DOWNLOAD, file_name):
return return
self._build_openssl(file_name) self._build_openssl(file_name)
@ -42,8 +53,8 @@ class BuilderBase:
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def build_libuv(self): def build_libuv(self):
file_name = 'libuv-{}.zip'.format(LIBUV_VER) file_name = 'libuv-{}.zip'.format(env.ver_libuv)
if not self._download_file('libuv source tarball', 'https://github.com/libuv/libuv/archive/v{}.zip'.format(LIBUV_VER), file_name): if not utils.download_file('libuv source tarball', 'https://github.com/libuv/libuv/archive/v{}.zip'.format(env.ver_libuv), PATH_DOWNLOAD, file_name):
return return
self._build_libuv(file_name) self._build_libuv(file_name)
@ -51,8 +62,8 @@ class BuilderBase:
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def build_mbedtls(self): def build_mbedtls(self):
file_name = 'mbedtls-mbedtls-{}.zip'.format(MBEDTLS_VER) file_name = 'mbedtls-mbedtls-{}.zip'.format(env.ver_mbedtls)
if not self._download_file('mbedtls source tarball', 'https://github.com/ARMmbed/mbedtls/archive/mbedtls-{}.zip'.format(MBEDTLS_VER), file_name): if not utils.download_file('mbedtls source tarball', 'https://github.com/ARMmbed/mbedtls/archive/mbedtls-{}.zip'.format(env.ver_mbedtls), PATH_DOWNLOAD, file_name):
return return
self._build_mbedtls(file_name) self._build_mbedtls(file_name)
@ -60,8 +71,8 @@ class BuilderBase:
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def build_libssh(self): def build_libssh(self):
file_name = 'libssh-{}.zip'.format(LIBSSH_VER) file_name = 'libssh-{}.zip'.format(env.ver_libssh)
if not self._download_file('mbedtls source tarball', 'https://git.libssh.org/projects/libssh.git/snapshot/libssh-{}.zip'.format(LIBSSH_VER), file_name): if not utils.download_file('libssh source tarball', 'https://git.libssh.org/projects/libssh.git/snapshot/libssh-{}.zip'.format(env.ver_libssh), PATH_DOWNLOAD, file_name):
return return
self._build_libssh(file_name) self._build_libssh(file_name)
@ -69,40 +80,157 @@ class BuilderBase:
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def build_sqlite(self): def build_sqlite(self):
file_name = 'sqlite-autoconf-{}.tar.gz'.format(SQLITE_VER) file_name = 'sqlite-autoconf-{}.tar.gz'.format(env.ver_sqlite)
if not self._download_file('mbedtls source tarball', 'http://sqlite.org/2016/{}'.format(file_name), file_name): if not utils.download_file('sqlite source tarball', 'http://sqlite.org/2017/{}'.format(file_name), PATH_DOWNLOAD, file_name):
return return
self._build_sqlite(file_name) self._build_sqlite(file_name)
def _build_sqlite(self, file_name): def _build_sqlite(self, file_name):
cc.e("this is a pure-virtual function.") cc.e("this is a pure-virtual function.")
def _download_file(self, desc, url, file_name):
cc.n('downloading {} ...'.format(desc))
if os.path.exists(os.path.join(PATH_DOWNLOAD, file_name)):
cc.w('already exists, skip.')
return True
os.system('wget --no-check-certificate {} -O "{}/{}"'.format(url, PATH_DOWNLOAD, file_name))
if not os.path.exists(os.path.join(PATH_DOWNLOAD, file_name)):
cc.e('downloading {} from {} failed.'.format(desc, url))
return True
return True
def fix_output(self): def fix_output(self):
pass pass
class BuilderWin(BuilderBase): class BuilderWin(BuilderBase):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
def _init_path(self): def _init_path(self):
cc.e("build external not works for Windows yet.") self.OPENSSL_PATH_SRC = os.path.join(PATH_EXTERNAL, 'openssl')
self.JSONCPP_PATH_SRC = os.path.join(PATH_EXTERNAL, 'jsoncpp')
self.MONGOOSE_PATH_SRC = os.path.join(PATH_EXTERNAL, 'mongoose')
self.MBEDTLS_PATH_SRC = os.path.join(PATH_EXTERNAL, 'mbedtls')
self.LIBSSH_PATH_SRC = os.path.join(PATH_EXTERNAL, 'libssh-win-static')
self._prepare_python_header()
def _prepare_python_header(self):
cc.n('prepare python header files ...', end='')
if os.path.exists(os.path.join(PATH_EXTERNAL, 'python', 'include', 'pyctype.h')):
cc.w('already exists, skip.')
return
cc.v('')
_header_path = None
for p in sys.path:
if os.path.exists(os.path.join(p, 'include', 'pyctype.h')):
_header_path = os.path.join(p, 'include')
if _header_path is None:
cc.e('\ncan not locate python development include path in:')
for p in sys.path:
cc.e(' ', p)
raise RuntimeError()
utils.copy_ex(_header_path, os.path.join(PATH_EXTERNAL, 'python', 'include'))
def _build_openssl(self, file_name): def _build_openssl(self, file_name):
cc.e('build openssl-static for Windows...not supported yet.') cc.n('build openssl static library from source code... ', end='')
_chk_output = [
os.path.join(self.OPENSSL_PATH_SRC, 'out32', 'libeay32.lib'),
os.path.join(self.OPENSSL_PATH_SRC, 'out32', 'ssleay32.lib'),
os.path.join(self.OPENSSL_PATH_SRC, 'inc32', 'openssl', 'opensslconf.h'),
]
need_build = False
for f in _chk_output:
if not os.path.exists(f):
need_build = True
break
if not need_build:
cc.w('already exists, skip.')
return
cc.v('')
cc.n('prepare openssl source code...')
_alt_ver = '_'.join(env.ver_openssl.split('.'))
if not os.path.exists(self.OPENSSL_PATH_SRC):
utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL)
os.rename(os.path.join(PATH_EXTERNAL, 'openssl-OpenSSL_{}'.format(_alt_ver)), self.OPENSSL_PATH_SRC)
if not os.path.exists(self.OPENSSL_PATH_SRC):
raise RuntimeError('can not prepare openssl source code.')
else:
cc.w('already exists, skip.')
os.chdir(self.OPENSSL_PATH_SRC)
os.system('""{}" Configure VC-WIN32"'.format(env.perl))
os.system(r'ms\do_nasm')
os.system(r'"{}\VC\bin\vcvars32.bat" && nmake -f ms\nt.mak'.format(env.visual_studio_path))
for f in _chk_output:
if not os.path.exists(f):
raise RuntimeError('build openssl static library from source code failed.')
def _build_libssh(self, file_name):
cc.n('build libssh static library from source code... ', end='')
out_file = os.path.join(self.LIBSSH_PATH_SRC, 'lib', 'libsshMT.lib')
need_build = False
if not os.path.exists(out_file):
need_build = True
if not need_build:
cc.w('already exists, skip.')
return
cc.v('')
cc.n('prepare libssh source code... ', end='')
_include = os.path.join(self.LIBSSH_PATH_SRC, 'include', 'libssh')
_src = os.path.join(self.LIBSSH_PATH_SRC, 'src')
if not os.path.exists(_include) or not os.path.exists(_src):
utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL)
# os.rename(os.path.join(PATH_EXTERNAL, 'openssl-OpenSSL_{}'.format(_alt_ver)), self.OPENSSL_PATH_SRC)
_unzipped_path = os.path.join(PATH_EXTERNAL, 'libssh-{}'.format(env.ver_libssh))
utils.copy_ex(os.path.join(_unzipped_path, 'include', 'libssh'), _include)
utils.copy_ex(os.path.join(_unzipped_path, 'src'), _src)
utils.remove(_unzipped_path)
if not os.path.exists(_include) or not os.path.exists(_src):
raise RuntimeError('\ncan not prepare libssh source code.')
else:
cc.w('already exists, skip.')
cc.i('build libssh...')
sln_file = os.path.join(self.LIBSSH_PATH_SRC, 'libssh.vs2015.sln')
utils.msvc_build(sln_file, 'libssh', ctx.target_path, ctx.bits_path, False)
utils.ensure_file_exists(out_file)
def _build_jsoncpp(self, file_name):
cc.n('prepare jsoncpp source code... ', end='')
if not os.path.exists(self.JSONCPP_PATH_SRC):
cc.v('')
utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL)
os.rename(os.path.join(PATH_EXTERNAL, 'jsoncpp-{}'.format(env.ver_jsoncpp)), self.JSONCPP_PATH_SRC)
else:
cc.w('already exists, skip.')
def _build_mongoose(self, file_name):
cc.n('prepare mongoose source code... ', end='')
if not os.path.exists(self.MONGOOSE_PATH_SRC):
cc.v('')
utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL)
os.rename(os.path.join(PATH_EXTERNAL, 'mongoose-{}'.format(env.ver_mongoose)), self.MONGOOSE_PATH_SRC)
else:
cc.w('already exists, skip.')
def _build_mbedtls(self, file_name):
cc.n('prepare mbedtls source code... ', end='')
if not os.path.exists(self.MBEDTLS_PATH_SRC):
cc.v('')
utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL)
os.rename(os.path.join(PATH_EXTERNAL, 'mbedtls-mbedtls-{}'.format(env.ver_mbedtls)), self.MBEDTLS_PATH_SRC)
else:
cc.w('already exists, skip.')
def build_sqlite(self):
cc.w('sqlite not need for Windows, skip.')
pass
def fix_output(self): def fix_output(self):
pass pass
@ -115,41 +243,65 @@ class BuilderLinux(BuilderBase):
def _init_path(self): def _init_path(self):
self.PATH_TMP = os.path.join(PATH_EXTERNAL, 'linux', 'tmp') self.PATH_TMP = os.path.join(PATH_EXTERNAL, 'linux', 'tmp')
self.PATH_RELEASE = os.path.join(PATH_EXTERNAL, 'linux', 'release') self.PATH_RELEASE = os.path.join(PATH_EXTERNAL, 'linux', 'release')
self.OPENSSL_PATH_SRC = os.path.join(self.PATH_TMP, 'openssl-{}'.format(OPENSSL_VER)) self.OPENSSL_PATH_SRC = os.path.join(self.PATH_TMP, 'openssl-{}'.format(env.ver_openssl))
self.LIBUV_PATH_SRC = os.path.join(self.PATH_TMP, 'libuv-{}'.format(LIBUV_VER)) self.LIBUV_PATH_SRC = os.path.join(self.PATH_TMP, 'libuv-{}'.format(env.ver_libuv))
self.MBEDTLS_PATH_SRC = os.path.join(self.PATH_TMP, 'mbedtls-mbedtls-{}'.format(MBEDTLS_VER)) self.MBEDTLS_PATH_SRC = os.path.join(self.PATH_TMP, 'mbedtls-mbedtls-{}'.format(env.ver_mbedtls))
self.LIBSSH_PATH_SRC = os.path.join(self.PATH_TMP, 'libssh-{}'.format(LIBSSH_VER)) self.LIBSSH_PATH_SRC = os.path.join(self.PATH_TMP, 'libssh-{}'.format(env.ver_libssh))
self.SQLITE_PATH_SRC = os.path.join(self.PATH_TMP, 'sqlite-autoconf-{}'.format(SQLITE_VER)) self.SQLITE_PATH_SRC = os.path.join(self.PATH_TMP, 'sqlite-autoconf-{}'.format(env.ver_sqlite))
self.JSONCPP_PATH_SRC = os.path.join(PATH_EXTERNAL, 'jsoncpp')
self.MONGOOSE_PATH_SRC = os.path.join(PATH_EXTERNAL, 'mongoose')
if not os.path.exists(self.PATH_TMP): if not os.path.exists(self.PATH_TMP):
utils.makedirs(self.PATH_TMP) utils.makedirs(self.PATH_TMP)
def _build_openssl(self, file_name): def _build_jsoncpp(self, file_name):
if not os.path.exists(self.OPENSSL_PATH_SRC): cc.n('prepare jsoncpp source code...', end='')
os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP)) if not os.path.exists(self.JSONCPP_PATH_SRC):
cc.v('')
cc.n('build openssl static...') os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, PATH_EXTERNAL))
if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libssl.a')): os.rename(os.path.join(PATH_EXTERNAL, 'jsoncpp-{}'.format(env.ver_jsoncpp)), self.JSONCPP_PATH_SRC)
else:
cc.w('already exists, skip.') cc.w('already exists, skip.')
return
old_p = os.getcwd() def _build_mongoose(self, file_name):
os.chdir(self.OPENSSL_PATH_SRC) cc.n('prepare mongoose source code...', end='')
#os.system('./config --prefix={} --openssldir={}/openssl no-zlib no-shared'.format(self.PATH_RELEASE, self.PATH_RELEASE)) if not os.path.exists(self.MONGOOSE_PATH_SRC):
os.system('./config --prefix={} --openssldir={}/openssl -fPIC no-zlib no-shared'.format(self.PATH_RELEASE, self.PATH_RELEASE)) cc.v('')
os.system('make') os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, PATH_EXTERNAL))
os.system('make install') os.rename(os.path.join(PATH_EXTERNAL, 'mongoose-{}'.format(env.ver_mongoose)), self.MONGOOSE_PATH_SRC)
os.chdir(old_p) else:
cc.w('already exists, skip.')
def _build_openssl(self, file_name):
pass # we do not need build openssl anymore, because first time run build.sh we built Python, it include openssl.
# if not os.path.exists(self.OPENSSL_PATH_SRC):
# os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP))
#
# cc.n('build openssl static...')
# if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libssl.a')):
# cc.w('already exists, skip.')
# return
#
# old_p = os.getcwd()
# os.chdir(self.OPENSSL_PATH_SRC)
# #os.system('./config --prefix={} --openssldir={}/openssl no-zlib no-shared'.format(self.PATH_RELEASE, self.PATH_RELEASE))
# os.system('./config --prefix={} --openssldir={}/openssl -fPIC no-zlib no-shared'.format(self.PATH_RELEASE, self.PATH_RELEASE))
# os.system('make')
# os.system('make install')
# os.chdir(old_p)
def _build_libuv(self, file_name): def _build_libuv(self, file_name):
if not os.path.exists(self.LIBUV_PATH_SRC): if not os.path.exists(self.LIBUV_PATH_SRC):
# os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP)) # os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP))
os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP)) os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP))
cc.n('build libuv...') cc.n('build libuv...', end='')
if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libuv.a')): if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libuv.a')):
cc.w('already exists, skip.') cc.w('already exists, skip.')
return return
cc.v('')
# we need following... # we need following...
# apt-get install autoconf aptitude libtool gcc-c++ # apt-get install autoconf aptitude libtool gcc-c++
@ -167,10 +319,11 @@ class BuilderLinux(BuilderBase):
# os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP)) # os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP))
os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP)) os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP))
cc.n('build mbedtls...') cc.n('build mbedtls...', end='')
if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libmbedtls.a')): if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libmbedtls.a')):
cc.w('already exists, skip.') cc.w('already exists, skip.')
return return
cc.v('')
# fix the Makefile # fix the Makefile
mkfile = os.path.join(self.MBEDTLS_PATH_SRC, 'Makefile') mkfile = os.path.join(self.MBEDTLS_PATH_SRC, 'Makefile')
@ -247,12 +400,13 @@ class BuilderLinux(BuilderBase):
if not os.path.exists(self.LIBSSH_PATH_SRC): if not os.path.exists(self.LIBSSH_PATH_SRC):
# os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP)) # os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, PATH_TMP))
os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP)) os.system('unzip "{}/{}" -d "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP))
# os.rename(os.path.join(self.PATH_TMP, 'master'), os.path.join(self.PATH_TMP, 'libssh-master')) # os.rename(os.path.join(self.PATH_TMP, 'master'), os.path.join(self.PATH_TMP, 'libssh-{}'.format(LIBSSH_VER)))
cc.n('build libssh...') cc.n('build libssh...', end='')
if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libssh.a')): if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libssh.a')):
cc.w('already exists, skip.') cc.w('already exists, skip.')
return return
cc.v('')
build_path = os.path.join(self.LIBSSH_PATH_SRC, 'build') build_path = os.path.join(self.LIBSSH_PATH_SRC, 'build')
# utils.makedirs(build_path) # utils.makedirs(build_path)
@ -299,7 +453,8 @@ class BuilderLinux(BuilderBase):
' -DWITH_EXAMPLES=OFF' \ ' -DWITH_EXAMPLES=OFF' \
' -DWITH_BENCHMARKS=OFF' \ ' -DWITH_BENCHMARKS=OFF' \
' -DWITH_NACL=OFF' \ ' -DWITH_NACL=OFF' \
' ..'.format(self.PATH_RELEASE, OPENSSL_VER, self.PATH_RELEASE, self.PATH_RELEASE) ' ..'.format(self.PATH_RELEASE, env.ver_openssl_number, self.PATH_RELEASE, self.PATH_RELEASE)
try: try:
utils.cmake(build_path, 'Release', False, cmake_define) utils.cmake(build_path, 'Release', False, cmake_define)
except: except:
@ -311,15 +466,15 @@ class BuilderLinux(BuilderBase):
utils.copy_file(os.path.join(self.LIBSSH_PATH_SRC, 'build', 'src'), os.path.join(self.PATH_RELEASE, 'lib'), 'libssh.a') utils.copy_file(os.path.join(self.LIBSSH_PATH_SRC, 'build', 'src'), os.path.join(self.PATH_RELEASE, 'lib'), 'libssh.a')
utils.copy_ex(os.path.join(self.LIBSSH_PATH_SRC, 'include'), os.path.join(self.PATH_RELEASE, 'include'), 'libssh') utils.copy_ex(os.path.join(self.LIBSSH_PATH_SRC, 'include'), os.path.join(self.PATH_RELEASE, 'include'), 'libssh')
def _build_sqlite(self, file_name): def _build_sqlite(self, file_name):
if not os.path.exists(self.SQLITE_PATH_SRC): if not os.path.exists(self.SQLITE_PATH_SRC):
os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP)) os.system('tar -zxvf "{}/{}" -C "{}"'.format(PATH_DOWNLOAD, file_name, self.PATH_TMP))
cc.n('build sqlite static...') cc.n('build sqlite static...', end='')
if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libsqlite3.a')): if os.path.exists(os.path.join(self.PATH_RELEASE, 'lib', 'libsqlite3.a')):
cc.w('already exists, skip.') cc.w('already exists, skip.')
return return
cc.v('')
old_p = os.getcwd() old_p = os.getcwd()
os.chdir(self.SQLITE_PATH_SRC) os.chdir(self.SQLITE_PATH_SRC)
@ -350,6 +505,9 @@ def gen_builder(dist):
def main(): def main():
if not env.init():
return
builder = None builder = None
argv = sys.argv[1:] argv = sys.argv[1:]
@ -367,13 +525,15 @@ def main():
if builder is None: if builder is None:
builder = gen_builder(ctx.host_os) builder = gen_builder(ctx.host_os)
# builder.build_openssl() builder.build_jsoncpp()
builder.build_mongoose()
builder.build_openssl()
####builder.build_libuv() ####builder.build_libuv()
builder.build_mbedtls() builder.build_mbedtls()
builder.build_libssh() builder.build_libssh()
builder.build_sqlite() builder.build_sqlite()
#
builder.fix_output() # builder.fix_output()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,4 +1,3 @@
#!/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import shutil import shutil
@ -6,13 +5,12 @@ import shutil
from core import colorconsole as cc from core import colorconsole as cc
from core import makepyo from core import makepyo
from core import utils from core import utils
from core.env import env
from core.context import * from core.context import *
from core.ver import * from core.ver import *
ctx = BuildContext() ctx = BuildContext()
ROOT_PATH = utils.cfg.ROOT_PATH
# COMMON_MODULES = ['paste', 'pyasn1', 'pymemcache', 'pymysql', 'rsa', 'tornado', 'six.py'] # COMMON_MODULES = ['paste', 'pyasn1', 'pymemcache', 'pymysql', 'rsa', 'tornado', 'six.py']
@ -26,55 +24,22 @@ class BuilderBase:
def _build_web(self, base_path, dist, target_path): def _build_web(self, base_path, dist, target_path):
cc.n('make Teleport Web package...') cc.n('make Teleport Web package...')
# src_path = os.path.join(ROOT_PATH, 'server', 'www', 'teleport') src_path = os.path.join(env.root_path, 'server', 'www')
# pkg_path = os.path.join(ROOT_PATH, 'server', 'www', 'packages')
src_path = os.path.join(ROOT_PATH, 'server', 'www')
pkg_path = os.path.join(src_path, 'packages') pkg_path = os.path.join(src_path, 'packages')
tmp_path = os.path.join(base_path, '_tmp_web_') tmp_path = os.path.join(base_path, '_tmp_web_')
if os.path.exists(tmp_path): if os.path.exists(tmp_path):
utils.remove(tmp_path) utils.remove(tmp_path)
# shutil.copytree(os.path.join(src_path, 'app'), os.path.join(tmp_path, 'app'))
shutil.copytree(os.path.join(src_path, 'teleport'), os.path.join(tmp_path, 'teleport')) shutil.copytree(os.path.join(src_path, 'teleport'), os.path.join(tmp_path, 'teleport'))
utils.remove(os.path.join(tmp_path, 'teleport', '.idea')) utils.remove(os.path.join(tmp_path, 'teleport', '.idea'))
# pkg_common = os.path.join(pkg_path, 'common')
# _s_path = os.listdir(pkg_common)
# for d in _s_path:
# s = os.path.join(pkg_common, d)
# t = os.path.join(tmp_path, 'app', d)
# if os.path.isdir(s):
# shutil.copytree(s, t)
# else:
# shutil.copy(s, t)
cc.n(' - copy packages...') cc.n(' - copy packages...')
pkgs = ['packages-common', 'packages-{}'.format(dist)] utils.copy_ex(pkg_path, os.path.join(tmp_path, 'packages'), 'packages-common')
for d in pkgs: utils.copy_ex(os.path.join(pkg_path, 'packages-{}'.format(dist)), os.path.join(tmp_path, 'packages', 'packages-{}'.format(dist)), ctx.bits_path)
s = os.path.join(pkg_path, d)
t = os.path.join(tmp_path, 'packages', d)
if os.path.isdir(s):
shutil.copytree(s, t)
else:
shutil.copy(s, t)
makepyo.remove_cache(tmp_path) makepyo.remove_cache(tmp_path)
# cc.n(' - copy static and view...')
# miscs = ['static', 'view', 'res', 'tools']
# for d in miscs:
# s = os.path.join(src_path, d)
# t = os.path.join(tmp_path, d)
# if os.path.isdir(s):
# shutil.copytree(s, t)
# else:
# shutil.copy(s, t)
# if not os.path.exists(os.path.join(tmp_path, 'static', 'download')):
# utils.makedirs(os.path.join(tmp_path, 'static', 'download'))
# utils.copy_file(os.path.join(ROOT_PATH, 'dist'), os.path.join(tmp_path, 'static', 'download'), 'teleport-assist-win.zip')
shutil.copytree(tmp_path, os.path.join(target_path, 'www')) shutil.copytree(tmp_path, os.path.join(target_path, 'www'))
utils.remove(tmp_path) utils.remove(tmp_path)
@ -82,15 +47,15 @@ class BuilderBase:
class BuilderWin(BuilderBase): class BuilderWin(BuilderBase):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
# now = time.localtime(time.time())
# _ver = '1.0.{:2d}.{:d}{:02d}'.format(now.tm_year - 2000, now.tm_mon, now.tm_mday)
# self.name = 'teleport-server-windows-{}-{}'.format(ctx.bits_path, _ver)
self.name = 'teleport-server-windows-{}-{}'.format(ctx.bits_path, VER_TELEPORT_SERVER) self.name = 'teleport-server-windows-{}-{}'.format(ctx.bits_path, VER_TELEPORT_SERVER)
self._final_file = os.path.join(env.root_path, 'out', 'installer', '{}.zip'.format(self.name))
self.base_path = os.path.join(ROOT_PATH, 'dist', 'installer', ctx.dist, 'server') self.dist_path = os.path.join(env.root_path, 'dist', 'server')
self.base_path = os.path.join(env.root_path, 'out', 'installer')
self.base_tmp = os.path.join(self.base_path, '_tmp_') self.base_tmp = os.path.join(self.base_path, '_tmp_')
self.tmp_path = os.path.join(self.base_tmp, self.name, 'data', 'teleport')
self.path_tmp = os.path.join(self.base_tmp, self.name)
self.path_tmp_data = os.path.join(self.path_tmp, 'data')
def build_installer(self): def build_installer(self):
cc.n('make teleport installer package...') cc.n('make teleport installer package...')
@ -98,78 +63,47 @@ class BuilderWin(BuilderBase):
if os.path.exists(self.base_tmp): if os.path.exists(self.base_tmp):
utils.remove(self.base_tmp) utils.remove(self.base_tmp)
# self._build_web_backend(self.base_path, 'windows', self.tmp_path) self._build_web(self.base_path, 'windows', self.path_tmp_data)
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'web-backend.conf') utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), ('web.ini.in', 'web.ini'))
# utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), ('core.ini.in', 'core.ini'))
# self._build_web_frontend(self.base_path, 'windows', self.tmp_path) utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), 'tp_ssh_server.key')
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'web-frontend.conf')
self._build_web(self.base_path, 'windows', self.tmp_path) out_path = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, ctx.target_path)
utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'web.conf') bin_path = os.path.join(self.path_tmp_data, 'bin')
utils.copy_ex(out_path, bin_path, 'tp_web.exe')
utils.copy_ex(out_path, bin_path, 'tp_core.exe')
utils.copy_ex(out_path, bin_path, 'tpssh.dll')
# out_path = os.path.join(ROOT_PATH, 'out', 'eom_ts', ctx.target_path, ctx.dist_path) utils.copy_ex(os.path.join(env.root_path, 'out', 'pysrt'), bin_path, (ctx.dist_path, 'pysrt'))
# bin_path = os.path.join(self.tmp_path, 'bin')
# utils.copy_file(out_path, bin_path, 'eom_ts')
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'etc'), 'eom_ts.ini')
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'etc'), 'ts_ssh_server.key')
out_path = os.path.join(ROOT_PATH, 'out', 'eom_ts', ctx.bits_path, ctx.target_path) # 复制安装所需的脚本
bin_path = os.path.join(self.tmp_path, 'bin') utils.copy_ex(os.path.join(self.dist_path), self.path_tmp, 'setup.bat')
utils.copy_ex(out_path, bin_path, 'eom_ts.exe') utils.copy_ex(os.path.join(self.dist_path), self.path_tmp, 'script')
utils.copy_ex(out_path, bin_path, 'pysrt')
utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'eom_ts.ini') if os.path.exists(self._final_file):
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'license.key') utils.remove(self._final_file)
utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'ts_ssh_server.key')
# utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'ssl')
# utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), ('ts_db_release.db', 'ts_db.db')) utils.make_zip(self.path_tmp, self._final_file)
utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), 'main.sql')
# utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'data'), os.path.join(self.tmp_path, 'data'), ('ts_db_release.db', 'ts_db.db')) # utils.remove(self.base_tmp)
# utils.make_zip(os.path.join(self.tmp_path, '..'), os.path.join(self.tmp_path, '..', '..', 'teleport.zip'))
# utils.copy_file(os.path.join(self.tmp_path, '..', '..'), os.path.join(self.tmp_path, '..'), 'teleport.zip')
# utils.remove(os.path.join(self.tmp_path, '..', '..', 'teleport.zip'))
# utils.remove(self.tmp_path)
# make final installer.
cc.n('pack final server installer...')
out_file = os.path.join(ROOT_PATH, 'dist', '{}.zip'.format(self.name))
if os.path.exists(out_file):
utils.remove(out_file)
# # copy installer scripts.
# for i in ['daemon', 'install.sh', 'start.sh', 'stop.sh', 'status.sh']:
# shutil.copy(os.path.join(self.base_path, 'script', i), os.path.join(self.base_tmp, self.name, i))
for i in ['install.bat', 'uninst.bat']:
shutil.copy(os.path.join(self.base_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', '..', i)))
# for i in ['7z.exe']:
# shutil.copy(os.path.join(self.base_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', '..', 'data', i)))
utils.make_zip(os.path.join(self.base_tmp, self.name, '..'), out_file)
class BuilderLinux(BuilderBase): class BuilderLinux(BuilderBase):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
# now = time.localtime(time.time())
# _ver = '1.0.{:2d}.{:d}{:02d}'.format(now.tm_year - 2000, now.tm_mon, now.tm_mday)
# self.name = 'teleport-server-linux-{}-{}'.format(ctx.bits_path, _ver)
self.name = 'teleport-server-linux-{}-{}'.format(ctx.bits_path, VER_TELEPORT_SERVER) self.name = 'teleport-server-linux-{}-{}'.format(ctx.bits_path, VER_TELEPORT_SERVER)
self._final_file = os.path.join(env.root_path, 'out', 'installer', '{}.tar.gz'.format(self.name))
self.dist_path = os.path.join(ROOT_PATH, 'dist', ctx.dist, 'server') self.dist_path = os.path.join(env.root_path, 'dist', 'server')
self.base_path = os.path.join(ROOT_PATH, 'out', 'installer', 'server') self.base_path = os.path.join(env.root_path, 'out', 'installer')
self.base_tmp = os.path.join(self.base_path, '_tmp_') self.base_tmp = os.path.join(self.base_path, '_tmp_')
self.tmp_path = os.path.join(self.base_tmp, self.name, 'data', 'teleport')
# self.server_path = os.path.join(ROOT_PATH, 'dist', 'installer', ctx.dist, 'server') self.path_tmp = os.path.join(self.base_tmp, self.name)
self.path_tmp_data = os.path.join(self.path_tmp, 'data')
# self.server_path = os.path.join(env.root_path, 'dist', 'installer', ctx.dist, 'server')
# self.script_path = self.tmp_path = os.path.join(self.server_path, 'script') # self.script_path = self.tmp_path = os.path.join(self.server_path, 'script')
# self.src_path = os.path.join(ROOT_PATH, 'source') # self.src_path = os.path.join(env.root_path, 'source')
# self.out_tmp_path = os.path.join(self.tmp_path, self.name, 'server') # self.out_tmp_path = os.path.join(self.tmp_path, self.name, 'server')
def build_installer(self): def build_installer(self):
@ -178,59 +112,62 @@ class BuilderLinux(BuilderBase):
if os.path.exists(self.base_tmp): if os.path.exists(self.base_tmp):
utils.remove(self.base_tmp) utils.remove(self.base_tmp)
# self._build_web_backend(self.base_path, 'linux', self.tmp_path) self._build_web(self.base_path, 'linux', self.path_tmp_data)
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'web-backend.conf')
#
# self._build_web_frontend(self.base_path, 'linux', self.tmp_path)
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'web-frontend.conf')
self._build_web(self.base_path, 'linux', self.tmp_path) utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), ('web.ini.in', 'web.ini'))
utils.copy_file(os.path.join(ROOT_PATH, 'server', 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), ('web.ini.in', 'web.ini')) utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), ('core.ini.in', 'core.ini'))
utils.copy_file(os.path.join(ROOT_PATH, 'server', 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), ('core.ini.in', 'core.ini')) utils.copy_file(os.path.join(env.root_path, 'server', 'share', 'etc'), os.path.join(self.path_tmp_data, 'tmp', 'etc'), 'tp_ssh_server.key')
# out_path = os.path.join(ROOT_PATH, 'out', 'eom_ts', ctx.target_path, ctx.dist_path) # out_path = os.path.join(env.root_path, 'out', 'eom_ts', ctx.target_path, ctx.dist_path)
# out_path = os.path.join(ROOT_PATH, 'out', 'eom_ts', ctx.bits_path, 'bin') # out_path = os.path.join(env.root_path, 'out', 'eom_ts', ctx.bits_path, 'bin')
# bin_path = os.path.join(self.tmp_path, 'bin') # bin_path = os.path.join(self.tmp_path, 'bin')
# utils.copy_file(out_path, bin_path, 'eom_ts') # utils.copy_file(out_path, bin_path, 'eom_ts')
out_path = os.path.join(ROOT_PATH, 'out', 'server', ctx.bits_path, 'bin') out_path = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, 'bin')
bin_path = os.path.join(self.tmp_path, 'bin') bin_path = os.path.join(self.path_tmp_data, 'bin')
utils.copy_ex(out_path, bin_path, 'tp_web') utils.copy_ex(out_path, bin_path, 'tp_web')
utils.copy_ex(out_path, bin_path, 'tp_core') utils.copy_ex(out_path, bin_path, 'tp_core')
utils.copy_ex(out_path, bin_path, 'libtpssh.so') utils.copy_ex(out_path, bin_path, 'libtpssh.so')
utils.copy_ex(os.path.join(ROOT_PATH, 'out', 'pysrt'), bin_path, (ctx.dist_path, 'pysrt')) utils.copy_ex(os.path.join(env.root_path, 'out', 'pysrt'), bin_path, (ctx.dist_path, 'pysrt'))
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'eom_ts.ini') # utils.copy_file(os.path.join(env.root_path, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'eom_ts.ini')
# utils.copy_file(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'license.key') # utils.copy_file(os.path.join(env.root_path, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'license.key')
utils.copy_file(os.path.join(ROOT_PATH, 'server', 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'tp_ssh_server.key') # utils.copy_ex(os.path.join(env.root_path, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'ssl')
# utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'etc'), os.path.join(self.tmp_path, 'tmp', 'etc'), 'ssl')
# utils.copy_ex(os.path.join(ROOT_PATH, 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), ('ts_db_release.db', 'ts_db.db')) # utils.copy_ex(os.path.join(env.root_path, 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), ('ts_db_release.db', 'ts_db.db'))
utils.copy_ex(os.path.join(ROOT_PATH, 'server', 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), 'main.sql') # utils.copy_ex(os.path.join(env.root_path, 'server', 'share', 'data'), os.path.join(self.tmp_path, 'tmp', 'data'), 'main.sql')
# utils.make_zip(self.tmp_path, os.path.join(self.tmp_path, '..', 'eom_ts.zip')) # utils.make_zip(self.tmp_path, os.path.join(self.tmp_path, '..', 'eom_ts.zip'))
utils.make_targz(os.path.join(self.tmp_path, '..'), 'teleport', 'teleport.tar.gz') # utils.make_targz(os.path.join(self.tmp_path, '..'), 'teleport', 'teleport.tar.gz')
utils.remove(self.tmp_path) # utils.remove(self.tmp_path)
# make final installer. # make final installer.
cc.n('pack final server installer...') # cc.n('pack final server installer...')
# out_file = os.path.join(ROOT_PATH, 'dist', '{}.zip'.format(self.name)) # out_file = os.path.join(env.root_path, 'dist', '{}.zip'.format(self.name))
out_file = os.path.join(ROOT_PATH, 'out', 'installer', '{}.tar.gz'.format(self.name)) # out_file = os.path.join(env.root_path, 'out', 'installer', '{}.tar.gz'.format(self.name))
if os.path.exists(out_file): # if os.path.exists(out_file):
utils.remove(out_file) # utils.remove(out_file)
# # copy installer scripts. # # copy installer scripts.
for i in ['daemon', 'start.sh', 'stop.sh', 'status.sh']: # for i in ['daemon', 'start.sh', 'stop.sh', 'status.sh']:
# for i in ['daemon_web', 'daemon_core', 'teleport.sh']: # # for i in ['daemon_web', 'daemon_core', 'teleport.sh']:
shutil.copy(os.path.join(self.dist_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', i))) # shutil.copy(os.path.join(self.dist_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', i)))
for i in ['install.sh', 'uninst.sh']: # for i in ['install.sh', 'uninst.sh']:
shutil.copy(os.path.join(self.dist_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', '..', i))) # shutil.copy(os.path.join(self.dist_path, 'script', i), os.path.abspath(os.path.join(self.tmp_path, '..', '..', i)))
# utils.make_zip(os.path.join(self.base_tmp, self.name), out_file) # 复制安装所需的脚本
utils.make_targz(self.base_tmp, self.name, out_file) # utils.copy_ex(os.path.join(self.dist_path, 'script'), self.path_tmp, 'install.sh')
# utils.copy_ex(os.path.join(self.dist_path, 'script'), self.path_tmp, 'uninst.sh')
utils.copy_ex(os.path.join(self.dist_path), self.path_tmp, 'setup.sh')
utils.copy_ex(os.path.join(self.dist_path), self.path_tmp, 'script')
utils.copy_ex(os.path.join(self.dist_path), self.path_tmp, 'daemon')
if os.path.exists(self._final_file):
utils.remove(self._final_file)
utils.make_targz(self.base_tmp, self.name, self._final_file)
# utils.remove(self.base_tmp) # utils.remove(self.base_tmp)
@ -248,6 +185,9 @@ def gen_builder(dist):
def main(): def main():
if not env.init():
return
builder = None builder = None
argv = sys.argv[1:] argv = sys.argv[1:]

View File

@ -3,18 +3,17 @@
import shutil import shutil
import struct import struct
import sys
from core import colorconsole as cc from core import colorconsole as cc
from core import makepyo from core import makepyo
from core import utils from core import utils
from core.context import * from core.context import *
from core.env import env
ctx = BuildContext() ctx = BuildContext()
#PY_VER = platform.python_version_tuple()
ROOT_PATH = utils.cfg.ROOT_PATH
PY_EXEC = utils.cfg.py_exec
MODULES_WIN = ['_bz2', '_ctypes', '_hashlib', '_lzma', '_overlapped', '_socket', '_sqlite3', '_ssl', 'select', 'sqlite3', 'unicodedata'] MODULES_WIN = ['_bz2', '_ctypes', '_hashlib', '_lzma', '_overlapped', '_socket', '_sqlite3', '_ssl', 'select', 'sqlite3', 'unicodedata']
PY_LIB_REMOVE_WIN = ['ctypes/test', 'curses', 'dbm', 'distutils', 'email/test', 'ensurepip', 'idlelib', 'lib2to3', PY_LIB_REMOVE_WIN = ['ctypes/test', 'curses', 'dbm', 'distutils', 'email/test', 'ensurepip', 'idlelib', 'lib2to3',
'lib-dynload', 'pydoc_data', 'site-packages', 'sqlite3/test', 'test', 'tkinter', 'turtledemo', 'lib-dynload', 'pydoc_data', 'site-packages', 'sqlite3/test', 'test', 'tkinter', 'turtledemo',
@ -28,7 +27,7 @@ PY_LIB_REMOVE_LINUX = ['ctypes/test', 'curses', 'config-3.4m-x86_64-linux-gnu',
class PYSBase: class PYSBase:
def __init__(self): def __init__(self):
self.base_path = os.path.join(ROOT_PATH, 'out', 'pysrt', ctx.dist_path) self.base_path = os.path.join(env.root_path, 'out', 'pysrt', ctx.dist_path)
self.py_dll_path = '' self.py_dll_path = ''
self.py_lib_path = '' self.py_lib_path = ''
@ -98,7 +97,7 @@ class PYSBase:
makepyo.make(_tmp_) makepyo.make(_tmp_)
cc.v('compress into python.zip...') cc.v('compress into python.zip...')
utils.make_zip(_tmp_, out_file) utils.make_zip(_tmp_, out_file, from_parent=False)
utils.ensure_file_exists(out_file) utils.ensure_file_exists(out_file)
cc.v('remove temp folder...') cc.v('remove temp folder...')
@ -172,7 +171,7 @@ class PYSBaseWin(PYSBase):
super()._copy_modules() super()._copy_modules()
def _make_py_ver_file(self): def _make_py_ver_file(self):
# 在python.zip尾部追加一个字符串补零到64字节指明python动态库的文件名这样壳在加载时才知道如何加载python动态库 # 指明python动态库的文件名这样壳在加载时才知道如何加载python动态库
out_file = os.path.join(self.base_path, 'python.ver') out_file = os.path.join(self.base_path, 'python.ver')
_data = struct.pack('=64s', self._get_py_dll_name().encode()) _data = struct.pack('=64s', self._get_py_dll_name().encode())
f = open(out_file, 'wb') f = open(out_file, 'wb')
@ -180,15 +179,14 @@ class PYSBaseWin(PYSBase):
f.close() f.close()
def _get_py_dll_name(self): def _get_py_dll_name(self):
#return 'python{}{}.dll'.format(PY_VER[0], PY_VER[1]) return 'python{}.dll'.format(env.py_ver_str)
return 'python{}.dll'.format(utils.cfg.py_ver_str)
class PYSBaseLinux(PYSBase): class PYSBaseLinux(PYSBase):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.PY_STATIC_PATH = os.path.join(os.path.join(ROOT_PATH, 'external', 'linux', 'release')) self.PY_STATIC_PATH = os.path.join(os.path.join(env.root_path, 'external', 'linux', 'release'))
if not os.path.exists(self.PY_STATIC_PATH): if not os.path.exists(self.PY_STATIC_PATH):
raise RuntimeError('can not locate py-static release folder.') raise RuntimeError('can not locate py-static release folder.')
@ -227,6 +225,9 @@ class PYSBaseLinux(PYSBase):
def main(): def main():
if not env.init():
return
if ctx.host_os == 'windows': if ctx.host_os == 'windows':
x = PYSBaseWin() x = PYSBaseWin()
elif ctx.host_os == 'linux': elif ctx.host_os == 'linux':

View File

@ -1,18 +1,15 @@
#!/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import codecs # import codecs
import shutil # import shutil
import time # import time
from core import colorconsole as cc from core import colorconsole as cc
from core import makepyo
from core import utils from core import utils
from core.context import * from core.context import *
from core.env import env
ctx = BuildContext() ctx = BuildContext()
ROOT_PATH = utils.cfg.ROOT_PATH
class BuilderBase: class BuilderBase:
def __init__(self): def __init__(self):
@ -28,32 +25,32 @@ class BuilderWin(BuilderBase):
def build_server(self): def build_server(self):
cc.n('build web server ...') cc.n('build web server ...')
sln_file = os.path.join(ROOT_PATH, 'server', 'tp_web', 'src', 'tp_web.vs2015.sln') sln_file = os.path.join(env.root_path, 'server', 'tp_web', 'src', 'tp_web.vs2015.sln')
out_file = os.path.join(ROOT_PATH, 'out', 'server', ctx.bits_path, ctx.target_path, 'tp_web.exe') out_file = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, ctx.target_path, 'tp_web.exe')
if os.path.exists(out_file): if os.path.exists(out_file):
utils.remove(out_file) utils.remove(out_file)
utils.msvc_build(sln_file, 'tp_web', ctx.target_path, ctx.bits_path, False) utils.msvc_build(sln_file, 'tp_web', ctx.target_path, ctx.bits_path, False)
utils.ensure_file_exists(out_file) utils.ensure_file_exists(out_file)
cc.n('build core server ...') cc.n('build core server ...')
sln_file = os.path.join(ROOT_PATH, 'server', 'tp_core', 'core', 'tp_core.vs2015.sln') sln_file = os.path.join(env.root_path, 'server', 'tp_core', 'core', 'tp_core.vs2015.sln')
out_file = os.path.join(ROOT_PATH, 'out', 'server', ctx.bits_path, ctx.target_path, 'tp_core.exe') out_file = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, ctx.target_path, 'tp_core.exe')
if os.path.exists(out_file): if os.path.exists(out_file):
utils.remove(out_file) utils.remove(out_file)
utils.msvc_build(sln_file, 'tp_core', ctx.target_path, ctx.bits_path, False) utils.msvc_build(sln_file, 'tp_core', ctx.target_path, ctx.bits_path, False)
utils.ensure_file_exists(out_file) utils.ensure_file_exists(out_file)
cc.n('build SSH protocol ...') cc.n('build SSH protocol ...')
sln_file = os.path.join(ROOT_PATH, 'server', 'tp_core', 'protocol', 'ssh', 'tpssh.vs2015.sln') sln_file = os.path.join(env.root_path, 'server', 'tp_core', 'protocol', 'ssh', 'tpssh.vs2015.sln')
out_file = os.path.join(ROOT_PATH, 'out', 'server', ctx.bits_path, ctx.target_path, 'tpssh.dll') out_file = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, ctx.target_path, 'tpssh.dll')
if os.path.exists(out_file): if os.path.exists(out_file):
utils.remove(out_file) utils.remove(out_file)
utils.msvc_build(sln_file, 'tpssh', ctx.target_path, ctx.bits_path, False) utils.msvc_build(sln_file, 'tpssh', ctx.target_path, ctx.bits_path, False)
utils.ensure_file_exists(out_file) utils.ensure_file_exists(out_file)
# #
# s = os.path.join(ROOT_PATH, 'out', 'console', ctx.bits_path, ctx.target_path, 'console.exe') # s = os.path.join(env.root_path, 'out', 'console', ctx.bits_path, ctx.target_path, 'console.exe')
# t = os.path.join(ROOT_PATH, 'out', 'eom_agent', ctx.target_path, ctx.dist_path, 'eom_agent.com') # t = os.path.join(env.root_path, 'out', 'eom_agent', ctx.target_path, ctx.dist_path, 'eom_agent.com')
# shutil.copy(s, t) # shutil.copy(s, t)
# utils.ensure_file_exists(t) # utils.ensure_file_exists(t)
@ -65,7 +62,7 @@ class BuilderLinux(BuilderBase):
def build_server(self): def build_server(self):
cc.n('build server app (tp_core/libtpssh/tp_web)...') cc.n('build server app (tp_core/libtpssh/tp_web)...')
out_path = os.path.join(ROOT_PATH, 'out', 'server', ctx.bits_path, 'bin') out_path = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, 'bin')
out_files = [os.path.join(out_path, 'tp_core'), os.path.join(out_path, 'libtpssh.so'), out_files = [os.path.join(out_path, 'tp_core'), os.path.join(out_path, 'libtpssh.so'),
os.path.join(out_path, 'tp_web')] os.path.join(out_path, 'tp_web')]
@ -75,7 +72,7 @@ class BuilderLinux(BuilderBase):
utils.makedirs(out_path) utils.makedirs(out_path)
utils.cmake(os.path.join(ROOT_PATH, 'server', 'cmake-build'), ctx.target_path, False) utils.cmake(os.path.join(env.root_path, 'server', 'cmake-build'), ctx.target_path, False)
# utils.strip(out_file) # utils.strip(out_file)
for f in out_files: for f in out_files:
@ -83,7 +80,6 @@ class BuilderLinux(BuilderBase):
utils.ensure_file_exists(f) utils.ensure_file_exists(f)
def gen_builder(dist): def gen_builder(dist):
if dist == 'windows': if dist == 'windows':
builder = BuilderWin() builder = BuilderWin()
@ -97,6 +93,9 @@ def gen_builder(dist):
def main(): def main():
if not env.init():
return
builder = None builder = None
argv = sys.argv[1:] argv = sys.argv[1:]

View File

@ -5,16 +5,18 @@ import codecs
from core import colorconsole as cc from core import colorconsole as cc
from core import utils from core import utils
from core.env import env
from core.context import * from core.context import *
ctx = BuildContext() ctx = BuildContext()
ROOT_PATH = utils.cfg.ROOT_PATH
# ROOT_PATH = utils.cfg.ROOT_PATH
class Builder: class Builder:
def __init__(self): def __init__(self):
self.ver_in = os.path.join(ROOT_PATH, 'version.in') self.ver_in = os.path.join(env.root_path, 'version.in')
self.VER_TELEPORT_SERVER = '' self.VER_TELEPORT_SERVER = ''
self.VER_TELEPORT_ASSIST = '' self.VER_TELEPORT_ASSIST = ''
@ -57,7 +59,7 @@ class Builder:
self.make_web_ver() self.make_web_ver()
def make_build_ver(self): def make_build_ver(self):
ver_file = os.path.join(ROOT_PATH, 'build', 'builder', 'core', 'ver.py') ver_file = os.path.join(env.root_path, 'build', 'builder', 'core', 'ver.py')
# ver_content = '# -*- coding: utf8 -*-\nVER_TELEPORT_SERVER = "{}"\nVER_TELEPORT_ASSIST = "{}"\nVER_TELEPORT_MAKECERT = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST, self.VER_TELEPORT_MAKECERT) # ver_content = '# -*- coding: utf8 -*-\nVER_TELEPORT_SERVER = "{}"\nVER_TELEPORT_ASSIST = "{}"\nVER_TELEPORT_MAKECERT = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST, self.VER_TELEPORT_MAKECERT)
ver_content = '# -*- coding: utf8 -*-\nVER_TELEPORT_SERVER = "{}"\nVER_TELEPORT_ASSIST = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST) ver_content = '# -*- coding: utf8 -*-\nVER_TELEPORT_SERVER = "{}"\nVER_TELEPORT_ASSIST = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST)
@ -77,7 +79,7 @@ class Builder:
f.write(ver_content) f.write(ver_content)
def make_web_ver(self): def make_web_ver(self):
ver_file = os.path.join(ROOT_PATH, 'server', 'www', 'teleport', 'app', 'eom_ver.py') ver_file = os.path.join(env.root_path, 'server', 'www', 'teleport', 'app', 'eom_ver.py')
# ver_content = '# -*- coding: utf8 -*-\n\nTS_VER = "{}"\n'.format(self.VER_TELEPORT_SERVER) # ver_content = '# -*- coding: utf8 -*-\n\nTS_VER = "{}"\n'.format(self.VER_TELEPORT_SERVER)
ver_content = '# -*- coding: utf8 -*-\nTS_VER = "{}"\nTP_ASSIST_LAST_VER = "{}"\nTP_ASSIST_REQUIRE = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST, self.VER_TELEPORT_ASSIST_REQUIRE) ver_content = '# -*- coding: utf8 -*-\nTS_VER = "{}"\nTP_ASSIST_LAST_VER = "{}"\nTP_ASSIST_REQUIRE = "{}"\n'.format(self.VER_TELEPORT_SERVER, self.VER_TELEPORT_ASSIST, self.VER_TELEPORT_ASSIST_REQUIRE)
@ -97,7 +99,7 @@ class Builder:
f.write(ver_content) f.write(ver_content)
def make_assist_ver(self): def make_assist_ver(self):
ver_file = os.path.join(ROOT_PATH, 'client', 'tp_assist', 'ts_ver.h') ver_file = os.path.join(env.root_path, 'client', 'tp_assist', 'ts_ver.h')
ver_content = '#ifndef __TS_ASSIST_VER_H__\n#define __TS_ASSIST_VER_H__\n\n#define TP_ASSIST_VER\tL"{}"\n\n#endif // __TS_ASSIST_VER_H__\n'.format(self.VER_TELEPORT_ASSIST) ver_content = '#ifndef __TS_ASSIST_VER_H__\n#define __TS_ASSIST_VER_H__\n\n#define TP_ASSIST_VER\tL"{}"\n\n#endif // __TS_ASSIST_VER_H__\n'.format(self.VER_TELEPORT_ASSIST)
rewrite = False rewrite = False
@ -115,14 +117,14 @@ class Builder:
with open(ver_file, 'w') as f: with open(ver_file, 'w') as f:
f.write(ver_content) f.write(ver_content)
rc_file = os.path.join(ROOT_PATH, 'client', 'tp_assist', 'tp_assist.rc') rc_file = os.path.join(env.root_path, 'client', 'tp_assist', 'tp_assist.rc')
self._update_vs_rc(rc_file, self.VER_TELEPORT_ASSIST) self._update_vs_rc(rc_file, self.VER_TELEPORT_ASSIST)
nsi_file = os.path.join(ROOT_PATH, 'dist', 'windows', 'client', 'assist', 'installer.nsi') nsi_file = os.path.join(env.root_path, 'dist', 'client', 'windows', 'assist', 'installer.nsi')
self._update_nsi_rc(nsi_file, self.VER_TELEPORT_ASSIST) self._update_nsi_rc(nsi_file, self.VER_TELEPORT_ASSIST)
def make_tp_core_ver(self): def make_tp_core_ver(self):
ver_file = os.path.join(ROOT_PATH, 'server', 'tp_core', 'core', 'ts_ver.h') ver_file = os.path.join(env.root_path, 'server', 'tp_core', 'core', 'ts_ver.h')
ver_content = '#ifndef __TS_SERVER_VER_H__\n#define __TS_SERVER_VER_H__\n\n#define TP_SERVER_VER\tL"{}"\n\n#endif // __TS_SERVER_VER_H__\n'.format(self.VER_TELEPORT_SERVER) ver_content = '#ifndef __TS_SERVER_VER_H__\n#define __TS_SERVER_VER_H__\n\n#define TP_SERVER_VER\tL"{}"\n\n#endif // __TS_SERVER_VER_H__\n'.format(self.VER_TELEPORT_SERVER)
rewrite = False rewrite = False
@ -140,11 +142,11 @@ class Builder:
with open(ver_file, 'w') as f: with open(ver_file, 'w') as f:
f.write(ver_content) f.write(ver_content)
rc_file = os.path.join(ROOT_PATH, 'server', 'tp_core', 'core', 'tp_core.rc') rc_file = os.path.join(env.root_path, 'server', 'tp_core', 'core', 'tp_core.rc')
self._update_vs_rc(rc_file, self.VER_TELEPORT_SERVER) self._update_vs_rc(rc_file, self.VER_TELEPORT_SERVER)
def make_tp_web_ver(self): def make_tp_web_ver(self):
ver_file = os.path.join(ROOT_PATH, 'server', 'tp_web', 'src', 'ts_ver.h') ver_file = os.path.join(env.root_path, 'server', 'tp_web', 'src', 'ts_ver.h')
ver_content = '#ifndef __TS_SERVER_VER_H__\n#define __TS_SERVER_VER_H__\n\n#define TP_SERVER_VER\tL"{}"\n\n#endif // __TS_SERVER_VER_H__\n'.format(self.VER_TELEPORT_SERVER) ver_content = '#ifndef __TS_SERVER_VER_H__\n#define __TS_SERVER_VER_H__\n\n#define TP_SERVER_VER\tL"{}"\n\n#endif // __TS_SERVER_VER_H__\n'.format(self.VER_TELEPORT_SERVER)
rewrite = False rewrite = False
@ -162,7 +164,7 @@ class Builder:
with open(ver_file, 'w') as f: with open(ver_file, 'w') as f:
f.write(ver_content) f.write(ver_content)
rc_file = os.path.join(ROOT_PATH, 'server', 'tp_web', 'src', 'tp_web.rc') rc_file = os.path.join(env.root_path, 'server', 'tp_web', 'src', 'tp_web.rc')
self._update_vs_rc(rc_file, self.VER_TELEPORT_SERVER) self._update_vs_rc(rc_file, self.VER_TELEPORT_SERVER)
def _update_vs_rc(self, rcFilePath, ver): def _update_vs_rc(self, rcFilePath, ver):
@ -352,6 +354,9 @@ class Builder:
def main(): def main():
if not env.init():
return
builder = Builder() builder = Builder()
builder.build() builder.build()

View File

@ -59,9 +59,6 @@ COLORS = {
} }
# env = eomcore.env.get_env()
class ColorConsole: class ColorConsole:
""" """
:type _win_color : Win32ColorConsole :type _win_color : Win32ColorConsole

View File

@ -1,97 +0,0 @@
# -*- coding: utf8 -*-
import os
import sys
import platform
import configparser
from . import colorconsole as cc
__all__ = ['cfg']
class AttrDict(dict):
"""
可以像属性一样访问字典的 Keyvar.key 等同于 var['key']
"""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
# print(self.__class__.__name__)
raise
def __setattr__(self, name, val):
self[name] = val
class ConfigFile(AttrDict):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def init(self, cfg_file):
self['ROOT_PATH'] = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
self['py_exec'] = sys.executable
_py_ver = platform.python_version_tuple()
self['py_ver'] = _py_ver
self['py_ver_str'] = '%s%s' % (_py_ver[0], _py_ver[1])
self['is_py2'] = sys.version_info[0] == 2
self['is_py3'] = sys.version_info[0] == 3
_bits = platform.architecture()[0]
if _bits == '64bit':
self['is_x64'] = True
self['is_x86'] = False
else:
self['is_x64'] = False
self['is_x86'] = True
_os = platform.system().lower()
self['is_win'] = False
self['is_linux'] = False
self['is_macos'] = False
self['dist'] = ''
if _os == 'windows':
self['is_win'] = True
self['dist'] = 'windows'
elif _os == 'linux':
self['is_linux'] = True
self['dist'] = 'linux'
elif _os == 'darwin':
self['is_macos'] = True
self['dist'] = 'macos'
else:
cc.e('not support this OS: {}'.format(platform.system()))
return False
_cfg = configparser.ConfigParser()
_cfg.read(cfg_file)
if 'external_ver' not in _cfg.sections() or 'toolchain' not in _cfg.sections():
cc.e('invalid configuration file: need `external_ver` and `toolchain` section.')
return False
_tmp = _cfg['external_ver']
if 'libuv' not in _tmp or 'mbedtls' not in _tmp or 'sqlite' not in _tmp:
cc.e('invalid configuration file: external version not set.')
return False
self['ver'] = AttrDict()
for k in _tmp:
self['ver'][k] = _tmp[k]
_tmp = _cfg['toolchain']
self['toolchain'] = AttrDict()
if self.is_win:
self['toolchain']['nsis'] = _tmp.get('nsis', None)
self['toolchain']['msbuild'] = None # msbuild always read from register.
else:
self['toolchain']['cmake'] = _tmp.get('cmake', '/usr/bin/cmake')
return True
cfg = ConfigFile()
del ConfigFile

View File

@ -1,4 +1,3 @@
#!/usr/bin/env python
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
import os import os

224
build/builder/core/env.py Normal file
View File

@ -0,0 +1,224 @@
# -*- coding: utf8 -*-
import os
import platform
import sys
import configparser
from . import colorconsole as cc
if platform.system().lower() == 'windows':
try:
import winreg
except ImportError:
cc.e('Can not load module `winreg`, so I can not locate toolchain for you.')
class Env(object):
BITS_32 = 32
BITS_64 = 64
def __init__(self):
_this_path = os.path.abspath(os.path.dirname(__file__))
self.root_path = os.path.abspath(os.path.join(_this_path, '..', '..', '..'))
self.build_path = os.path.abspath(os.path.join(_this_path, '..', '..'))
self.builder_path = os.path.join(self.build_path, 'builder')
self.win32_tools_path = os.path.join(self.build_path, 'tools', 'win32')
self.is_py2 = sys.version_info[0] == 2
self.is_py3 = sys.version_info[0] == 3
self.py_ver = platform.python_version_tuple()
self.py_ver_str = '%s%s' % (self.py_ver[0], self.py_ver[1])
self.py_exec = sys.executable
self.bits = self.BITS_32
self.bits_str = 'x86'
_bits = platform.architecture()[0]
if _bits == '64bit':
self.bits = self.BITS_64
self.bits_str = 'x64'
self.is_win = False
self.is_win_x64 = False
self.is_linux = False
self.is_macos = False
_os = platform.system().lower()
self.plat = ''
if _os == 'windows':
self.is_win = True
self.plat = 'windows'
self.is_win_x64 = 'PROGRAMFILES(X86)' in os.environ
elif _os == 'linux':
self.is_linux = True
self.plat = 'linux'
elif _os == 'darwin':
self.is_macos = True
self.plat = 'macos'
def init(self, warn_miss_tool=False):
if not self._load_config(warn_miss_tool):
return False
return True
def _load_config(self, warn_miss_tool):
_cfg_file = os.path.join(self.root_path, 'config.ini')
if not os.path.exists(_cfg_file):
cc.e('can not load configuration.\n\nplease copy `config.ini.in` into `config.ini` and modify it to fit your condition and try again.')
return False
_cfg = configparser.ConfigParser()
_cfg.read(_cfg_file)
if 'external_ver' not in _cfg.sections() or 'toolchain' not in _cfg.sections():
cc.e('invalid configuration file: need `external_ver` and `toolchain` section.')
return False
_tmp = _cfg['external_ver']
try:
_v_openssl = _tmp['openssl'].split(',')
self.ver_openssl = _v_openssl[0].strip()
self.ver_openssl_number = _v_openssl[1].strip()
self.ver_libuv = _tmp['libuv']
self.ver_mbedtls = _tmp['mbedtls']
self.ver_sqlite = _tmp['sqlite']
self.ver_libssh = _tmp['libssh']
self.ver_jsoncpp = _tmp['jsoncpp']
self.ver_mongoose = _tmp['mongoose']
except KeyError:
cc.e('invalid configuration file: not all necessary external version are set.')
return False
_tmp = _cfg['toolchain']
if self.is_win:
if 'wget' in _tmp:
self.wget = _tmp['wget']
else:
self.wget = None
if self.wget is None or not os.path.exists(self.wget):
if warn_miss_tool:
cc.w(' - can not find `wget.exe`, you can get it at https://eternallybored.org/misc/wget/')
if '7z' in _tmp:
self.zip7 = _tmp['7z']
else:
self.zip7 = None
if self.zip7 is None or not os.path.exists(self.zip7):
if warn_miss_tool:
cc.w(' - can not find `7z.exe`, you can get it at http://www.7-zip.org')
if 'nasm' in _tmp:
self.nasm = _tmp['nasm']
else:
self.nasm = self._get_nasm()
if self.nasm is None or not os.path.exists(self.nasm):
if warn_miss_tool:
cc.w(' - can not locate `nasm`, so I can build openssl.')
if 'perl' in _tmp:
self.perl = _tmp['perl']
else:
self.perl = self._get_perl()
if self.perl is None or not os.path.exists(self.perl):
if warn_miss_tool:
cc.w(' - can not locate `perl`, so I can build openssl.')
self.visual_studio_path = self._get_visual_studio_path()
if self.visual_studio_path is None or not os.path.exists(self.visual_studio_path):
if warn_miss_tool:
cc.w(' - can not locate Visual Studio installation, so I can build openssl.')
if 'msbuild' in _tmp:
self.msbuild = _tmp['msbuild']
else:
self.msbuild = self._get_msbuild()
if self.msbuild is None or not os.path.exists(self.msbuild):
if warn_miss_tool:
cc.w(' - can not locate `MSBuild`, so I can build nothing.')
if 'nsis' in _tmp:
self.nsis = _tmp['nsis']
else:
self.nsis = self._get_nsis()
if self.nsis is None or not os.path.exists(self.nsis):
if warn_miss_tool:
cc.w(' - can not locate `nsis`, so I can not make installer.')
elif self.is_linux:
if 'cmake' in _tmp:
self.cmake = _tmp['cmake']
else:
self.cmake = '/usr/bin/cmake'
if not os.path.exists(self.cmake):
if warn_miss_tool:
cc.e(' - can not locate `cmake`, so I can not build binary from source.')
return True
def _get_msbuild(self):
# 14.0 = VS2015
# 12.0 = VS2012
# 4.0 = VS2008
chk = ['14.0', '12.0', '4.0']
p = None
for c in chk:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\MSBuild\ToolsVersions\{}'.format(c), r'MSBuildToolsPath')
if p is not None:
break
return os.path.join(p[0], 'MSBuild.exe') if p is not None else None
def _get_visual_studio_path(self):
chk = ['14.0', '12.0', '4.0']
p = None
for c in chk:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\VisualStudio\{}'.format(c), r'ShellFolder')
if p is not None:
break
return p[0] if p is not None else None
def _get_perl(self):
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\perl', 'BinDir')
return p[0] if p is not None else None
def _get_nasm(self):
p = self._winreg_read(winreg.HKEY_CURRENT_USER, r'SOFTWARE\nasm', '')
return os.path.join(p[0], 'nasm.exe') if p is not None else None
def _get_nsis(self):
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS\Unicode', '')
if p is None:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS', '')
return os.path.join(p[0], 'makensis.exe') if p is not None else None
def _winreg_read(self, base, path, key):
try:
if self.is_win_x64:
hkey = winreg.CreateKeyEx(base, path, 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
else:
hkey = winreg.CreateKeyEx(base, path, 0, winreg.KEY_READ)
value = winreg.QueryValueEx(hkey, key)
return value
except OSError:
return None
env = Env()
del Env
if __name__ == '__main__':
pass

View File

@ -1,33 +1,78 @@
#!/usr/bin/env python
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
import os import os
import platform
import shutil import shutil
import subprocess import subprocess
import sys import sys
import time import time
from . import colorconsole as cc from . import colorconsole as cc
from .env import env
from .configs import cfg if env.is_py2:
try:
CONFIG_FILE = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')), 'config.ini')
if not cfg.init(CONFIG_FILE):
sys.exit(1)
except:
cc.e('can not load configuration.\n\nplease copy `config.ini.in` into `config.ini` and modify it to fit your condition and try again.')
sys.exit(1)
if cfg.is_py2:
import imp import imp
elif cfg.is_py3: elif env.is_py3:
import importlib import importlib
import importlib.machinery import importlib.machinery
if sys.platform == 'win32':
import winreg def _check_download_file(file_name):
if env.is_win:
# use 7z to test integrity of downloaded
ret, output = sys_exec('"{}" t "{}"'.format(env.zip7, file_name), False)
if 'Everything is Ok' in output:
return True
else:
x = os.path.splitext(file_name)
# print('ext:', x)
if x[-1].lower() == '.zip':
ret, output = sys_exec('zip -T "{}"'.format(file_name), False)
# print('test .zip:', ret, output)
if ret == 0:
return True
elif x[-1].lower() == '.xz':
ret, output = sys_exec('xz -t "{}"'.format(file_name), False)
# print('test .xz:', ret, output)
if ret == 0:
return True
elif x[-1].lower() == '.gz':
ret, output = sys_exec('gzip -t "{}"'.format(file_name), False)
# print('test .gz:', ret, output)
if ret == 0:
return True
else:
cc.w('[fixme] how to test {} on Linux? '.format(x[-1]), end='')
return True
return False
def download_file(desc, url, target_path, file_name):
cc.n('download {} ... '.format(desc), end='')
local_file_name = os.path.join(target_path, file_name)
if os.path.exists(local_file_name):
if not _check_download_file(local_file_name):
cc.w('already exists but broken, download it again...')
else:
cc.w('already exists, skip.')
return True
cc.v('')
# 因为下载过程会在命令行显示进度所以不能使用subprocess.Popen()的方式捕获输出,会很难看!
if env.is_win:
cmd = '""{}" --no-check-certificate {} -O "{}""'.format(env.wget, url, local_file_name)
os.system(cmd)
elif env.is_linux:
os.system('wget --no-check-certificate {} -O "{}"'.format(url, local_file_name))
else:
return False
if not os.path.exists(local_file_name) or not _check_download_file(local_file_name):
cc.e('downloading {} from {} failed.'.format(desc, url))
return False
return True
def extension_suffixes(): def extension_suffixes():
@ -38,7 +83,7 @@ def extension_suffixes():
# type为文件类型, 1代表PY_SOURCE, 2代表PY_COMPILED, 3代表C_EXTENSION # type为文件类型, 1代表PY_SOURCE, 2代表PY_COMPILED, 3代表C_EXTENSION
EXTENSION_SUFFIXES = list() EXTENSION_SUFFIXES = list()
if cfg.is_py2: if env.is_py2:
suf = imp.get_suffixes() suf = imp.get_suffixes()
for s in suf: for s in suf:
if s[2] == 3: if s[2] == 3:
@ -46,18 +91,17 @@ def extension_suffixes():
else: else:
EXTENSION_SUFFIXES = importlib.machinery.EXTENSION_SUFFIXES EXTENSION_SUFFIXES = importlib.machinery.EXTENSION_SUFFIXES
if cfg.dist == 'windows': if env.is_win:
if '.dll' not in EXTENSION_SUFFIXES: if '.dll' not in EXTENSION_SUFFIXES:
EXTENSION_SUFFIXES.append('.dll') EXTENSION_SUFFIXES.append('.dll')
elif cfg.dist == 'linux': elif env.is_linux:
if '.so' not in EXTENSION_SUFFIXES: if '.so' not in EXTENSION_SUFFIXES:
EXTENSION_SUFFIXES.append('.so') EXTENSION_SUFFIXES.append('.so')
elif cfg.dist == 'macos': else:
raise RuntimeError('not support MacOS now.') raise RuntimeError('not support this platform now.')
# cc.v(EXTENSION_SUFFIXES)
return EXTENSION_SUFFIXES return EXTENSION_SUFFIXES
@ -209,107 +253,34 @@ def ensure_file_exists(filename):
raise RuntimeError('path exists but not a file: {}'.format(filename)) raise RuntimeError('path exists but not a file: {}'.format(filename))
# def root_path():
# return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
def python_exec():
if not os.path.exists(sys.executable):
raise RuntimeError('Can not locate Python execute file.')
return sys.executable
def msbuild_path():
if cfg.toolchain.msbuild is not None:
return cfg.toolchain.msbuild
# 14.0 = VS2015
# 12.0 = VS2012
# 4.0 = VS2008
chk = ['14.0', '4.0', '12.0']
msp = None
for c in chk:
msp = winreg_read("SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}".format(c), 'MSBuildToolsPath')
if msp is not None:
break
if msp is None:
raise RuntimeError('Can not locate MSBuild.')
msb = os.path.join(msp[0], 'MSBuild.exe')
if not os.path.exists(msb):
raise RuntimeError('Can not locate MSBuild at {}'.format(msp))
cfg.toolchain.msbuild = msb
return msb
def nsis_path():
if cfg.toolchain.nsis is not None:
return cfg.toolchain.nsis
p = winreg_read_wow64_32(r'SOFTWARE\NSIS\Unicode', '')
if p is None:
raise RuntimeError('Can not locate unicode version of NSIS.')
p = os.path.join(p[0], 'makensis.exe')
if not os.path.exists(p):
raise RuntimeError('Can not locate NSIS at {}'.format(p))
cfg.toolchain.nsis = p
return p
def winreg_read(path, key):
try:
hkey = winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ)
value = winreg.QueryValueEx(hkey, key)
except OSError:
return None
return value
def winreg_read_wow64_32(path, key):
try:
hkey = winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
value = winreg.QueryValueEx(hkey, key)
except OSError:
return None
return value
def sys_exec(cmd, direct_output=False, output_codec=None): def sys_exec(cmd, direct_output=False, output_codec=None):
# 注意output_codec在windows默认为gb2312其他平台默认utf8
_os = platform.system().lower()
if output_codec is None: if output_codec is None:
if _os == 'windows': if env.is_win:
output_codec = 'gb2312' output_codec = 'gb2312'
else: else:
output_codec = 'utf8' output_codec = 'utf8'
p = None p = None
if _os == 'windows': if env.is_win:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
else: else:
p = subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True) p = subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, shell=True)
output = '' output = list()
f = p.stdout f = p.stdout
while True: while True:
line = f.readline() line = f.readline()
if 0 == len(line): if 0 == len(line):
break break
if direct_output: line = line.rstrip('\r\n')
# cc.v(line.decode(output_codec))
# cc.d(line, end='')
cc.o((cc.CR_GRAY, line), end='')
output += line if direct_output:
cc.o((cc.CR_GRAY, line), end='\n')
output.append(line)
ret = p.wait() ret = p.wait()
@ -317,45 +288,40 @@ def sys_exec(cmd, direct_output=False, output_codec=None):
def msvc_build(sln_file, proj_name, target, platform, force_rebuild): def msvc_build(sln_file, proj_name, target, platform, force_rebuild):
msbuild = msbuild_path() if env.msbuild is None:
raise RuntimeError('where is `msbuild`?')
if force_rebuild: if force_rebuild:
cmd = '"{}" "{}" "/target:clean" "/property:Configuration={};Platform={}"'.format(msbuild, sln_file, target, platform) cmd = '"{}" "{}" "/target:clean" "/property:Configuration={};Platform={}"'.format(env.msbuild, sln_file, target,
platform)
ret, _ = sys_exec(cmd, direct_output=True) ret, _ = sys_exec(cmd, direct_output=True)
cc.v('ret:', ret) cc.v('ret:', ret)
cmd = '"{}" "{}" "/target:{}" "/property:Configuration={};Platform={}"'.format(msbuild, sln_file, proj_name, target, platform) cmd = '"{}" "{}" "/target:{}" "/property:Configuration={};Platform={}"'.format(env.msbuild, sln_file, proj_name,
target, platform)
ret, _ = sys_exec(cmd, direct_output=True) ret, _ = sys_exec(cmd, direct_output=True)
if ret != 0: if ret != 0:
raise RuntimeError('build MSVC project `{}` failed.'.format(proj_name)) raise RuntimeError('build MSVC project `{}` failed.'.format(proj_name))
def nsis_build(nsi_file, _define=''): def nsis_build(nsi_file, _define=''):
nsis = nsis_path() if env.nsis is None:
cmd = '"{}" /V2 {} /X"SetCompressor /SOLID /FINAL lzma" "{}"'.format(nsis, _define, nsi_file) raise RuntimeError('where is `nsis`?')
cmd = '"{}" /V2 {} /X"SetCompressor /SOLID /FINAL lzma" "{}"'.format(env.nsis, _define, nsi_file)
ret, _ = sys_exec(cmd, direct_output=True) ret, _ = sys_exec(cmd, direct_output=True)
if ret != 0: if ret != 0:
raise RuntimeError('make installer with nsis failed. [{}]'.format(nsi_file)) raise RuntimeError('make installer with nsis failed. [{}]'.format(nsi_file))
def cmake(work_path, target, force_rebuild, cmake_define=''): def cmake(work_path, target, force_rebuild, cmake_define=''):
# because cmake v2.8 shipped with Ubuntu 14.04LTS, but we need 3.5. # I use cmake v3.5 which shipped with CLion.
# I copy a v3.5 cmake from CLion. if env.cmake is None:
print(cfg) raise RuntimeError('where is `cmake`?')
if 'cmake' not in cfg.toolchain:
raise RuntimeError('please set `cmake` path.')
print(cfg.toolchain.cmake)
if not os.path.exists(cfg.toolchain.cmake):
raise RuntimeError('`cmake` does not exists, please check your configuration and try again.')
CMAKE = cfg.toolchain.cmake
cc.n('make by cmake', target, sep=': ') cc.n('make by cmake', target, sep=': ')
old_p = os.getcwd() old_p = os.getcwd()
# new_p = os.path.dirname(wscript_file)
# work_path = os.path.join(root_path(), 'cmake-build')
if os.path.exists(work_path): if os.path.exists(work_path):
if force_rebuild: if force_rebuild:
remove(work_path) remove(work_path)
@ -367,7 +333,7 @@ def cmake(work_path, target, force_rebuild, cmake_define=''):
target = 'Debug' target = 'Debug'
else: else:
target = 'Release' target = 'Release'
cmd = '"{}" -DCMAKE_BUILD_TYPE={} {} ..;make'.format(CMAKE, target, cmake_define) cmd = '"{}" -DCMAKE_BUILD_TYPE={} {} ..;make'.format(env.cmake, target, cmake_define)
ret, _ = sys_exec(cmd, direct_output=True) ret, _ = sys_exec(cmd, direct_output=True)
os.chdir(old_p) os.chdir(old_p)
if ret != 0: if ret != 0:
@ -385,15 +351,49 @@ def strip(filename):
return True return True
def make_zip(src_path, to_file): def make_zip(src_path, to_file, from_parent=True):
cc.v('compress folder into .zip...') cc.v('compress folder into .zip...')
n, _ = os.path.splitext(to_file)
# x = os.path.split(to_file)[1].split('.') src_path = os.path.abspath(src_path)
p = os.path.dirname(to_file) _parent = os.path.abspath(os.path.join(src_path, '..'))
shutil.make_archive(os.path.join(p, n), 'zip', src_path) _folder = src_path[len(_parent) + 1:]
if env.is_win:
old_p = os.getcwd()
if from_parent:
os.chdir(_parent)
cmd = '""{}" a "{}" "{}""'.format(env.zip7, to_file, _folder)
else:
os.chdir(src_path)
cmd = '""{}" a "{}" "*""'.format(env.zip7, to_file)
os.system(cmd)
os.chdir(old_p)
elif env.is_linux:
old_p = os.getcwd()
if from_parent:
os.chdir(_parent)
cmd = 'zip -r "{}" "{}"'.format(to_file, _folder)
else:
os.chdir(src_path)
cmd = 'zip -q -r "{}" ./*'.format(to_file)
os.system(cmd)
os.chdir(old_p)
else:
raise RuntimeError('not support this platform.')
ensure_file_exists(to_file) ensure_file_exists(to_file)
def unzip(file_name, to_path):
if env.is_win:
cmd = '""{}" x "{}" -o"{}""'.format(env.zip7, file_name, to_path)
os.system(cmd)
elif env.is_linux:
os.system('unzip "{}" -d "{}"'.format(file_name, to_path))
else:
raise RuntimeError('not support this platform.')
def make_targz(work_path, folder, to_file): def make_targz(work_path, folder, to_file):
cc.v('compress folder into .tar.gz...') cc.v('compress folder into .tar.gz...')
old_p = os.getcwd() old_p = os.getcwd()
@ -405,37 +405,6 @@ def make_targz(work_path, folder, to_file):
os.chdir(old_p) os.chdir(old_p)
def fix_extension_files(s_path, t_path):
cc.n('\nfix extension files...')
# 遍历s_path目录下的所有Python扩展文件动态库并将其移动到t_path目录下同时改名。
# 例如, s_path/abc/def.pyd -> t_path/abc.def.pyd
s_path = os.path.abspath(s_path)
t_path = os.path.abspath(t_path)
ext = extension_suffixes()
s_path_len = len(s_path)
def _fix_(s_path, t_path, sub_path):
for parent, dir_list, file_list in os.walk(sub_path):
for d in dir_list:
_fix_(s_path, t_path, os.path.join(parent, d))
for filename in file_list:
_, e = os.path.splitext(filename)
if e in ext:
f_from = os.path.join(parent, filename)
f_to = f_from[s_path_len + 1:]
f_to = f_to.replace('\\', '.')
f_to = f_to.replace('/', '.')
f_to = os.path.join(t_path, f_to)
cc.v('move: ', f_from, '\n -> ', f_to)
shutil.move(f_from, f_to)
_fix_(s_path, t_path, s_path)
if __name__ == '__main__': if __name__ == '__main__':
# test() # test()
pass pass

View File

@ -1,3 +1,3 @@
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
VER_TELEPORT_SERVER = "2.0.0.1" VER_TELEPORT_SERVER = "2.1.2.1"
VER_TELEPORT_ASSIST = "2.0.0.1" VER_TELEPORT_ASSIST = "2.1.2.1"

View File

@ -4,6 +4,11 @@
#include "resource.h" #include "resource.h"
#include "dlg_main.h" #include "dlg_main.h"
#include "ts_http_rpc.h" #include "ts_http_rpc.h"
#ifdef _DEBUG
# include <vld.h>
#endif
#pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "shlwapi.lib")
#define WMU_INSTANCE_EXIT (WM_USER + 2) #define WMU_INSTANCE_EXIT (WM_USER + 2)
@ -128,6 +133,9 @@ int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmd
DispatchMessage(&msg); DispatchMessage(&msg);
} }
http_rpc_stop();
WaitForSingleObject(hThread, INFINITE);
CloseHandle(g_SingleInstanceMutexHandle); CloseHandle(g_SingleInstanceMutexHandle);
LocalFree(g_argv); LocalFree(g_argv);

Binary file not shown.

View File

@ -46,6 +46,8 @@
<LinkIncremental>true</LinkIncremental> <LinkIncremental>true</LinkIncremental>
<OutDir>..\..\out\client\$(PlatformTarget)\$(Configuration)\</OutDir> <OutDir>..\..\out\client\$(PlatformTarget)\$(Configuration)\</OutDir>
<IntDir>..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\</IntDir> <IntDir>..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\</IntDir>
<IncludePath>D:\apps\vld\include;$(IncludePath)</IncludePath>
<LibraryPath>D:\apps\vld\lib\Win32;$(LibraryPath)</LibraryPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental> <LinkIncremental>false</LinkIncremental>
@ -59,7 +61,7 @@
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32</AdditionalIncludeDirectories>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Windows</SubSystem> <SubSystem>Windows</SubSystem>
@ -76,7 +78,7 @@
<IntrinsicFunctions>true</IntrinsicFunctions> <IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary> <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile> </ClCompile>
<Link> <Link>
@ -98,6 +100,7 @@
<ClInclude Include="..\..\common\libex\include\ex\ex_thread.h" /> <ClInclude Include="..\..\common\libex\include\ex\ex_thread.h" />
<ClInclude Include="..\..\common\libex\include\ex\ex_types.h" /> <ClInclude Include="..\..\common\libex\include\ex\ex_types.h" />
<ClInclude Include="..\..\common\libex\include\ex\ex_util.h" /> <ClInclude Include="..\..\common\libex\include\ex\ex_util.h" />
<ClInclude Include="..\..\common\teleport\teleport_const.h" />
<ClInclude Include="..\..\external\mongoose\mongoose.h" /> <ClInclude Include="..\..\external\mongoose\mongoose.h" />
<ClInclude Include="dlg_main.h" /> <ClInclude Include="dlg_main.h" />
<ClInclude Include="msocketx.h" /> <ClInclude Include="msocketx.h" />

View File

@ -126,6 +126,9 @@
<ClInclude Include="..\..\common\libex\include\ex\ex_thread.h"> <ClInclude Include="..\..\common\libex\include\ex\ex_thread.h">
<Filter>libex\header</Filter> <Filter>libex\header</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\common\teleport\teleport_const.h">
<Filter>teleport</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Image Include="res\tp.ico"> <Image Include="res\tp.ico">
@ -160,6 +163,9 @@
<Filter Include="libex\src"> <Filter Include="libex\src">
<UniqueIdentifier>{d7d49fa4-5192-42c5-bc70-5584d9d646c6}</UniqueIdentifier> <UniqueIdentifier>{d7d49fa4-5192-42c5-bc70-5584d9d646c6}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="teleport">
<UniqueIdentifier>{1291a5cf-cb08-4ad6-8a86-8a0486297c63}</UniqueIdentifier>
</Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ResourceCompile Include="tp_assist.rc"> <ResourceCompile Include="tp_assist.rc">

View File

@ -6,7 +6,6 @@
#define TS_TRAY_MSG L"Teleport助手正常工作中" #define TS_TRAY_MSG L"Teleport助手正常工作中"
#define TS_HTTP_RPC_PORT 50022 #define TS_HTTP_RPC_PORT 50022
//#define TS_HTTP_RPC_HOST "0.0.0.0"
#define TS_HTTP_RPC_HOST "127.0.0.1" #define TS_HTTP_RPC_HOST "127.0.0.1"
#endif // __TS_CONST_H__ #endif // __TS_CONST_H__

View File

@ -28,26 +28,48 @@ bool TsEnv::init(void)
if (!ex_dirname(m_exec_path)) if (!ex_dirname(m_exec_path))
return false; return false;
#ifdef _DEBUG
m_ssh_client_conf_file = m_exec_path;
ex_path_join(m_ssh_client_conf_file, false, L"ssh.ini", NULL);
m_scp_client_conf_file = m_exec_path;
ex_path_join(m_scp_client_conf_file, false, L"scp.ini", NULL);
m_telnet_client_conf_file = m_exec_path;
ex_path_join(m_telnet_client_conf_file, false, L"telnet.ini", NULL);
m_log_path = m_exec_path;
ex_path_join(m_log_path, false, L"log", NULL);
m_site_path = m_exec_path;
ex_path_join(m_site_path, true, L"..", L"..", L"..", L"..", L"client", L"tp_assist", L"site", NULL);
m_tools_path = m_exec_path;
ex_path_join(m_tools_path, true, L"..", L"..", L"..", L"..", L"client", L"tools", NULL);
#else
TCHAR szBuf[PATH_MAX] = { 0 }; TCHAR szBuf[PATH_MAX] = { 0 };
SHGetSpecialFolderPathW(NULL, szBuf, CSIDL_APPDATA, FALSE); SHGetSpecialFolderPathW(NULL, szBuf, CSIDL_APPDATA, FALSE);
m_ssh_client_conf_file = szBuf;// m_exec_path; m_ssh_client_conf_file = szBuf;// m_exec_path;
ex_path_join(m_ssh_client_conf_file, false, _T("eomsoft"), _T("teleport"), _T("assist"), _T("cfg"), _T("ssh.ini"), NULL); ex_path_join(m_ssh_client_conf_file, false, L"eomsoft", L"teleport", L"assist", L"cfg", L"ssh.ini", NULL);
m_scp_client_conf_file = szBuf;// m_exec_path; m_scp_client_conf_file = szBuf;// m_exec_path;
ex_path_join(m_scp_client_conf_file, false, _T("eomsoft"), _T("teleport"), _T("assist"), _T("cfg"), _T("scp.ini"), NULL); ex_path_join(m_scp_client_conf_file, false, L"eomsoft", L"teleport", L"assist", L"cfg", L"scp.ini", NULL);
m_telnet_client_conf_file = szBuf;// m_exec_path; m_telnet_client_conf_file = szBuf;// m_exec_path;
ex_path_join(m_telnet_client_conf_file, false, _T("eomsoft"), _T("teleport"), _T("assist"), _T("cfg"), _T("telnet.ini"), NULL); ex_path_join(m_telnet_client_conf_file, false, L"eomsoft", L"teleport", L"assist", L"cfg", L"telnet.ini", NULL);
m_log_path = szBuf;// m_exec_path; m_log_path = szBuf;// m_exec_path;
ex_path_join(m_log_path, false, _T("eomsoft"), _T("teleport"), _T("assist"), _T("log"), NULL); ex_path_join(m_log_path, false, L"eomsoft", L"teleport", L"assist", L"log", NULL);
m_site_path = m_exec_path; m_site_path = m_exec_path;
ex_path_join(m_site_path, false, _T("site"), NULL); ex_path_join(m_site_path, false, L"site", NULL);
m_tools_path = m_exec_path; m_tools_path = m_exec_path;
ex_path_join(m_tools_path, false, _T("tools"), NULL); ex_path_join(m_tools_path, false, L"tools", NULL);
#endif
return true; return true;
} }

View File

@ -4,6 +4,9 @@
#include <commdlg.h> #include <commdlg.h>
#include <ShlObj.h> #include <ShlObj.h>
#include <teleport_const.h>
#include "ts_http_rpc.h" #include "ts_http_rpc.h"
#include "dlg_main.h" #include "dlg_main.h"
#include "ts_ver.h" #include "ts_ver.h"
@ -105,9 +108,15 @@ void http_rpc_main_loop(void)
g_http_interface.run(); g_http_interface.run();
EXLOGW("[prc] main loop end.\n"); EXLOGW("[rpc] main loop end.\n");
} }
void http_rpc_stop(void)
{
g_http_interface.stop();
}
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
int ts_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) int ts_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
@ -147,6 +156,7 @@ int ts_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_f
TsHttpRpc::TsHttpRpc() TsHttpRpc::TsHttpRpc()
{ {
m_stop = false;
mg_mgr_init(&m_mg_mgr, NULL); mg_mgr_init(&m_mg_mgr, NULL);
} }
@ -181,7 +191,6 @@ bool TsHttpRpc::init(const char* ip, int port)
else else
sprintf_s(addr, 128, "%s:%d", ip, port); sprintf_s(addr, 128, "%s:%d", ip, port);
mg_mgr_init(&m_mg_mgr, NULL);
nc = mg_bind(&m_mg_mgr, addr, _mg_event_handler); nc = mg_bind(&m_mg_mgr, addr, _mg_event_handler);
if (nc == NULL) if (nc == NULL)
{ {
@ -191,8 +200,6 @@ bool TsHttpRpc::init(const char* ip, int port)
nc->user_data = this; nc->user_data = this;
mg_set_protocol_http_websocket(nc); mg_set_protocol_http_websocket(nc);
mg_enable_multithreading(nc);
m_content_type_map[".js"] = "application/javascript"; m_content_type_map[".js"] = "application/javascript";
m_content_type_map[".png"] = "image/png"; m_content_type_map[".png"] = "image/png";
@ -212,12 +219,17 @@ bool TsHttpRpc::init(const char* ip, int port)
void TsHttpRpc::run(void) void TsHttpRpc::run(void)
{ {
for (;;) while(!m_stop)
{ {
mg_mgr_poll(&m_mg_mgr, 500); mg_mgr_poll(&m_mg_mgr, 500);
} }
} }
void TsHttpRpc::stop(void)
{
m_stop = true;
}
void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_data) void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_data)
{ {
struct http_message *hm = (struct http_message*)ev_data; struct http_message *hm = (struct http_message*)ev_data;
@ -240,7 +252,7 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
memcpy(&_uri[0], hm->uri.p, hm->uri.len); memcpy(&_uri[0], hm->uri.p, hm->uri.len);
uri = &_uri[0]; uri = &_uri[0];
#ifdef TS_DEBUG #ifdef EX_DEBUG
char* dbg_method = NULL; char* dbg_method = NULL;
if (hm->method.len == 3 && 0 == memcmp(hm->method.p, "GET", hm->method.len)) if (hm->method.len == 3 && 0 == memcmp(hm->method.p, "GET", hm->method.len))
dbg_method = "GET"; dbg_method = "GET";
@ -309,6 +321,7 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
mg_printf(nc, "HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: %d\r\nContent-Type: %s\r\n\r\n", file_size, content_type.c_str()); mg_printf(nc, "HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: %d\r\nContent-Type: %s\r\n\r\n", file_size, content_type.c_str());
mg_send(nc, buf, file_size); mg_send(nc, buf, file_size);
delete []buf;
nc->flags |= MG_F_SEND_AND_CLOSE; nc->flags |= MG_F_SEND_AND_CLOSE;
return; return;
} }
@ -325,7 +338,7 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
ex_astr method; ex_astr method;
ex_astr json_param; ex_astr json_param;
unsigned int rv = _this->_parse_request(hm, method, json_param); int rv = _this->_parse_request(hm, method, json_param);
if (0 != rv) if (0 != rv)
{ {
EXLOGE("[ERROR] http-rpc got invalid request.\n"); EXLOGE("[ERROR] http-rpc got invalid request.\n");
@ -345,10 +358,10 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
} }
} }
unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_cmd, ex_astr& func_args) int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_cmd, ex_astr& func_args)
{ {
if (NULL == req) if (NULL == req)
return TSR_INVALID_REQUEST; return TPE_FAILED;
bool is_get = true; bool is_get = true;
if (req->method.len == 3 && 0 == memcmp(req->method.p, "GET", req->method.len)) if (req->method.len == 3 && 0 == memcmp(req->method.p, "GET", req->method.len))
@ -356,7 +369,7 @@ unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_c
else if (req->method.len == 4 && 0 == memcmp(req->method.p, "POST", req->method.len)) else if (req->method.len == 4 && 0 == memcmp(req->method.p, "POST", req->method.len))
is_get = false; is_get = false;
else else
return TSR_INVALID_REQUEST; return TPE_HTTP_METHOD;
ex_astrs strs; ex_astrs strs;
@ -384,7 +397,7 @@ unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_c
} }
if (0 == strs.size()) if (0 == strs.size())
return TSR_INVALID_REQUEST; return TPE_PARAM;
if (is_get) if (is_get)
{ {
@ -399,7 +412,7 @@ unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_c
} }
else else
{ {
return TSR_INVALID_REQUEST; return TPE_PARAM;
} }
} }
else else
@ -410,7 +423,7 @@ unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_c
} }
else else
{ {
return TSR_INVALID_REQUEST; return TPE_PARAM;
} }
if (req->body.len > 0) if (req->body.len > 0)
@ -427,14 +440,14 @@ unsigned int TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_c
sztmp.resize(len); sztmp.resize(len);
memset(&sztmp[0], 0, len); memset(&sztmp[0], 0, len);
if (-1 == ts_url_decode(func_args.c_str(), func_args.length(), &sztmp[0], len, 0)) if (-1 == ts_url_decode(func_args.c_str(), func_args.length(), &sztmp[0], len, 0))
return TSR_INVALID_URL_ENCODE; return TPE_HTTP_URL_ENCODE;
func_args = &sztmp[0]; func_args = &sztmp[0];
} }
EXLOGV("[rpc] method=%s, json_param=%s\n", func_cmd.c_str(), func_args.c_str()); EXLOGV("[rpc] method=%s, json_param=%s\n", func_cmd.c_str(), func_args.c_str());
return TSR_OK; return TPE_OK;
} }
void TsHttpRpc::_process_js_request(const ex_astr& func_cmd, const ex_astr& func_args, ex_astr& buf) void TsHttpRpc::_process_js_request(const ex_astr& func_cmd, const ex_astr& func_args, ex_astr& buf)
@ -470,7 +483,7 @@ void TsHttpRpc::_process_js_request(const ex_astr& func_cmd, const ex_astr& func
else else
{ {
EXLOGE("[rpc] got unknown command: %s\n", func_cmd.c_str()); EXLOGE("[rpc] got unknown command: %s\n", func_cmd.c_str());
_create_json_ret(buf, TSR_NO_SUCH_METHOD); _create_json_ret(buf, TPE_UNKNOWN_CMD);
} }
} }
@ -504,12 +517,12 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
if (jsRoot.isArray()) if (jsRoot.isArray())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
@ -519,7 +532,7 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu
|| !jsRoot["session_id"].isString() || !jsRoot["pro_type"].isNumeric() || !jsRoot["session_id"].isString() || !jsRoot["pro_type"].isNumeric()
) )
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
@ -852,12 +865,12 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu
if (!CreateProcess(NULL, (wchar_t *)w_exe_path.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) if (!CreateProcess(NULL, (wchar_t *)w_exe_path.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{ {
EXLOGE(_T("CreateProcess() failed. Error=0x%08X.\n %s\n"), GetLastError(), w_exe_path.c_str()); EXLOGE(_T("CreateProcess() failed. Error=0x%08X.\n %s\n"), GetLastError(), w_exe_path.c_str());
root_ret["code"] = TSR_CREATE_PROCESS_ERROR; root_ret["code"] = TPE_START_CLIENT;
_create_json_ret(buf, root_ret); _create_json_ret(buf, root_ret);
return; return;
} }
root_ret["code"] = TSR_OK; root_ret["code"] = TPE_OK;
_create_json_ret(buf, root_ret); _create_json_ret(buf, root_ret);
} }
@ -909,12 +922,12 @@ void TsHttpRpc::_rpc_func_ts_check(const ex_astr& func_args, ex_astr& buf)
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
if (jsRoot.isArray()) if (jsRoot.isArray())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
int windows_size = 2; int windows_size = 2;
@ -926,7 +939,7 @@ void TsHttpRpc::_rpc_func_ts_check(const ex_astr& func_args, ex_astr& buf)
|| !jsRoot["rdp_port"].isNumeric() || !jsRoot["rdp_port"].isNumeric()
) )
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
@ -949,12 +962,12 @@ void TsHttpRpc::_rpc_func_ts_check(const ex_astr& func_args, ex_astr& buf)
if ((hptr = gethostbyname(ptr)) == NULL) if ((hptr = gethostbyname(ptr)) == NULL)
{ {
//printf("gethostbyname error for host:%s/n", ptr); //printf("gethostbyname error for host:%s/n", ptr);
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; /* 如果调用gethostbyname发生错误返回1 */ return; /* 如果调用gethostbyname发生错误返回1 */
} }
/* 将主机的规范名打出来 */ /* 将主机的规范名打出来 */
//printf("official hostname:%s/n", hptr->h_name); //printf("official hostname:%s/n", hptr->h_name);
///* 主机可能有多个别名,将所有别名分别打出来 */ // 主机可能有多个别名,将所有别名分别打出来
//for (pptr = hptr->h_aliases; *pptr != NULL; pptr++) //for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
// printf(" alias:%s/n", *pptr); // printf(" alias:%s/n", *pptr);
/* 根据地址类型,将地址打出来 */ /* 根据地址类型,将地址打出来 */
@ -978,24 +991,24 @@ void TsHttpRpc::_rpc_func_ts_check(const ex_astr& func_args, ex_astr& buf)
} }
if (!isIPAddress(server_ip.c_str())) if (!isIPAddress(server_ip.c_str()))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (TestTCPPort(server_ip, rdp_port) && TestTCPPort(server_ip, ssh_port)) if (TestTCPPort(server_ip, rdp_port) && TestTCPPort(server_ip, ssh_port))
{ {
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
ICMPheaderRet temp = { 0 }; ICMPheaderRet temp = { 0 };
int b_ok = ICMPSendTo(&temp, (char*)server_ip.c_str(), 16, 8); int b_ok = ICMPSendTo(&temp, (char*)server_ip.c_str(), 16, 8);
if (b_ok == 0) if (b_ok == 0)
{ {
_create_json_ret(buf, TSR_PING_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
else else
{ {
_create_json_ret(buf, TSR_PING_ERROR); _create_json_ret(buf, TPE_NETWORK);
} }
return; return;
@ -1008,24 +1021,24 @@ void TsHttpRpc::_rpc_func_ts_rdp_play(const ex_astr& func_args, ex_astr& buf)
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
// 判断参数是否正确 // 判断参数是否正确
if (!jsRoot["host"].isString()) if (!jsRoot["host"].isString())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (!jsRoot["port"].isInt()) if (!jsRoot["port"].isInt())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (!jsRoot["tail"].isString()) if (!jsRoot["tail"].isString())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
ex_astr a_host = jsRoot["host"].asCString(); ex_astr a_host = jsRoot["host"].asCString();
@ -1047,7 +1060,7 @@ void TsHttpRpc::_rpc_func_ts_rdp_play(const ex_astr& func_args, ex_astr& buf)
if ((hptr = gethostbyname(ptr)) == NULL) if ((hptr = gethostbyname(ptr)) == NULL)
{ {
//printf("gethostbyname error for host:%s/n", ptr); //printf("gethostbyname error for host:%s/n", ptr);
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
/* 将主机的规范名打出来 */ /* 将主机的规范名打出来 */
@ -1110,12 +1123,12 @@ void TsHttpRpc::_rpc_func_ts_rdp_play(const ex_astr& func_args, ex_astr& buf)
if (!CreateProcess(NULL, (wchar_t *)w_exe_path.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) if (!CreateProcess(NULL, (wchar_t *)w_exe_path.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{ {
EXLOGE(_T("CreateProcess() failed. Error=0x%08X.\n %s\n"), GetLastError(), w_exe_path.c_str()); EXLOGE(_T("CreateProcess() failed. Error=0x%08X.\n %s\n"), GetLastError(), w_exe_path.c_str());
root_ret["code"] = TSR_CREATE_PROCESS_ERROR; root_ret["code"] = TPE_START_CLIENT;
_create_json_ret(buf, root_ret); _create_json_ret(buf, root_ret);
return; return;
} }
root_ret["code"] = TSR_OK; root_ret["code"] = TPE_OK;
_create_json_ret(buf, root_ret); _create_json_ret(buf, root_ret);
return; return;
} }
@ -1127,13 +1140,13 @@ void TsHttpRpc::_rpc_func_get_config(const ex_astr& func_args, ex_astr& buf)
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
// 判断参数是否正确 // 判断参数是否正确
if (!jsRoot["type"].isNumeric()) if (!jsRoot["type"].isNumeric())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
int type = jsRoot["type"].asUInt(); int type = jsRoot["type"].asUInt();
@ -1268,7 +1281,7 @@ void TsHttpRpc::_rpc_func_get_config(const ex_astr& func_args, ex_astr& buf)
} }
else else
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
} }
@ -1280,12 +1293,12 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
if (jsRoot.isArray()) if (jsRoot.isArray())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
@ -1294,7 +1307,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
!jsRoot["commandline"].isString() || !jsRoot["commandline"].isString() ||
!jsRoot["type"].isNumeric()) !jsRoot["type"].isNumeric())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
int type = jsRoot["type"].asUInt(); int type = jsRoot["type"].asUInt();
@ -1315,7 +1328,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
clientsetmap::iterator it = g_cfgSSH.m_clientsetmap.find(w_name); clientsetmap::iterator it = g_cfgSSH.m_clientsetmap.find(w_name);
if (it == g_cfgSSH.m_clientsetmap.end()) { if (it == g_cfgSSH.m_clientsetmap.end()) {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (it->second.is_default) if (it->second.is_default)
@ -1323,7 +1336,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgSSH.set(_T("common"), _T("current_client"), w_name); g_cfgSSH.set(_T("common"), _T("current_client"), w_name);
g_cfgSSH.save(); g_cfgSSH.save();
g_cfgSSH.init(); g_cfgSSH.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
g_cfgSSH.set(w_name, _T("path"), w_path); g_cfgSSH.set(w_name, _T("path"), w_path);
@ -1332,7 +1345,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgSSH.save(); g_cfgSSH.save();
g_cfgSSH.init(); g_cfgSSH.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
@ -1340,7 +1353,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
{ {
clientsetmap::iterator it = g_cfgScp.m_clientsetmap.find(w_name); clientsetmap::iterator it = g_cfgScp.m_clientsetmap.find(w_name);
if (it == g_cfgScp.m_clientsetmap.end()) { if (it == g_cfgScp.m_clientsetmap.end()) {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (it->second.is_default) if (it->second.is_default)
@ -1348,7 +1361,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgScp.set(_T("common"), _T("current_client"), w_name); g_cfgScp.set(_T("common"), _T("current_client"), w_name);
g_cfgScp.save(); g_cfgScp.save();
g_cfgScp.init(); g_cfgScp.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
g_cfgScp.set(w_name, _T("path"), w_path); g_cfgScp.set(w_name, _T("path"), w_path);
@ -1357,14 +1370,14 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgScp.save(); g_cfgScp.save();
g_cfgScp.init(); g_cfgScp.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
else if (type == 3) else if (type == 3)
{ {
clientsetmap::iterator it = g_cfgTelnet.m_clientsetmap.find(w_name); clientsetmap::iterator it = g_cfgTelnet.m_clientsetmap.find(w_name);
if (it == g_cfgTelnet.m_clientsetmap.end()) { if (it == g_cfgTelnet.m_clientsetmap.end()) {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
if (it->second.is_default) if (it->second.is_default)
@ -1372,7 +1385,7 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgTelnet.set(_T("common"), _T("current_client"), w_name); g_cfgTelnet.set(_T("common"), _T("current_client"), w_name);
g_cfgTelnet.save(); g_cfgTelnet.save();
g_cfgTelnet.init(); g_cfgTelnet.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
g_cfgTelnet.set(w_name, _T("path"), w_path); g_cfgTelnet.set(w_name, _T("path"), w_path);
@ -1381,11 +1394,11 @@ void TsHttpRpc::_rpc_func_set_config(const ex_astr& func_args, ex_astr& buf)
g_cfgTelnet.save(); g_cfgTelnet.save();
g_cfgTelnet.init(); g_cfgTelnet.init();
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
else { else {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
} }
@ -1397,13 +1410,13 @@ void TsHttpRpc::_rpc_func_file_action(const ex_astr& func_args, ex_astr& buf) {
if (!jreader.parse(func_args.c_str(), jsRoot)) if (!jreader.parse(func_args.c_str(), jsRoot))
{ {
_create_json_ret(buf, TSR_INVALID_JSON_FORMAT); _create_json_ret(buf, TPE_JSON_FORMAT);
return; return;
} }
// 判断参数是否正确 // 判断参数是否正确
if (!jsRoot["action"].isNumeric()) if (!jsRoot["action"].isNumeric())
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
int action = jsRoot["action"].asUInt(); int action = jsRoot["action"].asUInt();
@ -1473,7 +1486,7 @@ void TsHttpRpc::_rpc_func_file_action(const ex_astr& func_args, ex_astr& buf) {
if (wsDefaultPath.length() == 0) if (wsDefaultPath.length() == 0)
{ {
_create_json_ret(buf, TSR_INVALID_JSON_PARAM); _create_json_ret(buf, TPE_PARAM);
return; return;
} }
@ -1508,13 +1521,13 @@ void TsHttpRpc::_rpc_func_file_action(const ex_astr& func_args, ex_astr& buf) {
} }
else else
{ {
_create_json_ret(buf, TSR_OK); _create_json_ret(buf, TPE_OK);
return; return;
} }
} }
else else
{ {
_create_json_ret(buf, TSR_INVALID_DATA); _create_json_ret(buf, TPE_DATA);
return; return;
} }
} }
@ -1526,7 +1539,7 @@ void TsHttpRpc::_rpc_func_get_version(const ex_astr& func_args, ex_astr& buf)
ex_astr version; ex_astr version;
ex_wstr2astr(w_version, version, EX_CODEPAGE_UTF8); ex_wstr2astr(w_version, version, EX_CODEPAGE_UTF8);
root_ret["version"] = version; root_ret["version"] = version;
root_ret["code"] = TSR_OK; root_ret["code"] = TPE_OK;
_create_json_ret(buf, root_ret); _create_json_ret(buf, root_ret);
return; return;
} }

View File

@ -13,25 +13,25 @@
#include "../../external/mongoose/mongoose.h" #include "../../external/mongoose/mongoose.h"
typedef ex_u32 ts_rv; // typedef ex_u32 ts_rv;
#define TSR_OK 0x0000 // #define TSR_OK 0x0000
#define TSR_INVALID_DATA 0x0001 // #define TSR_INVALID_DATA 0x0001
#define TSR_SEND_ERROR 0x0002 // #define TSR_SEND_ERROR 0x0002
#define TSR_NEED_MORE_DATA 0x0005 // #define TSR_NEED_MORE_DATA 0x0005
#define TSR_FAILED 0x0006 // #define TSR_FAILED 0x0006
#define TSR_PING_OK 0x0007 // #define TSR_PING_OK 0x0007
#define TSR_PING_ERROR 0x0008 // #define TSR_PING_ERROR 0x0008
//
#define TSR_INVALID_REQUEST 0x1000 // #define TSR_INVALID_REQUEST 0x1000
#define TSR_INVALID_URI 0x1001 // #define TSR_INVALID_URI 0x1001
#define TSR_INVALID_URL_ENCODE 0x1002 // #define TSR_INVALID_URL_ENCODE 0x1002
#define TSR_NO_SUCH_METHOD 0x1003 // #define TSR_NO_SUCH_METHOD 0x1003
#define TSR_INVALID_JSON_FORMAT 0x1004 // #define TSR_INVALID_JSON_FORMAT 0x1004
#define TSR_INVALID_JSON_PARAM 0x1005 // #define TSR_INVALID_JSON_PARAM 0x1005
#define TSR_CREATE_PROCESS_ERROR 0x1006 // #define TSR_CREATE_PROCESS_ERROR 0x1006
#define TSR_OPENFILE_ERROR 0x1007 // #define TSR_OPENFILE_ERROR 0x1007
#define TSR_GETTEMPPATH_ERROR 0x1007 // #define TSR_GETTEMPPATH_ERROR 0x1007
/* /*
//================================================================= //=================================================================
@ -61,6 +61,7 @@ json_param
*/ */
void http_rpc_main_loop(void); void http_rpc_main_loop(void);
void http_rpc_stop(void);
typedef std::map<ex_astr, ex_astr> content_type_map; typedef std::map<ex_astr, ex_astr> content_type_map;
@ -80,6 +81,7 @@ public:
bool init(const char* ip, int port); bool init(const char* ip, int port);
void run(void); void run(void);
void stop(void);
ex_astr get_content_type(ex_astr file_suffix) ex_astr get_content_type(ex_astr file_suffix)
{ {
@ -95,7 +97,7 @@ public:
}; };
private: private:
unsigned int _parse_request(struct http_message* req, ex_astr& func_cmd, ex_astr& func_args); int _parse_request(struct http_message* req, ex_astr& func_cmd, ex_astr& func_args);
void _process_js_request(const ex_astr& func_cmd, const ex_astr& func_args, ex_astr& buf); void _process_js_request(const ex_astr& func_cmd, const ex_astr& func_args, ex_astr& buf);
void _create_json_ret(ex_astr& buf, int errcode); void _create_json_ret(ex_astr& buf, int errcode);
void _create_json_ret(ex_astr& buf, Json::Value& jr_root); void _create_json_ret(ex_astr& buf, Json::Value& jr_root);
@ -113,6 +115,7 @@ private:
private: private:
content_type_map m_content_type_map; content_type_map m_content_type_map;
struct mg_mgr m_mg_mgr; struct mg_mgr m_mg_mgr;
bool m_stop;
}; };
#endif // __TS_HTTP_RPC_H__ #endif // __TS_HTTP_RPC_H__

View File

@ -1,6 +1,6 @@
#ifndef __TS_ASSIST_VER_H__ #ifndef __TS_ASSIST_VER_H__
#define __TS_ASSIST_VER_H__ #define __TS_ASSIST_VER_H__
#define TP_ASSIST_VER L"2.0.0.1" #define TP_ASSIST_VER L"2.1.2.1"
#endif // __TS_ASSIST_VER_H__ #endif // __TS_ASSIST_VER_H__

View File

@ -22,8 +22,8 @@ public:
bool set_log_file(const ex_wstr& log_path, const ex_wstr& log_name, ex_u32 max_filesize, ex_u8 max_count); bool set_log_file(const ex_wstr& log_path, const ex_wstr& log_name, ex_u32 max_filesize, ex_u8 max_count);
void log_a(int level, const char* fmt, va_list valist); void log_a(int level, const char* fmt, va_list valist);
void log_w(int level, const wchar_t* fmt, va_list valist); void log_w(int level, const wchar_t* fmt, va_list valist);
bool write(const char* buf); bool write_a(const char* buf);
bool write(const wchar_t* buf); bool write_w(const wchar_t* buf);
protected: protected:
bool _open_file(); bool _open_file();

View File

@ -374,8 +374,6 @@ ExIniSection* ExIniFile::GetSection(const ex_wstr& strName, bool bCreateIfNotExi
if (!bCreateIfNotExists) if (!bCreateIfNotExists)
return NULL; return NULL;
ExIniSection* pSec = new ExIniSection(strName); ExIniSection* pSec = new ExIniSection(strName);
m_secs.insert(std::make_pair(strName, pSec)); m_secs.insert(std::make_pair(strName, pSec));
return pSec; return pSec;

View File

@ -1,33 +1,27 @@
#include <ex/ex_log.h> #include <ex/ex_log.h>
#include <ex/ex_path.h> #include <ex/ex_path.h>
#include <ex/ex_thread.h> //#include <ex/ex_thread.h>
#include <vector> //#include <vector>
#include <deque> //#include <deque>
#include <algorithm> //#include <algorithm>
#ifdef EX_OS_WIN32 #ifdef EX_OS_WIN32
# include <io.h> # include <io.h>
# include <stdio.h> # include <stdio.h>
# include <direct.h> # include <direct.h>
#else #else
# include <dirent.h> //# include <dirent.h>
# include <sys/time.h> //# include <sys/time.h>
#endif #endif
#define EX_LOG_CONTENT_MAX_LEN 2048 #define EX_LOG_CONTENT_MAX_LEN 2048
//typedef std::deque<unsigned long long> log_file_deque; //typedef std::deque<unsigned long long> log_file_deque;
//ExLogger g_ex_logger; static ExLogger* g_exlog = NULL;
static ExLogger* g_exlog = NULL;//&g_ex_logger;
void EXLOG_USE_LOGGER(ExLogger* logger) void EXLOG_USE_LOGGER(ExLogger* logger)
{ {
// if (NULL == logger)
// g_exlog = &g_ex_logger;
// else
// g_exlog = logger;
g_exlog = logger; g_exlog = logger;
} }
@ -99,7 +93,7 @@ void ExLogger::log_a(int level, const char* fmt, va_list valist)
return; return;
char szTmp[4096] = { 0 }; char szTmp[4096] = { 0 };
int offset = 0; size_t offset = 0;
if (level == EX_LOG_LEVEL_ERROR) if (level == EX_LOG_LEVEL_ERROR)
{ {
@ -112,6 +106,8 @@ void ExLogger::log_a(int level, const char* fmt, va_list valist)
#ifdef EX_OS_WIN32 #ifdef EX_OS_WIN32
vsnprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist); vsnprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist);
if(to_console)
{
if (NULL != console_handle) if (NULL != console_handle)
{ {
printf_s("%s", szTmp); printf_s("%s", szTmp);
@ -119,15 +115,30 @@ void ExLogger::log_a(int level, const char* fmt, va_list valist)
} }
else else
{ {
if(debug_mode)
OutputDebugStringA(szTmp); OutputDebugStringA(szTmp);
} }
}
#else #else
vsnprintf(szTmp+offset, 4095-offset, fmt, valist); vsnprintf(szTmp+offset, 4095-offset, fmt, valist);
printf("%s", szTmp); if(to_console)
{
// On linux, the stdout only output the first time output format (char or wchar_t).
// e.g.: first time you use printf(), then after that, every wprintf() not work, and vice versa.
// so we always use wprintf() to fix that.
ex_astr tmp(szTmp);
ex_wstr _tmp;
ex_astr2wstr(tmp, _tmp);
wprintf(L"%ls", _tmp.c_str());
fflush(stdout); fflush(stdout);
// printf("%s", szTmp);
// fflush(stdout);
}
#endif #endif
write(szTmp); write_a(szTmp);
} }
void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist) void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist)
@ -136,7 +147,7 @@ void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist)
return; return;
wchar_t szTmp[4096] = { 0 }; wchar_t szTmp[4096] = { 0 };
int offset = 0; size_t offset = 0;
if (level == EX_LOG_LEVEL_ERROR) if (level == EX_LOG_LEVEL_ERROR)
{ {
@ -149,6 +160,8 @@ void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist)
#ifdef EX_OS_WIN32 #ifdef EX_OS_WIN32
_vsnwprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist); _vsnwprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist);
if(to_console)
{
if (NULL != console_handle) if (NULL != console_handle)
{ {
wprintf_s(_T("%s"), szTmp); wprintf_s(_T("%s"), szTmp);
@ -156,18 +169,23 @@ void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist)
} }
else else
{ {
if(debug_mode)
OutputDebugStringW(szTmp); OutputDebugStringW(szTmp);
} }
}
#else #else
vswprintf(szTmp+offset, 4095-offset, fmt, valist); vswprintf(szTmp+offset, 4095-offset, fmt, valist);
if(to_console)
{
wprintf(L"%ls", szTmp); wprintf(L"%ls", szTmp);
fflush(stdout); fflush(stdout);
}
#endif #endif
write(szTmp); write_w(szTmp);
} }
#define EX_PRINTF_X(fn, level) \ #define EX_PRINTF_XA(fn, level) \
void fn(const char* fmt, ...) \ void fn(const char* fmt, ...) \
{ \ { \
if(NULL == g_exlog) \ if(NULL == g_exlog) \
@ -179,7 +197,9 @@ void fn(const char* fmt, ...) \
va_start(valist, fmt); \ va_start(valist, fmt); \
g_exlog->log_a(level, fmt, valist); \ g_exlog->log_a(level, fmt, valist); \
va_end(valist); \ va_end(valist); \
} \ }
#define EX_PRINTF_XW(fn, level) \
void fn(const wchar_t* fmt, ...) \ void fn(const wchar_t* fmt, ...) \
{ \ { \
if(NULL == g_exlog) \ if(NULL == g_exlog) \
@ -193,11 +213,17 @@ void fn(const wchar_t* fmt, ...) \
va_end(valist); \ va_end(valist); \
} }
EX_PRINTF_X(ex_printf_d, EX_LOG_LEVEL_DEBUG) EX_PRINTF_XA(ex_printf_d, EX_LOG_LEVEL_DEBUG)
EX_PRINTF_X(ex_printf_v, EX_LOG_LEVEL_VERBOSE) EX_PRINTF_XA(ex_printf_v, EX_LOG_LEVEL_VERBOSE)
EX_PRINTF_X(ex_printf_i, EX_LOG_LEVEL_INFO) EX_PRINTF_XA(ex_printf_i, EX_LOG_LEVEL_INFO)
EX_PRINTF_X(ex_printf_w, EX_LOG_LEVEL_WARN) EX_PRINTF_XA(ex_printf_w, EX_LOG_LEVEL_WARN)
EX_PRINTF_X(ex_printf_e, EX_LOG_LEVEL_ERROR) EX_PRINTF_XA(ex_printf_e, EX_LOG_LEVEL_ERROR)
EX_PRINTF_XW(ex_printf_d, EX_LOG_LEVEL_DEBUG)
EX_PRINTF_XW(ex_printf_v, EX_LOG_LEVEL_VERBOSE)
EX_PRINTF_XW(ex_printf_i, EX_LOG_LEVEL_INFO)
EX_PRINTF_XW(ex_printf_w, EX_LOG_LEVEL_WARN)
EX_PRINTF_XW(ex_printf_e, EX_LOG_LEVEL_ERROR)
#ifdef EX_OS_WIN32 #ifdef EX_OS_WIN32
@ -268,7 +294,7 @@ void ex_printf_bin(const ex_u8* bin_data, size_t bin_size, const char* fmt, ...)
unsigned int i = 0; unsigned int i = 0;
char szTmp[128] = { 0 }; char szTmp[128] = { 0 };
int _offset = 0; size_t _offset = 0;
while (offset < bin_size) while (offset < bin_size)
{ {
@ -529,7 +555,7 @@ bool ExLogFile::_backup_file()
} }
#endif // if 0 #endif // if 0
bool ExLogger::write(const char* buf) bool ExLogger::write_a(const char* buf)
{ {
if (NULL == m_file) if (NULL == m_file)
return false; return false;
@ -561,7 +587,7 @@ bool ExLogger::write(const char* buf)
return false; return false;
sprintf(szTime, "[%04d-%02d-%02d %02d:%02d:%02d] ", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); sprintf(szTime, "[%04d-%02d-%02d %02d:%02d:%02d] ", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
int lenTime = strlen(szTime); size_t lenTime = strlen(szTime);
fwrite(szTime, lenTime, 1, m_file); fwrite(szTime, lenTime, 1, m_file);
m_filesize += lenTime; m_filesize += lenTime;
fwrite(buf, len, 1, m_file); fwrite(buf, len, 1, m_file);
@ -573,11 +599,11 @@ bool ExLogger::write(const char* buf)
return _rotate_file(); return _rotate_file();
} }
bool ExLogger::write(const wchar_t* buf) bool ExLogger::write_w(const wchar_t* buf)
{ {
ex_astr _buf; ex_astr _buf;
ex_wstr2astr(buf, _buf, EX_CODEPAGE_UTF8); ex_wstr2astr(buf, _buf, EX_CODEPAGE_UTF8);
return write(_buf.c_str()); return write_a(_buf.c_str());
} }

View File

@ -3,8 +3,6 @@
#include <ex/ex_str.h> #include <ex/ex_str.h>
#include <ex/ex_log.h> #include <ex/ex_log.h>
// #include <vld.h>
EX_BOOL ex_initialize(const char* lc_ctype) EX_BOOL ex_initialize(const char* lc_ctype)
{ {
#ifdef EX_OS_UNIX #ifdef EX_OS_UNIX

View File

@ -0,0 +1,56 @@
#ifndef __TELEPORT_CONST_H__
#define __TELEPORT_CONST_H__
// 本文件设定teleport各个模块之间通讯时的错误值JSON数据包括
// - WEB界面与助手
// - WEB界面与WEB后台
// - WEB后台与CORE核心服务
// 成功
#define TPE_OK 0
//-------------------------------------------------------
// 通用错误值
//-------------------------------------------------------
#define TPE_NEED_MORE_DATA 1 // 需要更多数据(不一定是错误)
// 100~299是通用错误值
#define TPE_FAILED 100 // 内部错误
#define TPE_NETWORK 101 // 网络错误
// HTTP请求相关错误
#define TPE_HTTP_METHOD 120 // 无效的请求方法不是GET/POST等或者错误的请求方法例如需要POST却使用GET方式请求
#define TPE_HTTP_URL_ENCODE 121 // URL编码错误无法解码
//#define TPE_HTTP_URI 122 // 无效的URI
#define TPE_UNKNOWN_CMD 124 // 未知的命令
#define TPE_JSON_FORMAT 125 // 错误的JSON格式需要JSON格式数据但是却无法按JSON格式解码
#define TPE_PARAM 126 // 参数错误
#define TPE_DATA 127 // 数据错误
// #define TPE_OPENFILE_ERROR 0x1007 // 无法打开文件
// #define TPE_GETTEMPPATH_ERROR 0x1007
//-------------------------------------------------------
// 助手程序专用错误值
//-------------------------------------------------------
#define TPE_NO_ASSIST 100000 // 未能检测到助手程序
#define TPE_OLD_ASSIST 100001 // 助手程序版本太低
#define TPE_START_CLIENT 100002 // 无法启动客户端程序(无法创建进程)
//-------------------------------------------------------
// 核心服务专用错误值
//-------------------------------------------------------
#define TPE_NO_CORE_SERVER 200000 // 未能检测到核心服务
#endif // __TELEPORT_CONST_H__

View File

@ -3,6 +3,19 @@
# for windows # for windows
#============================================ #============================================
# Need wget to download necessary dependency files.
wget = C:\Program Files (x86)\wget\wget.exe
# Need 7z to unzip downloaded files.
7z = C:\Program Files (x86)\7zip\7z.exe
# need perl to build openssl on Windows, if not set, default to get it from register.
# suggest install ActivePerl.
#perl = C:\Perl\bin\perl.exe
# need nasm to build openssl on Windows, if not set, default to locate it from register.
#nasm = C:\Users\username\AppData\Local\NASM\nasm.exe
# if not set nsis path, default to get it by register. # if not set nsis path, default to get it by register.
#nsis = C:\Program Files (x86)\NSIS\Unicode\makensis.exe #nsis = C:\Program Files (x86)\NSIS\Unicode\makensis.exe
@ -19,9 +32,12 @@ cmake = /opt/cmake/bin/cmake
[external_ver] [external_ver]
openssl = 1.0.2h openssl = 1.0.2h,1000208f
libuv = 1.9.1 libuv = 1.9.1
libssh = 0.7.4 libssh = 0.7.4
mbedtls = 2.3.0 mbedtls = 2.3.0
sqlite = 3160200 sqlite = 3170000
libssh = 0.7.4
jsoncpp = 0.10.6
mongoose = 6.6

View File

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

View File

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

View File

@ -1,21 +0,0 @@
#!/bin/bash
APP_PATH=/usr/local/eom/teleport
result=$( ps ax | grep "${APP_PATH}/bin/tp_core start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then
# echo "teleport core server is running."
echo -e "teleport core server is \e[32mrunning\033[0m."
else
# echo "teleport core server is not running."
echo -e "teleport core server is \e[31mnot running\033[0m."
fi
result=$( ps ax | grep "${APP_PATH}/bin/tp_web start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then
# echo "teleport web is running."
echo -e "teleport web server is \e[32mrunning\033[0m."
else
# echo "teleport web is not running."
echo -e "teleport web server is \e[31mnot running\033[0m."
fi

View File

@ -1,44 +0,0 @@
#!/bin/bash
####################################################################
# EOM Teleport Server Uninstall Script
####################################################################
if [ `id -u` -ne 0 ];then
echo ""
echo -e "\e[31mPlease run the uninstaller with ROOT.\033[0m"
echo ""
exit 1
fi
echo ""
echo "Uninstalling EOM Teleport Server..."
if [ -f /etc/init.d/eom_ts ]; then
service eom_ts stop
rm -rf /etc/init.d/eom_ts
fi
rm -rf /etc/rc2.d/S50eom_ts
rm -rf /etc/rc3.d/S50eom_ts
rm -rf /etc/rc4.d/S50eom_ts
rm -rf /etc/rc5.d/S50eom_ts
if [ -f /etc/init.d/teleport ]; then
service teleport stop
rm -rf /etc/init.d/teleport
fi
rm -rf /etc/rc2.d/S50teleport
rm -rf /etc/rc3.d/S50teleport
rm -rf /etc/rc4.d/S50teleport
rm -rf /etc/rc5.d/S50teleport
if [ -d /usr/local/eom/teleport ]; then
rm -rf /usr/local/eom/teleport
fi
echo ""
echo -e "\e[32mUninstallation done.\033[0m"
echo ""

View File

@ -11,12 +11,10 @@
### END INIT INFO ### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON_PATH=/usr/local/eom/teleport DAEMON_PATH={daemon_path}
NAME=teleport NAME=teleport
DESC=teleport DESC=teleport
# test -f "$DAEMON_PATH/teleport.sh" || exit 0
test -f "$DAEMON_PATH/start.sh" || exit 0 test -f "$DAEMON_PATH/start.sh" || exit 0
test -f "$DAEMON_PATH/stop.sh" || exit 0 test -f "$DAEMON_PATH/stop.sh" || exit 0
test -f "$DAEMON_PATH/status.sh" || exit 0 test -f "$DAEMON_PATH/status.sh" || exit 0
@ -51,7 +49,7 @@ case "$1" in
$DAEMON_PATH/status.sh $SRV $DAEMON_PATH/status.sh $SRV
;; ;;
*) *)
echo "Usage: $NAME {start|stop|restart|status}" >&2 echo "Usage: $NAME {{start|stop|restart|status}}" >&2
exit 1 exit 1
;; ;;
esac esac

26
dist/linux/server/script/start.sh → dist/server/daemon/start.sh.in vendored Executable file → Normal file
View File

@ -5,43 +5,47 @@ if [ x$1 != x ]; then
SRV=$1 SRV=$1
fi fi
APP_PATH=/usr/local/eom/teleport DAEMON_PATH={daemon_path}
shell_ret=0
cd "${APP_PATH}" cd "$DAEMON_PATH"
# start teleport core server...
if [ $SRV == all ] || [ $SRV == core ] ; then if [ $SRV == all ] || [ $SRV == core ] ; then
echo -n "starting teleport core server ... " echo -n "starting teleport core server ... "
result=$( ps ax | grep "${APP_PATH}/bin/tp_core start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_core start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then if [ $result -gt 0 ]; then
echo "already running, skip." echo "already running, skip."
else else
${APP_PATH}/bin/tp_core start $DAEMON_PATH/bin/tp_core start
result=$( ps ax | grep "${APP_PATH}/bin/tp_core start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_core start" | grep -v grep | wc -l )
if [ ! $result -gt 0 ]; then if [ ! $result -gt 0 ]; then
echo -e "\e[31m[FAILED]\033[0m" echo -e "\e[31m[FAILED]\033[0m"
shell_ret=1
else else
echo -e "\e[32m[done]\033[0m" echo -e "\e[32m[done]\033[0m"
fi fi
fi fi
fi fi
# start web
if [ $SRV == all ] || [ $SRV == web ] ; then if [ $SRV == all ] || [ $SRV == web ] ; then
echo -n "starting teleport web ... " echo -n "starting teleport web ... "
result=$( ps ax | grep "${APP_PATH}/bin/tp_web start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_web start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then if [ $result -gt 0 ]; then
echo "already running, skip." echo "already running, skip."
else else
${APP_PATH}/bin/tp_web start $DAEMON_PATH/bin/tp_web start
result=$( ps ax | grep "${APP_PATH}/bin/tp_web start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_web start" | grep -v grep | wc -l )
if [ ! $result -gt 0 ]; then if [ ! $result -gt 0 ]; then
echo -e "\e[31m[FAILED]\033[0m" echo -e "\e[31m[FAILED]\033[0m"
shell_ret=1
else else
echo -e "\e[32m[done]\033[0m" echo -e "\e[32m[done]\033[0m"
fi fi
fi fi
fi fi
exit $shell_ret

23
dist/server/daemon/status.sh.in vendored Normal file
View File

@ -0,0 +1,23 @@
#!/bin/bash
DAEMON_PATH={daemon_path}
shell_ret=0
result=$( ps ax | grep "$DAEMON_PATH/bin/tp_core start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then
echo -e "teleport core server is \e[32mrunning\033[0m."
else
echo -e "teleport core server is \e[31mnot running\033[0m."
shell_ret=1
fi
result=$( ps ax | grep "$DAEMON_PATH/bin/tp_web start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then
echo -e "teleport web server is \e[32mrunning\033[0m."
else
echo -e "teleport web server is \e[31mnot running\033[0m."
shell_ret=1
fi
exit $shell_ret

15
dist/linux/server/script/stop.sh → dist/server/daemon/stop.sh.in vendored Executable file → Normal file
View File

@ -5,28 +5,29 @@ if [ x$1 != x ]; then
SRV=$1 SRV=$1
fi fi
APP_PATH=/usr/local/eom/teleport DAEMON_PATH={daemon_path}
# start teleport core server...
if [ $SRV == all ] || [ $SRV == core ] ; then if [ $SRV == all ] || [ $SRV == core ] ; then
echo -n "stoping teleport core server ... " echo -n "stoping teleport core server ... "
result=$( ps ax | grep "${APP_PATH}/bin/tp_core start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_core start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then if [ $result -gt 0 ]; then
ps ax | grep "${APP_PATH}/bin/tp_core start" | grep -v grep | kill `awk '{print $1}'` ps ax | grep "$DAEMON_PATH/bin/tp_core start" | grep -v grep | kill `awk '{{print $1}}'`
echo 'done.' echo 'done.'
else else
echo "not running, skip." echo "not running, skip."
fi fi
fi fi
# stop web
if [ $SRV == all ] || [ $SRV == web ] ; then if [ $SRV == all ] || [ $SRV == web ] ; then
echo -n "stoping teleport web ... " echo -n "stoping teleport web ... "
result=$( ps ax | grep "${APP_PATH}/bin/tp_web start" | grep -v grep | wc -l ) result=$( ps ax | grep "$DAEMON_PATH/bin/tp_web start" | grep -v grep | wc -l )
if [ $result -gt 0 ]; then if [ $result -gt 0 ]; then
ps ax | grep "${APP_PATH}/bin/tp_web start" | grep -v grep | kill `awk '{print $1}'` ps ax | grep "$DAEMON_PATH/bin/tp_web start" | grep -v grep | kill `awk '{{print $1}}'`
echo 'done.' echo 'done.'
else else
echo "not running, skip." echo "not running, skip."
fi fi
fi fi
exit 0

2
dist/server/script/core/__init__.py vendored Normal file
View File

@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-

476
dist/server/script/core/colorconsole.py vendored Normal file
View File

@ -0,0 +1,476 @@
# -*- coding: utf-8 -*-
import os
import sys
import platform
import traceback
__all__ = ['o', 'v', 'i', 'w', 'e', 'f']
# ======================================
# 颜色
# ======================================
CR_RESTORE = 0 # 恢复正常 - 浅灰色
# BOLD = "[1m" # 高亮显示
# UNDERSCORE = "[4m" # 下划线
# REVERSE = "[7m" # 反白显示
CR_BLACK = 1 # 黑色
CR_LIGHT_GRAY = 2 # 浅灰色 - 普通文字
CR_GRAY = 3 # 深灰色 - 捕获别的命令的输出
CR_WHITE = 4 # 白色
CR_RED = 5 # 红色
CR_GREEN = 6 # 绿色
CR_YELLOW = 7 # 黄色 - Windows平台称之为棕色(Brown)
CR_BLUE = 8 # 蓝色
CR_MAGENTA = 9 # 紫红
CR_CYAN = 10 # 青色
CR_LIGHT_RED = 11 # 亮红色 - 失败
CR_LIGHT_GREEN = 12 # 亮绿色 - 成功
CR_LIGHT_YELLOW = 13 # 亮黄色 - 重要
CR_LIGHT_BLUE = 14 # 亮蓝色 - 其实在黑色背景上还是比较深
CR_LIGHT_MAGENTA = 15 # 亮紫色 - 警告
CR_LIGHT_CYAN = 16 # 亮青色
CR_VERBOSE = CR_LIGHT_GRAY
CR_NORMAL = CR_WHITE
CR_INFO = CR_GREEN
CR_WARN = CR_LIGHT_YELLOW
CR_ERROR = CR_LIGHT_RED
COLORS = {
# 常量定义 Linux色彩 WinConsole色彩
CR_RESTORE: ('[0m', 7), # 7 = 浅灰色 - 普通文字
CR_BLACK: ('[0;30m', 0), # 0 = 黑色
CR_RED: ("[0;31m", 4), # 红色
CR_GREEN: ("[0;32m", 2), # 绿色
CR_YELLOW: ("[0;33m", 6), # 黄色 - Windows平台称之为棕色(Brown)
CR_BLUE: ("[0;34m", 1), # 蓝色
CR_MAGENTA: ("[0;35m", 5), # 紫红
CR_CYAN: ("[0;36m", 3), # 青色
CR_LIGHT_GRAY: ('[0;37m', 7), # 浅灰色 - 普通文字
CR_GRAY: ("[1;30m", 8), # 深灰色 - 捕获别的命令的输出
CR_LIGHT_RED: ("[1;31m", 12), # 亮红色 - 失败
CR_LIGHT_GREEN: ("[1;32m", 10), # 亮绿色 - 成功
CR_LIGHT_YELLOW: ("[1;33m", 14), # 亮黄色 - 重要
CR_LIGHT_BLUE: ("[1;34m", 9), # 亮蓝色 - 其实在黑色背景上还是比较深
CR_LIGHT_MAGENTA: ("[1;35m", 13), # 亮紫色 - 警告
CR_LIGHT_CYAN: ("[1;36m", 11), # 亮青色
CR_WHITE: ("[1;37m", 15) # 白色
}
class ColorConsole:
"""
:type _win_color : Win32ColorConsole
"""
def __init__(self):
# self._log_console = self._console_default # 输出到控制台的方式为None时表示不输出到控制台
# self._console_set_color = self._console_set_color_default
self._sep = ' '
self._end = '\n'
self._win_color = None
self.o = self._func_output
self.v = self._func_verbose
self.n = self._func_normal
self.i = self._func_info
self.w = self._func_warn
self.e = self._func_error
self.f = self._func_fail
if sys.stdout is None:
self.o = self._func_pass
self.v = self._func_pass
self.n = self._func_pass
self.i = self._func_pass
self.w = self._func_pass
self.e = self._func_pass
self.f = self._func_pass
# self._log_console = self._func_pass
# self._console_set_color = self._console_set_color_default
else:
# python2.7 on Ubuntu, sys.platform is 'linux2', so we use platform.system() instead.
_platform = platform.system().lower()
if _platform == 'linux' or _platform == 'darwin':
self._console_set_color = self._console_set_color_linux
self._console_restore_color = self._console_restore_color_linux
elif _platform == 'windows':
if 'TERM' in os.environ and os.environ['TERM'] in ['xterm']:
self._console_set_color = self._console_set_color_linux
self._console_restore_color = self._console_restore_color_linux
else:
self._win_color = Win32ColorConsole()
if self._win_color.available():
self._console_set_color = self._console_set_color_win
self._console_restore_color = self._console_restore_color_win
else:
self._console_set_color = self._func_pass
self._console_restore_color = self._func_pass
def set_default(self, *args, **kwargs):
if 'sep' in kwargs:
self._sep = kwargs['sep']
if 'end' in kwargs:
self._end = kwargs['end']
def _func_pass(self, *args, **kwargs):
# do nothing.
pass
def _func_output(self, *args, **kwargs):
sep = kwargs['sep'] if 'sep' in kwargs else self._sep
end = kwargs['end'] if 'end' in kwargs else self._end
first = True
for x in args:
if not first:
sys.stdout.writelines(sep)
if isinstance(x, tuple):
cl = x[0]
z = x[1:]
self._console_set_color(cl)
self._console_output(*z, sep='', end='')
sys.stdout.flush()
elif isinstance(x, str):
self._console_output(x, sep='', end='')
sys.stdout.flush()
else:
raise RuntimeError('Invalid param.')
sys.stdout.writelines(end)
self._console_restore_color()
sys.stdout.flush()
def _func_verbose(self, *args, **kwargs):
self._console_set_color(CR_VERBOSE)
self._console_output(*args, **kwargs)
self._console_restore_color()
sys.stdout.flush()
# 普通的日志数据
def _func_normal(self, *args, **kwargs):
self._console_set_color(CR_NORMAL)
self._console_output(*args, **kwargs)
self._console_restore_color()
sys.stdout.flush()
# 重要信息
def _func_info(self, *args, **kwargs):
self._console_set_color(CR_INFO)
self._console_output(*args, **kwargs)
self._console_restore_color()
sys.stdout.flush()
# 警告
def _func_warn(self, *args, **kwargs):
self._console_set_color(CR_WARN)
self._console_output(*args, **kwargs)
self._console_restore_color()
sys.stdout.flush()
def _func_error(self, *args, **kwargs):
self._console_set_color(CR_ERROR)
self._console_output(*args, **kwargs)
self._console_restore_color()
sys.stdout.flush()
def _func_fail(self, *args, **kwargs):
self._console_set_color(CR_ERROR)
self._console_output('[FAIL] ', end='')
self._console_output(*args, **kwargs)
_type, _value, _tb = sys.exc_info()
if _type is not None:
x = traceback.format_exception_only(_type, _value)
self._console_output('[EXCEPTION] ', end='')
self._console_output(x[0], end='')
x = traceback.extract_tb(_tb)
c = len(x)
self._console_set_color(CR_RED)
for i in range(0, c):
self._console_output(os.path.abspath(x[i][0]), '(', x[i][1], '): ', x[i][3], sep='')
else:
s = traceback.extract_stack()
c = len(s)
self._console_set_color(CR_RED)
for i in range(2, c):
self._console_output(' ', os.path.abspath(s[c - i - 1][0]), '(', s[c - i - 1][1], '): ', s[c - i - 1][3], sep='')
self._console_restore_color()
sys.stdout.flush()
# def _do_log(self, msg, color=None):
# self._log_console(msg, color)
#
# def _console_default(self, msg, color=None):
# if msg is None:
# return
#
# sys.stdout.writelines(msg)
# sys.stdout.flush()
#
# def _console_win(self, msg, color=None):
# if msg is None:
# return
#
# # 这里的问题很复杂,日常使用没有问题,但是当在工作机上使用时,部分内容是捕获另一个脚本执行的结果再输出
# # 如果结果中有中文,这里就会显示乱码。如果尝试编码转换,会抛出异常。目前暂时采用显示乱码的方式了。
#
# # if CONSOLE_WIN_CMD == self.console_type:
# # try:
# # _msg = unicode(msg, 'utf-8')
# # except:
# # _msg = msg
# # else:
# # _msg = msg
# # _msg = None
# # if isinstance(msg, unicode):
# # _msg = msg
# # else:
# # # _msg = unicode(msg, 'utf-8')
# # try:
# # _msg = unicode(msg, 'utf-8')
# # except:
# # _msg = unicode(msg, 'gb2312')
# # # _msg = msg
# #
# # # if CONSOLE_WIN_CMD == self.console_type:
# # # sys.stdout.writelines(msg.encode('gb2312'))
# # # else:
# # # sys.stdout.writelines(msg.encode('utf-8'))
# #
# #
# # # try:
# # # _msg = unicode(msg, 'utf-8')
# # # except:
# # _msg = msg
#
# if color is None:
# sys.stdout.writelines(msg)
# else:
# self._win_color.set_color(COLORS[color][1])
# sys.stdout.writelines(msg)
# sys.stdout.flush()
# self._win_color.set_color(COLORS[CR_RESTORE][1])
#
# sys.stdout.flush()
#
# def _console_linux(self, msg, cr=None):
# if msg is None:
# return
#
# if cr is None:
# sys.stdout.writelines(msg)
# else:
# sys.stdout.writelines('\x1B')
# sys.stdout.writelines(COLORS[cr][0])
# sys.stdout.writelines(msg)
# sys.stdout.writelines('\x1B[0m')
#
# sys.stdout.flush()
# def _console_set_color_default(self, cr=None):
# pass
def _console_set_color_win(self, cr=None):
if cr is None:
return
self._win_color.set_color(COLORS[cr][1])
sys.stdout.flush()
def _console_set_color_linux(self, cr=None):
if cr is None:
return
sys.stdout.writelines('\x1B')
sys.stdout.writelines(COLORS[cr][0])
sys.stdout.flush()
def _console_restore_color_win(self):
self._win_color.set_color(COLORS[CR_RESTORE][1])
sys.stdout.flush()
def _console_restore_color_linux(self):
sys.stdout.writelines('\x1B[0m')
sys.stdout.flush()
def _console_output(self, *args, **kwargs):
sep = kwargs['sep'] if 'sep' in kwargs else self._sep
end = kwargs['end'] if 'end' in kwargs else self._end
first = True
for x in args:
if not first:
sys.stdout.writelines(sep)
first = False
if isinstance(x, str):
sys.stdout.writelines(x)
continue
else:
sys.stdout.writelines(x.__str__())
sys.stdout.writelines(end)
sys.stdout.flush()
# def _test(self):
# self.log('###################', CR_RESTORE)
# self.log(' CR_RESTORE\n')
# self.log('###################', CR_BLACK)
# self.log(' CR_BLACK\n')
# self.log('###################', CR_LIGHT_GRAY)
# self.log(' CR_LIGHT_GRAY\n')
# self.log('###################', CR_GRAY)
# self.log(' CR_GRAY\n')
# self.log('###################', CR_WHITE)
# self.log(' CR_WHITE\n')
# self.log('###################', CR_RED)
# self.log(' CR_RED\n')
# self.log('###################', CR_GREEN)
# self.log(' CR_GREEN\n')
# self.log('###################', CR_YELLOW)
# self.log(' CR_YELLOW\n')
# self.log('###################', CR_BLUE)
# self.log(' CR_BLUE\n')
# self.log('###################', CR_MAGENTA)
# self.log(' CR_MAGENTA\n')
# self.log('###################', CR_CYAN)
# self.log(' CR_CYAN\n')
# self.log('###################', CR_LIGHT_RED)
# self.log(' CR_LIGHT_RED\n')
# self.log('###################', CR_LIGHT_GREEN)
# self.log(' CR_LIGHT_GREEN\n')
# self.log('###################', CR_LIGHT_YELLOW)
# self.log(' CR_LIGHT_YELLOW\n')
# self.log('###################', CR_LIGHT_BLUE)
# self.log(' CR_LIGHT_BLUE\n')
# self.log('###################', CR_LIGHT_MAGENTA)
# self.log(' CR_LIGHT_MAGENTA\n')
# self.log('###################', CR_LIGHT_CYAN)
# self.log(' CR_LIGHT_CYAN\n')
# # data = b'This is a test string and you can see binary format data here.'
# # self.bin('Binary Data:\n', data)
# # data = b''
# # self.bin('Empty binary\n', data)
# # self.bin('This is string\n\n', 'data')
#
# # self.d('This is DEBUG message.\n')
# self.v('This is VERBOSE message.\n')
# self.i('This is INFORMATION message.\n')
# self.w('This is WARNING message.\n')
# self.e('This is ERROR message.\n')
# self.f('This is FAIL message.\n')
#
# self.v('test auto\nsplit lines.\nYou should see\nmulti-lines.\n')
class Win32ColorConsole:
def __init__(self):
from ctypes import WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HANDLE, DWORD, WORD
self.__original_stderr = sys.stderr
self.__stdout = None
self.__SetConsoleTextAttribute = None
# Work around <http://bugs.python.org/issue6058>.
# codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
# Make Unicode console output work independently of the current code page.
# This also fixes <http://bugs.python.org/issue1602>.
# Credit to Michael Kaplan <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx>
# and TZOmegaTZIOY
# <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
try:
# <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
# HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
# returns INVALID_HANDLE_VALUE, NULL, or a valid handle
#
# <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
# DWORD WINAPI GetFileType(DWORD hFile);
#
# <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
# BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);
STD_OUTPUT_HANDLE = DWORD(-11)
INVALID_HANDLE_VALUE = DWORD(-1).value
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
self.__SetConsoleTextAttribute = WINFUNCTYPE(BOOL, HANDLE, WORD)(("SetConsoleTextAttribute", windll.kernel32))
self.__stdout = GetStdHandle(STD_OUTPUT_HANDLE)
if self.__stdout == INVALID_HANDLE_VALUE:
self.__stdout = None
except Exception as e:
self.__stdout = None
self._complain("exception %r while fixing up sys.stdout and sys.stderr\n" % (str(e),))
# If any exception occurs in this code, we'll probably try to print it on stderr,
# which makes for frustrating debugging if stderr is directed to our wrapper.
# So be paranoid about catching errors and reporting them to original_stderr,
# so that we can at least see them.
@staticmethod
def _complain(message):
# print >> self.__original_stderr, message if isinstance(message, str) else repr(message)
sys.stderr.writelines(message)
def available(self):
if self.__stdout is None or self.__SetConsoleTextAttribute is None:
return False
else:
return True
def set_color(self, color):
# if not self.available():
# return
self.__SetConsoleTextAttribute(self.__stdout, color)
_cc = ColorConsole()
del ColorConsole
def set_default(*args, **kwargs):
_cc.set_default(*args, **kwargs)
def o(*args, **kwargs):
_cc.o(*args, **kwargs)
def v(*args, **kwargs):
_cc.v(*args, **kwargs)
def n(*args, **kwargs):
_cc.n(*args, **kwargs)
def i(*args, **kwargs):
_cc.i(*args, **kwargs)
def w(*args, **kwargs):
_cc.w(*args, **kwargs)
def e(*args, **kwargs):
_cc.e(*args, **kwargs)
def f(*args, **kwargs):
_cc.f(*args, **kwargs)

214
dist/server/script/core/env.py vendored Normal file
View File

@ -0,0 +1,214 @@
# -*- coding: utf8 -*-
import os
import platform
import sys
import configparser
from . import colorconsole as cc
if platform.system().lower() == 'windows':
try:
import winreg
except ImportError:
cc.e('Can not load module `winreg`, so I can not locate toolchain for you.')
class Env(object):
BITS_32 = 32
BITS_64 = 64
def __init__(self):
_this_path = os.path.abspath(os.path.dirname(__file__))
self.root_path = os.path.abspath(os.path.join(_this_path, '..', '..'))
self.src_path = os.path.join(self.root_path, 'data')
self.bits = self.BITS_32
self.bits_str = 'x86'
_bits = platform.architecture()[0]
if _bits == '64bit':
self.bits = self.BITS_64
self.bits_str = 'x64'
self.is_win = False
self.is_win_x64 = False
self.is_linux = False
self.is_macos = False
_os = platform.system().lower()
self.plat = ''
if _os == 'windows':
self.is_win = True
self.plat = 'windows'
self.is_win_x64 = 'PROGRAMFILES(X86)' in os.environ
elif _os == 'linux':
self.is_linux = True
self.plat = 'linux'
elif _os == 'darwin':
self.is_macos = True
self.plat = 'macos'
def init(self, warn_miss_tool=False):
# if not self._load_config(warn_miss_tool):
# return False
return True
def _load_config(self, warn_miss_tool):
_cfg_file = os.path.join(self.root_path, 'config.ini')
if not os.path.exists(_cfg_file):
cc.e('can not load configuration.\n\nplease copy `config.ini.in` into `config.ini` and modify it to fit your condition and try again.')
return False
_cfg = configparser.ConfigParser()
_cfg.read(_cfg_file)
if 'external_ver' not in _cfg.sections() or 'toolchain' not in _cfg.sections():
cc.e('invalid configuration file: need `external_ver` and `toolchain` section.')
return False
_tmp = _cfg['external_ver']
try:
_v_openssl = _tmp['openssl'].split(',')
self.ver_openssl = _v_openssl[0].strip()
self.ver_openssl_number = _v_openssl[1].strip()
self.ver_libuv = _tmp['libuv']
self.ver_mbedtls = _tmp['mbedtls']
self.ver_sqlite = _tmp['sqlite']
self.ver_libssh = _tmp['libssh']
self.ver_jsoncpp = _tmp['jsoncpp']
self.ver_mongoose = _tmp['mongoose']
except KeyError:
cc.e('invalid configuration file: not all necessary external version are set.')
return False
_tmp = _cfg['toolchain']
if self.is_win:
if 'wget' in _tmp:
self.wget = _tmp['wget']
else:
self.wget = None
if self.wget is None or not os.path.exists(self.wget):
if warn_miss_tool:
cc.w(' - can not find `wget.exe`, you can get it at https://eternallybored.org/misc/wget/')
if '7z' in _tmp:
self.zip7 = _tmp['7z']
else:
self.zip7 = None
if self.zip7 is None or not os.path.exists(self.zip7):
if warn_miss_tool:
cc.w(' - can not find `7z.exe`, you can get it at http://www.7-zip.org')
if 'nasm' in _tmp:
self.nasm = _tmp['nasm']
else:
self.nasm = self._get_nasm()
if self.nasm is None or not os.path.exists(self.nasm):
if warn_miss_tool:
cc.w(' - can not locate `nasm`, so I can build openssl.')
if 'perl' in _tmp:
self.perl = _tmp['perl']
else:
self.perl = self._get_perl()
if self.perl is None or not os.path.exists(self.perl):
if warn_miss_tool:
cc.w(' - can not locate `perl`, so I can build openssl.')
self.visual_studio_path = self._get_visual_studio_path()
if self.visual_studio_path is None or not os.path.exists(self.visual_studio_path):
if warn_miss_tool:
cc.w(' - can not locate Visual Studio installation, so I can build openssl.')
if 'msbuild' in _tmp:
self.msbuild = _tmp['msbuild']
else:
self.msbuild = self._get_msbuild()
if self.msbuild is None or not os.path.exists(self.msbuild):
if warn_miss_tool:
cc.w(' - can not locate `MSBuild`, so I can build nothing.')
if 'nsis' in _tmp:
self.nsis = _tmp['nsis']
else:
self.nsis = self._get_nsis()
if self.nsis is None or not os.path.exists(self.nsis):
if warn_miss_tool:
cc.w(' - can not locate `nsis`, so I can not make installer.')
elif self.is_linux:
if 'cmake' in _tmp:
self.cmake = _tmp['cmake']
else:
self.cmake = '/usr/bin/cmake'
if not os.path.exists(self.cmake):
if warn_miss_tool:
cc.e(' - can not locate `cmake`, so I can not build binary from source.')
return True
def _get_msbuild(self):
# 14.0 = VS2015
# 12.0 = VS2012
# 4.0 = VS2008
chk = ['14.0', '12.0', '4.0']
p = None
for c in chk:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\MSBuild\ToolsVersions\{}'.format(c), r'MSBuildToolsPath')
if p is not None:
break
return os.path.join(p[0], 'MSBuild.exe') if p is not None else None
def _get_visual_studio_path(self):
chk = ['14.0', '12.0', '4.0']
p = None
for c in chk:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\VisualStudio\{}'.format(c), r'ShellFolder')
if p is not None:
break
return p[0] if p is not None else None
def _get_perl(self):
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\perl', 'BinDir')
return p[0] if p is not None else None
def _get_nasm(self):
p = self._winreg_read(winreg.HKEY_CURRENT_USER, r'SOFTWARE\nasm', '')
return os.path.join(p[0], 'nasm.exe') if p is not None else None
def _get_nsis(self):
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS\Unicode', '')
if p is None:
p = self._winreg_read(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\NSIS', '')
return os.path.join(p[0], 'makensis.exe') if p is not None else None
def _winreg_read(self, base, path, key):
try:
if self.is_win_x64:
hkey = winreg.CreateKeyEx(base, path, 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
else:
hkey = winreg.CreateKeyEx(base, path, 0, winreg.KEY_READ)
value = winreg.QueryValueEx(hkey, key)
return value
except OSError:
return None
env = Env()
del Env
if __name__ == '__main__':
pass

144
dist/server/script/core/utils.py vendored Normal file
View File

@ -0,0 +1,144 @@
# -*- coding: utf8 -*-
import os
import platform
import shutil
import subprocess
import sys
import time
from . import colorconsole as cc
from .env import env
def remove(*args):
path = os.path.join(*args)
cc.v(' - remove [%s] ... ' % path, end='')
if not (os.path.exists(path) or os.path.islink(path)):
cc.v('not exists, skip.')
return
for i in range(5):
cc.v('.', end='')
try:
if os.path.isdir(path):
shutil.rmtree(path, ignore_errors=True)
time.sleep(0.5)
else:
os.unlink(path)
except:
pass
if os.path.exists(path):
time.sleep(1)
else:
break
if os.path.exists(path):
cc.e('[failed]')
raise RuntimeError('')
else:
cc.i('[done]')
def make_dirs(path, exist_ok=True):
if os.path.exists(path):
if not exist_ok:
raise RuntimeError('path already exists: %s' % path)
else:
return
for i in range(5):
try:
os.makedirs(path)
except:
time.sleep(1)
pass
if not os.path.exists(path):
time.sleep(1)
else:
break
if not os.path.exists(path):
raise RuntimeError('can not create: %s' % path)
def copy_ex(s_path, t_path, item_name=None, force=True):
if item_name is None:
s = s_path
t = t_path
else:
if isinstance(item_name, str):
f_from = item_name
f_to = item_name
elif isinstance(item_name, tuple):
f_from = item_name[0]
f_to = item_name[1]
else:
raise RuntimeError('utils.copy_ex() got invalid param.')
s = os.path.join(s_path, f_from)
t = os.path.join(t_path, f_to)
if os.path.exists(t):
if force:
remove(t)
else:
cc.w(t, 'already exists, skip copy.')
return
if os.path.isdir(s):
cc.v(' - copy [%s]\n -> [%s]' % (s, t))
shutil.copytree(s, t)
else:
if not os.path.exists(t_path):
os.makedirs(t_path)
cc.v(' - copy [%s]\n -> [%s]' % (s, t))
shutil.copy(s, t)
def ensure_file_exists(filename):
if not os.path.exists(filename):
raise RuntimeError('file not exists: {}'.format(filename))
if not os.path.isfile(filename):
raise RuntimeError('path exists but not a file: {}'.format(filename))
def sys_exec(cmd, direct_output=False, output_codec=None):
if output_codec is None:
if env.is_win:
output_codec = 'gb2312'
else:
output_codec = 'utf8'
p = None
if env.is_win:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
else:
p = subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
output = list()
f = p.stdout
while True:
line = f.readline()
if 0 == len(line):
break
line = line.rstrip('\r\n')
if direct_output:
# cc.o((cc.CR_GRAY, line), end='\n')
cc.v(line, end='\n')
output.append(line)
ret = p.wait()
return ret, output
if __name__ == '__main__':
pass

651
dist/server/script/main.py vendored Normal file
View File

@ -0,0 +1,651 @@
# -*- coding: utf-8 -*-
import os
import sys
import time
import stat
from core.env import env
import core.colorconsole as cc
import core.utils as utils
class InstallerBase:
def __init__(self):
self._all_ok = True
self._err_msg = list()
self._is_installed = False
self._install_path = ''
self._config_path = ''
self._data_path = ''
self._log_path = ''
self._installed_ver_str = 'UNKNOWN'
self._current_ver = 'UNKNOWN'
self._def_install_path = ''
ver_file = os.path.join(env.root_path, 'data', 'www', 'teleport', 'app', 'eom_ver.py')
try:
with open(ver_file, 'r') as f:
x = f.readlines()
for i in x:
s = i.split('=', 1)
if 'TS_VER' == s[0].strip():
self._current_ver = s[1].strip()[1:-1]
break
except FileNotFoundError:
raise RuntimeError('Cannot detect installer version.')
def _init(self):
_width = 79
cc.v('')
cc.v('[]{}[]'.format('=' * (_width - 4)))
_str = 'Teleport Server Installation'
cc.o((cc.CR_VERBOSE, ' | '), (cc.CR_INFO, _str), (cc.CR_VERBOSE, '{}|'.format(' ' * (_width - 5 - len(_str)))))
cc.v(' |{}|'.format('=' * (_width - 4)))
cc.o((cc.CR_VERBOSE, ' | ver: '), (cc.CR_NORMAL, self._current_ver),
(cc.CR_VERBOSE, '{}|'.format(' ' * (_width - 13 - len(self._current_ver)))))
_str = 'author: apexliu@eomsoft.net'
cc.v(' | {}{}|'.format(_str, ' ' * (_width - 5 - len(_str))))
cc.v('[]{}[]'.format('=' * (_width - 4)))
cc.v('')
cc.v('Welcome to install Teleport Server!')
cc.v('')
# cc.v(' NOTICE: if you want to use the default settings, just press `Enter`...')
cc.o((cc.CR_VERBOSE,
'NOTICE: There are a few steps need you enter information or make choice,\n if you want to use the '),
(cc.CR_WARN, 'default settings'), (cc.CR_VERBOSE, ', just press `Enter` key.'))
cc.o((cc.CR_VERBOSE, ' Otherwise you need enter the '), (cc.CR_NORMAL, 'highlight character'),
(cc.CR_VERBOSE, ' to make choice.'))
cc.v('')
cc.v('')
cc.v('Prepare installation...')
self._check_installation()
self._check_installation_ver()
cc.v('')
def run(self):
self._init()
if not self._is_installed:
self._do_install()
else:
cc.v('')
cc.v('Found teleport server have installed at `{}` already.'.format(self._install_path))
while True:
x = self._prompt_choice('What are you wanna to do?',
[('upgrade', 2, True), ('uninstall', 0, False), ('quit', 0, False)])
x = x.lower()
if 'q' == x:
break
elif 'u' == x:
self._do_uninstall()
break
elif 'g' == x:
self._do_upgrade()
break
def _do_install(self):
while True:
cc.v('')
self._install_path = self._prompt_input('Set installation path', self._def_install_path)
_use_anyway = False
if os.path.exists(self._install_path):
while True:
cc.v('')
x = self._prompt_choice(
'The target path `{}` has already exists,\ndo you want to use it anyway?'.format(
self._install_path), [('Yes', 0, True), ('No', 0, False)])
x = x.lower()
if 'y' == x:
_use_anyway = True
break
elif 'n' == x:
break
if _use_anyway:
break
else:
break
self._fix_path()
utils.make_dirs(self._install_path)
self._copy_files()
self._install_service()
self._start_service()
time.sleep(2)
self._check_service()
def _do_uninstall(self):
if not self._is_installed:
return
_del_settings = False
while True:
cc.v('')
x = self._prompt_choice('Do you want to keep your database and settings?',
[('Yes', 0, True), ('No', 0, False)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
_del_settings = True
break
if _del_settings:
while True:
cc.v('')
x = self._prompt_choice('Seriously!! Are you sure to remove all data and settings?',
[('Yes', 0, False), ('No', 0, True)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
_del_settings = False
break
self._stop_service()
time.sleep(2)
self._uninstall_service()
self._delete_files(_del_settings)
def _do_upgrade(self):
x = self._ver_compare(self._current_ver, self._installed_ver_str)
if x == 0:
while True:
cc.v('')
x = self._prompt_choice(
'The same version `{}` installed, are you sure to overwrite?'.format(self._current_ver),
[('Yes', 0, False), ('No', 0, True)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
return
elif x < 0:
while True:
cc.v('')
x = self._prompt_choice(
'A new version `{}` installed, rollback to old version `{}` may cause Teleport Server not functionally.\nAre you sure to rollback to old version?'.format(
self._installed_ver_str, self._current_ver), [('Yes', 0, False), ('No', 0, True)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
return
else:
while True:
cc.v('')
x = self._prompt_choice(
'Now upgrade from version `{}` to `{}`, \nAre you sure to upgrade to new version?'.format(
self._installed_ver_str, self._current_ver), [('Yes', 0, False), ('No', 0, True)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
return
while True:
cc.v('')
x = self._prompt_choice('Make sure you have backup your database and settings.\nAre you sure to continue?',
[('Yes', 0, False), ('No', 0, True)])
x = x.lower()
if 'y' == x:
break
elif 'n' == x:
return
self._stop_service()
time.sleep(2)
self._uninstall_service()
self._delete_files(False)
time.sleep(1)
self._copy_files()
self._install_service()
self._start_service()
time.sleep(2)
self._check_service()
@staticmethod
def _prompt_choice(message, choices):
cc.v('{} ['.format(message), end='')
def_choice = ''
for i in range(len(choices)):
if i > 0:
cc.v('/', end='')
msg = choices[i][0]
idx = choices[i][1]
if choices[i][2]:
msg = msg.upper()
def_choice = msg[idx].lower()
cc.w(msg[:idx], end='')
cc.n(msg[idx], end='')
cc.w(msg[idx + 1:], end='')
else:
msg = msg.lower()
cc.v(msg[:idx], end='')
cc.n(msg[idx], end='')
cc.v(msg[idx + 1:], end='')
cc.v(']: ', end='')
try:
x = input().strip()
if len(x) == 0:
x = def_choice
except EOFError:
x = def_choice
return x
@staticmethod
def _prompt_input(message, def_value):
cc.v('{} ['.format(message), end='')
cc.w(def_value, end='')
cc.v(']: ', end='')
try:
x = input().strip()
if len(x) == 0:
x = def_value
except EOFError:
x = def_value
return x
@staticmethod
def _ver_compare(left, right):
l = left.split('.')
r = right.split('.')
len_l = len(l)
len_r = len(r)
if len_l < len_r:
for i in range(len_r - len_l):
l.append('0')
elif len_l > len_r:
for i in range(len_l - len_r):
r.append('0')
cnt = len(l)
for i in range(cnt):
if int(l[i]) < int(r[i]):
return -1
elif int(l[i]) > int(r[i]):
return 1
return 0
def _check_installation(self):
raise RuntimeError('`check_installation` not implement.')
def _check_installation_ver(self):
if not self._is_installed:
return
# try to get the installed version from www/teleport/app/eom_ver.py
cc.v(' - check installed version ... ', end='')
ver_file = os.path.join(self._install_path, 'www', 'teleport', 'app', 'eom_ver.py')
try:
with open(ver_file) as f:
x = f.readlines()
for i in x:
s = i.split('=', 1)
if 'TS_VER' == s[0].strip():
self._installed_ver_str = s[1].strip()[1:-1]
cc.i('[{}]'.format(self._installed_ver_str))
# self._installed_ver = self._ver_str_to_ver(self._installed_ver_str)
break
except FileNotFoundError:
cc.e('[failed]')
cc.e(' the installation maybe broken')
def _fix_path(self):
raise RuntimeError('`_fix_path` not implement.')
def _copy_files(self):
raise RuntimeError('`copy_files` not implement.')
def _delete_files(self, del_settings):
raise RuntimeError('`delete_files` not implement.')
def _install_service(self):
raise RuntimeError('`install_service` not implement.')
def _start_service(self):
raise RuntimeError('`start_service` not implement.')
def _stop_service(self):
raise RuntimeError('`stop_service` not implement.')
def _uninstall_service(self):
raise RuntimeError('`uninstall_service` not implement.')
def _check_service(self):
raise RuntimeError('`check_service` not implement.')
class InstallerWin(InstallerBase):
def __init__(self):
super().__init__()
self._core_service_name = 'Teleport Core Service'
self._web_service_name = 'Teleport Web Service'
self._old_core_service_name = 'EOM Teleport Core Service'
self._old_web_service_name = 'EOM Teleport Web Service'
self._def_install_path = r'{}\teleport-server'.format(os.environ['SystemDrive'])
def _get_service_exec(self, service_name):
_err, _ = utils.sys_exec(r'sc query "{}"'.format(service_name))
if 1060 == _err:
return None
else:
_err, _o = utils.sys_exec(r'sc qc "{}"'.format(service_name))
if _err != 0:
raise RuntimeError('Can not get execute file path of service `{}`.'.format(service_name))
for i in _o:
_x = i.split(':', 1)
if 'BINARY_PATH_NAME' == _x[0].strip():
_path = _x[1].strip()
return _path
return None
def _check_installation(self):
cc.o(' - check local installation ... ', end='')
_check_service_name = [self._old_core_service_name, self._old_web_service_name, self._core_service_name,
self._web_service_name]
for _service_name in _check_service_name:
_exec_file = self._get_service_exec(_service_name)
if _exec_file is not None:
self._is_installed = True
self._install_path = os.path.abspath(os.path.join(os.path.dirname(_exec_file), '..'))
break
if self._is_installed:
cc.i('[{}]'.format(self._install_path))
self._fix_path()
else:
cc.i('[not exists]')
return
def _fix_path(self):
self._config_path = os.path.join(self._install_path, 'etc')
self._data_path = os.path.join(self._install_path, 'data')
self._log_path = os.path.join(self._install_path, 'log')
def _copy_files(self):
utils.copy_ex(os.path.join(env.src_path, 'bin'), os.path.join(self._install_path, 'bin'))
utils.copy_ex(os.path.join(env.src_path, 'www'), os.path.join(self._install_path, 'www'))
if not os.path.exists(self._config_path):
utils.copy_ex(os.path.join(env.src_path, 'tmp', 'etc'), self._config_path)
def _delete_files(self, del_settings):
utils.remove(os.path.join(self._install_path, 'bin'))
utils.remove(os.path.join(self._install_path, 'www'))
if del_settings:
utils.remove(self._data_path)
utils.remove(self._config_path)
utils.remove(self._log_path)
# only remove the installation path when it empty.
try:
os.rmdir(self._install_path)
except OSError:
pass
def _install_service(self):
cc.o(' - install teleport core service ... ', end='')
_core = os.path.join(self._install_path, 'bin', 'tp_core.exe')
_err, _ = utils.sys_exec(r'"{}" -i'.format(_core))
if _err == 0 or _err == 1:
cc.i('[done]')
else:
cc.e('[failed]')
raise RuntimeError('Install core service failed. error code: {}'.format(_err))
cc.o(' - install teleport web service ... ', end='')
_core = os.path.join(self._install_path, 'bin', 'tp_web.exe')
_err, _ = utils.sys_exec(r'"{}" -i'.format(_core))
if _err == 0 or _err == 1:
cc.i('[done]')
else:
cc.e('[failed]')
raise RuntimeError('Install web service failed. error code: {}'.format(_err))
return True
def _start_service(self):
cc.o(' - start teleport core service ... ', end='')
_err, _o = utils.sys_exec(r'sc start "{}"'.format(self._core_service_name))
# print('start core', _err, _o)
if _err == 0:
cc.i('[done]')
else:
cc.e('[failed]')
raise RuntimeError('Can not start core service.')
cc.o(' - start teleport web service ...', end='')
_err, _ = utils.sys_exec(r'sc start "{}"'.format(self._web_service_name))
if _err == 0:
cc.i('[done]')
else:
cc.e('[failed]')
raise RuntimeError('Can not start web service.')
def _stop_service(self):
_check_service_name = [self._old_core_service_name, self._old_web_service_name, self._core_service_name,
self._web_service_name]
for _service_name in _check_service_name:
cc.o(' - stop service [{}] ... '.format(_service_name), end='')
_err, _ = utils.sys_exec(r'sc stop "{}"'.format(_service_name))
if _err == 1060 or _err == 1062 or _err == 0:
cc.i('[done]')
elif _err == 1072:
cc.e('[failed]')
raise RuntimeError('can not stop service [{}]. please close Service Manager and try again.'.format(_service_name))
else:
cc.e('[failed]')
raise RuntimeError('can not stop service [{}].'.format(_service_name))
def _uninstall_service(self):
_check_service_name = [self._old_core_service_name, self._old_web_service_name, self._core_service_name,
self._web_service_name]
for _service_name in _check_service_name:
cc.o(' - remove service [{}] ... '.format(_service_name), end='')
_err, _ = utils.sys_exec(r'sc delete "{}"'.format(_service_name))
if _err == 1060 or _err == 0:
cc.i('[done]')
elif _err == 1072:
cc.e('[failed]')
raise RuntimeError('can not remove service [{}]. please close Service Manager and try again.'.format(_service_name))
else:
cc.e('[failed]')
raise RuntimeError('can not remove service [{}].'.format(_service_name))
def _check_service(self):
cc.o(' - check teleport core service status ... ', end='')
_err, _o = utils.sys_exec(r'sc query "{}"'.format(self._core_service_name))
if _err == 1060 or _err == 0:
cc.i('[running]')
else:
cc.e('[not running]')
cc.o(' - check teleport web service status ... ', end='')
_err, _o = utils.sys_exec(r'sc query "{}"'.format(self._web_service_name))
if _err == 1060 or _err == 0:
cc.i('[running]')
else:
cc.e('[not running]')
class InstallerLinux(InstallerBase):
def __init__(self):
super().__init__()
self._def_install_path = '/usr/local/teleport'
def _check_installation(self):
cc.o(' - check local installation ... ', end='')
# old version, the daemon named `eom_ts`.
# from 2.0.0.1, the daemon rename to `teleport`.
# we must check both.
if os.path.exists('/etc/init.d/eom_ts'):
self._is_installed = True
self._install_path = '/usr/local/eom/teleport'
# self._fix_path()
elif os.path.exists('/etc/init.d/teleport'):
self._is_installed = True
self._install_path = '/usr/local/teleport'
# self._fix_path()
if self._is_installed:
cc.i('[{}]'.format(self._install_path))
self._fix_path()
else:
cc.i('[not exists]')
return
def _fix_path(self):
self._config_path = '/etc/teleport'
self._data_path = os.path.join('/var/teleport')
self._log_path = os.path.join('/var/log/teleport')
def _copy_files(self):
utils.copy_ex(os.path.join(env.src_path, 'bin'), os.path.join(self._install_path, 'bin'))
utils.copy_ex(os.path.join(env.src_path, 'www'), os.path.join(self._install_path, 'www'))
if not os.path.exists(self._config_path):
utils.copy_ex(os.path.join(env.src_path, 'tmp', 'etc'), self._config_path)
def _delete_files(self, del_settings):
utils.remove(os.path.join(self._install_path, 'bin'))
utils.remove(os.path.join(self._install_path, 'www'))
utils.remove(os.path.join(self._install_path, 'start.sh'))
utils.remove(os.path.join(self._install_path, 'stop.sh'))
utils.remove(os.path.join(self._install_path, 'status.sh'))
# only remove the installation path when it empty.
try:
os.rmdir(self._install_path)
except OSError:
pass # maybe the install path not empty.
if del_settings:
utils.remove(self._data_path)
utils.remove(self._config_path)
utils.remove(self._log_path)
def _install_service(self):
daemon_files = [
['daemon.in', '/etc/init.d/teleport'],
['start.sh.in', os.path.join(self._install_path, 'start.sh')],
['stop.sh.in', os.path.join(self._install_path, 'stop.sh')],
['status.sh.in', os.path.join(self._install_path, 'status.sh')],
]
for _d in daemon_files:
cc.v('process [{}] to [{}]'.format(_d[0], _d[1]))
_orig_file = os.path.join(env.root_path, 'daemon', _d[0])
with open(_orig_file, 'r') as f:
_text = f.read()
_text = _text.format(daemon_path=self._install_path)
with open(_d[1], 'w') as f:
f.write(_text)
if not os.path.exists(_d[1]):
raise RuntimeError('can not generate daemon file [{}].'.format(_d[1]))
# owner: RWX, group: RX, others: RX
os.chmod(_d[1], stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
# create symbolic link
os.symlink('/etc/init.d/teleport', '/etc/rc2.d/S50teleport')
os.symlink('/etc/init.d/teleport', '/etc/rc3.d/S50teleport')
os.symlink('/etc/init.d/teleport', '/etc/rc4.d/S50teleport')
os.symlink('/etc/init.d/teleport', '/etc/rc5.d/S50teleport')
def _start_service(self):
cc.v('')
cc.o('start services...')
_ret, _ = utils.sys_exec('service teleport start', direct_output=True)
if _ret != 0:
raise RuntimeError('not all services started.')
def _stop_service(self):
cc.o(' - stop teleport core service ... ', end='')
# old version, the daemon named `eom_ts`.
if os.path.exists('/etc/init.d/eom_ts'):
utils.sys_exec('/etc/init.d/eom_ts stop')
# from 2.0.0.1, the daemon rename to `teleport`.
if os.path.exists('/etc/init.d/teleport'):
utils.sys_exec('/etc/init.d/teleport stop')
cc.i('[done]')
def _uninstall_service(self):
# old version, the daemon named `eom_ts`.
utils.remove('/etc/init.d/eom_ts')
utils.remove('/etc/rc2.d/S50eom_ts')
utils.remove('/etc/rc3.d/S50eom_ts')
utils.remove('/etc/rc4.d/S50eom_ts')
utils.remove('/etc/rc5.d/S50eom_ts')
# from 2.0.0.1, the daemon rename to `teleport`.
utils.remove('/etc/init.d/teleport')
utils.remove('/etc/rc2.d/S50teleport')
utils.remove('/etc/rc3.d/S50teleport')
utils.remove('/etc/rc4.d/S50teleport')
utils.remove('/etc/rc5.d/S50teleport')
def _check_service(self):
cc.v('')
cc.o('check services status...')
utils.sys_exec('service teleport status', direct_output=True)
def _main():
cc.set_default(sep='', end='\n')
env.init()
if env.is_win:
_installer = InstallerWin()
elif env.is_linux:
_installer = InstallerLinux()
else:
raise RuntimeError('Sorry, teleport server does not support this platform yet.')
_installer.run()
def main():
try:
_main()
cc.i('\n--==[ ALL DONE ]==--\n')
return 0
except KeyboardInterrupt:
return 1
except RuntimeError as err:
cc.v('')
cc.v('')
cc.e(err.__str__())
cc.v('')
return 2
except:
cc.f('got exception.')
return 3
if __name__ == '__main__':
main()

28
dist/server/setup.bat vendored Normal file
View File

@ -0,0 +1,28 @@
@echo off
pushd %~dp0
set TPINST_ROOT=%cd%
popd
:: Check admin permission by create a temp file in system32 folder.
set TempFile=%SystemRoot%\System32\6A5D77DDFCFB40CEB26A8444EEC5757E%Random%.tmp
(echo "check" >%TempFile%) 1>nul 2>nul
if not exist %TempFile% goto NOT_ADMIN
del %TempFile% 1>nul 2>nul
"%TPINST_ROOT%\data\bin\tp_web.exe" --py "%TPINST_ROOT%\script\main.py"
goto END
:NOT_ADMIN
echo.
echo Teleport Server Setup requires administrator rights!
echo.
goto END
:END
echo.
echo.
echo press any key to exit...
pause >nul

View File

@ -1,12 +1,8 @@
#!/bin/bash #!/bin/bash
####################################################################
# EOM Teleport Server Install Script
####################################################################
if [ `id -u` -ne 0 ];then if [ `id -u` -ne 0 ];then
echo "" echo ""
echo -e "\e[31mPlease run the installer with ROOT.\033[0m" echo -e "\e[31mPlease run setup as root.\033[0m"
echo "" echo ""
exit 1 exit 1
fi fi
@ -15,6 +11,10 @@ fi
PATH_ROOT=$(cd "$(dirname "$0")"; pwd) PATH_ROOT=$(cd "$(dirname "$0")"; pwd)
PATH_TARGET=/usr/local/eom PATH_TARGET=/usr/local/eom
"${PATH_ROOT}/data/bin/tp_web" --py "${PATH_ROOT}/script/main.py"
exit 0
if [ ! -d "${PATH_TARGET}" ]; then if [ ! -d "${PATH_TARGET}" ]; then
mkdir -p "${PATH_TARGET}" mkdir -p "${PATH_TARGET}"
fi fi

View File

@ -1,8 +1,12 @@
#ifdef _DEBUG
#include <vld.h>
#endif
/* Name of package */ /* Name of package */
#define PACKAGE "libssh" #define PACKAGE "libssh"
/* Version number of package */ /* Version number of package */
#define VERSION "0.7.0" #define VERSION "0.7.4"
/* #undef LOCALEDIR */ /* #undef LOCALEDIR */
/* #undef DATADIR */ /* #undef DATADIR */
@ -77,10 +81,10 @@
/*************************** FUNCTIONS ***************************/ /*************************** FUNCTIONS ***************************/
/* Define to 1 if you have the `EVP_aes128_ctr' function. */ /* Define to 1 if you have the `EVP_aes128_ctr' function. */
/*#define HAVE_OPENSSL_EVP_AES_CTR 1*/ #define HAVE_OPENSSL_EVP_AES_CTR 1
/* Define to 1 if you have the `EVP_aes128_cbc' function. */ /* Define to 1 if you have the `EVP_aes128_cbc' function. */
/*#define HAVE_OPENSSL_EVP_AES_CBC 1*/ #define HAVE_OPENSSL_EVP_AES_CBC 1
/* Define to 1 if you have the `snprintf' function. */ /* Define to 1 if you have the `snprintf' function. */
#define HAVE_SNPRINTF 1 #define HAVE_SNPRINTF 1
@ -153,7 +157,7 @@
#define HAVE_MSC_THREAD_LOCAL_STORAGE 1 #define HAVE_MSC_THREAD_LOCAL_STORAGE 1
/* #undef HAVE_GCC_VOLATILE_MEMORY_PROTECTION */ /* #undef HAVE_GCC_VOLATILE_MEMORY_PROTECTION */
#define HAVE_GCC_NARG_MACRO 1 /*#define HAVE_GCC_NARG_MACRO 1*/
/* #undef HAVE_COMPILER__FUNC__ */ /* #undef HAVE_COMPILER__FUNC__ */
#define HAVE_COMPILER__FUNCTION__ 1 #define HAVE_COMPILER__FUNCTION__ 1

View File

@ -1,118 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2008-2009 Andreas Schneider <asn@cryptomilk.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __AGENT_H
#define __AGENT_H
#include "libssh/libssh.h"
/* Messages for the authentication agent connection. */
#define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
#define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
#define SSH_AGENTC_RSA_CHALLENGE 3
#define SSH_AGENT_RSA_RESPONSE 4
#define SSH_AGENT_FAILURE 5
#define SSH_AGENT_SUCCESS 6
#define SSH_AGENTC_ADD_RSA_IDENTITY 7
#define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
#define SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9
/* private OpenSSH extensions for SSH2 */
#define SSH2_AGENTC_REQUEST_IDENTITIES 11
#define SSH2_AGENT_IDENTITIES_ANSWER 12
#define SSH2_AGENTC_SIGN_REQUEST 13
#define SSH2_AGENT_SIGN_RESPONSE 14
#define SSH2_AGENTC_ADD_IDENTITY 17
#define SSH2_AGENTC_REMOVE_IDENTITY 18
#define SSH2_AGENTC_REMOVE_ALL_IDENTITIES 19
/* smartcard */
#define SSH_AGENTC_ADD_SMARTCARD_KEY 20
#define SSH_AGENTC_REMOVE_SMARTCARD_KEY 21
/* lock/unlock the agent */
#define SSH_AGENTC_LOCK 22
#define SSH_AGENTC_UNLOCK 23
/* add key with constraints */
#define SSH_AGENTC_ADD_RSA_ID_CONSTRAINED 24
#define SSH2_AGENTC_ADD_ID_CONSTRAINED 25
#define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26
#define SSH_AGENT_CONSTRAIN_LIFETIME 1
#define SSH_AGENT_CONSTRAIN_CONFIRM 2
/* extended failure messages */
#define SSH2_AGENT_FAILURE 30
/* additional error code for ssh.com's ssh-agent2 */
#define SSH_COM_AGENT2_FAILURE 102
#define SSH_AGENT_OLD_SIGNATURE 0x01
struct ssh_agent_struct {
struct ssh_socket_struct *sock;
ssh_buffer ident;
unsigned int count;
ssh_channel channel;
};
#ifndef _WIN32
/* agent.c */
/**
* @brief Create a new ssh agent structure.
*
* @return An allocated ssh agent structure or NULL on error.
*/
struct ssh_agent_struct *ssh_agent_new(struct ssh_session_struct *session);
void ssh_agent_close(struct ssh_agent_struct *agent);
/**
* @brief Free an allocated ssh agent structure.
*
* @param agent The ssh agent structure to free.
*/
void ssh_agent_free(struct ssh_agent_struct *agent);
/**
* @brief Check if the ssh agent is running.
*
* @param session The ssh session to check for the agent.
*
* @return 1 if it is running, 0 if not.
*/
int ssh_agent_is_running(struct ssh_session_struct *session);
int ssh_agent_get_ident_count(struct ssh_session_struct *session);
ssh_key ssh_agent_get_next_ident(struct ssh_session_struct *session,
char **comment);
ssh_key ssh_agent_get_first_ident(struct ssh_session_struct *session,
char **comment);
ssh_string ssh_agent_sign_data(ssh_session session,
const ssh_key pubkey,
struct ssh_buffer_struct *data);
#endif
#endif /* __AGENT_H */
/* vim: set ts=2 sw=2 et cindent: */

View File

@ -1,111 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AUTH_H_
#define AUTH_H_
#include "config.h"
#include "libssh/callbacks.h"
SSH_PACKET_CALLBACK(ssh_packet_userauth_banner);
SSH_PACKET_CALLBACK(ssh_packet_userauth_failure);
SSH_PACKET_CALLBACK(ssh_packet_userauth_success);
SSH_PACKET_CALLBACK(ssh_packet_userauth_pk_ok);
SSH_PACKET_CALLBACK(ssh_packet_userauth_info_request);
SSH_PACKET_CALLBACK(ssh_packet_userauth_info_response);
/** @internal
* kdbint structure must be shared with message.c
* and server.c
*/
struct ssh_kbdint_struct {
uint32_t nprompts;
uint32_t nanswers;
char *name;
char *instruction;
char **prompts;
unsigned char *echo; /* bool array */
char **answers;
};
typedef struct ssh_kbdint_struct* ssh_kbdint;
ssh_kbdint ssh_kbdint_new(void);
void ssh_kbdint_clean(ssh_kbdint kbd);
void ssh_kbdint_free(ssh_kbdint kbd);
#ifdef WITH_SSH1
void ssh_auth1_handler(ssh_session session, uint8_t type);
/* auth1.c */
int ssh_userauth1_none(ssh_session session, const char *username);
int ssh_userauth1_offer_pubkey(ssh_session session, const char *username,
int type, ssh_string pubkey);
int ssh_userauth1_password(ssh_session session, const char *username,
const char *password);
#endif
/** @internal
* States of authentication in the client-side. They describe
* what was the last response from the server
*/
enum ssh_auth_state_e {
/** No authentication asked */
SSH_AUTH_STATE_NONE=0,
/** Last authentication response was a partial success */
SSH_AUTH_STATE_PARTIAL,
/** Last authentication response was a success */
SSH_AUTH_STATE_SUCCESS,
/** Last authentication response was failed */
SSH_AUTH_STATE_FAILED,
/** Last authentication was erroneous */
SSH_AUTH_STATE_ERROR,
/** Last state was a keyboard-interactive ask for info */
SSH_AUTH_STATE_INFO,
/** Last state was a public key accepted for authentication */
SSH_AUTH_STATE_PK_OK,
/** We asked for a keyboard-interactive authentication */
SSH_AUTH_STATE_KBDINT_SENT,
/** We have sent an userauth request with gssapi-with-mic */
SSH_AUTH_STATE_GSSAPI_REQUEST_SENT,
/** We are exchanging tokens until authentication */
SSH_AUTH_STATE_GSSAPI_TOKEN,
/** We have sent the MIC and expecting to be authenticated */
SSH_AUTH_STATE_GSSAPI_MIC_SENT,
};
/** @internal
* @brief states of the authentication service request
*/
enum ssh_auth_service_state_e {
/** initial state */
SSH_AUTH_SERVICE_NONE=0,
/** Authentication service request packet sent */
SSH_AUTH_SERVICE_SENT,
/** Service accepted */
SSH_AUTH_SERVICE_ACCEPTED,
/** Access to service denied (fatal) */
SSH_AUTH_SERVICE_DENIED,
/** Specific to SSH1 */
SSH_AUTH_SERVICE_USER_SENT
};
#endif /* AUTH_H_ */

View File

@ -1,33 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2014 by Aris Adamantiadis <aris@badcode.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BIGNUM_H_
#define BIGNUM_H_
#include "libssh/libcrypto.h"
#include "libssh/libgcrypt.h"
bignum ssh_make_string_bn(ssh_string string);
void ssh_make_string_bn_inplace(ssh_string string, bignum bnout);
ssh_string ssh_make_bignum_string(bignum num);
void ssh_print_bignum(const char *which,bignum num);
#endif /* BIGNUM_H_ */

View File

@ -1,55 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BIND_H_
#define BIND_H_
#include "libssh/priv.h"
#include "libssh/session.h"
struct ssh_bind_struct {
struct ssh_common_struct common; /* stuff common to ssh_bind and ssh_session */
struct ssh_bind_callbacks_struct *bind_callbacks;
void *bind_callbacks_userdata;
struct ssh_poll_handle_struct *poll;
/* options */
char *wanted_methods[10];
char *banner;
char *ecdsakey;
char *dsakey;
char *rsakey;
char *ed25519key;
ssh_key ecdsa;
ssh_key dsa;
ssh_key rsa;
ssh_key ed25519;
char *bindaddr;
socket_t bindfd;
unsigned int bindport;
int blocking;
int toaccept;
};
struct ssh_poll_handle_struct *ssh_bind_get_poll(struct ssh_bind_struct
*sshbind);
#endif /* BIND_H_ */

View File

@ -1,87 +0,0 @@
/* $OpenBSD: blf.h,v 1.7 2007/03/14 17:59:41 grunk Exp $ */
/*
* Blowfish - a fast block cipher designed by Bruce Schneier
*
* Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Niels Provos.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _BLF_H_
#define _BLF_H_
//#include "includes.h"
#if !defined(HAVE_BCRYPT_PBKDF) && !defined(HAVE_BLH_H)
/* Schneier specifies a maximum key length of 56 bytes.
* This ensures that every key bit affects every cipher
* bit. However, the subkeys can hold up to 72 bytes.
* Warning: For normal blowfish encryption only 56 bytes
* of the key affect all cipherbits.
*/
#define BLF_N 16 /* Number of Subkeys */
#define BLF_MAXKEYLEN ((BLF_N-2)*4) /* 448 bits */
#define BLF_MAXUTILIZED ((BLF_N+2)*4) /* 576 bits */
/* Blowfish context */
typedef struct BlowfishContext {
uint32_t S[4][256]; /* S-Boxes */
uint32_t P[BLF_N + 2]; /* Subkeys */
} ssh_blf_ctx;
/* Raw access to customized Blowfish
* blf_key is just:
* Blowfish_initstate( state )
* Blowfish_expand0state( state, key, keylen )
*/
void Blowfish_encipher(ssh_blf_ctx *, uint32_t *, uint32_t *);
void Blowfish_decipher(ssh_blf_ctx *, uint32_t *, uint32_t *);
void Blowfish_initstate(ssh_blf_ctx *);
void Blowfish_expand0state(ssh_blf_ctx *, const uint8_t *, uint16_t);
void Blowfish_expandstate
(ssh_blf_ctx *, const uint8_t *, uint16_t, const uint8_t *, uint16_t);
/* Standard Blowfish */
void ssh_blf_key(ssh_blf_ctx *, const uint8_t *, uint16_t);
void ssh_blf_enc(ssh_blf_ctx *, uint32_t *, uint16_t);
void ssh_blf_dec(ssh_blf_ctx *, uint32_t *, uint16_t);
void ssh_blf_ecb_encrypt(ssh_blf_ctx *, uint8_t *, uint32_t);
void ssh_blf_ecb_decrypt(ssh_blf_ctx *, uint8_t *, uint32_t);
void ssh_blf_cbc_encrypt(ssh_blf_ctx *, uint8_t *, uint8_t *, uint32_t);
void ssh_blf_cbc_decrypt(ssh_blf_ctx *, uint8_t *, uint8_t *, uint32_t);
/* Converts uint8_t to uint32_t */
uint32_t Blowfish_stream2word(const uint8_t *, uint16_t , uint16_t *);
#endif /* !defined(HAVE_BCRYPT_PBKDF) && !defined(HAVE_BLH_H) */
#endif /* _BLF_H */

View File

@ -1,88 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef BUFFER_H_
#define BUFFER_H_
#include <stdarg.h>
#include "libssh/libssh.h"
/*
* Describes a buffer state
* [XXXXXXXXXXXXDATA PAYLOAD XXXXXXXXXXXXXXXXXXXXXXXX]
* ^ ^ ^ ^]
* \_data points\_pos points here \_used points here | /
* here Allocated
*/
struct ssh_buffer_struct {
char *data;
uint32_t used;
uint32_t allocated;
uint32_t pos;
int secure;
};
#define SSH_BUFFER_PACK_END ((uint32_t) 0x4f65feb3)
void ssh_buffer_set_secure(ssh_buffer buffer);
int ssh_buffer_add_ssh_string(ssh_buffer buffer, ssh_string string);
int ssh_buffer_add_u8(ssh_buffer buffer, uint8_t data);
int ssh_buffer_add_u16(ssh_buffer buffer, uint16_t data);
int ssh_buffer_add_u32(ssh_buffer buffer, uint32_t data);
int ssh_buffer_add_u64(ssh_buffer buffer, uint64_t data);
int ssh_buffer_pack_va(struct ssh_buffer_struct *buffer,
const char *format,
int argc,
va_list ap);
int _ssh_buffer_pack(struct ssh_buffer_struct *buffer,
const char *format,
int argc,
...);
#define ssh_buffer_pack(buffer, format, ...) \
_ssh_buffer_pack((buffer), (format), __VA_NARG__(__VA_ARGS__), __VA_ARGS__, SSH_BUFFER_PACK_END)
int ssh_buffer_unpack_va(struct ssh_buffer_struct *buffer,
const char *format, int argc,
va_list ap);
int _ssh_buffer_unpack(struct ssh_buffer_struct *buffer,
const char *format,
int argc,
...);
#define ssh_buffer_unpack(buffer, format, ...) \
_ssh_buffer_unpack((buffer), (format), __VA_NARG__(__VA_ARGS__), __VA_ARGS__, SSH_BUFFER_PACK_END)
int ssh_buffer_prepend_data(ssh_buffer buffer, const void *data, uint32_t len);
int ssh_buffer_add_buffer(ssh_buffer buffer, ssh_buffer source);
/* buffer_read_*() returns the number of bytes read, except for ssh strings */
int ssh_buffer_get_u8(ssh_buffer buffer, uint8_t *data);
int ssh_buffer_get_u32(ssh_buffer buffer, uint32_t *data);
int ssh_buffer_get_u64(ssh_buffer buffer, uint64_t *data);
/* ssh_buffer_get_ssh_string() is an exception. if the String read is too large or invalid, it will answer NULL. */
ssh_string ssh_buffer_get_ssh_string(ssh_buffer buffer);
/* ssh_gets a string out of a SSH-1 mpint */
ssh_string ssh_buffer_get_mpint(ssh_buffer buffer);
/* ssh_buffer_pass_bytes acts as if len bytes have been read (used for padding) */
uint32_t ssh_buffer_pass_bytes_end(ssh_buffer buffer, uint32_t len);
uint32_t ssh_buffer_pass_bytes(ssh_buffer buffer, uint32_t len);
#endif /* BUFFER_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -1,119 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CHANNELS_H_
#define CHANNELS_H_
#include "libssh/priv.h"
/** @internal
* Describes the different possible states in a
* outgoing (client) channel request
*/
enum ssh_channel_request_state_e {
/** No request has been made */
SSH_CHANNEL_REQ_STATE_NONE = 0,
/** A request has been made and answer is pending */
SSH_CHANNEL_REQ_STATE_PENDING,
/** A request has been replied and accepted */
SSH_CHANNEL_REQ_STATE_ACCEPTED,
/** A request has been replied and refused */
SSH_CHANNEL_REQ_STATE_DENIED,
/** A request has been replied and an error happend */
SSH_CHANNEL_REQ_STATE_ERROR
};
enum ssh_channel_state_e {
SSH_CHANNEL_STATE_NOT_OPEN = 0,
SSH_CHANNEL_STATE_OPENING,
SSH_CHANNEL_STATE_OPEN_DENIED,
SSH_CHANNEL_STATE_OPEN,
SSH_CHANNEL_STATE_CLOSED
};
/* The channel has been closed by the remote side */
#define SSH_CHANNEL_FLAG_CLOSED_REMOTE 0x1
/* The channel has been freed by the calling program */
#define SSH_CHANNEL_FLAG_FREED_LOCAL 0x2
/* the channel has not yet been bound to a remote one */
#define SSH_CHANNEL_FLAG_NOT_BOUND 0x4
struct ssh_channel_struct {
ssh_session session; /* SSH_SESSION pointer */
uint32_t local_channel;
uint32_t local_window;
int local_eof;
uint32_t local_maxpacket;
uint32_t remote_channel;
uint32_t remote_window;
int remote_eof; /* end of file received */
uint32_t remote_maxpacket;
enum ssh_channel_state_e state;
int delayed_close;
int flags;
ssh_buffer stdout_buffer;
ssh_buffer stderr_buffer;
void *userarg;
int version;
int exit_status;
enum ssh_channel_request_state_e request_state;
struct ssh_list *callbacks; /* list of ssh_channel_callbacks */
/* counters */
ssh_counter counter;
};
SSH_PACKET_CALLBACK(ssh_packet_channel_open_conf);
SSH_PACKET_CALLBACK(ssh_packet_channel_open_fail);
SSH_PACKET_CALLBACK(ssh_packet_channel_success);
SSH_PACKET_CALLBACK(ssh_packet_channel_failure);
SSH_PACKET_CALLBACK(ssh_request_success);
SSH_PACKET_CALLBACK(ssh_request_denied);
SSH_PACKET_CALLBACK(channel_rcv_change_window);
SSH_PACKET_CALLBACK(channel_rcv_eof);
SSH_PACKET_CALLBACK(channel_rcv_close);
SSH_PACKET_CALLBACK(channel_rcv_request);
SSH_PACKET_CALLBACK(channel_rcv_data);
ssh_channel ssh_channel_new(ssh_session session);
int channel_default_bufferize(ssh_channel channel, void *data, int len,
int is_stderr);
int ssh_channel_flush(ssh_channel channel);
uint32_t ssh_channel_new_id(ssh_session session);
ssh_channel ssh_channel_from_local(ssh_session session, uint32_t id);
void ssh_channel_do_free(ssh_channel channel);
#ifdef WITH_SSH1
SSH_PACKET_CALLBACK(ssh_packet_data1);
SSH_PACKET_CALLBACK(ssh_packet_close1);
SSH_PACKET_CALLBACK(ssh_packet_exist_status1);
/* channels1.c */
int ssh_channel_open_session1(ssh_channel channel);
int ssh_channel_request_pty_size1(ssh_channel channel, const char *terminal,
int cols, int rows);
int ssh_channel_change_pty_size1(ssh_channel channel, int cols, int rows);
int ssh_channel_request_shell1(ssh_channel channel);
int ssh_channel_request_exec1(ssh_channel channel, const char *cmd);
int ssh_channel_write1(ssh_channel channel, const void *data, int len);
ssh_channel ssh_get_channel1(ssh_session session);
#endif
#endif /* CHANNELS_H_ */

View File

@ -1,28 +0,0 @@
/*
* crc32.c - simple CRC32 code
*
* This file is part of the SSH Library
*
* Copyright (c) 2005 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CRC32_H
#define _CRC32_H
uint32_t ssh_crc32(const char *buf, uint32_t len);
#endif /* _CRC32_H */

View File

@ -1,143 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* crypto.h is an include file for internal cryptographic structures of libssh
*/
#ifndef _CRYPTO_H_
#define _CRYPTO_H_
#include "config.h"
#ifdef HAVE_LIBGCRYPT
#include <gcrypt.h>
#endif
#include "libssh/wrapper.h"
#ifdef cbc_encrypt
#undef cbc_encrypt
#endif
#ifdef cbc_decrypt
#undef cbc_decrypt
#endif
#ifdef HAVE_OPENSSL_ECDH_H
#include <openssl/ecdh.h>
#endif
#include "libssh/ecdh.h"
#include "libssh/kex.h"
#include "libssh/curve25519.h"
#define DIGEST_MAX_LEN 64
enum ssh_key_exchange_e {
/* diffie-hellman-group1-sha1 */
SSH_KEX_DH_GROUP1_SHA1=1,
/* diffie-hellman-group14-sha1 */
SSH_KEX_DH_GROUP14_SHA1,
/* ecdh-sha2-nistp256 */
SSH_KEX_ECDH_SHA2_NISTP256,
/* curve25519-sha256@libssh.org */
SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG
};
enum ssh_cipher_e {
SSH_NO_CIPHER=0,
SSH_BLOWFISH_CBC,
SSH_3DES_CBC,
SSH_3DES_CBC_SSH1,
SSH_DES_CBC_SSH1,
SSH_AES128_CBC,
SSH_AES192_CBC,
SSH_AES256_CBC,
SSH_AES128_CTR,
SSH_AES192_CTR,
SSH_AES256_CTR
};
struct ssh_crypto_struct {
bignum e,f,x,k,y;
#ifdef HAVE_ECDH
EC_KEY *ecdh_privkey;
ssh_string ecdh_client_pubkey;
ssh_string ecdh_server_pubkey;
#endif
#ifdef HAVE_CURVE25519
ssh_curve25519_privkey curve25519_privkey;
ssh_curve25519_pubkey curve25519_client_pubkey;
ssh_curve25519_pubkey curve25519_server_pubkey;
#endif
ssh_string dh_server_signature; /* information used by dh_handshake. */
size_t digest_len; /* len of all the fields below */
unsigned char *session_id;
unsigned char *secret_hash; /* Secret hash is same as session id until re-kex */
unsigned char *encryptIV;
unsigned char *decryptIV;
unsigned char *decryptkey;
unsigned char *encryptkey;
unsigned char *encryptMAC;
unsigned char *decryptMAC;
unsigned char hmacbuf[DIGEST_MAX_LEN];
struct ssh_cipher_struct *in_cipher, *out_cipher; /* the cipher structures/objects */
enum ssh_hmac_e in_hmac, out_hmac; /* the MAC algorithms used */
ssh_string server_pubkey;
const char *server_pubkey_type;
int do_compress_out; /* idem */
int do_compress_in; /* don't set them, set the option instead */
int delayed_compress_in; /* Use of zlib@openssh.org */
int delayed_compress_out;
void *compress_out_ctx; /* don't touch it */
void *compress_in_ctx; /* really, don't */
/* kex sent by server, client, and mutually elected methods */
struct ssh_kex_struct server_kex;
struct ssh_kex_struct client_kex;
char *kex_methods[SSH_KEX_METHODS];
enum ssh_key_exchange_e kex_type;
enum ssh_mac_e mac_type; /* Mac operations to use for key gen */
};
struct ssh_cipher_struct {
const char *name; /* ssh name of the algorithm */
unsigned int blocksize; /* blocksize of the algo */
enum ssh_cipher_e ciphertype;
#ifdef HAVE_LIBGCRYPT
size_t keylen; /* length of the key structure */
gcry_cipher_hd_t *key;
#elif defined HAVE_LIBCRYPTO
struct ssh_3des_key_schedule *des3_key;
struct ssh_aes_key_schedule *aes_key;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
#endif
unsigned int keysize; /* bytes of key used. != keylen */
/* sets the new key for immediate use */
int (*set_encrypt_key)(struct ssh_cipher_struct *cipher, void *key, void *IV);
int (*set_decrypt_key)(struct ssh_cipher_struct *cipher, void *key, void *IV);
void (*encrypt)(struct ssh_cipher_struct *cipher, void *in, void *out,
unsigned long len);
void (*decrypt)(struct ssh_cipher_struct *cipher, void *in, void *out,
unsigned long len);
void (*cleanup)(struct ssh_cipher_struct *cipher);
};
/* vim: set ts=2 sw=2 et cindent: */
#endif /* _CRYPTO_H_ */

View File

@ -1,57 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2013 by Aris Adamantiadis <aris@badcode.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation,
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CURVE25519_H_
#define CURVE25519_H_
#include "config.h"
#include "libssh.h"
#ifdef WITH_NACL
#include <nacl/crypto_scalarmult_curve25519.h>
#define CURVE25519_PUBKEY_SIZE crypto_scalarmult_curve25519_BYTES
#define CURVE25519_PRIVKEY_SIZE crypto_scalarmult_curve25519_SCALARBYTES
#define crypto_scalarmult_base crypto_scalarmult_curve25519_base
#define crypto_scalarmult crypto_scalarmult_curve25519
#else
#define CURVE25519_PUBKEY_SIZE 32
#define CURVE25519_PRIVKEY_SIZE 32
int crypto_scalarmult_base(unsigned char *q, const unsigned char *n);
int crypto_scalarmult(unsigned char *q, const unsigned char *n, const unsigned char *p);
#endif /* WITH_NACL */
#ifdef HAVE_ECC
#define HAVE_CURVE25519 1
#endif
typedef unsigned char ssh_curve25519_pubkey[CURVE25519_PUBKEY_SIZE];
typedef unsigned char ssh_curve25519_privkey[CURVE25519_PRIVKEY_SIZE];
int ssh_client_curve25519_init(ssh_session session);
int ssh_client_curve25519_reply(ssh_session session, ssh_buffer packet);
#ifdef WITH_SERVER
int ssh_server_curve25519_init(ssh_session session, ssh_buffer packet);
#endif /* WITH_SERVER */
#endif /* CURVE25519_H_ */

View File

@ -1,51 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef DH_H_
#define DH_H_
#include "config.h"
#include "libssh/crypto.h"
int ssh_dh_generate_e(ssh_session session);
int ssh_dh_generate_f(ssh_session session);
int ssh_dh_generate_x(ssh_session session);
int ssh_dh_generate_y(ssh_session session);
int ssh_crypto_init(void);
void ssh_crypto_finalize(void);
ssh_string ssh_dh_get_e(ssh_session session);
ssh_string ssh_dh_get_f(ssh_session session);
int ssh_dh_import_f(ssh_session session,ssh_string f_string);
int ssh_dh_import_e(ssh_session session, ssh_string e_string);
void ssh_dh_import_pubkey(ssh_session session,ssh_string pubkey_string);
int ssh_dh_build_k(ssh_session session);
int ssh_client_dh_init(ssh_session session);
int ssh_client_dh_reply(ssh_session session, ssh_buffer packet);
int ssh_make_sessionid(ssh_session session);
/* add data for the final cookie */
int ssh_hashbufin_add_cookie(ssh_session session, unsigned char *cookie);
int ssh_hashbufout_add_cookie(ssh_session session);
int ssh_generate_session_keys(ssh_session session);
#endif /* DH_H_ */

View File

@ -1,43 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2011 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ECDH_H_
#define ECDH_H_
#include "config.h"
#ifdef HAVE_LIBCRYPTO
#ifdef HAVE_OPENSSL_ECDH_H
#ifdef HAVE_ECC
#define HAVE_ECDH 1
#endif
#endif /* HAVE_OPENSSL_ECDH_H */
#endif /* HAVE_LIBCRYPTO */
int ssh_client_ecdh_init(ssh_session session);
int ssh_client_ecdh_reply(ssh_session session, ssh_buffer packet);
#ifdef WITH_SERVER
int ssh_server_ecdh_init(ssh_session session, ssh_buffer packet);
#endif /* WITH_SERVER */
#endif /* ECDH_H_ */

View File

@ -1,79 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2014 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ED25519_H_
#define ED25519_H_
#include "libssh/priv.h"
/**
* @defgroup ed25519 ed25519 API
* @internal
* @brief API for DJB's ed25519
*
* @{ */
#define ED25519_PK_LEN 32
#define ED25519_SK_LEN 64
#define ED25519_SIG_LEN 64
typedef uint8_t ed25519_pubkey[ED25519_PK_LEN];
typedef uint8_t ed25519_privkey[ED25519_SK_LEN];
typedef uint8_t ed25519_signature[ED25519_SIG_LEN];
/** @internal
* @brief generate an ed25519 key pair
* @param[out] pk generated public key
* @param[out] sk generated secret key
* @return 0 on success, -1 on error.
* */
int crypto_sign_ed25519_keypair(ed25519_pubkey pk, ed25519_privkey sk);
/** @internal
* @brief sign a message with ed25519
* @param[out] sm location to store the signed message.
* Its length should be mlen + 64.
* @param[out] smlen pointer to the size of the signed message
* @param[in] m message to be signed
* @param[in] mlen length of the message to be signed
* @param[in] sk secret key to sign the message with
* @return 0 on success.
*/
int crypto_sign_ed25519(
unsigned char *sm,unsigned long long *smlen,
const unsigned char *m,unsigned long long mlen,
const ed25519_privkey sk);
/** @internal
* @brief "open" and verify the signature of a signed message
* @param[out] m location to store the verified message.
* Its length should be equal to smlen.
* @param[out] mlen pointer to the size of the verified message
* @param[in] sm signed message to verify
* @param[in] smlen length of the signed message to verify
* @param[in] pk public key used to sign the message
* @returns 0 on success (supposedly).
*/
int crypto_sign_ed25519_open(
unsigned char *m,unsigned long long *mlen,
const unsigned char *sm,unsigned long long smlen,
const ed25519_pubkey pk);
/** @} */
#endif /* ED25519_H_ */

View File

@ -1,68 +0,0 @@
/* $OpenBSD: fe25519.h,v 1.3 2013/12/09 11:03:45 markus Exp $ */
/*
* Public Domain, Authors: Daniel J. Bernstein, Niels Duif, Tanja Lange,
* Peter Schwabe, Bo-Yin Yang.
* Copied from supercop-20130419/crypto_sign/ed25519/ref/fe25519.h
*/
#ifndef FE25519_H
#define FE25519_H
#include "libssh/priv.h"
#define fe25519 crypto_sign_ed25519_ref_fe25519
#define fe25519_freeze crypto_sign_ed25519_ref_fe25519_freeze
#define fe25519_unpack crypto_sign_ed25519_ref_fe25519_unpack
#define fe25519_pack crypto_sign_ed25519_ref_fe25519_pack
#define fe25519_iszero crypto_sign_ed25519_ref_fe25519_iszero
#define fe25519_iseq_vartime crypto_sign_ed25519_ref_fe25519_iseq_vartime
#define fe25519_cmov crypto_sign_ed25519_ref_fe25519_cmov
#define fe25519_setone crypto_sign_ed25519_ref_fe25519_setone
#define fe25519_setzero crypto_sign_ed25519_ref_fe25519_setzero
#define fe25519_neg crypto_sign_ed25519_ref_fe25519_neg
#define fe25519_getparity crypto_sign_ed25519_ref_fe25519_getparity
#define fe25519_add crypto_sign_ed25519_ref_fe25519_add
#define fe25519_sub crypto_sign_ed25519_ref_fe25519_sub
#define fe25519_mul crypto_sign_ed25519_ref_fe25519_mul
#define fe25519_square crypto_sign_ed25519_ref_fe25519_square
#define fe25519_invert crypto_sign_ed25519_ref_fe25519_invert
#define fe25519_pow2523 crypto_sign_ed25519_ref_fe25519_pow2523
typedef struct {
uint32_t v[32];
} fe25519;
void fe25519_freeze(fe25519 *r);
void fe25519_unpack(fe25519 *r, const unsigned char x[32]);
void fe25519_pack(unsigned char r[32], const fe25519 *x);
int fe25519_iszero(const fe25519 *x);
int fe25519_iseq_vartime(const fe25519 *x, const fe25519 *y);
void fe25519_cmov(fe25519 *r, const fe25519 *x, unsigned char b);
void fe25519_setone(fe25519 *r);
void fe25519_setzero(fe25519 *r);
void fe25519_neg(fe25519 *r, const fe25519 *x);
unsigned char fe25519_getparity(const fe25519 *x);
void fe25519_add(fe25519 *r, const fe25519 *x, const fe25519 *y);
void fe25519_sub(fe25519 *r, const fe25519 *x, const fe25519 *y);
void fe25519_mul(fe25519 *r, const fe25519 *x, const fe25519 *y);
void fe25519_square(fe25519 *r, const fe25519 *x);
void fe25519_invert(fe25519 *r, const fe25519 *x);
void fe25519_pow2523(fe25519 *r, const fe25519 *x);
#endif

View File

@ -1,43 +0,0 @@
/* $OpenBSD: ge25519.h,v 1.3 2013/12/09 11:03:45 markus Exp $ */
/*
* Public Domain, Authors: Daniel J. Bernstein, Niels Duif, Tanja Lange,
* Peter Schwabe, Bo-Yin Yang.
* Copied from supercop-20130419/crypto_sign/ed25519/ref/ge25519.h
*/
#ifndef GE25519_H
#define GE25519_H
#include "fe25519.h"
#include "sc25519.h"
#define ge25519 crypto_sign_ed25519_ref_ge25519
#define ge25519_base crypto_sign_ed25519_ref_ge25519_base
#define ge25519_unpackneg_vartime crypto_sign_ed25519_ref_unpackneg_vartime
#define ge25519_pack crypto_sign_ed25519_ref_pack
#define ge25519_isneutral_vartime crypto_sign_ed25519_ref_isneutral_vartime
#define ge25519_double_scalarmult_vartime crypto_sign_ed25519_ref_double_scalarmult_vartime
#define ge25519_scalarmult_base crypto_sign_ed25519_ref_scalarmult_base
typedef struct
{
fe25519 x;
fe25519 y;
fe25519 z;
fe25519 t;
} ge25519;
const ge25519 ge25519_base;
int ge25519_unpackneg_vartime(ge25519 *r, const unsigned char p[32]);
void ge25519_pack(unsigned char r[32], const ge25519 *p);
int ge25519_isneutral_vartime(const ge25519 *p);
void ge25519_double_scalarmult_vartime(ge25519 *r, const ge25519 *p1, const sc25519 *s1, const ge25519 *p2, const sc25519 *s2);
void ge25519_scalarmult_base(ge25519 *r, const sc25519 *s);
#endif

View File

@ -1,45 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2013 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef GSSAPI_H_
#define GSSAPI_H_
#include "config.h"
#include "session.h"
/* all OID begin with the tag identifier + length */
#define SSH_OID_TAG 06
typedef struct ssh_gssapi_struct *ssh_gssapi;
#ifdef WITH_SERVER
int ssh_gssapi_handle_userauth(ssh_session session, const char *user, uint32_t n_oid, ssh_string *oids);
SSH_PACKET_CALLBACK(ssh_packet_userauth_gssapi_token_server);
SSH_PACKET_CALLBACK(ssh_packet_userauth_gssapi_mic);
#endif /* WITH_SERVER */
SSH_PACKET_CALLBACK(ssh_packet_userauth_gssapi_token);
SSH_PACKET_CALLBACK(ssh_packet_userauth_gssapi_token_client);
SSH_PACKET_CALLBACK(ssh_packet_userauth_gssapi_response);
int ssh_gssapi_auth_mic(ssh_session session);
#endif /* GSSAPI_H */

View File

@ -1,50 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef KEX_H_
#define KEX_H_
#include "libssh/priv.h"
#include "libssh/callbacks.h"
#define SSH_KEX_METHODS 10
struct ssh_kex_struct {
unsigned char cookie[16];
char *methods[SSH_KEX_METHODS];
};
SSH_PACKET_CALLBACK(ssh_packet_kexinit);
#ifdef WITH_SSH1
SSH_PACKET_CALLBACK(ssh_packet_publickey1);
#endif
int ssh_send_kex(ssh_session session, int server_kex);
void ssh_list_kex(struct ssh_kex_struct *kex);
int ssh_set_client_kex(ssh_session session);
int ssh_kex_select_methods(ssh_session session);
int ssh_verify_existing_algo(int algo, const char *name);
char **ssh_space_tokenize(const char *chain);
int ssh_get_kex1(ssh_session session);
char *ssh_find_matching(const char *in_d, const char *what_d);
const char *ssh_kex_get_supported_method(uint32_t algo);
const char *ssh_kex_get_description(uint32_t algo);
#endif /* KEX_H_ */

View File

@ -1,56 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef KEYS_H_
#define KEYS_H_
#include "config.h"
#include "libssh/libssh.h"
#include "libssh/wrapper.h"
struct ssh_public_key_struct {
int type;
const char *type_c; /* Don't free it ! it is static */
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa_pub;
gcry_sexp_t rsa_pub;
#elif HAVE_LIBCRYPTO
DSA *dsa_pub;
RSA *rsa_pub;
#endif
};
struct ssh_private_key_struct {
int type;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa_priv;
gcry_sexp_t rsa_priv;
#elif defined HAVE_LIBCRYPTO
DSA *dsa_priv;
RSA *rsa_priv;
#endif
};
const char *ssh_type_to_char(int type);
int ssh_type_from_name(const char *name);
ssh_public_key publickey_from_string(ssh_session session, ssh_string pubkey_s);
#endif /* KEYS_H_ */

View File

@ -1,27 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 20014 by Aris Adamantiadis <aris@badcode.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef KNOWNHOSTS_H_
#define KNOWNHOSTS_H_
char **ssh_knownhosts_algorithms(ssh_session session);
#endif /* KNOWNHOSTS_H_ */

View File

@ -1,120 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Since libssh.h includes legacy.h, it's important that libssh.h is included
* first. we don't define LEGACY_H now because we want it to be defined when
* included from libssh.h
* All function calls declared in this header are deprecated and meant to be
* removed in future.
*/
#ifndef LEGACY_H_
#define LEGACY_H_
typedef struct ssh_private_key_struct* ssh_private_key;
typedef struct ssh_public_key_struct* ssh_public_key;
LIBSSH_API int ssh_auth_list(ssh_session session);
LIBSSH_API int ssh_userauth_offer_pubkey(ssh_session session, const char *username, int type, ssh_string publickey);
LIBSSH_API int ssh_userauth_pubkey(ssh_session session, const char *username, ssh_string publickey, ssh_private_key privatekey);
#ifndef _WIN32
LIBSSH_API int ssh_userauth_agent_pubkey(ssh_session session, const char *username,
ssh_public_key publickey);
#endif
LIBSSH_API int ssh_userauth_autopubkey(ssh_session session, const char *passphrase);
LIBSSH_API int ssh_userauth_privatekey_file(ssh_session session, const char *username,
const char *filename, const char *passphrase);
SSH_DEPRECATED LIBSSH_API void buffer_free(ssh_buffer buffer);
SSH_DEPRECATED LIBSSH_API void *buffer_get(ssh_buffer buffer);
SSH_DEPRECATED LIBSSH_API uint32_t buffer_get_len(ssh_buffer buffer);
SSH_DEPRECATED LIBSSH_API ssh_buffer buffer_new(void);
SSH_DEPRECATED LIBSSH_API ssh_channel channel_accept_x11(ssh_channel channel, int timeout_ms);
SSH_DEPRECATED LIBSSH_API int channel_change_pty_size(ssh_channel channel,int cols,int rows);
SSH_DEPRECATED LIBSSH_API ssh_channel channel_forward_accept(ssh_session session, int timeout_ms);
SSH_DEPRECATED LIBSSH_API int channel_close(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_forward_cancel(ssh_session session, const char *address, int port);
SSH_DEPRECATED LIBSSH_API int channel_forward_listen(ssh_session session, const char *address, int port, int *bound_port);
SSH_DEPRECATED LIBSSH_API void channel_free(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_get_exit_status(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API ssh_session channel_get_session(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_is_closed(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_is_eof(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_is_open(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API ssh_channel channel_new(ssh_session session);
SSH_DEPRECATED LIBSSH_API int channel_open_forward(ssh_channel channel, const char *remotehost,
int remoteport, const char *sourcehost, int localport);
SSH_DEPRECATED LIBSSH_API int channel_open_session(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_poll(ssh_channel channel, int is_stderr);
SSH_DEPRECATED LIBSSH_API int channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr);
SSH_DEPRECATED LIBSSH_API int channel_read_buffer(ssh_channel channel, ssh_buffer buffer, uint32_t count,
int is_stderr);
SSH_DEPRECATED LIBSSH_API int channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count,
int is_stderr);
SSH_DEPRECATED LIBSSH_API int channel_request_env(ssh_channel channel, const char *name, const char *value);
SSH_DEPRECATED LIBSSH_API int channel_request_exec(ssh_channel channel, const char *cmd);
SSH_DEPRECATED LIBSSH_API int channel_request_pty(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_request_pty_size(ssh_channel channel, const char *term,
int cols, int rows);
SSH_DEPRECATED LIBSSH_API int channel_request_shell(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_request_send_signal(ssh_channel channel, const char *signum);
SSH_DEPRECATED LIBSSH_API int channel_request_sftp(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_request_subsystem(ssh_channel channel, const char *subsystem);
SSH_DEPRECATED LIBSSH_API int channel_request_x11(ssh_channel channel, int single_connection, const char *protocol,
const char *cookie, int screen_number);
SSH_DEPRECATED LIBSSH_API int channel_send_eof(ssh_channel channel);
SSH_DEPRECATED LIBSSH_API int channel_select(ssh_channel *readchans, ssh_channel *writechans, ssh_channel *exceptchans, struct
timeval * timeout);
SSH_DEPRECATED LIBSSH_API void channel_set_blocking(ssh_channel channel, int blocking);
SSH_DEPRECATED LIBSSH_API int channel_write(ssh_channel channel, const void *data, uint32_t len);
LIBSSH_API void privatekey_free(ssh_private_key prv);
LIBSSH_API ssh_private_key privatekey_from_file(ssh_session session, const char *filename,
int type, const char *passphrase);
LIBSSH_API void publickey_free(ssh_public_key key);
LIBSSH_API int ssh_publickey_to_file(ssh_session session, const char *file,
ssh_string pubkey, int type);
LIBSSH_API ssh_string publickey_from_file(ssh_session session, const char *filename,
int *type);
LIBSSH_API ssh_public_key publickey_from_privatekey(ssh_private_key prv);
LIBSSH_API ssh_string publickey_to_string(ssh_public_key key);
LIBSSH_API int ssh_try_publickey_from_file(ssh_session session, const char *keyfile,
ssh_string *publickey, int *type);
LIBSSH_API enum ssh_keytypes_e ssh_privatekey_type(ssh_private_key privatekey);
LIBSSH_API ssh_string ssh_get_pubkey(ssh_session session);
LIBSSH_API ssh_message ssh_message_retrieve(ssh_session session, uint32_t packettype);
LIBSSH_API ssh_public_key ssh_message_auth_publickey(ssh_message msg);
SSH_DEPRECATED LIBSSH_API void string_burn(ssh_string str);
SSH_DEPRECATED LIBSSH_API ssh_string string_copy(ssh_string str);
SSH_DEPRECATED LIBSSH_API void *string_data(ssh_string str);
SSH_DEPRECATED LIBSSH_API int string_fill(ssh_string str, const void *data, size_t len);
SSH_DEPRECATED LIBSSH_API void string_free(ssh_string str);
SSH_DEPRECATED LIBSSH_API ssh_string string_from_char(const char *what);
SSH_DEPRECATED LIBSSH_API size_t string_len(ssh_string str);
SSH_DEPRECATED LIBSSH_API ssh_string string_new(size_t size);
SSH_DEPRECATED LIBSSH_API char *string_to_char(ssh_string str);
#endif /* LEGACY_H_ */

View File

@ -1,102 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef LIBCRYPTO_H_
#define LIBCRYPTO_H_
#include "config.h"
#ifdef HAVE_LIBCRYPTO
#include <openssl/dsa.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
typedef EVP_MD_CTX* SHACTX;
typedef EVP_MD_CTX* SHA256CTX;
typedef EVP_MD_CTX* SHA384CTX;
typedef EVP_MD_CTX* SHA512CTX;
typedef EVP_MD_CTX* MD5CTX;
typedef HMAC_CTX* HMACCTX;
#ifdef HAVE_ECC
typedef EVP_MD_CTX *EVPCTX;
#else
typedef void *EVPCTX;
#endif
#define SHA_DIGEST_LEN SHA_DIGEST_LENGTH
#define SHA256_DIGEST_LEN SHA256_DIGEST_LENGTH
#define SHA384_DIGEST_LEN SHA384_DIGEST_LENGTH
#define SHA512_DIGEST_LEN SHA512_DIGEST_LENGTH
#ifdef MD5_DIGEST_LEN
#undef MD5_DIGEST_LEN
#endif
#define MD5_DIGEST_LEN MD5_DIGEST_LENGTH
#ifdef HAVE_OPENSSL_ECC
#define EVP_DIGEST_LEN EVP_MAX_MD_SIZE
#endif
#include <openssl/bn.h>
#include <openssl/opensslv.h>
#define OPENSSL_0_9_7b 0x0090702fL
#if (OPENSSL_VERSION_NUMBER <= OPENSSL_0_9_7b)
#define BROKEN_AES_CTR
#endif
typedef BIGNUM* bignum;
typedef BN_CTX* bignum_CTX;
#define bignum_new() BN_new()
#define bignum_free(num) BN_clear_free(num)
#define bignum_set_word(bn,n) BN_set_word(bn,n)
#define bignum_bin2bn(bn,datalen,data) BN_bin2bn(bn,datalen,data)
#define bignum_bn2dec(num) BN_bn2dec(num)
#define bignum_dec2bn(bn,data) BN_dec2bn(data,bn)
#define bignum_bn2hex(num) BN_bn2hex(num)
#define bignum_rand(rnd, bits, top, bottom) BN_rand(rnd,bits,top,bottom)
#define bignum_ctx_new() BN_CTX_new()
#define bignum_ctx_free(num) BN_CTX_free(num)
#define bignum_mod_exp(dest,generator,exp,modulo,ctx) BN_mod_exp(dest,generator,exp,modulo,ctx)
#define bignum_num_bytes(num) BN_num_bytes(num)
#define bignum_num_bits(num) BN_num_bits(num)
#define bignum_is_bit_set(num,bit) BN_is_bit_set(num,bit)
#define bignum_bn2bin(num,ptr) BN_bn2bin(num,ptr)
#define bignum_cmp(num1,num2) BN_cmp(num1,num2)
SHA256CTX sha256_init(void);
void sha256_update(SHA256CTX c, const void *data, unsigned long len);
void sha256_final(unsigned char *md, SHA256CTX c);
SHA384CTX sha384_init(void);
void sha384_update(SHA384CTX c, const void *data, unsigned long len);
void sha384_final(unsigned char *md, SHA384CTX c);
SHA512CTX sha512_init(void);
void sha512_update(SHA512CTX c, const void *data, unsigned long len);
void sha512_final(unsigned char *md, SHA512CTX c);
struct ssh_cipher_struct *ssh_get_ciphertab(void);
#endif /* HAVE_LIBCRYPTO */
#endif /* LIBCRYPTO_H_ */

View File

@ -1,88 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef LIBGCRYPT_H_
#define LIBGCRYPT_H_
#include "config.h"
#ifdef HAVE_LIBGCRYPT
#include <gcrypt.h>
typedef gcry_md_hd_t SHACTX;
typedef gcry_md_hd_t SHA256CTX;
typedef gcry_md_hd_t SHA384CTX;
typedef gcry_md_hd_t SHA512CTX;
typedef gcry_md_hd_t MD5CTX;
typedef gcry_md_hd_t HMACCTX;
typedef void *EVPCTX;
#define SHA_DIGEST_LENGTH 20
#define SHA_DIGEST_LEN SHA_DIGEST_LENGTH
#define MD5_DIGEST_LEN 16
#define SHA256_DIGEST_LENGTH 32
#define SHA256_DIGEST_LEN SHA256_DIGEST_LENGTH
#define SHA384_DIGEST_LENGTH 48
#define SHA384_DIGEST_LEN SHA384_DIGEST_LENGTH
#define SHA512_DIGEST_LENGTH 64
#define SHA512_DIGEST_LEN SHA512_DIGEST_LENGTH
#ifndef EVP_MAX_MD_SIZE
#define EVP_MAX_MD_SIZE 64
#endif
#define EVP_DIGEST_LEN EVP_MAX_MD_SIZE
typedef gcry_mpi_t bignum;
/* missing gcrypt functions */
int ssh_gcry_dec2bn(bignum *bn, const char *data);
char *ssh_gcry_bn2dec(bignum bn);
#define bignum_new() gcry_mpi_new(0)
#define bignum_free(num) gcry_mpi_release(num)
#define bignum_set_word(bn,n) gcry_mpi_set_ui(bn,n)
#define bignum_bin2bn(bn,datalen,data) gcry_mpi_scan(data,GCRYMPI_FMT_USG,bn,datalen,NULL)
#define bignum_bn2dec(num) ssh_gcry_bn2dec(num)
#define bignum_dec2bn(num, data) ssh_gcry_dec2bn(data, num)
#define bignum_bn2hex(num,data) gcry_mpi_aprint(GCRYMPI_FMT_HEX,data,NULL,num)
#define bignum_hex2bn(num,datalen,data) gcry_mpi_scan(num,GCRYMPI_FMT_HEX,data,datalen,NULL)
#define bignum_rand(num,bits) gcry_mpi_randomize(num,bits,GCRY_STRONG_RANDOM),gcry_mpi_set_bit(num,bits-1),gcry_mpi_set_bit(num,0)
#define bignum_mod_exp(dest,generator,exp,modulo) gcry_mpi_powm(dest,generator,exp,modulo)
#define bignum_num_bits(num) gcry_mpi_get_nbits(num)
#define bignum_num_bytes(num) ((gcry_mpi_get_nbits(num)+7)/8)
#define bignum_is_bit_set(num,bit) gcry_mpi_test_bit(num,bit)
#define bignum_bn2bin(num,datalen,data) gcry_mpi_print(GCRYMPI_FMT_USG,data,datalen,NULL,num)
#define bignum_cmp(num1,num2) gcry_mpi_cmp(num1,num2)
/* Helper functions for data conversions. */
/* Extract an MPI from the given s-expression SEXP named NAME which is
encoded using INFORMAT and store it in a newly allocated ssh_string
encoded using OUTFORMAT. */
ssh_string ssh_sexp_extract_mpi(const gcry_sexp_t sexp,
const char *name,
enum gcry_mpi_format informat,
enum gcry_mpi_format outformat);
#endif /* HAVE_LIBGCRYPT */
struct ssh_cipher_struct *ssh_get_ciphertab(void);
#endif /* LIBGCRYPT_H_ */

View File

@ -1,727 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LIBSSH_H
#define _LIBSSH_H
#if defined _WIN32 || defined __CYGWIN__
#ifdef LIBSSH_STATIC
#define LIBSSH_API
#else
#ifdef LIBSSH_EXPORTS
#ifdef __GNUC__
#define LIBSSH_API __attribute__((dllexport))
#else
#define LIBSSH_API __declspec(dllexport)
#endif
#else
#ifdef __GNUC__
#define LIBSSH_API __attribute__((dllimport))
#else
#define LIBSSH_API __declspec(dllimport)
#endif
#endif
#endif
#else
#if __GNUC__ >= 4 && !defined(__OS2__)
#define LIBSSH_API __attribute__((visibility("default")))
#else
#define LIBSSH_API
#endif
#endif
#ifdef _MSC_VER
/* Visual Studio hasn't inttypes.h so it doesn't know uint32_t */
typedef int int32_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef unsigned char uint8_t;
typedef unsigned long long uint64_t;
typedef int mode_t;
#else /* _MSC_VER */
#include <unistd.h>
#include <inttypes.h>
#include <sys/types.h>
#endif /* _MSC_VER */
#ifdef _WIN32
#include <winsock2.h>
#else /* _WIN32 */
#include <sys/select.h> /* for fd_set * */
#include <netdb.h>
#endif /* _WIN32 */
#define SSH_STRINGIFY(s) SSH_TOSTRING(s)
#define SSH_TOSTRING(s) #s
/* libssh version macros */
#define SSH_VERSION_INT(a, b, c) ((a) << 16 | (b) << 8 | (c))
#define SSH_VERSION_DOT(a, b, c) a ##.## b ##.## c
#define SSH_VERSION(a, b, c) SSH_VERSION_DOT(a, b, c)
/* libssh version */
#define LIBSSH_VERSION_MAJOR 0
#define LIBSSH_VERSION_MINOR 7
#define LIBSSH_VERSION_MICRO 0
#define LIBSSH_VERSION_INT SSH_VERSION_INT(LIBSSH_VERSION_MAJOR, \
LIBSSH_VERSION_MINOR, \
LIBSSH_VERSION_MICRO)
#define LIBSSH_VERSION SSH_VERSION(LIBSSH_VERSION_MAJOR, \
LIBSSH_VERSION_MINOR, \
LIBSSH_VERSION_MICRO)
/* GCC have printf type attribute check. */
#ifdef __GNUC__
#define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
#else
#define PRINTF_ATTRIBUTE(a,b)
#endif /* __GNUC__ */
#ifdef __GNUC__
#define SSH_DEPRECATED __attribute__ ((deprecated))
#else
#define SSH_DEPRECATED
#endif
#ifdef __cplusplus
extern "C" {
#endif
struct ssh_counter_struct {
uint64_t in_bytes;
uint64_t out_bytes;
uint64_t in_packets;
uint64_t out_packets;
};
typedef struct ssh_counter_struct *ssh_counter;
typedef struct ssh_agent_struct* ssh_agent;
typedef struct ssh_buffer_struct* ssh_buffer;
typedef struct ssh_channel_struct* ssh_channel;
typedef struct ssh_message_struct* ssh_message;
typedef struct ssh_pcap_file_struct* ssh_pcap_file;
typedef struct ssh_key_struct* ssh_key;
typedef struct ssh_scp_struct* ssh_scp;
typedef struct ssh_session_struct* ssh_session;
typedef struct ssh_string_struct* ssh_string;
typedef struct ssh_event_struct* ssh_event;
typedef struct ssh_connector_struct * ssh_connector;
typedef void* ssh_gssapi_creds;
/* Socket type */
#ifdef _WIN32
#ifndef socket_t
typedef SOCKET socket_t;
#endif /* socket_t */
#else /* _WIN32 */
#ifndef socket_t
typedef int socket_t;
#endif
#endif /* _WIN32 */
#define SSH_INVALID_SOCKET ((socket_t) -1)
/* the offsets of methods */
enum ssh_kex_types_e {
SSH_KEX=0,
SSH_HOSTKEYS,
SSH_CRYPT_C_S,
SSH_CRYPT_S_C,
SSH_MAC_C_S,
SSH_MAC_S_C,
SSH_COMP_C_S,
SSH_COMP_S_C,
SSH_LANG_C_S,
SSH_LANG_S_C
};
#define SSH_CRYPT 2
#define SSH_MAC 3
#define SSH_COMP 4
#define SSH_LANG 5
enum ssh_auth_e {
SSH_AUTH_SUCCESS=0,
SSH_AUTH_DENIED,
SSH_AUTH_PARTIAL,
SSH_AUTH_INFO,
SSH_AUTH_AGAIN,
SSH_AUTH_ERROR=-1
};
/* auth flags */
#define SSH_AUTH_METHOD_UNKNOWN 0
#define SSH_AUTH_METHOD_NONE 0x0001
#define SSH_AUTH_METHOD_PASSWORD 0x0002
#define SSH_AUTH_METHOD_PUBLICKEY 0x0004
#define SSH_AUTH_METHOD_HOSTBASED 0x0008
#define SSH_AUTH_METHOD_INTERACTIVE 0x0010
#define SSH_AUTH_METHOD_GSSAPI_MIC 0x0020
/* messages */
enum ssh_requests_e {
SSH_REQUEST_AUTH=1,
SSH_REQUEST_CHANNEL_OPEN,
SSH_REQUEST_CHANNEL,
SSH_REQUEST_SERVICE,
SSH_REQUEST_GLOBAL
};
enum ssh_channel_type_e {
SSH_CHANNEL_UNKNOWN=0,
SSH_CHANNEL_SESSION,
SSH_CHANNEL_DIRECT_TCPIP,
SSH_CHANNEL_FORWARDED_TCPIP,
SSH_CHANNEL_X11,
SSH_CHANNEL_AUTH_AGENT
};
enum ssh_channel_requests_e {
SSH_CHANNEL_REQUEST_UNKNOWN=0,
SSH_CHANNEL_REQUEST_PTY,
SSH_CHANNEL_REQUEST_EXEC,
SSH_CHANNEL_REQUEST_SHELL,
SSH_CHANNEL_REQUEST_ENV,
SSH_CHANNEL_REQUEST_SUBSYSTEM,
SSH_CHANNEL_REQUEST_WINDOW_CHANGE,
SSH_CHANNEL_REQUEST_X11
};
enum ssh_global_requests_e {
SSH_GLOBAL_REQUEST_UNKNOWN=0,
SSH_GLOBAL_REQUEST_TCPIP_FORWARD,
SSH_GLOBAL_REQUEST_CANCEL_TCPIP_FORWARD,
SSH_GLOBAL_REQUEST_KEEPALIVE
};
enum ssh_publickey_state_e {
SSH_PUBLICKEY_STATE_ERROR=-1,
SSH_PUBLICKEY_STATE_NONE=0,
SSH_PUBLICKEY_STATE_VALID=1,
SSH_PUBLICKEY_STATE_WRONG=2
};
/* Status flags */
/** Socket is closed */
#define SSH_CLOSED 0x01
/** Reading to socket won't block */
#define SSH_READ_PENDING 0x02
/** Session was closed due to an error */
#define SSH_CLOSED_ERROR 0x04
/** Output buffer not empty */
#define SSH_WRITE_PENDING 0x08
enum ssh_server_known_e {
SSH_SERVER_ERROR=-1,
SSH_SERVER_NOT_KNOWN=0,
SSH_SERVER_KNOWN_OK,
SSH_SERVER_KNOWN_CHANGED,
SSH_SERVER_FOUND_OTHER,
SSH_SERVER_FILE_NOT_FOUND
};
#ifndef MD5_DIGEST_LEN
#define MD5_DIGEST_LEN 16
#endif
/* errors */
enum ssh_error_types_e {
SSH_NO_ERROR=0,
SSH_REQUEST_DENIED,
SSH_FATAL,
SSH_EINTR
};
/* some types for keys */
enum ssh_keytypes_e{
SSH_KEYTYPE_UNKNOWN=0,
SSH_KEYTYPE_DSS=1,
SSH_KEYTYPE_RSA,
SSH_KEYTYPE_RSA1,
SSH_KEYTYPE_ECDSA,
SSH_KEYTYPE_ED25519,
SSH_KEYTYPE_DSS_CERT01,
SSH_KEYTYPE_RSA_CERT01
};
enum ssh_keycmp_e {
SSH_KEY_CMP_PUBLIC = 0,
SSH_KEY_CMP_PRIVATE
};
/* Error return codes */
#define SSH_OK 0 /* No error */
#define SSH_ERROR -1 /* Error of some kind */
#define SSH_AGAIN -2 /* The nonblocking call must be repeated */
#define SSH_EOF -127 /* We have already a eof */
/**
* @addtogroup libssh_log
*
* @{
*/
enum {
/** No logging at all
*/
SSH_LOG_NOLOG=0,
/** Only warnings
*/
SSH_LOG_WARNING,
/** High level protocol information
*/
SSH_LOG_PROTOCOL,
/** Lower level protocol infomations, packet level
*/
SSH_LOG_PACKET,
/** Every function path
*/
SSH_LOG_FUNCTIONS
};
/** @} */
#define SSH_LOG_RARE SSH_LOG_WARNING
/**
* @name Logging levels
*
* @brief Debug levels for logging.
* @{
*/
/** No logging at all */
#define SSH_LOG_NONE 0
/** Show only warnings */
#define SSH_LOG_WARN 1
/** Get some information what's going on */
#define SSH_LOG_INFO 2
/** Get detailed debuging information **/
#define SSH_LOG_DEBUG 3
/** Get trace output, packet information, ... */
#define SSH_LOG_TRACE 4
/** @} */
enum ssh_options_e {
SSH_OPTIONS_HOST,
SSH_OPTIONS_PORT,
SSH_OPTIONS_PORT_STR,
SSH_OPTIONS_FD,
SSH_OPTIONS_USER,
SSH_OPTIONS_SSH_DIR,
SSH_OPTIONS_IDENTITY,
SSH_OPTIONS_ADD_IDENTITY,
SSH_OPTIONS_KNOWNHOSTS,
SSH_OPTIONS_TIMEOUT,
SSH_OPTIONS_TIMEOUT_USEC,
SSH_OPTIONS_SSH1,
SSH_OPTIONS_SSH2,
SSH_OPTIONS_LOG_VERBOSITY,
SSH_OPTIONS_LOG_VERBOSITY_STR,
SSH_OPTIONS_CIPHERS_C_S,
SSH_OPTIONS_CIPHERS_S_C,
SSH_OPTIONS_COMPRESSION_C_S,
SSH_OPTIONS_COMPRESSION_S_C,
SSH_OPTIONS_PROXYCOMMAND,
SSH_OPTIONS_BINDADDR,
SSH_OPTIONS_STRICTHOSTKEYCHECK,
SSH_OPTIONS_COMPRESSION,
SSH_OPTIONS_COMPRESSION_LEVEL,
SSH_OPTIONS_KEY_EXCHANGE,
SSH_OPTIONS_HOSTKEYS,
SSH_OPTIONS_GSSAPI_SERVER_IDENTITY,
SSH_OPTIONS_GSSAPI_CLIENT_IDENTITY,
SSH_OPTIONS_GSSAPI_DELEGATE_CREDENTIALS,
SSH_OPTIONS_HMAC_C_S,
SSH_OPTIONS_HMAC_S_C,
};
enum {
/** Code is going to write/create remote files */
SSH_SCP_WRITE,
/** Code is going to read remote files */
SSH_SCP_READ,
SSH_SCP_RECURSIVE=0x10
};
enum ssh_scp_request_types {
/** A new directory is going to be pulled */
SSH_SCP_REQUEST_NEWDIR=1,
/** A new file is going to be pulled */
SSH_SCP_REQUEST_NEWFILE,
/** End of requests */
SSH_SCP_REQUEST_EOF,
/** End of directory */
SSH_SCP_REQUEST_ENDDIR,
/** Warning received */
SSH_SCP_REQUEST_WARNING
};
enum ssh_connector_flags_e {
/** Only the standard stream of the channel */
SSH_CONNECTOR_STDOUT = 1,
/** Only the exception stream of the channel */
SSH_CONNECTOR_STDERR = 2,
/** Merge both standard and exception streams */
SSH_CONNECTOR_BOTH = 3
};
LIBSSH_API int ssh_blocking_flush(ssh_session session, int timeout);
LIBSSH_API ssh_channel ssh_channel_accept_x11(ssh_channel channel, int timeout_ms);
LIBSSH_API int ssh_channel_change_pty_size(ssh_channel channel,int cols,int rows);
LIBSSH_API int ssh_channel_close(ssh_channel channel);
LIBSSH_API void ssh_channel_free(ssh_channel channel);
LIBSSH_API int ssh_channel_get_exit_status(ssh_channel channel);
LIBSSH_API ssh_session ssh_channel_get_session(ssh_channel channel);
LIBSSH_API int ssh_channel_is_closed(ssh_channel channel);
LIBSSH_API int ssh_channel_is_eof(ssh_channel channel);
LIBSSH_API int ssh_channel_is_open(ssh_channel channel);
LIBSSH_API ssh_channel ssh_channel_new(ssh_session session);
LIBSSH_API int ssh_channel_open_auth_agent(ssh_channel channel);
LIBSSH_API int ssh_channel_open_forward(ssh_channel channel, const char *remotehost,
int remoteport, const char *sourcehost, int localport);
LIBSSH_API int ssh_channel_open_session(ssh_channel channel);
LIBSSH_API int ssh_channel_open_x11(ssh_channel channel, const char *orig_addr, int orig_port);
LIBSSH_API int ssh_channel_poll(ssh_channel channel, int is_stderr);
LIBSSH_API int ssh_channel_poll_timeout(ssh_channel channel, int timeout, int is_stderr);
LIBSSH_API int ssh_channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr);
LIBSSH_API int ssh_channel_read_timeout(ssh_channel channel, void *dest, uint32_t count, int is_stderr, int timeout_ms);
LIBSSH_API int ssh_channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count,
int is_stderr);
LIBSSH_API int ssh_channel_request_env(ssh_channel channel, const char *name, const char *value);
LIBSSH_API int ssh_channel_request_exec(ssh_channel channel, const char *cmd);
LIBSSH_API int ssh_channel_request_pty(ssh_channel channel);
LIBSSH_API int ssh_channel_request_pty_size(ssh_channel channel, const char *term,
int cols, int rows);
LIBSSH_API int ssh_channel_request_shell(ssh_channel channel);
LIBSSH_API int ssh_channel_request_send_signal(ssh_channel channel, const char *signum);
LIBSSH_API int ssh_channel_request_sftp(ssh_channel channel);
LIBSSH_API int ssh_channel_request_subsystem(ssh_channel channel, const char *subsystem);
LIBSSH_API int ssh_channel_request_x11(ssh_channel channel, int single_connection, const char *protocol,
const char *cookie, int screen_number);
LIBSSH_API int ssh_channel_request_auth_agent(ssh_channel channel);
LIBSSH_API int ssh_channel_send_eof(ssh_channel channel);
LIBSSH_API int ssh_channel_select(ssh_channel *readchans, ssh_channel *writechans, ssh_channel *exceptchans, struct
timeval * timeout);
LIBSSH_API void ssh_channel_set_blocking(ssh_channel channel, int blocking);
LIBSSH_API void ssh_channel_set_counter(ssh_channel channel,
ssh_counter counter);
LIBSSH_API int ssh_channel_write(ssh_channel channel, const void *data, uint32_t len);
LIBSSH_API int ssh_channel_write_stderr(ssh_channel channel,
const void *data,
uint32_t len);
LIBSSH_API uint32_t ssh_channel_window_size(ssh_channel channel);
LIBSSH_API char *ssh_basename (const char *path);
LIBSSH_API void ssh_clean_pubkey_hash(unsigned char **hash);
LIBSSH_API int ssh_connect(ssh_session session);
LIBSSH_API ssh_connector ssh_connector_new(ssh_session session);
LIBSSH_API void ssh_connector_free(ssh_connector connector);
LIBSSH_API int ssh_connector_set_in_channel(ssh_connector connector,
ssh_channel channel,
enum ssh_connector_flags_e flags);
LIBSSH_API int ssh_connector_set_out_channel(ssh_connector connector,
ssh_channel channel,
enum ssh_connector_flags_e flags);
LIBSSH_API void ssh_connector_set_in_fd(ssh_connector connector, socket_t fd);
LIBSSH_API void ssh_connector_set_out_fd(ssh_connector connector, socket_t fd);
LIBSSH_API const char *ssh_copyright(void);
LIBSSH_API void ssh_disconnect(ssh_session session);
LIBSSH_API char *ssh_dirname (const char *path);
LIBSSH_API int ssh_finalize(void);
/* REVERSE PORT FORWARDING */
LIBSSH_API ssh_channel ssh_channel_accept_forward(ssh_session session,
int timeout_ms,
int *destination_port);
LIBSSH_API int ssh_channel_cancel_forward(ssh_session session,
const char *address,
int port);
LIBSSH_API int ssh_channel_listen_forward(ssh_session session,
const char *address,
int port,
int *bound_port);
LIBSSH_API void ssh_free(ssh_session session);
LIBSSH_API const char *ssh_get_disconnect_message(ssh_session session);
LIBSSH_API const char *ssh_get_error(void *error);
LIBSSH_API int ssh_get_error_code(void *error);
LIBSSH_API socket_t ssh_get_fd(ssh_session session);
LIBSSH_API char *ssh_get_hexa(const unsigned char *what, size_t len);
LIBSSH_API char *ssh_get_issue_banner(ssh_session session);
LIBSSH_API int ssh_get_openssh_version(ssh_session session);
LIBSSH_API int ssh_get_server_publickey(ssh_session session, ssh_key *key);
enum ssh_publickey_hash_type {
SSH_PUBLICKEY_HASH_SHA1,
SSH_PUBLICKEY_HASH_MD5
};
LIBSSH_API int ssh_get_publickey_hash(const ssh_key key,
enum ssh_publickey_hash_type type,
unsigned char **hash,
size_t *hlen);
/* DEPRECATED FUNCTIONS */
SSH_DEPRECATED LIBSSH_API int ssh_get_pubkey_hash(ssh_session session, unsigned char **hash);
SSH_DEPRECATED LIBSSH_API ssh_channel ssh_forward_accept(ssh_session session, int timeout_ms);
SSH_DEPRECATED LIBSSH_API int ssh_forward_cancel(ssh_session session, const char *address, int port);
SSH_DEPRECATED LIBSSH_API int ssh_forward_listen(ssh_session session, const char *address, int port, int *bound_port);
SSH_DEPRECATED LIBSSH_API int ssh_get_publickey(ssh_session session, ssh_key *key);
LIBSSH_API int ssh_get_random(void *where,int len,int strong);
LIBSSH_API int ssh_get_version(ssh_session session);
LIBSSH_API int ssh_get_status(ssh_session session);
LIBSSH_API int ssh_get_poll_flags(ssh_session session);
LIBSSH_API int ssh_init(void);
LIBSSH_API int ssh_is_blocking(ssh_session session);
LIBSSH_API int ssh_is_connected(ssh_session session);
LIBSSH_API int ssh_is_server_known(ssh_session session);
/* LOGGING */
LIBSSH_API int ssh_set_log_level(int level);
LIBSSH_API int ssh_get_log_level(void);
LIBSSH_API void *ssh_get_log_userdata(void);
LIBSSH_API int ssh_set_log_userdata(void *data);
LIBSSH_API void _ssh_log(int verbosity,
const char *function,
const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
/* legacy */
SSH_DEPRECATED LIBSSH_API void ssh_log(ssh_session session,
int prioriry,
const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
LIBSSH_API ssh_channel ssh_message_channel_request_open_reply_accept(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_reply_success(ssh_message msg);
LIBSSH_API void ssh_message_free(ssh_message msg);
LIBSSH_API ssh_message ssh_message_get(ssh_session session);
LIBSSH_API int ssh_message_subtype(ssh_message msg);
LIBSSH_API int ssh_message_type(ssh_message msg);
LIBSSH_API int ssh_mkdir (const char *pathname, mode_t mode);
LIBSSH_API ssh_session ssh_new(void);
LIBSSH_API int ssh_options_copy(ssh_session src, ssh_session *dest);
LIBSSH_API int ssh_options_getopt(ssh_session session, int *argcptr, char **argv);
LIBSSH_API int ssh_options_parse_config(ssh_session session, const char *filename);
LIBSSH_API int ssh_options_set(ssh_session session, enum ssh_options_e type,
const void *value);
LIBSSH_API int ssh_options_get(ssh_session session, enum ssh_options_e type,
char **value);
LIBSSH_API int ssh_options_get_port(ssh_session session, unsigned int * port_target);
LIBSSH_API int ssh_pcap_file_close(ssh_pcap_file pcap);
LIBSSH_API void ssh_pcap_file_free(ssh_pcap_file pcap);
LIBSSH_API ssh_pcap_file ssh_pcap_file_new(void);
LIBSSH_API int ssh_pcap_file_open(ssh_pcap_file pcap, const char *filename);
/**
* @brief SSH authentication callback.
*
* @param prompt Prompt to be displayed.
* @param buf Buffer to save the password. You should null-terminate it.
* @param len Length of the buffer.
* @param echo Enable or disable the echo of what you type.
* @param verify Should the password be verified?
* @param userdata Userdata to be passed to the callback function. Useful
* for GUI applications.
*
* @return 0 on success, < 0 on error.
*/
typedef int (*ssh_auth_callback) (const char *prompt, char *buf, size_t len,
int echo, int verify, void *userdata);
LIBSSH_API ssh_key ssh_key_new(void);
LIBSSH_API void ssh_key_free (ssh_key key);
LIBSSH_API enum ssh_keytypes_e ssh_key_type(const ssh_key key);
LIBSSH_API const char *ssh_key_type_to_char(enum ssh_keytypes_e type);
LIBSSH_API enum ssh_keytypes_e ssh_key_type_from_name(const char *name);
LIBSSH_API int ssh_key_is_public(const ssh_key k);
LIBSSH_API int ssh_key_is_private(const ssh_key k);
LIBSSH_API int ssh_key_cmp(const ssh_key k1,
const ssh_key k2,
enum ssh_keycmp_e what);
LIBSSH_API int ssh_pki_generate(enum ssh_keytypes_e type, int parameter,
ssh_key *pkey);
LIBSSH_API int ssh_pki_import_privkey_base64(const char *b64_key,
const char *passphrase,
ssh_auth_callback auth_fn,
void *auth_data,
ssh_key *pkey);
LIBSSH_API int ssh_pki_import_privkey_file(const char *filename,
const char *passphrase,
ssh_auth_callback auth_fn,
void *auth_data,
ssh_key *pkey);
LIBSSH_API int ssh_pki_export_privkey_file(const ssh_key privkey,
const char *passphrase,
ssh_auth_callback auth_fn,
void *auth_data,
const char *filename);
LIBSSH_API int ssh_pki_copy_cert_to_privkey(const ssh_key cert_key,
ssh_key privkey);
LIBSSH_API int ssh_pki_import_pubkey_base64(const char *b64_key,
enum ssh_keytypes_e type,
ssh_key *pkey);
LIBSSH_API int ssh_pki_import_pubkey_file(const char *filename,
ssh_key *pkey);
LIBSSH_API int ssh_pki_import_cert_base64(const char *b64_cert,
enum ssh_keytypes_e type,
ssh_key *pkey);
LIBSSH_API int ssh_pki_import_cert_file(const char *filename,
ssh_key *pkey);
LIBSSH_API int ssh_pki_export_privkey_to_pubkey(const ssh_key privkey,
ssh_key *pkey);
LIBSSH_API int ssh_pki_export_pubkey_base64(const ssh_key key,
char **b64_key);
LIBSSH_API int ssh_pki_export_pubkey_file(const ssh_key key,
const char *filename);
LIBSSH_API const char *ssh_pki_key_ecdsa_name(const ssh_key key);
LIBSSH_API void ssh_print_hexa(const char *descr, const unsigned char *what, size_t len);
LIBSSH_API int ssh_send_ignore (ssh_session session, const char *data);
LIBSSH_API int ssh_send_debug (ssh_session session, const char *message, int always_display);
LIBSSH_API void ssh_gssapi_set_creds(ssh_session session, const ssh_gssapi_creds creds);
LIBSSH_API int ssh_scp_accept_request(ssh_scp scp);
LIBSSH_API int ssh_scp_close(ssh_scp scp);
LIBSSH_API int ssh_scp_deny_request(ssh_scp scp, const char *reason);
LIBSSH_API void ssh_scp_free(ssh_scp scp);
LIBSSH_API int ssh_scp_init(ssh_scp scp);
LIBSSH_API int ssh_scp_leave_directory(ssh_scp scp);
LIBSSH_API ssh_scp ssh_scp_new(ssh_session session, int mode, const char *location);
LIBSSH_API int ssh_scp_pull_request(ssh_scp scp);
LIBSSH_API int ssh_scp_push_directory(ssh_scp scp, const char *dirname, int mode);
LIBSSH_API int ssh_scp_push_file(ssh_scp scp, const char *filename, size_t size, int perms);
LIBSSH_API int ssh_scp_push_file64(ssh_scp scp, const char *filename, uint64_t size, int perms);
LIBSSH_API int ssh_scp_read(ssh_scp scp, void *buffer, size_t size);
LIBSSH_API const char *ssh_scp_request_get_filename(ssh_scp scp);
LIBSSH_API int ssh_scp_request_get_permissions(ssh_scp scp);
LIBSSH_API size_t ssh_scp_request_get_size(ssh_scp scp);
LIBSSH_API uint64_t ssh_scp_request_get_size64(ssh_scp scp);
LIBSSH_API const char *ssh_scp_request_get_warning(ssh_scp scp);
LIBSSH_API int ssh_scp_write(ssh_scp scp, const void *buffer, size_t len);
LIBSSH_API int ssh_select(ssh_channel *channels, ssh_channel *outchannels, socket_t maxfd,
fd_set *readfds, struct timeval *timeout);
LIBSSH_API int ssh_service_request(ssh_session session, const char *service);
LIBSSH_API int ssh_set_agent_channel(ssh_session session, ssh_channel channel);
LIBSSH_API int ssh_set_agent_socket(ssh_session session, socket_t fd);
LIBSSH_API void ssh_set_blocking(ssh_session session, int blocking);
LIBSSH_API void ssh_set_counters(ssh_session session, ssh_counter scounter,
ssh_counter rcounter);
LIBSSH_API void ssh_set_fd_except(ssh_session session);
LIBSSH_API void ssh_set_fd_toread(ssh_session session);
LIBSSH_API void ssh_set_fd_towrite(ssh_session session);
LIBSSH_API void ssh_silent_disconnect(ssh_session session);
LIBSSH_API int ssh_set_pcap_file(ssh_session session, ssh_pcap_file pcapfile);
/* USERAUTH */
LIBSSH_API int ssh_userauth_none(ssh_session session, const char *username);
LIBSSH_API int ssh_userauth_list(ssh_session session, const char *username);
LIBSSH_API int ssh_userauth_try_publickey(ssh_session session,
const char *username,
const ssh_key pubkey);
LIBSSH_API int ssh_userauth_publickey(ssh_session session,
const char *username,
const ssh_key privkey);
#ifndef _WIN32
LIBSSH_API int ssh_userauth_agent(ssh_session session,
const char *username);
#endif
LIBSSH_API int ssh_userauth_publickey_auto(ssh_session session,
const char *username,
const char *passphrase);
LIBSSH_API int ssh_userauth_password(ssh_session session,
const char *username,
const char *password);
LIBSSH_API int ssh_userauth_kbdint(ssh_session session, const char *user, const char *submethods);
LIBSSH_API const char *ssh_userauth_kbdint_getinstruction(ssh_session session);
LIBSSH_API const char *ssh_userauth_kbdint_getname(ssh_session session);
LIBSSH_API int ssh_userauth_kbdint_getnprompts(ssh_session session);
LIBSSH_API const char *ssh_userauth_kbdint_getprompt(ssh_session session, unsigned int i, char *echo);
LIBSSH_API int ssh_userauth_kbdint_getnanswers(ssh_session session);
LIBSSH_API const char *ssh_userauth_kbdint_getanswer(ssh_session session, unsigned int i);
LIBSSH_API int ssh_userauth_kbdint_setanswer(ssh_session session, unsigned int i,
const char *answer);
LIBSSH_API int ssh_userauth_gssapi(ssh_session session);
LIBSSH_API const char *ssh_version(int req_version);
LIBSSH_API int ssh_write_knownhost(ssh_session session);
LIBSSH_API void ssh_string_burn(ssh_string str);
LIBSSH_API ssh_string ssh_string_copy(ssh_string str);
LIBSSH_API void *ssh_string_data(ssh_string str);
LIBSSH_API int ssh_string_fill(ssh_string str, const void *data, size_t len);
LIBSSH_API void ssh_string_free(ssh_string str);
LIBSSH_API ssh_string ssh_string_from_char(const char *what);
LIBSSH_API size_t ssh_string_len(ssh_string str);
LIBSSH_API ssh_string ssh_string_new(size_t size);
LIBSSH_API const char *ssh_string_get_char(ssh_string str);
LIBSSH_API char *ssh_string_to_char(ssh_string str);
LIBSSH_API void ssh_string_free_char(char *s);
LIBSSH_API int ssh_getpass(const char *prompt, char *buf, size_t len, int echo,
int verify);
typedef int (*ssh_event_callback)(socket_t fd, int revents, void *userdata);
LIBSSH_API ssh_event ssh_event_new(void);
LIBSSH_API int ssh_event_add_fd(ssh_event event, socket_t fd, short events,
ssh_event_callback cb, void *userdata);
LIBSSH_API int ssh_event_add_session(ssh_event event, ssh_session session);
LIBSSH_API int ssh_event_add_connector(ssh_event event, ssh_connector connector);
LIBSSH_API int ssh_event_dopoll(ssh_event event, int timeout);
LIBSSH_API int ssh_event_remove_fd(ssh_event event, socket_t fd);
LIBSSH_API int ssh_event_remove_session(ssh_event event, ssh_session session);
LIBSSH_API int ssh_event_remove_connector(ssh_event event, ssh_connector connector);
LIBSSH_API void ssh_event_free(ssh_event event);
LIBSSH_API const char* ssh_get_clientbanner(ssh_session session);
LIBSSH_API const char* ssh_get_serverbanner(ssh_session session);
LIBSSH_API const char* ssh_get_kex_algo(ssh_session session);
LIBSSH_API const char* ssh_get_cipher_in(ssh_session session);
LIBSSH_API const char* ssh_get_cipher_out(ssh_session session);
LIBSSH_API const char* ssh_get_hmac_in(ssh_session session);
LIBSSH_API const char* ssh_get_hmac_out(ssh_session session);
LIBSSH_API ssh_buffer ssh_buffer_new(void);
LIBSSH_API void ssh_buffer_free(ssh_buffer buffer);
LIBSSH_API int ssh_buffer_reinit(ssh_buffer buffer);
LIBSSH_API int ssh_buffer_add_data(ssh_buffer buffer, const void *data, uint32_t len);
LIBSSH_API uint32_t ssh_buffer_get_data(ssh_buffer buffer, void *data, uint32_t requestedlen);
LIBSSH_API void *ssh_buffer_get(ssh_buffer buffer);
LIBSSH_API uint32_t ssh_buffer_get_len(ssh_buffer buffer);
#ifndef LIBSSH_LEGACY_0_4
#include "libssh/legacy.h"
#endif
#ifdef __cplusplus
}
#endif
#endif /* _LIBSSH_H */
/* vim: set ts=2 sw=2 et cindent: */

View File

@ -1,614 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef LIBSSHPP_HPP_
#define LIBSSHPP_HPP_
/**
* @defgroup ssh_cpp The libssh C++ wrapper
*
* The C++ bindings for libssh are completely embedded in a single .hpp file, and
* this for two reasons:
* - C++ is hard to keep binary compatible, C is easy. We try to keep libssh C version
* as much as possible binary compatible between releases, while this would be hard for
* C++. If you compile your program with these headers, you will only link to the C version
* of libssh which will be kept ABI compatible. No need to recompile your C++ program
* each time a new binary-compatible version of libssh is out
* - Most of the functions in this file are really short and are probably worth the "inline"
* linking mode, which the compiler can decide to do in some case. There would be nearly no
* performance penalty of using the wrapper rather than native calls.
*
* Please visit the documentation of ssh::Session and ssh::Channel
* @see ssh::Session
* @see ssh::Channel
*
* If you wish not to use C++ exceptions, please define SSH_NO_CPP_EXCEPTIONS:
* @code
* #define SSH_NO_CPP_EXCEPTIONS
* #include <libssh/libsshpp.hpp>
* @endcode
* All functions will then return SSH_ERROR in case of error.
* @{
*/
/* do not use deprecated functions */
#define LIBSSH_LEGACY_0_4
#include <libssh/libssh.h>
#include <libssh/server.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string>
namespace ssh {
class Channel;
/** Some people do not like C++ exceptions. With this define, we give
* the choice to use or not exceptions.
* @brief if defined, disable C++ exceptions for libssh c++ wrapper
*/
#ifndef SSH_NO_CPP_EXCEPTIONS
/** @brief This class describes a SSH Exception object. This object can be thrown
* by several SSH functions that interact with the network, and may fail because of
* socket, protocol or memory errors.
*/
class SshException{
public:
SshException(ssh_session csession){
code=ssh_get_error_code(csession);
description=std::string(ssh_get_error(csession));
}
SshException(const SshException &e){
code=e.code;
description=e.description;
}
/** @brief returns the Error code
* @returns SSH_FATAL Fatal error happened (not recoverable)
* @returns SSH_REQUEST_DENIED Request was denied by remote host
* @see ssh_get_error_code
*/
int getCode(){
return code;
}
/** @brief returns the error message of the last exception
* @returns pointer to a c string containing the description of error
* @see ssh_get_error
*/
std::string getError(){
return description;
}
private:
int code;
std::string description;
};
/** @internal
* @brief Macro to throw exception if there was an error
*/
#define ssh_throw(x) if((x)==SSH_ERROR) throw SshException(getCSession())
#define ssh_throw_null(CSession,x) if((x)==NULL) throw SshException(CSession)
#define void_throwable void
#define return_throwable return
#else
/* No exception at all. All functions will return an error code instead
* of an exception
*/
#define ssh_throw(x) if((x)==SSH_ERROR) return SSH_ERROR
#define ssh_throw_null(CSession,x) if((x)==NULL) return NULL
#define void_throwable int
#define return_throwable return SSH_OK
#endif
/**
* The ssh::Session class contains the state of a SSH connection.
*/
class Session {
friend class Channel;
public:
Session(){
c_session=ssh_new();
}
~Session(){
ssh_free(c_session);
c_session=NULL;
}
/** @brief sets an SSH session options
* @param type Type of option
* @param option cstring containing the value of option
* @throws SshException on error
* @see ssh_options_set
*/
void_throwable setOption(enum ssh_options_e type, const char *option){
ssh_throw(ssh_options_set(c_session,type,option));
return_throwable;
}
/** @brief sets an SSH session options
* @param type Type of option
* @param option long integer containing the value of option
* @throws SshException on error
* @see ssh_options_set
*/
void_throwable setOption(enum ssh_options_e type, long int option){
ssh_throw(ssh_options_set(c_session,type,&option));
return_throwable;
}
/** @brief sets an SSH session options
* @param type Type of option
* @param option void pointer containing the value of option
* @throws SshException on error
* @see ssh_options_set
*/
void_throwable setOption(enum ssh_options_e type, void *option){
ssh_throw(ssh_options_set(c_session,type,option));
return_throwable;
}
/** @brief connects to the remote host
* @throws SshException on error
* @see ssh_connect
*/
void_throwable connect(){
int ret=ssh_connect(c_session);
ssh_throw(ret);
return_throwable;
}
/** @brief Authenticates automatically using public key
* @throws SshException on error
* @returns SSH_AUTH_SUCCESS, SSH_AUTH_PARTIAL, SSH_AUTH_DENIED
* @see ssh_userauth_autopubkey
*/
int userauthPublickeyAuto(void){
int ret=ssh_userauth_publickey_auto(c_session, NULL, NULL);
ssh_throw(ret);
return ret;
}
/** @brief Authenticates using the "none" method. Prefer using autopubkey if
* possible.
* @throws SshException on error
* @returns SSH_AUTH_SUCCESS, SSH_AUTH_PARTIAL, SSH_AUTH_DENIED
* @see ssh_userauth_none
* @see Session::userauthAutoPubkey
*/
int userauthNone(){
int ret=ssh_userauth_none(c_session,NULL);
ssh_throw(ret);
return ret;
}
/** @brief Authenticates using the password method.
* @param[in] password password to use for authentication
* @throws SshException on error
* @returns SSH_AUTH_SUCCESS, SSH_AUTH_PARTIAL, SSH_AUTH_DENIED
* @see ssh_userauth_password
*/
int userauthPassword(const char *password){
int ret=ssh_userauth_password(c_session,NULL,password);
ssh_throw(ret);
return ret;
}
/** @brief Try to authenticate using the publickey method.
* @param[in] pubkey public key to use for authentication
* @throws SshException on error
* @returns SSH_AUTH_SUCCESS if the pubkey is accepted,
* @returns SSH_AUTH_DENIED if the pubkey is denied
* @see ssh_userauth_try_pubkey
*/
int userauthTryPublickey(ssh_key pubkey){
int ret=ssh_userauth_try_publickey(c_session, NULL, pubkey);
ssh_throw(ret);
return ret;
}
/** @brief Authenticates using the publickey method.
* @param[in] privkey private key to use for authentication
* @throws SshException on error
* @returns SSH_AUTH_SUCCESS, SSH_AUTH_PARTIAL, SSH_AUTH_DENIED
* @see ssh_userauth_pubkey
*/
int userauthPublickey(ssh_key privkey){
int ret=ssh_userauth_publickey(c_session, NULL, privkey);
ssh_throw(ret);
return ret;
}
int userauthPrivatekeyFile(const char *filename,
const char *passphrase);
/** @brief Returns the available authentication methods from the server
* @throws SshException on error
* @returns Bitfield of available methods.
* @see ssh_userauth_list
*/
int getAuthList(){
int ret=ssh_userauth_list(c_session, NULL);
ssh_throw(ret);
return ret;
}
/** @brief Disconnects from the SSH server and closes connection
* @see ssh_disconnect
*/
void disconnect(){
ssh_disconnect(c_session);
}
/** @brief Returns the disconnect message from the server, if any
* @returns pointer to the message, or NULL. Do not attempt to free
* the pointer.
*/
const char *getDisconnectMessage(){
const char *msg=ssh_get_disconnect_message(c_session);
return msg;
}
/** @internal
* @brief gets error message
*/
const char *getError(){
return ssh_get_error(c_session);
}
/** @internal
* @brief returns error code
*/
int getErrorCode(){
return ssh_get_error_code(c_session);
}
/** @brief returns the file descriptor used for the communication
* @returns the file descriptor
* @warning if a proxycommand is used, this function will only return
* one of the two file descriptors being used
* @see ssh_get_fd
*/
socket_t getSocket(){
return ssh_get_fd(c_session);
}
/** @brief gets the Issue banner from the ssh server
* @returns the issue banner. This is generally a MOTD from server
* @see ssh_get_issue_banner
*/
std::string getIssueBanner(){
char *banner=ssh_get_issue_banner(c_session);
std::string ret= std::string(banner);
::free(banner);
return ret;
}
/** @brief returns the OpenSSH version (server) if possible
* @returns openssh version code
* @see ssh_get_openssh_version
*/
int getOpensshVersion(){
return ssh_get_openssh_version(c_session);
}
/** @brief returns the version of the SSH protocol being used
* @returns the SSH protocol version
* @see ssh_get_version
*/
int getVersion(){
return ssh_get_version(c_session);
}
/** @brief verifies that the server is known
* @throws SshException on error
* @returns Integer value depending on the knowledge of the
* server key
* @see ssh_is_server_known
*/
int isServerKnown(){
int ret=ssh_is_server_known(c_session);
ssh_throw(ret);
return ret;
}
void log(int priority, const char *format, ...){
char buffer[1024];
va_list va;
va_start(va, format);
vsnprintf(buffer, sizeof(buffer), format, va);
va_end(va);
_ssh_log(priority, "libsshpp", "%s", buffer);
}
/** @brief copies options from a session to another
* @throws SshException on error
* @see ssh_options_copy
*/
void_throwable optionsCopy(const Session &source){
ssh_throw(ssh_options_copy(source.c_session,&c_session));
return_throwable;
}
/** @brief parses a configuration file for options
* @throws SshException on error
* @param[in] file configuration file name
* @see ssh_options_parse_config
*/
void_throwable optionsParseConfig(const char *file){
ssh_throw(ssh_options_parse_config(c_session,file));
return_throwable;
}
/** @brief silently disconnect from remote host
* @see ssh_silent_disconnect
*/
void silentDisconnect(){
ssh_silent_disconnect(c_session);
}
/** @brief Writes the known host file with current
* host key
* @throws SshException on error
* @see ssh_write_knownhost
*/
int writeKnownhost(){
int ret = ssh_write_knownhost(c_session);
ssh_throw(ret);
return ret;
}
/** @brief accept an incoming forward connection
* @param[in] timeout_ms timeout for waiting, in ms
* @returns new Channel pointer on the forward connection
* @returns NULL in case of error
* @warning you have to delete this pointer after use
* @see ssh_channel_forward_accept
* @see Session::listenForward
*/
inline Channel *acceptForward(int timeout_ms);
/* implemented outside the class due Channel references */
void_throwable cancelForward(const char *address, int port){
int err=ssh_channel_cancel_forward(c_session, address, port);
ssh_throw(err);
return_throwable;
}
void_throwable listenForward(const char *address, int port,
int &boundport){
int err=ssh_channel_listen_forward(c_session, address, port, &boundport);
ssh_throw(err);
return_throwable;
}
private:
ssh_session c_session;
ssh_session getCSession(){
return c_session;
}
/* No copy constructor, no = operator */
Session(const Session &);
Session& operator=(const Session &);
};
/** @brief the ssh::Channel class describes the state of an SSH
* channel.
* @see ssh_channel
*/
class Channel {
friend class Session;
public:
Channel(Session &session){
channel=ssh_channel_new(session.getCSession());
this->session=&session;
}
~Channel(){
ssh_channel_free(channel);
channel=NULL;
}
/** @brief accept an incoming X11 connection
* @param[in] timeout_ms timeout for waiting, in ms
* @returns new Channel pointer on the X11 connection
* @returns NULL in case of error
* @warning you have to delete this pointer after use
* @see ssh_channel_accept_x11
* @see Channel::requestX11
*/
Channel *acceptX11(int timeout_ms){
ssh_channel x11chan = ssh_channel_accept_x11(channel,timeout_ms);
ssh_throw_null(getCSession(),x11chan);
Channel *newchan = new Channel(getSession(),x11chan);
return newchan;
}
/** @brief change the size of a pseudoterminal
* @param[in] cols number of columns
* @param[in] rows number of rows
* @throws SshException on error
* @see ssh_channel_change_pty_size
*/
void_throwable changePtySize(int cols, int rows){
int err=ssh_channel_change_pty_size(channel,cols,rows);
ssh_throw(err);
return_throwable;
}
/** @brief closes a channel
* @throws SshException on error
* @see ssh_channel_close
*/
void_throwable close(){
ssh_throw(ssh_channel_close(channel));
return_throwable;
}
int getExitStatus(){
return ssh_channel_get_exit_status(channel);
}
Session &getSession(){
return *session;
}
/** @brief returns true if channel is in closed state
* @see ssh_channel_is_closed
*/
bool isClosed(){
return ssh_channel_is_closed(channel) != 0;
}
/** @brief returns true if channel is in EOF state
* @see ssh_channel_is_eof
*/
bool isEof(){
return ssh_channel_is_eof(channel) != 0;
}
/** @brief returns true if channel is in open state
* @see ssh_channel_is_open
*/
bool isOpen(){
return ssh_channel_is_open(channel) != 0;
}
int openForward(const char *remotehost, int remoteport,
const char *sourcehost=NULL, int localport=0){
int err=ssh_channel_open_forward(channel,remotehost,remoteport,
sourcehost, localport);
ssh_throw(err);
return err;
}
/* TODO: completely remove this ? */
void_throwable openSession(){
int err=ssh_channel_open_session(channel);
ssh_throw(err);
return_throwable;
}
int poll(bool is_stderr=false){
int err=ssh_channel_poll(channel,is_stderr);
ssh_throw(err);
return err;
}
int read(void *dest, size_t count, bool is_stderr){
int err;
/* handle int overflow */
if(count > 0x7fffffff)
count = 0x7fffffff;
err=ssh_channel_read_timeout(channel,dest,count,is_stderr,-1);
ssh_throw(err);
return err;
}
int read(void *dest, size_t count, int timeout){
int err;
/* handle int overflow */
if(count > 0x7fffffff)
count = 0x7fffffff;
err=ssh_channel_read_timeout(channel,dest,count,false,timeout);
ssh_throw(err);
return err;
}
int read(void *dest, size_t count, bool is_stderr=false, int timeout=-1){
int err;
/* handle int overflow */
if(count > 0x7fffffff)
count = 0x7fffffff;
err=ssh_channel_read_timeout(channel,dest,count,is_stderr,timeout);
ssh_throw(err);
return err;
}
int readNonblocking(void *dest, size_t count, bool is_stderr=false){
int err;
/* handle int overflow */
if(count > 0x7fffffff)
count = 0x7fffffff;
err=ssh_channel_read_nonblocking(channel,dest,count,is_stderr);
ssh_throw(err);
return err;
}
void_throwable requestEnv(const char *name, const char *value){
int err=ssh_channel_request_env(channel,name,value);
ssh_throw(err);
return_throwable;
}
void_throwable requestExec(const char *cmd){
int err=ssh_channel_request_exec(channel,cmd);
ssh_throw(err);
return_throwable;
}
void_throwable requestPty(const char *term=NULL, int cols=0, int rows=0){
int err;
if(term != NULL && cols != 0 && rows != 0)
err=ssh_channel_request_pty_size(channel,term,cols,rows);
else
err=ssh_channel_request_pty(channel);
ssh_throw(err);
return_throwable;
}
void_throwable requestShell(){
int err=ssh_channel_request_shell(channel);
ssh_throw(err);
return_throwable;
}
void_throwable requestSendSignal(const char *signum){
int err=ssh_channel_request_send_signal(channel, signum);
ssh_throw(err);
return_throwable;
}
void_throwable requestSubsystem(const char *subsystem){
int err=ssh_channel_request_subsystem(channel,subsystem);
ssh_throw(err);
return_throwable;
}
int requestX11(bool single_connection,
const char *protocol, const char *cookie, int screen_number){
int err=ssh_channel_request_x11(channel,single_connection,
protocol, cookie, screen_number);
ssh_throw(err);
return err;
}
void_throwable sendEof(){
int err=ssh_channel_send_eof(channel);
ssh_throw(err);
return_throwable;
}
/** @brief Writes on a channel
* @param data data to write.
* @param len number of bytes to write.
* @param is_stderr write should be done on the stderr channel (server only)
* @returns number of bytes written
* @throws SshException in case of error
* @see channel_write
* @see channel_write_stderr
*/
int write(const void *data, size_t len, bool is_stderr=false){
int ret;
if(is_stderr){
ret=ssh_channel_write_stderr(channel,data,len);
} else {
ret=ssh_channel_write(channel,data,len);
}
ssh_throw(ret);
return ret;
}
private:
ssh_session getCSession(){
return session->getCSession();
}
Channel (Session &session, ssh_channel c_channel){
this->channel=c_channel;
this->session=&session;
}
Session *session;
ssh_channel channel;
/* No copy and no = operator */
Channel(const Channel &);
Channel &operator=(const Channel &);
};
inline Channel *Session::acceptForward(int timeout_ms){
ssh_channel forward =
ssh_channel_accept_forward(c_session, timeout_ms, NULL);
ssh_throw_null(c_session,forward);
Channel *newchan = new Channel(*this,forward);
return newchan;
}
} // namespace ssh
/** @} */
#endif /* LIBSSHPP_HPP_ */

View File

@ -1,108 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MESSAGES_H_
#define MESSAGES_H_
#include "config.h"
struct ssh_auth_request {
char *username;
int method;
char *password;
struct ssh_key_struct *pubkey;
char signature_state;
char kbdint_response;
};
struct ssh_channel_request_open {
int type;
uint32_t sender;
uint32_t window;
uint32_t packet_size;
char *originator;
uint16_t originator_port;
char *destination;
uint16_t destination_port;
};
struct ssh_service_request {
char *service;
};
struct ssh_global_request {
int type;
uint8_t want_reply;
char *bind_address;
uint16_t bind_port;
};
struct ssh_channel_request {
int type;
ssh_channel channel;
uint8_t want_reply;
/* pty-req type specifics */
char *TERM;
uint32_t width;
uint32_t height;
uint32_t pxwidth;
uint32_t pxheight;
ssh_string modes;
/* env type request */
char *var_name;
char *var_value;
/* exec type request */
char *command;
/* subsystem */
char *subsystem;
/* X11 */
uint8_t x11_single_connection;
char *x11_auth_protocol;
char *x11_auth_cookie;
uint32_t x11_screen_number;
};
struct ssh_message_struct {
ssh_session session;
int type;
struct ssh_auth_request auth_request;
struct ssh_channel_request_open channel_request_open;
struct ssh_channel_request channel_request;
struct ssh_service_request service_request;
struct ssh_global_request global_request;
};
SSH_PACKET_CALLBACK(ssh_packet_channel_open);
SSH_PACKET_CALLBACK(ssh_packet_global_request);
#ifdef WITH_SERVER
SSH_PACKET_CALLBACK(ssh_packet_service_request);
SSH_PACKET_CALLBACK(ssh_packet_userauth_request);
#endif /* WITH_SERVER */
int ssh_message_handle_channel_request(ssh_session session, ssh_channel channel, ssh_buffer packet,
const char *request, uint8_t want_reply);
void ssh_message_queue(ssh_session session, ssh_message message);
ssh_message ssh_message_pop_head(ssh_session session);
int ssh_message_channel_request_open_reply_accept_channel(ssh_message msg, ssh_channel chan);
#endif /* MESSAGES_H_ */

View File

@ -1,92 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MISC_H_
#define MISC_H_
/* in misc.c */
/* gets the user home dir. */
char *ssh_get_user_home_dir(void);
char *ssh_get_local_username(void);
int ssh_file_readaccess_ok(const char *file);
char *ssh_path_expand_tilde(const char *d);
char *ssh_path_expand_escape(ssh_session session, const char *s);
int ssh_analyze_banner(ssh_session session, int server, int *ssh1, int *ssh2);
int ssh_is_ipaddr_v4(const char *str);
int ssh_is_ipaddr(const char *str);
#ifndef HAVE_NTOHLL
/* macro for byte ordering */
uint64_t ntohll(uint64_t);
#endif
#ifndef HAVE_HTONLL
#define htonll(x) ntohll((x))
#endif
/* list processing */
struct ssh_list {
struct ssh_iterator *root;
struct ssh_iterator *end;
};
struct ssh_iterator {
struct ssh_iterator *next;
const void *data;
};
struct ssh_timestamp {
long seconds;
long useconds;
};
struct ssh_list *ssh_list_new(void);
void ssh_list_free(struct ssh_list *list);
struct ssh_iterator *ssh_list_get_iterator(const struct ssh_list *list);
struct ssh_iterator *ssh_list_find(const struct ssh_list *list, void *value);
int ssh_list_append(struct ssh_list *list, const void *data);
int ssh_list_prepend(struct ssh_list *list, const void *data);
void ssh_list_remove(struct ssh_list *list, struct ssh_iterator *iterator);
char *ssh_lowercase(const char* str);
char *ssh_hostport(const char *host, int port);
const void *_ssh_list_pop_head(struct ssh_list *list);
#define ssh_iterator_value(type, iterator)\
((type)((iterator)->data))
/** @brief fetch the head element of a list and remove it from list
* @param type type of the element to return
* @param list the ssh_list to use
* @return the first element of the list, or NULL if the list is empty
*/
#define ssh_list_pop_head(type, ssh_list)\
((type)_ssh_list_pop_head(ssh_list))
int ssh_make_milliseconds(long sec, long usec);
void ssh_timestamp_init(struct ssh_timestamp *ts);
int ssh_timeout_elapsed(struct ssh_timestamp *ts, int timeout);
int ssh_timeout_update(struct ssh_timestamp *ts, int timeout);
int ssh_match_group(const char *group, const char *object);
#endif /* MISC_H_ */

View File

@ -1,28 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2011 Andreas Schneider <asn@cryptomilk.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _OPTIONS_H
#define _OPTIONS_H
int ssh_config_parse_file(ssh_session session, const char *filename);
int ssh_options_set_algo(ssh_session session, int algo, const char *list);
int ssh_options_apply(ssh_session session);
#endif /* _OPTIONS_H */

View File

@ -1,89 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PACKET_H_
#define PACKET_H_
#include "libssh/wrapper.h"
struct ssh_socket_struct;
/* this structure should go someday */
typedef struct packet_struct {
int valid;
uint32_t len;
uint8_t type;
} PACKET;
/** different state of packet reading. */
enum ssh_packet_state_e {
/** Packet not initialized, must read the size of packet */
PACKET_STATE_INIT,
/** Size was read, waiting for the rest of data */
PACKET_STATE_SIZEREAD,
/** Full packet was read and callbacks are being called. Future packets
* should wait for the end of the callback. */
PACKET_STATE_PROCESSING
};
int ssh_packet_send(ssh_session session);
#ifdef WITH_SSH1
int ssh_packet_send1(ssh_session session) ;
void ssh_packet_set_default_callbacks1(ssh_session session);
SSH_PACKET_CALLBACK(ssh_packet_disconnect1);
SSH_PACKET_CALLBACK(ssh_packet_smsg_success1);
SSH_PACKET_CALLBACK(ssh_packet_smsg_failure1);
int ssh_packet_socket_callback1(const void *data, size_t receivedlen, void *user);
#endif
SSH_PACKET_CALLBACK(ssh_packet_unimplemented);
SSH_PACKET_CALLBACK(ssh_packet_disconnect_callback);
SSH_PACKET_CALLBACK(ssh_packet_ignore_callback);
SSH_PACKET_CALLBACK(ssh_packet_dh_reply);
SSH_PACKET_CALLBACK(ssh_packet_newkeys);
SSH_PACKET_CALLBACK(ssh_packet_service_accept);
#ifdef WITH_SERVER
SSH_PACKET_CALLBACK(ssh_packet_kexdh_init);
#endif
int ssh_packet_send_unimplemented(ssh_session session, uint32_t seqnum);
int ssh_packet_parse_type(ssh_session session);
//int packet_flush(ssh_session session, int enforce_blocking);
int ssh_packet_socket_callback(const void *data, size_t len, void *user);
void ssh_packet_register_socket_callback(ssh_session session, struct ssh_socket_struct *s);
void ssh_packet_set_callbacks(ssh_session session, ssh_packet_callbacks callbacks);
void ssh_packet_set_default_callbacks(ssh_session session);
void ssh_packet_process(ssh_session session, uint8_t type);
/* PACKET CRYPT */
uint32_t ssh_packet_decrypt_len(ssh_session session, char *crypted);
int ssh_packet_decrypt(ssh_session session, void *packet, unsigned int len);
unsigned char *ssh_packet_encrypt(ssh_session session,
void *packet,
unsigned int len);
int ssh_packet_hmac_verify(ssh_session session,ssh_buffer buffer,
unsigned char *mac, enum ssh_hmac_e type);
#endif /* PACKET_H_ */

View File

@ -1,46 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PCAP_H_
#define PCAP_H_
#include "config.h"
#include "libssh/libssh.h"
#ifdef WITH_PCAP
typedef struct ssh_pcap_context_struct* ssh_pcap_context;
int ssh_pcap_file_write_packet(ssh_pcap_file pcap, ssh_buffer packet, uint32_t original_len);
ssh_pcap_context ssh_pcap_context_new(ssh_session session);
void ssh_pcap_context_free(ssh_pcap_context ctx);
enum ssh_pcap_direction{
SSH_PCAP_DIR_IN,
SSH_PCAP_DIR_OUT
};
void ssh_pcap_context_set_file(ssh_pcap_context, ssh_pcap_file);
int ssh_pcap_context_write(ssh_pcap_context,enum ssh_pcap_direction direction, void *data,
uint32_t len, uint32_t origlen);
#endif /* WITH_PCAP */
#endif /* PCAP_H_ */
/* vim: set ts=2 sw=2 et cindent: */

View File

@ -1,133 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PKI_H_
#define PKI_H_
#include "libssh/priv.h"
#ifdef HAVE_OPENSSL_EC_H
#include <openssl/ec.h>
#endif
#ifdef HAVE_OPENSSL_ECDSA_H
#include <openssl/ecdsa.h>
#endif
#include "libssh/crypto.h"
#include "libssh/ed25519.h"
#define MAX_PUBKEY_SIZE 0x100000 /* 1M */
#define MAX_PRIVKEY_SIZE 0x400000 /* 4M */
#define SSH_KEY_FLAG_EMPTY 0x0
#define SSH_KEY_FLAG_PUBLIC 0x0001
#define SSH_KEY_FLAG_PRIVATE 0x0002
struct ssh_key_struct {
enum ssh_keytypes_e type;
int flags;
const char *type_c; /* Don't free it ! it is static */
int ecdsa_nid;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa;
gcry_sexp_t rsa;
void *ecdsa;
#elif HAVE_LIBCRYPTO
DSA *dsa;
RSA *rsa;
#ifdef HAVE_OPENSSL_ECC
EC_KEY *ecdsa;
#else
void *ecdsa;
#endif /* HAVE_OPENSSL_EC_H */
#endif
ed25519_pubkey *ed25519_pubkey;
ed25519_privkey *ed25519_privkey;
void *cert;
enum ssh_keytypes_e cert_type;
};
struct ssh_signature_struct {
enum ssh_keytypes_e type;
const char *type_c;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa_sig;
gcry_sexp_t rsa_sig;
void *ecdsa_sig;
#elif defined HAVE_LIBCRYPTO
DSA_SIG *dsa_sig;
ssh_string rsa_sig;
# ifdef HAVE_OPENSSL_ECC
ECDSA_SIG *ecdsa_sig;
# else
void *ecdsa_sig;
# endif
#endif
ed25519_signature *ed25519_sig;
};
typedef struct ssh_signature_struct *ssh_signature;
/* SSH Key Functions */
ssh_key ssh_key_dup(const ssh_key key);
void ssh_key_clean (ssh_key key);
/* SSH Signature Functions */
ssh_signature ssh_signature_new(void);
void ssh_signature_free(ssh_signature sign);
int ssh_pki_export_signature_blob(const ssh_signature sign,
ssh_string *sign_blob);
int ssh_pki_import_signature_blob(const ssh_string sig_blob,
const ssh_key pubkey,
ssh_signature *psig);
int ssh_pki_signature_verify_blob(ssh_session session,
ssh_string sig_blob,
const ssh_key key,
unsigned char *digest,
size_t dlen);
/* SSH Public Key Functions */
int ssh_pki_export_pubkey_blob(const ssh_key key,
ssh_string *pblob);
int ssh_pki_import_pubkey_blob(const ssh_string key_blob,
ssh_key *pkey);
int ssh_pki_export_pubkey_rsa1(const ssh_key key,
const char *host,
char *rsa1,
size_t rsa1_len);
int ssh_pki_import_cert_blob(const ssh_string cert_blob,
ssh_key *pkey);
/* SSH Signing Functions */
ssh_string ssh_pki_do_sign(ssh_session session, ssh_buffer sigbuf,
const ssh_key privatekey);
ssh_string ssh_pki_do_sign_agent(ssh_session session,
struct ssh_buffer_struct *buf,
const ssh_key pubkey);
ssh_string ssh_srv_pki_do_sign_sessionid(ssh_session session,
const ssh_key privkey);
/* Temporary functions, to be removed after migration to ssh_key */
ssh_public_key ssh_pki_convert_key_to_publickey(const ssh_key key);
ssh_private_key ssh_pki_convert_key_to_privatekey(const ssh_key key);
#endif /* PKI_H_ */

View File

@ -1,124 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PKI_PRIV_H_
#define PKI_PRIV_H_
#include "libssh/pki.h"
/* defined in bcrypt_pbkdf.c */
int bcrypt_pbkdf(const char *pass,
size_t passlen,
const uint8_t *salt,
size_t saltlen,
uint8_t *key,
size_t keylen,
unsigned int rounds);
#define RSA_HEADER_BEGIN "-----BEGIN RSA PRIVATE KEY-----"
#define RSA_HEADER_END "-----END RSA PRIVATE KEY-----"
#define DSA_HEADER_BEGIN "-----BEGIN DSA PRIVATE KEY-----"
#define DSA_HEADER_END "-----END DSA PRIVATE KEY-----"
#define ECDSA_HEADER_BEGIN "-----BEGIN EC PRIVATE KEY-----"
#define ECDSA_HEADER_END "-----END EC PRIVATE KEY-----"
#define OPENSSH_HEADER_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----"
#define OPENSSH_HEADER_END "-----END OPENSSH PRIVATE KEY-----"
/* Magic defined in OpenSSH/PROTOCOL.key */
#define OPENSSH_AUTH_MAGIC "openssh-key-v1"
int pki_key_ecdsa_nid_from_name(const char *name);
const char *pki_key_ecdsa_nid_to_name(int nid);
/* SSH Key Functions */
ssh_key pki_key_dup(const ssh_key key, int demote);
int pki_key_generate_rsa(ssh_key key, int parameter);
int pki_key_generate_dss(ssh_key key, int parameter);
int pki_key_generate_ecdsa(ssh_key key, int parameter);
int pki_key_generate_ed25519(ssh_key key);
int pki_key_compare(const ssh_key k1,
const ssh_key k2,
enum ssh_keycmp_e what);
/* SSH Private Key Functions */
enum ssh_keytypes_e pki_privatekey_type_from_string(const char *privkey);
ssh_key pki_private_key_from_base64(const char *b64_key,
const char *passphrase,
ssh_auth_callback auth_fn,
void *auth_data);
ssh_string pki_private_key_to_pem(const ssh_key key,
const char *passphrase,
ssh_auth_callback auth_fn,
void *auth_data);
/* SSH Public Key Functions */
int pki_pubkey_build_dss(ssh_key key,
ssh_string p,
ssh_string q,
ssh_string g,
ssh_string pubkey);
int pki_pubkey_build_rsa(ssh_key key,
ssh_string e,
ssh_string n);
int pki_pubkey_build_ecdsa(ssh_key key, int nid, ssh_string e);
ssh_string pki_publickey_to_blob(const ssh_key key);
int pki_export_pubkey_rsa1(const ssh_key key,
const char *host,
char *rsa1,
size_t rsa1_len);
/* SSH Signature Functions */
ssh_string pki_signature_to_blob(const ssh_signature sign);
ssh_signature pki_signature_from_blob(const ssh_key pubkey,
const ssh_string sig_blob,
enum ssh_keytypes_e type);
int pki_signature_verify(ssh_session session,
const ssh_signature sig,
const ssh_key key,
const unsigned char *hash,
size_t hlen);
/* SSH Signing Functions */
ssh_signature pki_do_sign(const ssh_key privkey,
const unsigned char *hash,
size_t hlen);
ssh_signature pki_do_sign_sessionid(const ssh_key key,
const unsigned char *hash,
size_t hlen);
int pki_ed25519_sign(const ssh_key privkey, ssh_signature sig,
const unsigned char *hash, size_t hlen);
int pki_ed25519_verify(const ssh_key pubkey, ssh_signature sig,
const unsigned char *hash, size_t hlen);
int pki_ed25519_key_cmp(const ssh_key k1,
const ssh_key k2,
enum ssh_keycmp_e what);
int pki_ed25519_key_dup(ssh_key new, const ssh_key key);
int pki_ed25519_public_key_to_blob(ssh_buffer buffer, ssh_key key);
ssh_string pki_ed25519_sig_to_blob(ssh_signature sig);
int pki_ed25519_sig_from_blob(ssh_signature sig, ssh_string sig_blob);
/* PKI Container OpenSSH */
ssh_key ssh_pki_openssh_privkey_import(const char *text_key,
const char *passphrase, ssh_auth_callback auth_fn, void *auth_data);
ssh_string ssh_pki_openssh_privkey_export(const ssh_key privkey,
const char *passphrase, ssh_auth_callback auth_fn, void *auth_data);
#endif /* PKI_PRIV_H_ */

View File

@ -1,161 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef POLL_H_
#define POLL_H_
#include "config.h"
#ifdef HAVE_POLL
#include <poll.h>
typedef struct pollfd ssh_pollfd_t;
#else /* HAVE_POLL */
/* poll emulation support */
typedef struct ssh_pollfd_struct {
socket_t fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
} ssh_pollfd_t;
typedef unsigned long int nfds_t;
#ifdef _WIN32
#ifndef POLLRDNORM
#define POLLRDNORM 0x0100
#endif
#ifndef POLLRDBAND
#define POLLRDBAND 0x0200
#endif
#ifndef POLLIN
#define POLLIN (POLLRDNORM | POLLRDBAND)
#endif
#ifndef POLLPRI
#define POLLPRI 0x0400
#endif
#ifndef POLLWRNORM
#define POLLWRNORM 0x0010
#endif
#ifndef POLLOUT
#define POLLOUT (POLLWRNORM)
#endif
#ifndef POLLWRBAND
#define POLLWRBAND 0x0020
#endif
#ifndef POLLERR
#define POLLERR 0x0001
#endif
#ifndef POLLHUP
#define POLLHUP 0x0002
#endif
#ifndef POLLNVAL
#define POLLNVAL 0x0004
#endif
#else /* _WIN32 */
/* poll.c */
#ifndef POLLIN
#define POLLIN 0x001 /* There is data to read. */
#endif
#ifndef POLLPRI
#define POLLPRI 0x002 /* There is urgent data to read. */
#endif
#ifndef POLLOUT
#define POLLOUT 0x004 /* Writing now will not block. */
#endif
#ifndef POLLERR
#define POLLERR 0x008 /* Error condition. */
#endif
#ifndef POLLHUP
#define POLLHUP 0x010 /* Hung up. */
#endif
#ifndef POLLNVAL
#define POLLNVAL 0x020 /* Invalid polling request. */
#endif
#ifndef POLLRDNORM
#define POLLRDNORM 0x040 /* mapped to read fds_set */
#endif
#ifndef POLLRDBAND
#define POLLRDBAND 0x080 /* mapped to exception fds_set */
#endif
#ifndef POLLWRNORM
#define POLLWRNORM 0x100 /* mapped to write fds_set */
#endif
#ifndef POLLWRBAND
#define POLLWRBAND 0x200 /* mapped to write fds_set */
#endif
#endif /* WIN32 */
#endif /* HAVE_POLL */
void ssh_poll_init(void);
void ssh_poll_cleanup(void);
int ssh_poll(ssh_pollfd_t *fds, nfds_t nfds, int timeout);
typedef struct ssh_poll_ctx_struct *ssh_poll_ctx;
typedef struct ssh_poll_handle_struct *ssh_poll_handle;
/**
* @brief SSH poll callback. This callback will be used when an event
* caught on the socket.
*
* @param p Poll object this callback belongs to.
* @param fd The raw socket.
* @param revents The current poll events on the socket.
* @param userdata Userdata to be passed to the callback function.
*
* @return 0 on success, < 0 if you removed the poll object from
* its poll context.
*/
typedef int (*ssh_poll_callback)(ssh_poll_handle p, socket_t fd, int revents,
void *userdata);
struct ssh_socket_struct;
ssh_poll_handle ssh_poll_new(socket_t fd, short events, ssh_poll_callback cb,
void *userdata);
void ssh_poll_free(ssh_poll_handle p);
ssh_poll_ctx ssh_poll_get_ctx(ssh_poll_handle p);
short ssh_poll_get_events(ssh_poll_handle p);
void ssh_poll_set_events(ssh_poll_handle p, short events);
void ssh_poll_add_events(ssh_poll_handle p, short events);
void ssh_poll_remove_events(ssh_poll_handle p, short events);
socket_t ssh_poll_get_fd(ssh_poll_handle p);
void ssh_poll_set_fd(ssh_poll_handle p, socket_t fd);
void ssh_poll_set_callback(ssh_poll_handle p, ssh_poll_callback cb, void *userdata);
ssh_poll_ctx ssh_poll_ctx_new(size_t chunk_size);
void ssh_poll_ctx_free(ssh_poll_ctx ctx);
int ssh_poll_ctx_add(ssh_poll_ctx ctx, ssh_poll_handle p);
int ssh_poll_ctx_add_socket (ssh_poll_ctx ctx, struct ssh_socket_struct *s);
void ssh_poll_ctx_remove(ssh_poll_ctx ctx, ssh_poll_handle p);
int ssh_poll_ctx_dopoll(ssh_poll_ctx ctx, int timeout);
ssh_poll_ctx ssh_poll_get_default_ctx(ssh_session session);
int ssh_event_add_poll(ssh_event event, ssh_poll_handle p);
void ssh_event_remove_poll(ssh_event event, ssh_poll_handle p);
#endif /* POLL_H_ */

View File

@ -1,371 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* priv.h file
* This include file contains everything you shouldn't deal with in
* user programs. Consider that anything in this file might change
* without notice; libssh.h file will keep backward compatibility
* on binary & source
*/
#ifndef _LIBSSH_PRIV_H
#define _LIBSSH_PRIV_H
#include "config.h"
#if !defined(HAVE_STRTOULL)
# if defined(HAVE___STRTOULL)
# define strtoull __strtoull
# elif defined(HAVE__STRTOUI64)
# define strtoull _strtoui64
# elif defined(__hpux) && defined(__LP64__)
# define strtoull strtoul
# else
# error "no strtoull function found"
# endif
#endif /* !defined(HAVE_STRTOULL) */
#ifdef HAVE_BYTESWAP_H
#include <byteswap.h>
#endif
#ifndef bswap_32
#define bswap_32(x) \
((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
#endif
#ifdef _WIN32
/* Imitate define of inttypes.h */
# ifndef PRIdS
# define PRIdS "Id"
# endif
# ifndef PRIu64
# if __WORDSIZE == 64
# define PRIu64 "lu"
# else
# define PRIu64 "llu"
# endif /* __WORDSIZE */
# endif /* PRIu64 */
# ifdef _MSC_VER
# include <stdio.h>
# include <stdarg.h> /* va_copy define check */
/* On Microsoft compilers define inline to __inline on all others use inline */
# undef inline
# define inline __inline
# ifndef va_copy
# define va_copy(dest, src) (dest = src)
# endif
# define strcasecmp _stricmp
# define strncasecmp _strnicmp
# if ! defined(HAVE_ISBLANK)
# define isblank(ch) ((ch) == ' ' || (ch) == '\t' || (ch) == '\n' || (ch) == '\r')
# endif
# define usleep(X) Sleep(((X)+1000)/1000)
# undef strtok_r
# define strtok_r strtok_s
# if defined(HAVE__SNPRINTF_S)
# undef snprintf
# define snprintf(d, n, ...) _snprintf_s((d), (n), _TRUNCATE, __VA_ARGS__)
# else /* HAVE__SNPRINTF_S */
# if defined(HAVE__SNPRINTF)
# undef snprintf
# define snprintf _snprintf
# else /* HAVE__SNPRINTF */
# if !defined(HAVE_SNPRINTF)
# error "no snprintf compatible function found"
# endif /* HAVE_SNPRINTF */
# endif /* HAVE__SNPRINTF */
# endif /* HAVE__SNPRINTF_S */
# if defined(HAVE__VSNPRINTF_S)
# undef vsnprintf
# define vsnprintf(s, n, f, v) _vsnprintf_s((s), (n), _TRUNCATE, (f), (v))
# else /* HAVE__VSNPRINTF_S */
# if defined(HAVE__VSNPRINTF)
# undef vsnprintf
# define vsnprintf _vsnprintf
# else
# if !defined(HAVE_VSNPRINTF)
# error "No vsnprintf compatible function found"
# endif /* HAVE_VSNPRINTF */
# endif /* HAVE__VSNPRINTF */
# endif /* HAVE__VSNPRINTF_S */
# endif /* _MSC_VER */
struct timeval;
int gettimeofday(struct timeval *__p, void *__t);
#define _XCLOSESOCKET closesocket
#else /* _WIN32 */
#include <unistd.h>
#define PRIdS "zd"
#define _XCLOSESOCKET close
#endif /* _WIN32 */
#include "libssh/libssh.h"
#include "libssh/callbacks.h"
/* some constants */
#ifndef MAX_PACKAT_LEN
#define MAX_PACKET_LEN 262144
#endif
#ifndef ERROR_BUFFERLEN
#define ERROR_BUFFERLEN 1024
#endif
#ifndef CLIENTBANNER1
#define CLIENTBANNER1 "SSH-1.5-libssh_" SSH_STRINGIFY(LIBSSH_VERSION)
#endif
#ifndef CLIENTBANNER2
#define CLIENTBANNER2 "SSH-2.0-libssh_" SSH_STRINGIFY(LIBSSH_VERSION)
#endif
#ifndef KBDINT_MAX_PROMPT
#define KBDINT_MAX_PROMPT 256 /* more than openssh's :) */
#endif
#ifndef MAX_BUF_SIZE
#define MAX_BUF_SIZE 4096
#endif
#ifndef HAVE_COMPILER__FUNC__
# ifdef HAVE_COMPILER__FUNCTION__
# define __func__ __FUNCTION__
# else
# error "Your system must provide a __func__ macro"
# endif
#endif
#if defined(HAVE_GCC_THREAD_LOCAL_STORAGE)
# define LIBSSH_THREAD __thread
#elif defined(HAVE_MSC_THREAD_LOCAL_STORAGE)
# define LIBSSH_THREAD __declspec(thread)
#else
# define LIBSSH_THREAD
#endif
/*
* This makes sure that the compiler doesn't optimize out the code
*
* Use it in a macro where the provided variable is 'x'.
*/
#if defined(HAVE_GCC_VOLATILE_MEMORY_PROTECTION)
# define LIBSSH_MEM_PROTECTION __asm__ volatile("" : : "r"(&(x)) : "memory")
#else
# define LIBSSH_MEM_PROTECTION
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
/* forward declarations */
struct ssh_common_struct;
struct ssh_kex_struct;
int ssh_get_key_params(ssh_session session, ssh_key *privkey);
/* LOGGING */
void ssh_log_function(int verbosity,
const char *function,
const char *buffer);
#define SSH_LOG(priority, ...) \
_ssh_log(priority, __func__, __VA_ARGS__)
/* LEGACY */
void ssh_log_common(struct ssh_common_struct *common,
int verbosity,
const char *function,
const char *format, ...) PRINTF_ATTRIBUTE(4, 5);
/* ERROR HANDLING */
/* error handling structure */
struct error_struct {
int error_code;
char error_buffer[ERROR_BUFFERLEN];
};
#define ssh_set_error(error, code, ...) \
_ssh_set_error(error, code, __func__, __VA_ARGS__)
void _ssh_set_error(void *error,
int code,
const char *function,
const char *descr, ...) PRINTF_ATTRIBUTE(4, 5);
#define ssh_set_error_oom(error) \
_ssh_set_error_oom(error, __func__)
void _ssh_set_error_oom(void *error, const char *function);
#define ssh_set_error_invalid(error) \
_ssh_set_error_invalid(error, __func__)
void _ssh_set_error_invalid(void *error, const char *function);
/* server.c */
#ifdef WITH_SERVER
int ssh_auth_reply_default(ssh_session session,int partial);
int ssh_auth_reply_success(ssh_session session, int partial);
#endif
/* client.c */
int ssh_send_banner(ssh_session session, int is_server);
/* connect.c */
socket_t ssh_connect_host(ssh_session session, const char *host,const char
*bind_addr, int port, long timeout, long usec);
socket_t ssh_connect_host_nonblocking(ssh_session session, const char *host,
const char *bind_addr, int port);
/* in base64.c */
ssh_buffer base64_to_bin(const char *source);
unsigned char *bin_to_base64(const unsigned char *source, int len);
/* gzip.c */
int compress_buffer(ssh_session session,ssh_buffer buf);
int decompress_buffer(ssh_session session,ssh_buffer buf, size_t maxlen);
/* match.c */
int match_hostname(const char *host, const char *pattern, unsigned int len);
/* connector.c */
int ssh_connector_set_event(ssh_connector connector, ssh_event event);
int ssh_connector_remove_event(ssh_connector connector);
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
/** Free memory space */
#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)
/** Zero a structure */
#define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x))
/** Zero a structure given a pointer to the structure */
#define ZERO_STRUCTP(x) do { if ((x) != NULL) memset((char *)(x), 0, sizeof(*(x))); } while(0)
/** Get the size of an array */
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
/*
* See http://llvm.org/bugs/show_bug.cgi?id=15495
*/
#if defined(HAVE_GCC_VOLATILE_MEMORY_PROTECTION)
/** Overwrite a string with '\0' */
# define BURN_STRING(x) do { \
if ((x) != NULL) \
memset((x), '\0', strlen((x))); __asm__ volatile("" : : "r"(&(x)) : "memory"); \
} while(0)
/** Overwrite the buffer with '\0' */
# define BURN_BUFFER(x, size) do { \
if ((x) != NULL) \
memset((x), '\0', (size)); __asm__ volatile("" : : "r"(&(x)) : "memory"); \
} while(0)
#else /* HAVE_GCC_VOLATILE_MEMORY_PROTECTION */
/** Overwrite a string with '\0' */
# define BURN_STRING(x) do { \
if ((x) != NULL) memset((x), '\0', strlen((x))); \
} while(0)
/** Overwrite the buffer with '\0' */
# define BURN_BUFFER(x, size) do { \
if ((x) != NULL) \
memset((x), '\0', (size)); \
} while(0)
#endif /* HAVE_GCC_VOLATILE_MEMORY_PROTECTION */
/**
* This is a hack to fix warnings. The idea is to use this everywhere that we
* get the "discarding const" warning by the compiler. That doesn't actually
* fix the real issue, but marks the place and you can search the code for
* discard_const.
*
* Please use this macro only when there is no other way to fix the warning.
* We should use this function in only in a very few places.
*
* Also, please call this via the discard_const_p() macro interface, as that
* makes the return type safe.
*/
#define discard_const(ptr) ((void *)((uintptr_t)(ptr)))
/**
* Type-safe version of discard_const
*/
#define discard_const_p(type, ptr) ((type *)discard_const(ptr))
/**
* Get the argument cound of variadic arguments
*/
#ifdef HAVE_GCC_NARG_MACRO
/*
* Since MSVC 2010 there is a bug in passing __VA_ARGS__ to subsequent
* macros as a single token, which results in:
* warning C4003: not enough actual parameters for macro '_VA_ARG_N'
* and incorrect behavior. This fixes issue.
*/
#define VA_APPLY_VARIADIC_MACRO(macro, tuple) macro tuple
#define __VA_NARG__(...) \
(__VA_NARG_(_0, ## __VA_ARGS__, __RSEQ_N()) - 1)
#define __VA_NARG_(...) \
VA_APPLY_VARIADIC_MACRO(__VA_ARG_N, (__VA_ARGS__))
#define __VA_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define __RSEQ_N() \
63, 62, 61, 60, \
59, 58, 57, 56, 55, 54, 53, 52, 51, 50, \
49, 48, 47, 46, 45, 44, 43, 42, 41, 40, \
39, 38, 37, 36, 35, 34, 33, 32, 31, 30, \
29, 28, 27, 26, 25, 24, 23, 22, 21, 20, \
19, 18, 17, 16, 15, 14, 13, 12, 11, 10, \
9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#else
/* clang does not support the above construction */
#define __VA_NARG__(...) (-1)
#endif
#define CLOSE_SOCKET(s) do { if ((s) != SSH_INVALID_SOCKET) { _XCLOSESOCKET(s); (s) = SSH_INVALID_SOCKET;} } while(0)
void ssh_agent_state_free(void *data);
#endif /* _LIBSSH_PRIV_H */
/* vim: set ts=4 sw=4 et cindent: */

View File

@ -1,74 +0,0 @@
/* $OpenBSD: sc25519.h,v 1.3 2013/12/09 11:03:45 markus Exp $ */
/*
* Public Domain, Authors: Daniel J. Bernstein, Niels Duif, Tanja Lange,
* Peter Schwabe, Bo-Yin Yang.
* Copied from supercop-20130419/crypto_sign/ed25519/ref/sc25519.h
*/
#ifndef SC25519_H
#define SC25519_H
#define sc25519 crypto_sign_ed25519_ref_sc25519
#define shortsc25519 crypto_sign_ed25519_ref_shortsc25519
#define sc25519_from32bytes crypto_sign_ed25519_ref_sc25519_from32bytes
#define shortsc25519_from16bytes crypto_sign_ed25519_ref_shortsc25519_from16bytes
#define sc25519_from64bytes crypto_sign_ed25519_ref_sc25519_from64bytes
#define sc25519_from_shortsc crypto_sign_ed25519_ref_sc25519_from_shortsc
#define sc25519_to32bytes crypto_sign_ed25519_ref_sc25519_to32bytes
#define sc25519_iszero_vartime crypto_sign_ed25519_ref_sc25519_iszero_vartime
#define sc25519_isshort_vartime crypto_sign_ed25519_ref_sc25519_isshort_vartime
#define sc25519_lt_vartime crypto_sign_ed25519_ref_sc25519_lt_vartime
#define sc25519_add crypto_sign_ed25519_ref_sc25519_add
#define sc25519_sub_nored crypto_sign_ed25519_ref_sc25519_sub_nored
#define sc25519_mul crypto_sign_ed25519_ref_sc25519_mul
#define sc25519_mul_shortsc crypto_sign_ed25519_ref_sc25519_mul_shortsc
#define sc25519_window3 crypto_sign_ed25519_ref_sc25519_window3
#define sc25519_window5 crypto_sign_ed25519_ref_sc25519_window5
#define sc25519_2interleave2 crypto_sign_ed25519_ref_sc25519_2interleave2
typedef struct {
uint32_t v[32];
} sc25519;
typedef struct {
uint32_t v[16];
} shortsc25519;
void sc25519_from32bytes(sc25519 *r, const unsigned char x[32]);
void shortsc25519_from16bytes(shortsc25519 *r, const unsigned char x[16]);
void sc25519_from64bytes(sc25519 *r, const unsigned char x[64]);
void sc25519_from_shortsc(sc25519 *r, const shortsc25519 *x);
void sc25519_to32bytes(unsigned char r[32], const sc25519 *x);
int sc25519_iszero_vartime(const sc25519 *x);
int sc25519_isshort_vartime(const sc25519 *x);
int sc25519_lt_vartime(const sc25519 *x, const sc25519 *y);
void sc25519_add(sc25519 *r, const sc25519 *x, const sc25519 *y);
void sc25519_sub_nored(sc25519 *r, const sc25519 *x, const sc25519 *y);
void sc25519_mul(sc25519 *r, const sc25519 *x, const sc25519 *y);
void sc25519_mul_shortsc(sc25519 *r, const sc25519 *x, const shortsc25519 *y);
/* Convert s into a representation of the form \sum_{i=0}^{84}r[i]2^3
* with r[i] in {-4,...,3}
*/
void sc25519_window3(signed char r[85], const sc25519 *s);
/* Convert s into a representation of the form \sum_{i=0}^{50}r[i]2^5
* with r[i] in {-16,...,15}
*/
void sc25519_window5(signed char r[51], const sc25519 *s);
void sc25519_2interleave2(unsigned char r[127], const sc25519 *s1, const sc25519 *s2);
#endif

View File

@ -1,55 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _SCP_H
#define _SCP_H
enum ssh_scp_states {
SSH_SCP_NEW, //Data structure just created
SSH_SCP_WRITE_INITED, //Gave our intention to write
SSH_SCP_WRITE_WRITING,//File was opened and currently writing
SSH_SCP_READ_INITED, //Gave our intention to read
SSH_SCP_READ_REQUESTED, //We got a read request
SSH_SCP_READ_READING, //File is opened and reading
SSH_SCP_ERROR, //Something bad happened
SSH_SCP_TERMINATED //Transfer finished
};
struct ssh_scp_struct {
ssh_session session;
int mode;
int recursive;
ssh_channel channel;
char *location;
enum ssh_scp_states state;
uint64_t filelen;
uint64_t processed;
enum ssh_scp_request_types request_type;
char *request_name;
char *warning;
int request_mode;
};
int ssh_scp_read_string(ssh_scp scp, char *buffer, size_t len);
int ssh_scp_integer_mode(const char *mode);
char *ssh_scp_string_mode(int mode);
int ssh_scp_response(ssh_scp scp, char **response);
#endif

View File

@ -1,333 +0,0 @@
/* Public include file for server support */
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @defgroup libssh_server The libssh server API
*
* @{
*/
#ifndef SERVER_H
#define SERVER_H
#include "libssh/libssh.h"
#define SERVERBANNER CLIENTBANNER
#ifdef __cplusplus
extern "C" {
#endif
enum ssh_bind_options_e {
SSH_BIND_OPTIONS_BINDADDR,
SSH_BIND_OPTIONS_BINDPORT,
SSH_BIND_OPTIONS_BINDPORT_STR,
SSH_BIND_OPTIONS_HOSTKEY,
SSH_BIND_OPTIONS_DSAKEY,
SSH_BIND_OPTIONS_RSAKEY,
SSH_BIND_OPTIONS_BANNER,
SSH_BIND_OPTIONS_LOG_VERBOSITY,
SSH_BIND_OPTIONS_LOG_VERBOSITY_STR,
SSH_BIND_OPTIONS_ECDSAKEY
};
typedef struct ssh_bind_struct* ssh_bind;
/* Callback functions */
/**
* @brief Incoming connection callback. This callback is called when a ssh_bind
* has a new incoming connection.
* @param sshbind Current sshbind session handler
* @param userdata Userdata to be passed to the callback function.
*/
typedef void (*ssh_bind_incoming_connection_callback) (ssh_bind sshbind,
void *userdata);
/**
* @brief These are the callbacks exported by the ssh_bind structure.
*
* They are called by the server module when events appear on the network.
*/
struct ssh_bind_callbacks_struct {
/** DON'T SET THIS use ssh_callbacks_init() instead. */
size_t size;
/** A new connection is available. */
ssh_bind_incoming_connection_callback incoming_connection;
};
typedef struct ssh_bind_callbacks_struct *ssh_bind_callbacks;
/**
* @brief Creates a new SSH server bind.
*
* @return A newly allocated ssh_bind session pointer.
*/
LIBSSH_API ssh_bind ssh_bind_new(void);
LIBSSH_API int ssh_bind_options_set(ssh_bind sshbind,
enum ssh_bind_options_e type, const void *value);
/**
* @brief Start listening to the socket.
*
* @param ssh_bind_o The ssh server bind to use.
*
* @return 0 on success, < 0 on error.
*/
LIBSSH_API int ssh_bind_listen(ssh_bind ssh_bind_o);
/**
* @brief Set the callback for this bind.
*
* @param[in] sshbind The bind to set the callback on.
*
* @param[in] callbacks An already set up ssh_bind_callbacks instance.
*
* @param[in] userdata A pointer to private data to pass to the callbacks.
*
* @return SSH_OK on success, SSH_ERROR if an error occured.
*
* @code
* struct ssh_callbacks_struct cb = {
* .userdata = data,
* .auth_function = my_auth_function
* };
* ssh_callbacks_init(&cb);
* ssh_bind_set_callbacks(session, &cb);
* @endcode
*/
LIBSSH_API int ssh_bind_set_callbacks(ssh_bind sshbind, ssh_bind_callbacks callbacks,
void *userdata);
/**
* @brief Set the session to blocking/nonblocking mode.
*
* @param ssh_bind_o The ssh server bind to use.
*
* @param blocking Zero for nonblocking mode.
*/
LIBSSH_API void ssh_bind_set_blocking(ssh_bind ssh_bind_o, int blocking);
/**
* @brief Recover the file descriptor from the session.
*
* @param ssh_bind_o The ssh server bind to get the fd from.
*
* @return The file descriptor.
*/
LIBSSH_API socket_t ssh_bind_get_fd(ssh_bind ssh_bind_o);
/**
* @brief Set the file descriptor for a session.
*
* @param ssh_bind_o The ssh server bind to set the fd.
*
* @param fd The file descriptssh_bind B
*/
LIBSSH_API void ssh_bind_set_fd(ssh_bind ssh_bind_o, socket_t fd);
/**
* @brief Allow the file descriptor to accept new sessions.
*
* @param ssh_bind_o The ssh server bind to use.
*/
LIBSSH_API void ssh_bind_fd_toaccept(ssh_bind ssh_bind_o);
/**
* @brief Accept an incoming ssh connection and initialize the session.
*
* @param ssh_bind_o The ssh server bind to accept a connection.
* @param session A preallocated ssh session
* @see ssh_new
* @return SSH_OK when a connection is established
*/
LIBSSH_API int ssh_bind_accept(ssh_bind ssh_bind_o, ssh_session session);
/**
* @brief Accept an incoming ssh connection on the given file descriptor
* and initialize the session.
*
* @param ssh_bind_o The ssh server bind to accept a connection.
* @param session A preallocated ssh session
* @param fd A file descriptor of an already established TCP
* inbound connection
* @see ssh_new
* @see ssh_bind_accept
* @return SSH_OK when a connection is established
*/
LIBSSH_API int ssh_bind_accept_fd(ssh_bind ssh_bind_o, ssh_session session,
socket_t fd);
LIBSSH_API ssh_gssapi_creds ssh_gssapi_get_creds(ssh_session session);
/**
* @brief Handles the key exchange and set up encryption
*
* @param session A connected ssh session
* @see ssh_bind_accept
* @return SSH_OK if the key exchange was successful
*/
LIBSSH_API int ssh_handle_key_exchange(ssh_session session);
/**
* @brief Free a ssh servers bind.
*
* @param ssh_bind_o The ssh server bind to free.
*/
LIBSSH_API void ssh_bind_free(ssh_bind ssh_bind_o);
LIBSSH_API void ssh_set_auth_methods(ssh_session session, int auth_methods);
/**********************************************************
* SERVER MESSAGING
**********************************************************/
/**
* @brief Reply with a standard reject message.
*
* Use this function if you don't know what to respond or if you want to reject
* a request.
*
* @param[in] msg The message to use for the reply.
*
* @return 0 on success, -1 on error.
*
* @see ssh_message_get()
*/
LIBSSH_API int ssh_message_reply_default(ssh_message msg);
/**
* @brief Get the name of the authenticated user.
*
* @param[in] msg The message to get the username from.
*
* @return The username or NULL if an error occured.
*
* @see ssh_message_get()
* @see ssh_message_type()
*/
LIBSSH_API const char *ssh_message_auth_user(ssh_message msg);
/**
* @brief Get the password of the authenticated user.
*
* @param[in] msg The message to get the password from.
*
* @return The username or NULL if an error occured.
*
* @see ssh_message_get()
* @see ssh_message_type()
*/
LIBSSH_API const char *ssh_message_auth_password(ssh_message msg);
/**
* @brief Get the publickey of the authenticated user.
*
* If you need the key for later user you should duplicate it.
*
* @param[in] msg The message to get the public key from.
*
* @return The public key or NULL.
*
* @see ssh_key_dup()
* @see ssh_key_cmp()
* @see ssh_message_get()
* @see ssh_message_type()
*/
LIBSSH_API ssh_key ssh_message_auth_pubkey(ssh_message msg);
LIBSSH_API int ssh_message_auth_kbdint_is_response(ssh_message msg);
LIBSSH_API enum ssh_publickey_state_e ssh_message_auth_publickey_state(ssh_message msg);
LIBSSH_API int ssh_message_auth_reply_success(ssh_message msg,int partial);
LIBSSH_API int ssh_message_auth_reply_pk_ok(ssh_message msg, ssh_string algo, ssh_string pubkey);
LIBSSH_API int ssh_message_auth_reply_pk_ok_simple(ssh_message msg);
LIBSSH_API int ssh_message_auth_set_methods(ssh_message msg, int methods);
LIBSSH_API int ssh_message_auth_interactive_request(ssh_message msg,
const char *name, const char *instruction,
unsigned int num_prompts, const char **prompts, char *echo);
LIBSSH_API int ssh_message_service_reply_success(ssh_message msg);
LIBSSH_API const char *ssh_message_service_service(ssh_message msg);
LIBSSH_API int ssh_message_global_request_reply_success(ssh_message msg,
uint16_t bound_port);
LIBSSH_API void ssh_set_message_callback(ssh_session session,
int(*ssh_bind_message_callback)(ssh_session session, ssh_message msg, void *data),
void *data);
LIBSSH_API int ssh_execute_message_callbacks(ssh_session session);
LIBSSH_API const char *ssh_message_channel_request_open_originator(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_open_originator_port(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_open_destination(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_open_destination_port(ssh_message msg);
LIBSSH_API ssh_channel ssh_message_channel_request_channel(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_pty_term(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_pty_width(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_pty_height(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_pty_pxwidth(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_pty_pxheight(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_env_name(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_env_value(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_command(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_subsystem(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_x11_single_connection(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_x11_auth_protocol(ssh_message msg);
LIBSSH_API const char *ssh_message_channel_request_x11_auth_cookie(ssh_message msg);
LIBSSH_API int ssh_message_channel_request_x11_screen_number(ssh_message msg);
LIBSSH_API const char *ssh_message_global_request_address(ssh_message msg);
LIBSSH_API int ssh_message_global_request_port(ssh_message msg);
LIBSSH_API int ssh_channel_open_reverse_forward(ssh_channel channel, const char *remotehost,
int remoteport, const char *sourcehost, int localport);
LIBSSH_API int ssh_channel_open_x11(ssh_channel channel,
const char *orig_addr, int orig_port);
LIBSSH_API int ssh_channel_request_send_exit_status(ssh_channel channel,
int exit_status);
LIBSSH_API int ssh_channel_request_send_exit_signal(ssh_channel channel,
const char *signum,
int core,
const char *errmsg,
const char *lang);
LIBSSH_API int ssh_send_keepalive(ssh_session session);
/* deprecated functions */
SSH_DEPRECATED LIBSSH_API int ssh_accept(ssh_session session);
SSH_DEPRECATED LIBSSH_API int channel_write_stderr(ssh_channel channel,
const void *data, uint32_t len);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* SERVER_H */
/** @} */

View File

@ -1,216 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SESSION_H_
#define SESSION_H_
#include "libssh/priv.h"
#include "libssh/kex.h"
#include "libssh/packet.h"
#include "libssh/pcap.h"
#include "libssh/auth.h"
#include "libssh/channels.h"
#include "libssh/poll.h"
/* These are the different states a SSH session can be into its life */
enum ssh_session_state_e {
SSH_SESSION_STATE_NONE=0,
SSH_SESSION_STATE_CONNECTING,
SSH_SESSION_STATE_SOCKET_CONNECTED,
SSH_SESSION_STATE_BANNER_RECEIVED,
SSH_SESSION_STATE_INITIAL_KEX,
SSH_SESSION_STATE_KEXINIT_RECEIVED,
SSH_SESSION_STATE_DH,
SSH_SESSION_STATE_AUTHENTICATING,
SSH_SESSION_STATE_AUTHENTICATED,
SSH_SESSION_STATE_ERROR,
SSH_SESSION_STATE_DISCONNECTED
};
enum ssh_dh_state_e {
DH_STATE_INIT=0,
DH_STATE_INIT_SENT,
DH_STATE_NEWKEYS_SENT,
DH_STATE_FINISHED
};
enum ssh_pending_call_e {
SSH_PENDING_CALL_NONE = 0,
SSH_PENDING_CALL_CONNECT,
SSH_PENDING_CALL_AUTH_NONE,
SSH_PENDING_CALL_AUTH_PASSWORD,
SSH_PENDING_CALL_AUTH_OFFER_PUBKEY,
SSH_PENDING_CALL_AUTH_PUBKEY,
SSH_PENDING_CALL_AUTH_AGENT,
SSH_PENDING_CALL_AUTH_KBDINT_INIT,
SSH_PENDING_CALL_AUTH_KBDINT_SEND,
SSH_PENDING_CALL_AUTH_GSSAPI_MIC
};
/* libssh calls may block an undefined amount of time */
#define SSH_SESSION_FLAG_BLOCKING 1
/* Client successfully authenticated */
#define SSH_SESSION_FLAG_AUTHENTICATED 2
/* codes to use with ssh_handle_packets*() */
/* Infinite timeout */
#define SSH_TIMEOUT_INFINITE -1
/* Use the timeout defined by user if any. Mostly used with new connections */
#define SSH_TIMEOUT_USER -2
/* Use the default timeout, depending on ssh_is_blocking() */
#define SSH_TIMEOUT_DEFAULT -3
/* Don't block at all */
#define SSH_TIMEOUT_NONBLOCKING 0
/* members that are common to ssh_session and ssh_bind */
struct ssh_common_struct {
struct error_struct error;
ssh_callbacks callbacks; /* Callbacks to user functions */
int log_verbosity; /* verbosity of the log functions */
};
struct ssh_session_struct {
struct ssh_common_struct common;
struct ssh_socket_struct *socket;
char *serverbanner;
char *clientbanner;
int protoversion;
int server;
int client;
int openssh;
uint32_t send_seq;
uint32_t recv_seq;
int connected;
/* !=0 when the user got a session handle */
int alive;
/* two previous are deprecated */
/* int auth_service_asked; */
/* session flags (SSH_SESSION_FLAG_*) */
int flags;
ssh_string banner; /* that's the issue banner from
the server */
char *discon_msg; /* disconnect message from
the remote host */
ssh_buffer in_buffer;
PACKET in_packet;
ssh_buffer out_buffer;
/* the states are used by the nonblocking stuff to remember */
/* where it was before being interrupted */
enum ssh_pending_call_e pending_call_state;
enum ssh_session_state_e session_state;
int packet_state;
enum ssh_dh_state_e dh_handshake_state;
enum ssh_auth_service_state_e auth_service_state;
enum ssh_auth_state_e auth_state;
enum ssh_channel_request_state_e global_req_state;
struct ssh_agent_state_struct *agent_state;
struct ssh_auth_auto_state_struct *auth_auto_state;
/*
* RFC 4253, 7.1: if the first_kex_packet_follows flag was set in
* the received SSH_MSG_KEXINIT, but the guess was wrong, this
* field will be set such that the following guessed packet will
* be ignored. Once that packet has been received and ignored,
* this field is cleared.
*/
int first_kex_follows_guess_wrong;
ssh_buffer in_hashbuf;
ssh_buffer out_hashbuf;
struct ssh_crypto_struct *current_crypto;
struct ssh_crypto_struct *next_crypto; /* next_crypto is going to be used after a SSH2_MSG_NEWKEYS */
struct ssh_list *channels; /* linked list of channels */
int maxchannel;
int exec_channel_opened; /* version 1 only. more
info in channels1.c */
ssh_agent agent; /* ssh agent */
/* keyb interactive data */
struct ssh_kbdint_struct *kbdint;
struct ssh_gssapi_struct *gssapi;
int version; /* 1 or 2 */
/* server host keys */
struct {
ssh_key rsa_key;
ssh_key dsa_key;
ssh_key ecdsa_key;
ssh_key ed25519_key;
/* The type of host key wanted by client */
enum ssh_keytypes_e hostkey;
} srv;
/* auths accepted by server */
int auth_methods;
struct ssh_list *ssh_message_list; /* list of delayed SSH messages */
int (*ssh_message_callback)( struct ssh_session_struct *session, ssh_message msg, void *userdata);
void *ssh_message_callback_data;
ssh_server_callbacks server_callbacks;
void (*ssh_connection_callback)( struct ssh_session_struct *session);
struct ssh_packet_callbacks_struct default_packet_callbacks;
struct ssh_list *packet_callbacks;
struct ssh_socket_callbacks_struct socket_callbacks;
ssh_poll_ctx default_poll_ctx;
/* options */
#ifdef WITH_PCAP
ssh_pcap_context pcap_ctx; /* pcap debugging context */
#endif
struct {
struct ssh_list *identity;
char *username;
char *host;
char *bindaddr; /* bind the client to an ip addr */
char *sshdir;
char *knownhosts;
char *wanted_methods[10];
char *ProxyCommand;
char *custombanner;
unsigned long timeout; /* seconds */
unsigned long timeout_usec;
unsigned int port;
socket_t fd;
int StrictHostKeyChecking;
int ssh2;
int ssh1;
char compressionlevel;
char *gss_server_identity;
char *gss_client_identity;
int gss_delegate_creds;
} opts;
/* counters */
ssh_counter socket_counter;
ssh_counter raw_counter;
};
/** @internal
* @brief a termination function evaluates the status of an object
* @param user[in] object to evaluate
* @returns 1 if the polling routine should terminate, 0 instead
*/
typedef int (*ssh_termination_function)(void *user);
int ssh_handle_packets(ssh_session session, int timeout);
int ssh_handle_packets_termination(ssh_session session, int timeout,
ssh_termination_function fct, void *user);
void ssh_socket_exception_callback(int code, int errno_code, void *user);
#endif /* SESSION_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SOCKET_H_
#define SOCKET_H_
#include "libssh/callbacks.h"
struct ssh_poll_handle_struct;
/* socket.c */
struct ssh_socket_struct;
typedef struct ssh_socket_struct* ssh_socket;
int ssh_socket_init(void);
void ssh_socket_cleanup(void);
ssh_socket ssh_socket_new(ssh_session session);
void ssh_socket_reset(ssh_socket s);
void ssh_socket_free(ssh_socket s);
void ssh_socket_set_fd(ssh_socket s, socket_t fd);
socket_t ssh_socket_get_fd_in(ssh_socket s);
#ifndef _WIN32
int ssh_socket_unix(ssh_socket s, const char *path);
void ssh_execute_command(const char *command, socket_t in, socket_t out);
int ssh_socket_connect_proxycommand(ssh_socket s, const char *command);
#endif
void ssh_socket_close(ssh_socket s);
int ssh_socket_write(ssh_socket s,const void *buffer, int len);
int ssh_socket_is_open(ssh_socket s);
int ssh_socket_fd_isset(ssh_socket s, fd_set *set);
void ssh_socket_fd_set(ssh_socket s, fd_set *set, socket_t *max_fd);
void ssh_socket_set_fd_in(ssh_socket s, socket_t fd);
void ssh_socket_set_fd_out(ssh_socket s, socket_t fd);
int ssh_socket_nonblocking_flush(ssh_socket s);
void ssh_socket_set_write_wontblock(ssh_socket s);
void ssh_socket_set_read_wontblock(ssh_socket s);
void ssh_socket_set_except(ssh_socket s);
int ssh_socket_get_status(ssh_socket s);
int ssh_socket_get_poll_flags(ssh_socket s);
int ssh_socket_buffered_write_bytes(ssh_socket s);
int ssh_socket_data_available(ssh_socket s);
int ssh_socket_data_writable(ssh_socket s);
int ssh_socket_set_nonblocking(socket_t fd);
int ssh_socket_set_blocking(socket_t fd);
void ssh_socket_set_callbacks(ssh_socket s, ssh_socket_callbacks callbacks);
int ssh_socket_pollcallback(struct ssh_poll_handle_struct *p, socket_t fd, int revents, void *v_s);
struct ssh_poll_handle_struct * ssh_socket_get_poll_handle_in(ssh_socket s);
struct ssh_poll_handle_struct * ssh_socket_get_poll_handle_out(ssh_socket s);
int ssh_socket_connect(ssh_socket s, const char *host, int port, const char *bind_addr);
#endif /* SOCKET_H_ */

View File

@ -1,82 +0,0 @@
#ifndef __SSH1_H
#define __SSH1_H
#define SSH_MSG_NONE 0 /* no message */
#define SSH_MSG_DISCONNECT 1 /* cause (string) */
#define SSH_SMSG_PUBLIC_KEY 2 /* ck,msk,srvk,hostk */
#define SSH_CMSG_SESSION_KEY 3 /* key (BIGNUM) */
#define SSH_CMSG_USER 4 /* user (string) */
#define SSH_CMSG_AUTH_RHOSTS 5 /* user (string) */
#define SSH_CMSG_AUTH_RSA 6 /* modulus (BIGNUM) */
#define SSH_SMSG_AUTH_RSA_CHALLENGE 7 /* int (BIGNUM) */
#define SSH_CMSG_AUTH_RSA_RESPONSE 8 /* int (BIGNUM) */
#define SSH_CMSG_AUTH_PASSWORD 9 /* pass (string) */
#define SSH_CMSG_REQUEST_PTY 10 /* TERM, tty modes */
#define SSH_CMSG_WINDOW_SIZE 11 /* row,col,xpix,ypix */
#define SSH_CMSG_EXEC_SHELL 12 /* */
#define SSH_CMSG_EXEC_CMD 13 /* cmd (string) */
#define SSH_SMSG_SUCCESS 14 /* */
#define SSH_SMSG_FAILURE 15 /* */
#define SSH_CMSG_STDIN_DATA 16 /* data (string) */
#define SSH_SMSG_STDOUT_DATA 17 /* data (string) */
#define SSH_SMSG_STDERR_DATA 18 /* data (string) */
#define SSH_CMSG_EOF 19 /* */
#define SSH_SMSG_EXITSTATUS 20 /* status (int) */
#define SSH_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* channel (int) */
#define SSH_MSG_CHANNEL_OPEN_FAILURE 22 /* channel (int) */
#define SSH_MSG_CHANNEL_DATA 23 /* ch,data (int,str) */
#define SSH_MSG_CHANNEL_CLOSE 24 /* channel (int) */
#define SSH_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* channel (int) */
/* SSH_CMSG_X11_REQUEST_FORWARDING 26 OBSOLETE */
#define SSH_SMSG_X11_OPEN 27 /* channel (int) */
#define SSH_CMSG_PORT_FORWARD_REQUEST 28 /* p,host,hp (i,s,i) */
#define SSH_MSG_PORT_OPEN 29 /* ch,h,p (i,s,i) */
#define SSH_CMSG_AGENT_REQUEST_FORWARDING 30 /* */
#define SSH_SMSG_AGENT_OPEN 31 /* port (int) */
#define SSH_MSG_IGNORE 32 /* string */
#define SSH_CMSG_EXIT_CONFIRMATION 33 /* */
#define SSH_CMSG_X11_REQUEST_FORWARDING 34 /* proto,data (s,s) */
#define SSH_CMSG_AUTH_RHOSTS_RSA 35 /* user,mod (s,mpi) */
#define SSH_MSG_DEBUG 36 /* string */
#define SSH_CMSG_REQUEST_COMPRESSION 37 /* level 1-9 (int) */
#define SSH_CMSG_MAX_PACKET_SIZE 38 /* size 4k-1024k (int) */
#define SSH_CMSG_AUTH_TIS 39 /* we use this for s/key */
#define SSH_SMSG_AUTH_TIS_CHALLENGE 40 /* challenge (string) */
#define SSH_CMSG_AUTH_TIS_RESPONSE 41 /* response (string) */
#define SSH_CMSG_AUTH_KERBEROS 42 /* (KTEXT) */
#define SSH_SMSG_AUTH_KERBEROS_RESPONSE 43 /* (KTEXT) */
#define SSH_CMSG_HAVE_KERBEROS_TGT 44 /* credentials (s) */
#define SSH_CMSG_HAVE_AFS_TOKEN 65 /* token (s) */
/* protocol version 1.5 overloads some version 1.3 message types */
#define SSH_MSG_CHANNEL_INPUT_EOF SSH_MSG_CHANNEL_CLOSE
#define SSH_MSG_CHANNEL_OUTPUT_CLOSE SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
/*
* Authentication methods. New types can be added, but old types should not
* be removed for compatibility. The maximum allowed value is 31.
*/
#define SSH_AUTH_RHOSTS 1
#define SSH_AUTH_RSA 2
#define SSH_AUTH_PASSWORD 3
#define SSH_AUTH_RHOSTS_RSA 4
#define SSH_AUTH_TIS 5
#define SSH_AUTH_KERBEROS 6
#define SSH_PASS_KERBEROS_TGT 7
/* 8 to 15 are reserved */
#define SSH_PASS_AFS_TOKEN 21
/* Protocol flags. These are bit masks. */
#define SSH_PROTOFLAG_SCREEN_NUMBER 1 /* X11 forwarding includes screen */
#define SSH_PROTOFLAG_HOST_IN_FWD_OPEN 2 /* forwarding opens contain host */
/* cipher flags. they are bit numbers */
#define SSH_CIPHER_NONE 0 /* No encryption */
#define SSH_CIPHER_IDEA 1 /* IDEA in CFB mode */
#define SSH_CIPHER_DES 2 /* DES in CBC mode */
#define SSH_CIPHER_3DES 3 /* Triple-DES in CBC mode */
#define SSH_CIPHER_RC4 5 /* RC4 */
#define SSH_CIPHER_BLOWFISH 6
#endif

View File

@ -1,80 +0,0 @@
#ifndef __SSH2_H
#define __SSH2_H
#define SSH2_MSG_DISCONNECT 1
#define SSH2_MSG_IGNORE 2
#define SSH2_MSG_UNIMPLEMENTED 3
#define SSH2_MSG_DEBUG 4
#define SSH2_MSG_SERVICE_REQUEST 5
#define SSH2_MSG_SERVICE_ACCEPT 6
#define SSH2_MSG_KEXINIT 20
#define SSH2_MSG_NEWKEYS 21
#define SSH2_MSG_KEXDH_INIT 30
#define SSH2_MSG_KEXDH_REPLY 31
#define SSH2_MSG_KEX_ECDH_INIT 30
#define SSH2_MSG_KEX_ECDH_REPLY 31
#define SSH2_MSG_ECMQV_INIT 30
#define SSH2_MSG_ECMQV_REPLY 31
#define SSH2_MSG_KEX_DH_GEX_REQUEST_OLD 30
#define SSH2_MSG_KEX_DH_GEX_GROUP 31
#define SSH2_MSG_KEX_DH_GEX_INIT 32
#define SSH2_MSG_KEX_DH_GEX_REPLY 33
#define SSH2_MSG_KEX_DH_GEX_REQUEST 34
#define SSH2_MSG_USERAUTH_REQUEST 50
#define SSH2_MSG_USERAUTH_FAILURE 51
#define SSH2_MSG_USERAUTH_SUCCESS 52
#define SSH2_MSG_USERAUTH_BANNER 53
#define SSH2_MSG_USERAUTH_PK_OK 60
#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60
#define SSH2_MSG_USERAUTH_INFO_REQUEST 60
#define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
#define SSH2_MSG_USERAUTH_INFO_RESPONSE 61
#define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
#define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
#define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
#define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
#define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
#define SSH2_MSG_GLOBAL_REQUEST 80
#define SSH2_MSG_REQUEST_SUCCESS 81
#define SSH2_MSG_REQUEST_FAILURE 82
#define SSH2_MSG_CHANNEL_OPEN 90
#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91
#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92
#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93
#define SSH2_MSG_CHANNEL_DATA 94
#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95
#define SSH2_MSG_CHANNEL_EOF 96
#define SSH2_MSG_CHANNEL_CLOSE 97
#define SSH2_MSG_CHANNEL_REQUEST 98
#define SSH2_MSG_CHANNEL_SUCCESS 99
#define SSH2_MSG_CHANNEL_FAILURE 100
#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1
#define SSH2_DISCONNECT_PROTOCOL_ERROR 2
#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3
#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4
#define SSH2_DISCONNECT_RESERVED 4
#define SSH2_DISCONNECT_MAC_ERROR 5
#define SSH2_DISCONNECT_COMPRESSION_ERROR 6
#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7
#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8
#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9
#define SSH2_DISCONNECT_CONNECTION_LOST 10
#define SSH2_DISCONNECT_BY_APPLICATION 11
#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12
#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13
#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14
#define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15
#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1
#define SSH2_OPEN_CONNECT_FAILED 2
#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3
#define SSH2_OPEN_RESOURCE_SHORTAGE 4
#define SSH2_EXTENDED_DATA_STDERR 1
#endif

View File

@ -1,41 +0,0 @@
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef STRING_H_
#define STRING_H_
#include "libssh/priv.h"
/* must be 32 bits number + immediately our data */
#ifdef _MSC_VER
#pragma pack(1)
#endif
struct ssh_string_struct {
uint32_t size;
unsigned char data[1];
}
#if defined(__GNUC__)
__attribute__ ((packed))
#endif
#ifdef _MSC_VER
#pragma pack()
#endif
;
#endif /* STRING_H_ */

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