diff --git a/.gitignore b/.gitignore index 3205411..3c52813 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,7 @@ __pycache__ /external/libssh-win-static/lib /external/mbedtls /external/sqlite +/external/libuv /client/tools/putty /client/tools/winscp @@ -69,3 +70,5 @@ __pycache__ # for not finished code /common/libex/test /client/tp_rdp +/server/tp_core/protocol/rdp +/client/tools/tprdp diff --git a/build/.idea/build.iml b/build/.idea/build.iml index 9081e23..8a94704 100644 --- a/build/.idea/build.iml +++ b/build/.idea/build.iml @@ -2,7 +2,7 @@ - + diff --git a/build/builder/build-assist.py b/build/builder/build-assist.py index a068001..85ab1e0 100644 --- a/build/builder/build-assist.py +++ b/build/builder/build-assist.py @@ -58,72 +58,27 @@ class BuilderWin(BuilderBase): self._build_installer() - # last_ver = 'teleport-assist-last-win.zip' - # if os.path.exists(os.path.join(ROOT_PATH, 'dist', last_ver)): - # utils.remove(os.path.join(ROOT_PATH, 'dist', last_ver)) - - # utils.copy_file(os.path.join(ROOT_PATH, 'dist'), os.path.join(ROOT_PATH, 'dist'), ('{}.zip'.format(name), last_ver)) - - # cc.n('build assist package for backend...') - # name = 'teleport-assist-last-win' - # utils.remove(os.path.join(ROOT_PATH, 'dist', '{}.zip'.format(name))) - # self._build_installer(name) - - # utils.copy_file(os.path.join(ROOT_PATH, 'dist'), os.path.join(ROOT_PATH, 'web', 'site', 'teleport', 'static', 'download'), 'teleport-assist-win.zip') - utils.ensure_file_exists(out_file) - # @staticmethod - # def _build_installer(name): - # base_path = os.path.join(ROOT_PATH, 'out', 'client') - # base_tmp = os.path.join(base_path, '_tmp_') - # tmp_path = os.path.join(base_tmp, name) - # - # if os.path.exists(base_tmp): - # utils.remove(base_tmp) - # - # utils.makedirs(tmp_path) - # - # utils.copy_file(os.path.join(ROOT_PATH, 'out', 'client', ctx.bits_path, ctx.target_path), tmp_path, 'tp_assist.exe') - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_path, ('ssh_client.ini', 'ssh_client.ini')) - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_path, ('scp_client.ini', 'scp_client.ini')) - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tp_assist', 'cfg'), tmp_path, ('telnet_client.ini', 'telnet_client.ini')) - # - # utils.copy_ex(os.path.join(ROOT_PATH, 'client', 'tp_assist'), tmp_path, 'site') - # - # # utils.makedirs(os.path.join(tmp_path, 'tools', 'tprdp')) - # utils.makedirs(os.path.join(tmp_path, 'tools', 'putty')) - # utils.makedirs(os.path.join(tmp_path, 'tools', 'winscp')) - # # utils.copy_file(os.path.join(ROOT_PATH, 'out', 'tp_rdp', ctx.bits_path, ctx.target_path), os.path.join(tmp_path, 'tools', 'tprdp'), 'tp_rdp.exe') - # # utils.copy_file(os.path.join(ROOT_PATH, 'tools', 'tprdp'), os.path.join(tmp_path, 'tools', 'tprdp'), 'tprdp-client.exe') - # # utils.copy_file(os.path.join(ROOT_PATH, 'tools', 'tprdp'), os.path.join(tmp_path, 'tools', 'tprdp'), 'tprdp-replay.exe') - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'putty'), os.path.join(tmp_path, 'tools', 'putty'), 'putty.exe') - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'winscp'), os.path.join(tmp_path, 'tools', 'winscp'), 'WinSCP.exe') - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools', 'winscp'), os.path.join(tmp_path, 'tools', 'winscp'), 'license.txt') - # utils.copy_file(os.path.join(ROOT_PATH, 'client', 'tools'), os.path.join(tmp_path, 'tools'), 'securecrt-telnet.vbs') - # - # # utils.makedirs(os.path.join(tmp_path, 'data')) - # # 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) - @staticmethod def _build_installer(): tmp_path = os.path.join(env.root_path, 'dist', 'client', 'windows', 'assist') 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_app_path, 'cfg') if os.path.exists(tmp_app_path): utils.remove(tmp_app_path) - if os.path.exists(tmp_cfg_path): - utils.remove(tmp_cfg_path) + # if os.path.exists(tmp_cfg_path): + # utils.remove(tmp_cfg_path) utils.makedirs(tmp_app_path) utils.makedirs(tmp_cfg_path) 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(env.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, 'scp.ini') + # utils.copy_file(os.path.join(env.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, 'ssh.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(env.root_path, 'client', 'tp_assist', 'cfg'), tmp_cfg_path, 'telnet.ini') @@ -131,10 +86,18 @@ class BuilderWin(BuilderBase): 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', 'putty')) - utils.makedirs(os.path.join(tmp_app_path, 'tools', 'winscp')) utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'putty'), os.path.join(tmp_app_path, 'tools', 'putty'), 'putty.exe') + + utils.makedirs(os.path.join(tmp_app_path, 'tools', 'winscp')) 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(env.root_path, 'client', 'tools', 'winscp'), os.path.join(tmp_app_path, 'tools', 'winscp'), 'license.txt') + + utils.makedirs(os.path.join(tmp_app_path, 'tools', 'tprdp')) + utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'tprdp-client.exe') + utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'tprdp-replay.exe') + utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'libeay32.dll') + utils.copy_file(os.path.join(env.root_path, 'client', 'tools', 'tprdp'), os.path.join(tmp_app_path, 'tools', 'tprdp'), 'ssleay32.dll') + utils.copy_file(os.path.join(env.root_path, 'client', 'tools'), os.path.join(tmp_app_path, 'tools'), 'securecrt-telnet.vbs') utils.nsis_build(os.path.join(env.root_path, 'dist', 'client', 'windows', 'assist', 'installer.nsi')) diff --git a/build/builder/build-external.py b/build/builder/build-external.py index 0f7ed8d..70b34db 100644 --- a/build/builder/build-external.py +++ b/build/builder/build-external.py @@ -100,6 +100,7 @@ class BuilderWin(BuilderBase): 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.LIBUV_PATH_SRC = os.path.join(PATH_EXTERNAL, 'libuv') self.LIBSSH_PATH_SRC = os.path.join(PATH_EXTERNAL, 'libssh-win-static') self._prepare_python_header() @@ -226,6 +227,23 @@ class BuilderWin(BuilderBase): os.rename(os.path.join(PATH_EXTERNAL, 'mbedtls-mbedtls-{}'.format(env.ver_mbedtls)), self.MBEDTLS_PATH_SRC) else: cc.w('already exists, skip.') + return + cc.v('') + + # fix source file + utils.ensure_file_exists(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'include', 'mbedtls', 'config.h')) + utils.copy_file(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'include', 'mbedtls'), os.path.join(self.MBEDTLS_PATH_SRC, 'include', 'mbedtls'), 'config.h') + utils.ensure_file_exists(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'library', 'rsa.c')) + utils.copy_file(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'library'), os.path.join(self.MBEDTLS_PATH_SRC, 'library'), 'rsa.c') + + def _build_libuv(self, file_name): + cc.n('prepare libuv source code... ', end='') + if not os.path.exists(self.LIBUV_PATH_SRC): + cc.v('') + utils.unzip(os.path.join(PATH_DOWNLOAD, file_name), PATH_EXTERNAL) + os.rename(os.path.join(PATH_EXTERNAL, 'libuv-{}'.format(env.ver_libuv)), self.LIBUV_PATH_SRC) + else: + cc.w('already exists, skip.') def build_sqlite(self): cc.w('sqlite not need for Windows, skip.') @@ -308,7 +326,7 @@ class BuilderLinux(BuilderBase): old_p = os.getcwd() os.chdir(self.LIBUV_PATH_SRC) os.system('sh autogen.sh') - os.system('./configure --prefix={}'.format(self.PATH_RELEASE)) + os.system('./configure --prefix={} --with-pic'.format(self.PATH_RELEASE)) os.system('make') os.system('make install') os.chdir(old_p) @@ -346,52 +364,54 @@ class BuilderLinux(BuilderBase): f.writelines(fl) f.close() - # fix config.h - mkfile = os.path.join(self.MBEDTLS_PATH_SRC, 'include', 'mbedtls', 'config.h') - f = open(mkfile) - fl = f.readlines() - f.close() - - for i in range(len(fl)): - if fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED') >= 0: - fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n' - elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED') >= 0: - fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n' - elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED') >= 0: - fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n' - elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED') >= 0: - fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n' - elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED') >= 0: - fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n' - elif fl[i].find('#define MBEDTLS_SELF_TEST') >= 0: - fl[i] = '//#define MBEDTLS_SELF_TEST\n' - elif fl[i].find('#define MBEDTLS_SSL_RENEGOTIATION') >= 0: - fl[i] = '//#define MBEDTLS_SSL_RENEGOTIATION\n' - elif fl[i].find('#define MBEDTLS_ECDH_C') >= 0: - fl[i] = '//#define MBEDTLS_ECDH_C\n' - elif fl[i].find('#define MBEDTLS_ECDSA_C') >= 0: - fl[i] = '//#define MBEDTLS_ECDSA_C\n' - elif fl[i].find('#define MBEDTLS_ECP_C') >= 0: - fl[i] = '//#define MBEDTLS_ECP_C\n' - elif fl[i].find('#define MBEDTLS_NET_C') >= 0: - fl[i] = '//#define MBEDTLS_NET_C\n' - - elif fl[i].find('#define MBEDTLS_RSA_NO_CRT') >= 0: - fl[i] = '#define MBEDTLS_RSA_NO_CRT\n' - elif fl[i].find('#define MBEDTLS_SSL_PROTO_SSL3') >= 0: - fl[i] = '#define MBEDTLS_SSL_PROTO_SSL3\n' - - f = open(mkfile, 'w') - f.writelines(fl) - f.close() + # # fix config.h + # mkfile = os.path.join(self.MBEDTLS_PATH_SRC, 'include', 'mbedtls', 'config.h') + # f = open(mkfile) + # fl = f.readlines() + # f.close() + # + # for i in range(len(fl)): + # if fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED') >= 0: + # fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED\n' + # elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED') >= 0: + # fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED\n' + # elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED') >= 0: + # fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED\n' + # elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED') >= 0: + # fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED\n' + # elif fl[i].find('#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED') >= 0: + # fl[i] = '//#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED\n' + # elif fl[i].find('#define MBEDTLS_SELF_TEST') >= 0: + # fl[i] = '//#define MBEDTLS_SELF_TEST\n' + # elif fl[i].find('#define MBEDTLS_SSL_RENEGOTIATION') >= 0: + # fl[i] = '//#define MBEDTLS_SSL_RENEGOTIATION\n' + # elif fl[i].find('#define MBEDTLS_ECDH_C') >= 0: + # fl[i] = '//#define MBEDTLS_ECDH_C\n' + # elif fl[i].find('#define MBEDTLS_ECDSA_C') >= 0: + # fl[i] = '//#define MBEDTLS_ECDSA_C\n' + # elif fl[i].find('#define MBEDTLS_ECP_C') >= 0: + # fl[i] = '//#define MBEDTLS_ECP_C\n' + # elif fl[i].find('#define MBEDTLS_NET_C') >= 0: + # fl[i] = '//#define MBEDTLS_NET_C\n' + # + # elif fl[i].find('#define MBEDTLS_RSA_NO_CRT') >= 0: + # fl[i] = '#define MBEDTLS_RSA_NO_CRT\n' + # elif fl[i].find('#define MBEDTLS_SSL_PROTO_SSL3') >= 0: + # fl[i] = '#define MBEDTLS_SSL_PROTO_SSL3\n' + # + # f = open(mkfile, 'w') + # f.writelines(fl) + # f.close() # fix source file + utils.ensure_file_exists(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'include', 'mbedtls', 'config.h')) + utils.copy_file(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'include', 'mbedtls'), os.path.join(self.MBEDTLS_PATH_SRC, 'include', 'mbedtls'), 'config.h') utils.ensure_file_exists(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'library', 'rsa.c')) utils.copy_file(os.path.join(PATH_EXTERNAL, 'fix-external', 'mbedtls', 'library'), os.path.join(self.MBEDTLS_PATH_SRC, 'library'), 'rsa.c') old_p = os.getcwd() os.chdir(self.MBEDTLS_PATH_SRC) - os.system('make lib') + os.system('make CFLAGS="-fPIC" lib') os.system('make install') os.chdir(old_p) @@ -483,8 +503,8 @@ class BuilderLinux(BuilderBase): os.chdir(old_p) def fix_output(self): - # remove .so files, otherwise eom_ts will link to .so but not .a in default. - rm = ['libsqlite3.la', 'libsqlite3.so.0', 'libuv.la', 'libuv.so.1', 'libsqlite3.so', 'libsqlite3.so.0.8.6', 'libuv.so', 'libuv.so.1.0.0'] + # remove .so files, otherwise will link to .so but not .a in default. + rm = ['libsqlite3.la', 'libsqlite3.so.0', 'libsqlite3.so', 'libsqlite3.so.0.8.6', 'libuv.la', 'libuv.so.1', 'libuv.so', 'libuv.so.1.0.0'] for i in rm: _path = os.path.join(self.PATH_RELEASE, 'lib', i) if os.path.exists(_path): @@ -527,12 +547,12 @@ def main(): builder.build_jsoncpp() builder.build_mongoose() builder.build_openssl() - ####builder.build_libuv() + builder.build_libuv() builder.build_mbedtls() builder.build_libssh() builder.build_sqlite() - # - # builder.fix_output() + + builder.fix_output() if __name__ == '__main__': diff --git a/build/builder/build-installer.py b/build/builder/build-installer.py index c597633..e7f4fa8 100644 --- a/build/builder/build-installer.py +++ b/build/builder/build-installer.py @@ -128,6 +128,7 @@ class BuilderLinux(BuilderBase): 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, 'libtpssh.so') + utils.copy_ex(out_path, bin_path, 'libtprdp.so') utils.copy_ex(os.path.join(env.root_path, 'out', 'pysrt'), bin_path, (ctx.dist_path, 'pysrt')) diff --git a/build/builder/build-server.py b/build/builder/build-server.py index cfc6184..a0dcf4d 100644 --- a/build/builder/build-server.py +++ b/build/builder/build-server.py @@ -25,12 +25,16 @@ class BuilderWin(BuilderBase): def build_server(self): cc.n('build web server ...') - sln_file = os.path.join(env.root_path, 'server', 'tp_web', 'src', 'tp_web.vs2015.sln') - 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): - utils.remove(out_file) - utils.msvc_build(sln_file, 'tp_web', ctx.target_path, ctx.bits_path, False) - utils.ensure_file_exists(out_file) + # notice: now we can not build debug version of tp_web.exe + if ctx.target_path == 'debug': + cc.w('cannot build debug version of tp_web, skip.') + else: + sln_file = os.path.join(env.root_path, 'server', 'tp_web', 'src', 'tp_web.vs2015.sln') + 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): + utils.remove(out_file) + utils.msvc_build(sln_file, 'tp_web', ctx.target_path, ctx.bits_path, False) + utils.ensure_file_exists(out_file) cc.n('build core server ...') sln_file = os.path.join(env.root_path, 'server', 'tp_core', 'core', 'tp_core.vs2015.sln') @@ -48,11 +52,14 @@ class BuilderWin(BuilderBase): utils.msvc_build(sln_file, 'tpssh', ctx.target_path, ctx.bits_path, False) utils.ensure_file_exists(out_file) - # - # s = os.path.join(env.root_path, 'out', 'console', ctx.bits_path, ctx.target_path, 'console.exe') - # t = os.path.join(env.root_path, 'out', 'eom_agent', ctx.target_path, ctx.dist_path, 'eom_agent.com') - # shutil.copy(s, t) - # utils.ensure_file_exists(t) + if os.path.exists(os.path.join(env.root_path, 'server', 'tp_core', 'protocol', 'ssh', 'tpssh.vs2015.sln')): + cc.n('build RDP protocol ...') + sln_file = os.path.join(env.root_path, 'server', 'tp_core', 'protocol', 'rdp', 'tprdp.vs2015.sln') + out_file = os.path.join(env.root_path, 'out', 'server', ctx.bits_path, ctx.target_path, 'tprdp.dll') + if os.path.exists(out_file): + utils.remove(out_file) + utils.msvc_build(sln_file, 'tprdp', ctx.target_path, ctx.bits_path, False) + utils.ensure_file_exists(out_file) class BuilderLinux(BuilderBase): diff --git a/build/builder/core/ver.py b/build/builder/core/ver.py index 3f9aceb..153b46d 100644 --- a/build/builder/core/ver.py +++ b/build/builder/core/ver.py @@ -1,3 +1,3 @@ # -*- coding: utf8 -*- -VER_TELEPORT_SERVER = "2.1.2.1" -VER_TELEPORT_ASSIST = "2.1.2.1" +VER_TELEPORT_SERVER = "2.2.5.1" +VER_TELEPORT_ASSIST = "2.2.5.1" diff --git a/client/tp_assist/site/index.html b/client/tp_assist/site/index.html index dda9547..2325531 100644 --- a/client/tp_assist/site/index.html +++ b/client/tp_assist/site/index.html @@ -16,9 +16,6 @@ - - - @@ -33,7 +30,7 @@ @@ -82,21 +79,6 @@ - - - - - - - - - - - - - - -
diff --git a/client/tp_assist/tp_assist.rc b/client/tp_assist/tp_assist.rc index 015023a..3297ee5 100644 Binary files a/client/tp_assist/tp_assist.rc and b/client/tp_assist/tp_assist.rc differ diff --git a/client/tp_assist/tp_assist.vs2015.vcxproj b/client/tp_assist/tp_assist.vs2015.vcxproj index a7293a5..cdfceab 100644 --- a/client/tp_assist/tp_assist.vs2015.vcxproj +++ b/client/tp_assist/tp_assist.vs2015.vcxproj @@ -1,185 +1,185 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {63B7A8F2-9722-487C-A92A-3DB5D8CA1473} - Win32Proj - tp_assist - tp_assist - 8.1 - - - - Application - true - v140_xp - Unicode - - - Application - false - v140_xp - true - Unicode - false - - - - - - - - - - - - - true - ..\..\out\client\$(PlatformTarget)\$(Configuration)\ - ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - D:\apps\vld\include;$(IncludePath) - D:\apps\vld\lib\Win32;$(LibraryPath) - - - false - ..\..\out\client\$(PlatformTarget)\$(Configuration)\ - ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - - Use - Level3 - Disabled - 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) - true - ..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32 - - - Windows - true - ..\..\external\openssl\out32\ssleay32.lib;..\..\external\openssl\out32\libeay32.lib;%(AdditionalDependencies) - - - - - Level3 - Use - MaxSpeed - true - true - 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) - true - ..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32 - MultiThreaded - - - Windows - true - true - true - ..\..\external\openssl\out32\ssleay32.lib;..\..\external\openssl\out32\libeay32.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - NotUsing - NotUsing - - - - - Create - Create - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + + {63B7A8F2-9722-487C-A92A-3DB5D8CA1473} + Win32Proj + tp_assist + tp_assist + 8.1 + + + + Application + true + v140_xp + Unicode + + + Application + false + v140_xp + true + Unicode + false + + + + + + + + + + + + + true + ..\..\out\client\$(PlatformTarget)\$(Configuration)\ + ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + false + ..\..\out\client\$(PlatformTarget)\$(Configuration)\ + ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + + Use + Level3 + Disabled + 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) + true + ..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32 + + + Windows + true + ..\..\external\openssl\out32\ssleay32.lib;..\..\external\openssl\out32\libeay32.lib;%(AdditionalDependencies) + + + + + Level3 + Use + MaxSpeed + true + true + 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) + true + ..\..\common\teleport;..\..\common\libex\include;..\..\external\jsoncpp\include;..\..\external\openssl\inc32 + MultiThreaded + + + Windows + true + true + true + ..\..\external\openssl\out32\ssleay32.lib;..\..\external\openssl\out32\libeay32.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + NotUsing + NotUsing + + + + + Create + Create + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/client/tp_assist/ts_env.cpp b/client/tp_assist/ts_env.cpp index 9d0be5b..c2d24ee 100644 --- a/client/tp_assist/ts_env.cpp +++ b/client/tp_assist/ts_env.cpp @@ -4,7 +4,7 @@ #include #ifdef EX_OS_WIN32 # include -# include +//# include #endif TsEnv g_env; @@ -28,20 +28,31 @@ bool TsEnv::init(void) if (!ex_dirname(m_exec_path)) 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); + ex_path_join(m_ssh_client_conf_file, false, L"cfg", 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); + ex_path_join(m_scp_client_conf_file, false, L"cfg", 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); + ex_path_join(m_telnet_client_conf_file, false, L"cfg", L"telnet.ini", NULL); m_log_path = m_exec_path; ex_path_join(m_log_path, false, L"log", NULL); +#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); @@ -49,20 +60,20 @@ bool TsEnv::init(void) ex_path_join(m_tools_path, true, L"..", L"..", L"..", L"..", L"client", L"tools", NULL); #else - TCHAR szBuf[PATH_MAX] = { 0 }; - SHGetSpecialFolderPathW(NULL, szBuf, CSIDL_APPDATA, FALSE); - - m_ssh_client_conf_file = szBuf;// m_exec_path; - 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; - 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; - 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; - ex_path_join(m_log_path, false, L"eomsoft", L"teleport", L"assist", L"log", NULL); +// TCHAR szBuf[PATH_MAX] = { 0 }; +// SHGetSpecialFolderPathW(NULL, szBuf, CSIDL_APPDATA, FALSE); +// +// m_ssh_client_conf_file = szBuf;// m_exec_path; +// 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; +// 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; +// 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; +// ex_path_join(m_log_path, false, L"eomsoft", L"teleport", L"assist", L"log", NULL); m_site_path = m_exec_path; ex_path_join(m_site_path, false, L"site", NULL); diff --git a/client/tp_assist/ts_http_rpc.cpp b/client/tp_assist/ts_http_rpc.cpp index f7622dc..012ed45 100644 --- a/client/tp_assist/ts_http_rpc.cpp +++ b/client/tp_assist/ts_http_rpc.cpp @@ -44,8 +44,15 @@ End Sub ֹˣubuntuԣ֪Ƿܹ֧еLinuxSecureCRTԴ˱ʾԡ */ +// #define RDP_CLIENT_SYSTEM_BUILTIN +// #define RDP_CLIENT_SYSTEM_ACTIVE_CONTROL +#define RDP_CLIENT_FREERDP + + +#ifdef RDP_CLIENT_SYSTEM_BUILTIN +#include +#pragma comment(lib, "Crypt32.lib") -#if 0 std::string rdp_content = "\ connect to console:i:%d\n\ screen mode id:i:%d\n\ @@ -64,31 +71,30 @@ audiocapturemode:i:0\n\ negotiate security layer:i:1\n\ videoplaybackmode:i:1\n\ connection type:i:2\n\ -prompt for credentials on client:i:1\r\n\ +prompt for credentials on client:i:0\n\ displayconnectionbar:i:1\n\ disable wallpaper:i:1\n\ allow font smoothing:i:0\n\ allow desktop composition:i:0\n\ disable full window drag:i:1\n\ disable menu anims:i:1\n\ -disable themes:i:0\n\ +disable themes:i:1\n\ disable cursor setting:i:0\n\ bitmapcachepersistenable:i:1\n\ audiomode:i:0\n\ -redirectprinters:i:1\n\ +redirectprinters:i:0\n\ redirectcomports:i:0\n\ -redirectsmartcards:i:1\n\ +redirectsmartcards:i:0\n\ redirectclipboard:i:1\n\ redirectposdevices:i:0\n\ -redirectdirectx:i:1\n\ -autoreconnection enabled:i:1\n\ -autoreconnection enabled:i:1\n\ +redirectdirectx:i:0\n\ +autoreconnection enabled:i:0\n\ drivestoredirect:s:*\n\ -password 51:b:01000000D08C9DDF0115D1118C7A00C04FC297EB0100000052A9E191EA75A948B359790578C9371A0000000008000000700073007700000003660000A8000000100000000A1DCCD2E50775CA25EC3857164B34DC0000000004800000A000000010000000FCE1A645B9B61AA450946BB6F955058108020000D83591CA47562D6DDAA689F050AE145039EBE22E00D1D3AEAA98373C7B63C3E8E7149072DF989EA43EFCE20513AD3D27B11BE7F17066A688E1DCE828AF85460AAC327B38E90776DB962888E4393D19637578984B19A187AAD95F6D2726ADE7DD315FF56C15FF5B3031014EDDCC3C24D1B81779AFDB006EE575F5BEFB8D2D2138D9D9D642BBB251CC5ED7226968764856EC660A646BACE748A13D6002A9A537AA70710615650B9387EED66DE28BD57B304BBDD7B581B943DA628EB0289E30A8BA784B76F7885BECCAB4FEF7820E97EE3C6E036EEAF6EAA669288DF2FCACC9BEC045C907EBBDE87AFB8CC6B07A600BD63AC891B61D95C2265DD9FD5E635D61BFBF5EDC28311375066611C610FB533D64515B643C82F57D9B183B05C156D91BC0974D38E546022B139E82452E6F1EDF76E52F732C3904E5E433F8F3D488DB0698427DBB0791A9F207F8CB6654CB8410BAF4A59C4F9E821E589ABC1E6E6E1D432181B690408F6884FE1007895A4D26D4A5A2C7458EE747DA35D44AC9FB08AB5477EA3E7CCDB3E37EE20FAFD0D0CF9584E420598B7003B347943AC28048F45E0FD21AD08148FFADCE0E7877219259A7BE722FFAE845A429BA2CF0A71F2D19EA7495530FABDB5106E8D404A38A7E6394C38457640EA7398C5D55F0C4D342CC6A39C77E10A2A5145AEA40B14F5C7C3760334D83C9BE748383FADE231248537353817D51F7B44F61B406ABC61400000071C354139F458B02D978015F785B97F7F6B307380\n\ +password 51:b:%s\n\ "; -//password\n\ -//51:b:01000000"; +//password 51:b:01000000D08C9DDF0115D1118C7A00C04FC297EB0100000052A9E191EA75A948B359790578C9371A0000000008000000700073007700000003660000A8000000100000000A1DCCD2E50775CA25EC3857164B34DC0000000004800000A000000010000000FCE1A645B9B61AA450946BB6F955058108020000D83591CA47562D6DDAA689F050AE145039EBE22E00D1D3AEAA98373C7B63C3E8E7149072DF989EA43EFCE20513AD3D27B11BE7F17066A688E1DCE828AF85460AAC327B38E90776DB962888E4393D19637578984B19A187AAD95F6D2726ADE7DD315FF56C15FF5B3031014EDDCC3C24D1B81779AFDB006EE575F5BEFB8D2D2138D9D9D642BBB251CC5ED7226968764856EC660A646BACE748A13D6002A9A537AA70710615650B9387EED66DE28BD57B304BBDD7B581B943DA628EB0289E30A8BA784B76F7885BECCAB4FEF7820E97EE3C6E036EEAF6EAA669288DF2FCACC9BEC045C907EBBDE87AFB8CC6B07A600BD63AC891B61D95C2265DD9FD5E635D61BFBF5EDC28311375066611C610FB533D64515B643C82F57D9B183B05C156D91BC0974D38E546022B139E82452E6F1EDF76E52F732C3904E5E433F8F3D488DB0698427DBB0791A9F207F8CB6654CB8410BAF4A59C4F9E821E589ABC1E6E6E1D432181B690408F6884FE1007895A4D26D4A5A2C7458EE747DA35D44AC9FB08AB5477EA3E7CCDB3E37EE20FAFD0D0CF9584E420598B7003B347943AC28048F45E0FD21AD08148FFADCE0E7877219259A7BE722FFAE845A429BA2CF0A71F2D19EA7495530FABDB5106E8D404A38A7E6394C38457640EA7398C5D55F0C4D342CC6A39C77E10A2A5145AEA40B14F5C7C3760334D83C9BE748383FADE231248537353817D51F7B44F61B406ABC61400000071C354139F458B02D978015F785B97F7F6B307380\n\ +//password 51:b:01000000"; #endif @@ -116,7 +122,6 @@ void http_rpc_stop(void) g_http_interface.stop(); } - #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) @@ -154,6 +159,34 @@ int ts_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_f return i >= src_len ? j : -1; } +#ifdef RDP_CLIENT_SYSTEM_BUILTIN +bool calc_psw51b(const char* password, std::string& ret) +{ + DATA_BLOB DataIn; + DATA_BLOB DataOut; + + ex_wstr w_pswd; + ex_astr2wstr(password, w_pswd, EX_CODEPAGE_ACP); + + DataIn.cbData = w_pswd.length() * sizeof(wchar_t); + DataIn.pbData = (BYTE*)w_pswd.c_str(); + + + if (!CryptProtectData(&DataIn, L"psw", NULL, NULL, NULL, 0, &DataOut)) + return false; + + char szRet[5] = {0}; + for (int i = 0; i < DataOut.cbData; ++i) + { + sprintf_s(szRet, 5, "%02X", DataOut.pbData[i]); + ret += szRet; + } + + LocalFree(DataOut.pbData); + return true; +} +#endif + TsHttpRpc::TsHttpRpc() { m_stop = false; @@ -582,9 +615,9 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu //============================================== // RDP //============================================== -#if 1 +//#if 1 -#if 0 +#if defined(RDP_CLIENT_SYSTEM_ACTIVE_CONTROL) int split_pos = session_id.length() - 2; std::string real_s_id = session_id.substr(0, split_pos); std::string str_pwd_len = session_id.substr(split_pos, session_id.length()); @@ -624,7 +657,7 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu w_exe_path += w_szCommandLine; //BOOL bRet = DeleteFile(w_sz_file_name.c_str()); -#else +#elif defined(RDP_CLIENT_FREERDP) wchar_t* w_screen = NULL; switch (windows_size) @@ -677,9 +710,9 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu w_exe_path += w_szCommandLine; -#endif +//#endif -#else +#elif defined(RDP_CLIENT_SYSTEM_BUILTIN) int width = 800; int higth = 600; int cx = 0; @@ -741,12 +774,21 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu int split_pos = sid.length() - 2; std::string real_sid = sid.substr(0, split_pos); + std::string psw51b; + if (!calc_psw51b("Abcd1234", psw51b)) + { + printf("calc password failed.\n"); + _create_json_ret(buf, TPE_FAILED); + return; + } + char sz_rdp_file_content[4096] = { 0 }; sprintf_s(sz_rdp_file_content, rdp_content.c_str(), console, display, width, higth , cx, cy, cx + width + 20, cy + higth + 40 , teleport_ip.c_str(), teleport_port , real_sid.c_str() + , psw51b.c_str() ); char sz_file_name[MAX_PATH] = { 0 }; @@ -755,29 +797,32 @@ void TsHttpRpc::_rpc_func_create_ts_client(const ex_astr& func_args, ex_astr& bu if (ret <= 0) { printf("fopen failed (%d).\n", GetLastError()); - _create_json_ret(buf, TSR_GETTEMPPATH_ERROR); + _create_json_ret(buf, TPE_FAILED); return; } ex_wstr w_s_id; - ex_astr2str(real_sid, w_s_id); + ex_astr2wstr(real_sid, w_s_id); - ex_astr temp_host_ip = replace_all_distinct(real_host_ip, ("."), "-"); + ex_astr temp_host_ip = real_host_ip;// replace_all_distinct(real_host_ip, ("."), "-"); + ex_replace_all(temp_host_ip, ".", "-"); - sprintf_s(sz_file_name, ("%s\\%s.rdp"), temp_path, temp_host_ip.c_str()); - FILE* f = fopen(sz_file_name, ("wt")); - if (f == NULL) + sprintf_s(sz_file_name, ("%s%s.rdp"), temp_path, temp_host_ip.c_str()); + //FILE* f = fopen(sz_file_name, ("wt")); + //if (f == NULL) + FILE* f = NULL; + if(fopen_s(&f, sz_file_name, "wt") != 0) { printf("fopen failed (%d).\n", GetLastError()); - _create_json_ret(buf, TSR_OPENFILE_ERROR); + _create_json_ret(buf, TPE_OPENFILE); return; } // Write a string into the file. fwrite(sz_rdp_file_content, strlen(sz_rdp_file_content), 1, f); fclose(f); ex_wstr w_sz_file_name; - ex_astr2str(sz_file_name, w_sz_file_name); + ex_astr2wstr(sz_file_name, w_sz_file_name); - swprintf_s(w_szCommandLine, _T("mstsc %s"), w_sz_file_name.c_str()); + swprintf_s(w_szCommandLine, _T("mstsc \"%s\""), w_sz_file_name.c_str()); w_exe_path = w_szCommandLine; //BOOL bRet = DeleteFile(w_sz_file_name.c_str()); #endif diff --git a/client/tp_assist/ts_ver.h b/client/tp_assist/ts_ver.h index 42fc7d4..e015b3e 100644 --- a/client/tp_assist/ts_ver.h +++ b/client/tp_assist/ts_ver.h @@ -1,6 +1,6 @@ #ifndef __TS_ASSIST_VER_H__ #define __TS_ASSIST_VER_H__ -#define TP_ASSIST_VER L"2.1.2.1" +#define TP_ASSIST_VER L"2.2.5.1" #endif // __TS_ASSIST_VER_H__ diff --git a/common/libex/include/ex/ex_ini.h b/common/libex/include/ex/ex_ini.h index 7bd7f0a..746afa2 100644 --- a/common/libex/include/ex/ex_ini.h +++ b/common/libex/include/ex/ex_ini.h @@ -2,13 +2,13 @@ #define __EX_INI_H__ /* -رע⣺ +�ر�ע�⣺ -1. ֺ';' '#' Ϊעеĵһַ -2. ֧ע -3. ֵԵһȺŷָȺǰпոᱻԣ֮Ŀոᱣβո -4. вijСڵֵԣʹGetDumySection()ȡ - DumySectionҪΪܹݼ򵥵Pythonļļ +1. �� �ֺ�';' ���� ����'#' ��Ϊע���еĵ�һ���ַ� +2. ��֧������ע�� +3. ֵ���Ե�һ���Ⱥŷָ����Ⱥ�ǰ������пո�ᱻ���ԣ�֮��Ŀո�ᱣ����������β�ո� +4. ����в�����ij��С�ڵ�ֵ�ԣ�����ʹ��GetDumySection()��ȡ + DumySection��Ҫ��Ϊ���ܹ����ݼ򵥵�Python�ļ��������ļ��� */ #include "ex_str.h" @@ -77,6 +77,8 @@ public: ExIniFile(); ~ExIniFile(); + const ex_wstr& get_filename(void){return m_file_path;} + void ClearUp(void); // Read and parse special file. diff --git a/common/libex/include/ex/ex_log.h b/common/libex/include/ex/ex_log.h index 8f2ea78..29a1b41 100644 --- a/common/libex/include/ex/ex_log.h +++ b/common/libex/include/ex/ex_log.h @@ -61,6 +61,7 @@ protected: void EXLOG_USE_LOGGER(ExLogger* logger); void EXLOG_LEVEL(int min_level); +void EXLOG_DEBUG(bool debug_mode); // 趨־ļ·δָ·ΪִгĿ¼µlogĿ¼ void EXLOG_FILE(const wchar_t* log_file, const wchar_t* log_path = NULL, ex_u32 max_filesize = EX_LOG_FILE_MAX_SIZE, ex_u8 max_filecount = EX_LOG_FILE_MAX_COUNT); diff --git a/common/libex/include/ex/ex_platform.h b/common/libex/include/ex/ex_platform.h index a30ff36..f73ecdd 100644 --- a/common/libex/include/ex/ex_platform.h +++ b/common/libex/include/ex/ex_platform.h @@ -1,118 +1,143 @@ -#ifndef __LIB_EX_PLATFORM_H__ -#define __LIB_EX_PLATFORM_H__ - -#if defined(_WIN32) || defined(WIN32) -# define EX_OS_WIN32 -#elif defined(__linux__) -# define EX_OS_LINUX -# define EX_OS_UNIX -#elif defined(__APPLE__) -# define EX_OS_MACOS -# define EX_OS_UNIX -#else -# error unsupported platform. -#endif - -// compiler -#ifdef EX_OS_WIN32 -# ifndef _MSC_VER -# error need VisualStudio on Windows. -# endif -# if _MSC_VER < 1900 // need VisualStudio 2015 and above. -# error need VisualStudio 2015 and above. -# endif -#endif - -#ifdef EX_OS_WIN32 -# if !defined(UNICODE) && !defined(_UNICODE) -# error "Does not support `Multi-Byte Character Set` on Windows." -# endif -# ifdef _DEBUG -# ifndef EX_DEBUG -# define EX_DEBUG -# endif -# endif -#endif - - -#ifdef EX_OS_WIN32 -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0500 // 0x0500 = Windows2000 -# endif -# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers -# define _CRT_RAND_S // for rand_s(). -# include -# include -# include -# include -# define _CSTDIO_ -# define _CSTRING_ -# define _CWCHAR_ -# include -# include -# include -#else -# include -# include -# include -# include // free() -# include // va_start() -# include // readlink() -# include -# include -# include -# include -# include -#endif - - -/* -* On Windows PATH_MAX does not exist but MAX_PATH does. -* WinAPI MAX_PATH limit is only 256. MSVCR fuctions does not have this limit. -* Redefine PATH_MAX for Windows to support longer path names. -*/ -#if defined(EX_OS_WIN32) -# ifdef PATH_MAX -# undef PATH_MAX /* On Windows override PATH_MAX if defined. */ -# endif -# define PATH_MAX 1024 -#elif defined(EX_OS_LINUX) -# ifndef PATH_MAX -# define PATH_MAX 1024 -# endif -#elif defined(EX_OS_MACOS) -# define PATH_MAX 1024 /* Recommended value for OSX. */ -#endif - -// assert -#ifdef EX_DEBUG -# define ASSERT(exp) -# define CHECK(exp) do { if (!(exp)) abort(); } while (0) -//# define DEBUG_CHECKS (0) -#else -# include -# define ASSERT(exp) assert(exp) -# define CHECK(exp) assert(exp) -//# define DEBUG_CHECKS (1) -#endif - -#ifndef UNUSED -# if defined(_MSC_VER) -# define UNUSED(x) (void)(x) -# elif defined(__GUNC__) -# defined UNUSED(x) UNUSED_ ## x __attribute__((unused)) -# elif defined(__LCLINT__) -# define UNUSED(x) /*@unused@*/ x -# elif defined(__cplusplus) -# define UNUSED(x) -# else -# define UNUSED(x) (void)(x) -# endif -#endif - -#ifdef EX_OS_WIN32 -# pragma comment(lib, "shlwapi.lib") -#endif - - -#endif // __LIB_EX_PLATFORM_H__ +#ifndef __LIB_EX_PLATFORM_H__ +#define __LIB_EX_PLATFORM_H__ + +#if defined(_WIN32) || defined(WIN32) +# define EX_OS_WIN32 +#elif defined(__linux__) +# define EX_OS_LINUX +# define EX_OS_UNIX +#elif defined(__APPLE__) +# define EX_OS_MACOS +# define EX_OS_UNIX +#else +# error unsupported platform. +#endif + +// compiler +#ifdef EX_OS_WIN32 +# ifndef _MSC_VER +# error need VisualStudio on Windows. +# endif +# if _MSC_VER < 1900 // need VisualStudio 2015 and above. +# error need VisualStudio 2015 and above. +# endif +#endif + +#ifdef EX_OS_WIN32 +# if !defined(UNICODE) && !defined(_UNICODE) +# error "Does not support `Multi-Byte Character Set` on Windows." +# endif +# ifdef _DEBUG +# ifndef EX_DEBUG +# define EX_DEBUG +# endif +# endif +#endif + + +#ifdef EX_OS_WIN32 +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0502 // 0x0502 = WinServer2003 (libuv need this) 0x0501 = WinXP, 0x0500 = Win2000 +# endif +# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +# define _CRT_RAND_S // for rand_s(). +# include +# include +# include +# include +# define _CSTDIO_ +# define _CSTRING_ +# define _CWCHAR_ +# include +# include +# include +#else +# include +# include +# include +# include // free() +# include // va_start() +# include // readlink() +# include +# include +# include +# include +# include +#endif + + +/* +* On Windows PATH_MAX does not exist but MAX_PATH does. +* WinAPI MAX_PATH limit is only 256. MSVCR fuctions does not have this limit. +* Redefine PATH_MAX for Windows to support longer path names. +*/ +#if defined(EX_OS_WIN32) +# ifdef PATH_MAX +# undef PATH_MAX /* On Windows override PATH_MAX if defined. */ +# endif +# define PATH_MAX 1024 +#elif defined(EX_OS_LINUX) +# ifndef PATH_MAX +# define PATH_MAX 1024 +# endif +#elif defined(EX_OS_MACOS) +# define PATH_MAX 1024 /* Recommended value for OSX. */ +#endif + +// assert +#ifdef EX_DEBUG +# define ASSERT(exp) +# define CHECK(exp) do { if (!(exp)) abort(); } while (0) +//# define DEBUG_CHECKS (0) +#else +# include +# define ASSERT(exp) assert(exp) +# define CHECK(exp) assert(exp) +//# define DEBUG_CHECKS (1) +#endif + +#define UNREACHABLE() CHECK(!"Unreachable code reached.") + +#ifndef UNUSED +# if defined(_MSC_VER) +# define UNUSED(x) (void)(x) +# elif defined(__GUNC__) +# defined UNUSED(x) UNUSED_ ## x __attribute__((unused)) +# elif defined(__LCLINT__) +# define UNUSED(x) /*@unused@*/ x +# elif defined(__cplusplus) +# define UNUSED(x) +# else +# define UNUSED(x) (void)(x) +# endif +#endif + +/* check endian */ +#if !(defined(L_ENDIAN) || defined(B_ENDIAN)) +# if !defined(__BYTE_ORDER) && defined(__linux__) +# include +# endif + +# if defined(BYTE_ORDER) +# if BYTE_ORDER == BIG_ENDIAN +# define B_ENDIAN +# else +# define L_ENDIAN +# endif +# endif + +# if !(defined(L_ENDIAN) || defined(B_ENDIAN)) +# if defined(__sparc__) || defined(__PPC__) || defined(__ppc__) || defined(__hppa__) +# define B_ENDIAN +# else +# define L_ENDIAN +# endif +# endif +#endif + +#ifdef EX_OS_WIN32 +# pragma comment(lib, "shlwapi.lib") +#endif + + +#endif // __LIB_EX_PLATFORM_H__ diff --git a/common/libex/include/ex/ex_str.h b/common/libex/include/ex/ex_str.h index d204581..b5c4a43 100644 --- a/common/libex/include/ex/ex_str.h +++ b/common/libex/include/ex/ex_str.h @@ -1,83 +1,86 @@ -#ifndef __LIB_EX_STR_H__ -#define __LIB_EX_STR_H__ - -#include "ex_types.h" - -#define EX_CODEPAGE_ACP 0 -#define EX_CODEPAGE_UTF8 1 -#ifdef EX_OS_WIN32 -# define EX_CODEPAGE_DEFAULT EX_CODEPAGE_ACP -#else -# define EX_CODEPAGE_DEFAULT EX_CODEPAGE_UTF8 -#endif - -#define EX_RSC_BEGIN 0x01 -#define EX_RSC_END 0x02 -#define EX_RSC_ALL EX_RSC_BEGIN | EX_RSC_END - -//================================================= -// C Interface -//================================================= - -// copy a string from `source` to `target`. -// `size` is size of target buffer. -// if buffer is to small, NULL will return, but `size-1` characters have been copied. -char* ex_strcpy(char* target, size_t size, const char* source); -wchar_t* ex_wcscpy(wchar_t* target, size_t size, const wchar_t* source); - - -// dupilicate a string. -// must use ex_free() to release the returned value. -char* ex_strdup(const char* src); -wchar_t* ex_wcsdup(const wchar_t* src); - -// convert between mutli-bytes and wide char string. -// must use ex_free() to release the returned value. -wchar_t* ex_str2wcs_alloc(const char* in_buffer, int code_page); -char* ex_wcs2str_alloc(const wchar_t* in_buffer, int code_page); - -// convert char** argv to wchar_t** argv. -// must use ex_free_argv() to release the returned value. -wchar_t** ex_make_wargv(int argc, char** argv); -void ex_free_wargv(int argc, wchar_t** argv); - -EX_BOOL ex_str_only_white_space(const wchar_t* src); -EX_BOOL ex_wcs_only_white_space(const char* src); - - -int ex_strformat(char* out_buf, size_t buf_size, const char* fmt, ...); -int ex_wcsformat(wchar_t* out_buf, size_t buf_size, const wchar_t* fmt, ...); - -//================================================= -// C++ Interface -//================================================= -#ifdef __cplusplus - -#include -#include - -typedef std::string ex_astr; -typedef std::wstring ex_wstr; - -typedef std::vector ex_astrs; -typedef std::vector ex_wstrs; - -bool ex_wstr2astr(const ex_wstr& in_str, ex_astr& out_str, int code_page = EX_CODEPAGE_DEFAULT); -bool ex_wstr2astr(const wchar_t* in_str, ex_astr& out_str, int code_page = EX_CODEPAGE_DEFAULT); -bool ex_astr2wstr(const ex_astr& in_str, ex_wstr& out_str, int code_page = EX_CODEPAGE_DEFAULT); -bool ex_astr2wstr(const char* in_str, ex_wstr& out_str, int code_page = EX_CODEPAGE_DEFAULT); - -bool ex_only_white_space(const ex_astr& str_check); -bool ex_only_white_space(const ex_wstr& str_check); - -void ex_remove_white_space(ex_astr& str_fix, int ulFlag = EX_RSC_ALL); -void ex_remove_white_space(ex_wstr& str_fix, int ulFlag = EX_RSC_ALL); - -ex_astr& ex_replace_all(ex_astr& str, const ex_astr& old_value, const ex_astr& new_value); -ex_wstr& ex_replace_all(ex_wstr& str, const ex_wstr& old_value, const ex_wstr& new_value); - - -#endif - - -#endif // __LIB_EX_STR_H__ +#ifndef __LIB_EX_STR_H__ +#define __LIB_EX_STR_H__ + +#include "ex_types.h" + +#define EX_CODEPAGE_ACP 0 +#define EX_CODEPAGE_UTF8 1 +#ifdef EX_OS_WIN32 +# define EX_CODEPAGE_DEFAULT EX_CODEPAGE_ACP +#else +# define EX_CODEPAGE_DEFAULT EX_CODEPAGE_UTF8 +#endif + +#define EX_RSC_BEGIN 0x01 +#define EX_RSC_END 0x02 +#define EX_RSC_ALL EX_RSC_BEGIN | EX_RSC_END + +//================================================= +// C Interface +//================================================= + +// copy a string from `source` to `target`. +// `size` is size of target buffer. +// if buffer is to small, NULL will return, but `size-1` characters have been copied. +char* ex_strcpy(char* target, size_t size, const char* source); +wchar_t* ex_wcscpy(wchar_t* target, size_t size, const wchar_t* source); + + +// dupilicate a string. +// must use ex_free() to release the returned value. +char* ex_strdup(const char* src); +wchar_t* ex_wcsdup(const wchar_t* src); + +// convert between mutli-bytes and wide char string. +// must use ex_free() to release the returned value. +wchar_t* ex_str2wcs_alloc(const char* in_buffer, int code_page); +char* ex_wcs2str_alloc(const wchar_t* in_buffer, int code_page); + +// convert char** argv to wchar_t** argv. +// must use ex_free_argv() to release the returned value. +wchar_t** ex_make_wargv(int argc, char** argv); +void ex_free_wargv(int argc, wchar_t** argv); + +EX_BOOL ex_str_only_white_space(const wchar_t* src); +EX_BOOL ex_wcs_only_white_space(const char* src); + + +int ex_strformat(char* out_buf, size_t buf_size, const char* fmt, ...); +int ex_wcsformat(wchar_t* out_buf, size_t buf_size, const wchar_t* fmt, ...); + +//================================================= +// C++ Interface +//================================================= +#ifdef __cplusplus + +#include +#include + +typedef std::string ex_astr; +typedef std::wstring ex_wstr; + +typedef std::vector ex_astrs; +typedef std::vector ex_wstrs; +typedef std::vector ex_str_utf16le; + +bool ex_wstr2astr(const ex_wstr& in_str, ex_astr& out_str, int code_page = EX_CODEPAGE_DEFAULT); +bool ex_wstr2astr(const wchar_t* in_str, ex_astr& out_str, int code_page = EX_CODEPAGE_DEFAULT); +bool ex_astr2wstr(const ex_astr& in_str, ex_wstr& out_str, int code_page = EX_CODEPAGE_DEFAULT); +bool ex_astr2wstr(const char* in_str, ex_wstr& out_str, int code_page = EX_CODEPAGE_DEFAULT); + +bool ex_only_white_space(const ex_astr& str_check); +bool ex_only_white_space(const ex_wstr& str_check); + +void ex_remove_white_space(ex_astr& str_fix, int ulFlag = EX_RSC_ALL); +void ex_remove_white_space(ex_wstr& str_fix, int ulFlag = EX_RSC_ALL); + +ex_astr& ex_replace_all(ex_astr& str, const ex_astr& old_value, const ex_astr& new_value); +ex_wstr& ex_replace_all(ex_wstr& str, const ex_wstr& old_value, const ex_wstr& new_value); + +// UTF8ַתΪUTF16-LEַ\0 +bool ex_utf8_to_utf16le(const std::string& from, ex_str_utf16le& to); + +#endif + + +#endif // __LIB_EX_STR_H__ diff --git a/common/libex/include/ex/ex_types.h b/common/libex/include/ex/ex_types.h index 8993600..0187b0a 100644 --- a/common/libex/include/ex/ex_types.h +++ b/common/libex/include/ex/ex_types.h @@ -1,44 +1,44 @@ -#ifndef __LIB_EX_TYPE_H__ -#define __LIB_EX_TYPE_H__ - -#include "ex_platform.h" - -#include - -typedef signed char ex_i8; -typedef signed short ex_i16; - -typedef unsigned char ex_u8; -typedef unsigned short ex_u16; -typedef unsigned int ex_u32; -typedef unsigned long ex_ulong; - -#if defined(EX_OS_WIN32) -typedef unsigned __int64 ex_u64; -typedef signed __int64 ex_i64; -typedef wchar_t ex_utf16; -#else -typedef unsigned long long ex_u64; -typedef signed long long ex_i64; -typedef ex_u16 ex_utf16; -#endif - -typedef int EX_BOOL; -#define EX_TRUE 1 -#define EX_FALSE 0 - - -typedef std::vector ex_bin; -typedef std::vector ex_chars; - -typedef ex_u32 ex_rv; - - -#if defined(EX_OS_WIN32) -# define EX_DYLIB_HANDLE HINSTANCE -#else -# define EX_DYLIB_HANDLE void* -#endif - - -#endif // __LIB_EX_TYPE_H__ +#ifndef __LIB_EX_TYPE_H__ +#define __LIB_EX_TYPE_H__ + +#include "ex_platform.h" + +#include + +typedef signed char ex_i8; +typedef signed short ex_i16; + +typedef unsigned char ex_u8; +typedef unsigned short ex_u16; +typedef unsigned int ex_u32; +typedef unsigned long ex_ulong; + +#if defined(EX_OS_WIN32) +typedef unsigned __int64 ex_u64; +typedef signed __int64 ex_i64; +typedef wchar_t ex_utf16; +#else +typedef unsigned long long ex_u64; +typedef signed long long ex_i64; +typedef ex_i16 ex_utf16; +#endif + +typedef int EX_BOOL; +#define EX_TRUE 1 +#define EX_FALSE 0 + + +typedef std::vector ex_bin; +typedef std::vector ex_chars; + +typedef ex_u32 ex_rv; + + +#if defined(EX_OS_WIN32) +# define EX_DYLIB_HANDLE HINSTANCE +#else +# define EX_DYLIB_HANDLE void* +#endif + + +#endif // __LIB_EX_TYPE_H__ diff --git a/common/libex/include/ex/ex_util.h b/common/libex/include/ex/ex_util.h index eaaf3d0..f98918a 100644 --- a/common/libex/include/ex/ex_util.h +++ b/common/libex/include/ex/ex_util.h @@ -1,44 +1,45 @@ -#ifndef __LIB_EX_UTIL_H__ -#define __LIB_EX_UTIL_H__ - -#include -#include - -#ifdef EX_OS_WIN32 -# include -//# include -//# include -// #include -#else -// #include -# include -# include -#endif - -EX_BOOL ex_initialize(const char* lc_ctype); - -void ex_free(void* buffer); - -// haystackΪhaystacklenֽڣвneedleΪneedlelenʼַNULLʾûҵ -const ex_u8* ex_memmem(const ex_u8* haystack, size_t haystacklen, const ex_u8* needle, size_t needlelen); - -void ex_printf(const char* fmt, ...); -void ex_wprintf(const wchar_t* fmt, ...); - -ex_u64 ex_get_tick_count(void); -void ex_sleep_ms(int ms); - -EX_BOOL ex_localtime_now(int* t, struct tm* dt); - - -FILE* ex_fopen(const ex_wstr& filename, const wchar_t* mode); - - -EX_DYLIB_HANDLE ex_dlopen(const wchar_t* dylib_path); -void ex_dlclose(EX_DYLIB_HANDLE dylib); - - -// inet... -int ex_ip4_name(const struct sockaddr_in* src, char* dst, size_t size); - -#endif // __LIB_EX_UTIL_H__ +#ifndef __LIB_EX_UTIL_H__ +#define __LIB_EX_UTIL_H__ + +#include +#include + +#ifdef EX_OS_WIN32 +# include +//# include +//# include +// #include +#else +// #include +# include +# include +#endif + +EX_BOOL ex_initialize(const char* lc_ctype); + +void ex_free(void* buffer); + +// haystackΪhaystacklenֽڣвneedleΪneedlelenʼַNULLʾûҵ +const ex_u8* ex_memmem(const ex_u8* haystack, size_t haystacklen, const ex_u8* needle, size_t needlelen); +void ex_mem_reverse(ex_u8* p, size_t l); + +void ex_printf(const char* fmt, ...); +void ex_wprintf(const wchar_t* fmt, ...); + +ex_u64 ex_get_tick_count(void); +void ex_sleep_ms(int ms); + +EX_BOOL ex_localtime_now(int* t, struct tm* dt); + + +FILE* ex_fopen(const ex_wstr& filename, const wchar_t* mode); + + +EX_DYLIB_HANDLE ex_dlopen(const wchar_t* dylib_path); +void ex_dlclose(EX_DYLIB_HANDLE dylib); + + +// inet... +int ex_ip4_name(const struct sockaddr_in* src, char* dst, size_t size); + +#endif // __LIB_EX_UTIL_H__ diff --git a/common/libex/src/ex_ini.cpp b/common/libex/src/ex_ini.cpp index 71ac593..cbd60fc 100644 --- a/common/libex/src/ex_ini.cpp +++ b/common/libex/src/ex_ini.cpp @@ -232,6 +232,8 @@ bool ExIniFile::LoadFromFile(const ex_wstr& strFileName, bool bClearOld) fseek(f, 0L, SEEK_SET); fread(&vFile[0], 1, ulFileSize, f); fclose(f); + + m_file_path = strFileName; #endif char *pOffset = &vFile[0]; diff --git a/common/libex/src/ex_log.cpp b/common/libex/src/ex_log.cpp index 7b15378..7d1b552 100644 --- a/common/libex/src/ex_log.cpp +++ b/common/libex/src/ex_log.cpp @@ -31,6 +31,12 @@ void EXLOG_LEVEL(int min_level) g_exlog->min_level = min_level; } +void EXLOG_DEBUG(bool debug_mode) +{ + if (NULL != g_exlog) + g_exlog->debug_mode = debug_mode; +} + void EXLOG_CONSOLE(bool output_to_console) { if(NULL != g_exlog) diff --git a/common/libex/src/ex_str.cpp b/common/libex/src/ex_str.cpp index 0189168..560d6df 100644 --- a/common/libex/src/ex_str.cpp +++ b/common/libex/src/ex_str.cpp @@ -1,380 +1,855 @@ -#include -#include -#include - -char* ex_strcpy(char* target, size_t size, const char* source) -{ - if (target == source) - return target; - -#ifdef EX_OS_WIN32 - if (SUCCEEDED(StringCchCopyA(target, size, source))) - return target; - else - return NULL; -#else - size_t len = strlen(source); - if (size > len) - { - return strcpy(target, source); - } - else - { - memmove(target, source, size - 1); - return NULL; - } -#endif -} - -wchar_t* ex_wcscpy(wchar_t* target, size_t size, const wchar_t* source) -{ - if (target == source) - return target; - -#ifdef EX_OS_WIN32 - if (SUCCEEDED(StringCchCopyW(target, size, source))) - return target; - else - return NULL; -#else - size_t len = wcslen(source); - if (size > len) - { - return wcscpy(target, source); - } - else - { - memmove(target, source, (size - 1)*sizeof(wchar_t)); - return NULL; - } -#endif -} - -char* ex_strdup(const char* src) -{ - if (NULL == src) - return NULL; - size_t len = strlen(src) + 1; - char* ret = (char*)calloc(1, len); - memcpy(ret, src, len); - return ret; -} - -wchar_t* ex_wcsdup(const wchar_t* src) -{ - if (NULL == src) - return NULL; - size_t len = wcslen(src) + 1; - wchar_t* ret = (wchar_t*)calloc(sizeof(wchar_t), len); - memcpy(ret, src, sizeof(wchar_t)*len); - return ret; -} - -wchar_t* ex_str2wcs_alloc(const char* in_buffer, int code_page) -{ - wchar_t* out_buffer = NULL; -#ifdef EX_OS_WIN32 - int wlen = 0; - UINT _cp = 0; - if (code_page == EX_CODEPAGE_ACP) - _cp = CP_ACP; - else if (code_page == EX_CODEPAGE_UTF8) - _cp = CP_UTF8; - - wlen = MultiByteToWideChar(_cp, 0, in_buffer, -1, NULL, 0); - if (0 == wlen) - return NULL; - - out_buffer = (wchar_t*)calloc(wlen + 1, sizeof(wchar_t)); - if (NULL == out_buffer) - return NULL; - - wlen = MultiByteToWideChar(_cp, 0, in_buffer, -1, out_buffer, wlen); - if (0 == wlen) - { - free(out_buffer); - return NULL; - } - -#else - size_t wlen = 0; - wlen = mbstowcs(NULL, in_buffer, 0); - if (wlen < 0) - return NULL; - - out_buffer = (wchar_t*)calloc(wlen + 1, sizeof(wchar_t)); - if (NULL == out_buffer) - return NULL; - - wlen = mbstowcs(out_buffer, in_buffer, wlen); - if (wlen < 0) - { - free(out_buffer); - return NULL; - } - -#endif - - return out_buffer; -} - - -char* ex_wcs2str_alloc(const wchar_t* in_buffer, int code_page) -{ - char* out_buffer = NULL; - - if(NULL == in_buffer) - return NULL; - -#ifdef EX_OS_WIN32 - int len = 0; - UINT _cp = 0; - if (code_page == EX_CODEPAGE_ACP) - _cp = CP_ACP; - else if (code_page == EX_CODEPAGE_UTF8) - _cp = CP_UTF8; - - len = WideCharToMultiByte(_cp, 0, in_buffer, -1, NULL, 0, NULL, NULL); - if (0 == len) - return NULL; - - out_buffer = (char*)calloc(len + 1, sizeof(char)); - if (NULL == out_buffer) - return NULL; - - len = WideCharToMultiByte(_cp, 0, in_buffer, -1, out_buffer, len, NULL, NULL); - if (0 == len) - { - free(out_buffer); - return NULL; - } - -#else - size_t len = 0; - len = wcstombs(NULL, in_buffer, 0); - if (len < 0) - return NULL; - - out_buffer = (char*)calloc(len + 1, sizeof(char)); - if (NULL == out_buffer) - return NULL; - - len = wcstombs(out_buffer, in_buffer, len); - if (len < 0) - { - free(out_buffer); - return NULL; - } - -#endif - - return out_buffer; -} - -wchar_t** ex_make_wargv(int argc, char** argv) -{ - int i = 0; - wchar_t** ret = NULL; - - ret = (wchar_t**)calloc(argc + 1, sizeof(wchar_t*)); - if (!ret) - { - return NULL; - } - - for (i = 0; i < argc; ++i) - { - ret[i] = ex_str2wcs_alloc(argv[i], EX_CODEPAGE_DEFAULT); - if (NULL == ret[i]) - goto err; - } - - return ret; - -err: - ex_free_wargv(argc, ret); - return NULL; -} - -void ex_free_wargv(int argc, wchar_t** argv) -{ - int i = 0; - for (i = 0; i < argc; ++i) - free(argv[i]); - - free(argv); -} - -EX_BOOL ex_str_only_white_space(const wchar_t* src) -{ - if (ex_only_white_space(src)) - return EX_TRUE; - else - return EX_FALSE; -} - -EX_BOOL ex_wcs_only_white_space(const char* src) -{ - if (ex_only_white_space(src)) - return EX_TRUE; - else - return EX_FALSE; -} - -int ex_strformat(char* out_buf, size_t buf_size, const char* fmt, ...) -{ - int ret = 0; - va_list valist; - va_start(valist, fmt); - //_ts_printf_a(level, EX_COLOR_BLACK, fmt, valist); -#ifdef EX_OS_WIN32 - ret = vsnprintf(out_buf, buf_size, fmt, valist); -#else - ret = vsprintf(out_buf, fmt, valist); -#endif - va_end(valist); - return ret; -} - -int ex_wcsformat(wchar_t* out_buf, size_t buf_size, const wchar_t* fmt, ...) -{ - int ret = 0; - va_list valist; - va_start(valist, fmt); - //_ts_printf_a(level, EX_COLOR_BLACK, fmt, valist); -#ifdef EX_OS_WIN32 - //ret = vsnprintf(out_buf, buf_size, fmt, valist); - ret = _vsnwprintf_s(out_buf, buf_size, buf_size, fmt, valist); -#else - //ret = vsprintf(out_buf, fmt, valist); - ret = vswprintf(out_buf, buf_size, fmt, valist); -#endif - va_end(valist); - return ret; -} - - -#ifdef __cplusplus -bool ex_wstr2astr(const ex_wstr& in_str, ex_astr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) -{ - return ex_wstr2astr(in_str.c_str(), out_str, code_page); -} - -bool ex_wstr2astr(const wchar_t* in_str, ex_astr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) -{ - char* astr = ex_wcs2str_alloc(in_str, code_page); - if (NULL == astr) - return false; - - out_str = astr; - ex_free(astr); - return true; -} - -bool ex_astr2wstr(const ex_astr& in_str, ex_wstr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) -{ - return ex_astr2wstr(in_str.c_str(), out_str, code_page); -} - -bool ex_astr2wstr(const char* in_str, ex_wstr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) -{ - wchar_t* wstr = ex_str2wcs_alloc(in_str, code_page); - if (NULL == wstr) - return false; - - out_str = wstr; - ex_free(wstr); - return true; -} - -bool ex_only_white_space(const ex_astr& str_check) -{ - ex_astr::size_type pos = 0; - ex_astr strFilter(" \t\r\n"); - pos = str_check.find_first_not_of(strFilter); - if (ex_astr::npos == pos) - return true; - else - return false; -} - -bool ex_only_white_space(const ex_wstr& str_check) -{ - ex_wstr::size_type pos = 0; - ex_wstr strFilter(L" \t\r\n"); - pos = str_check.find_first_not_of(strFilter); - if (ex_wstr::npos == pos) - return true; - else - return false; -} - -void ex_remove_white_space(ex_astr& str_fix, int ulFlag /*= EX_RSC_ALL*/) -{ - ex_astr::size_type pos = 0; - ex_astr strFilter(" \t\r\n"); - - if (ulFlag & EX_RSC_BEGIN) - { - pos = str_fix.find_first_not_of(strFilter); - if (ex_astr::npos != pos) - str_fix.erase(0, pos); - // FIXME - } - if (ulFlag & EX_RSC_END) - { - pos = str_fix.find_last_not_of(strFilter); - if (ex_astr::npos != pos) - str_fix.erase(pos + 1); - // FIXME - } -} - -void ex_remove_white_space(ex_wstr& str_fix, int ulFlag /*= EX_RSC_ALL*/) -{ - ex_wstr::size_type pos = 0; - ex_wstr strFilter(L" \t\r\n"); - - if (ulFlag & EX_RSC_BEGIN) - { - pos = str_fix.find_first_not_of(strFilter); - if (ex_wstr::npos != pos) - str_fix.erase(0, pos); - // FIXME - } - if (ulFlag & EX_RSC_END) - { - pos = str_fix.find_last_not_of(strFilter); - if (ex_wstr::npos != pos) - str_fix.erase(pos + 1); - // FIXME - } -} - -ex_astr& ex_replace_all(ex_astr& str, const ex_astr& old_value, const ex_astr& new_value) -{ - for (ex_astr::size_type pos(0); pos != ex_astr::npos; pos += new_value.length()) - { - if ((pos = str.find(old_value, pos)) != ex_astr::npos) - str.replace(pos, old_value.length(), new_value); - else - break; - } - - return str; -} - -ex_wstr& ex_replace_all(ex_wstr& str, const ex_wstr& old_value, const ex_wstr& new_value) -{ - for (ex_wstr::size_type pos(0); pos != ex_wstr::npos; pos += new_value.length()) - { - if ((pos = str.find(old_value, pos)) != ex_wstr::npos) - str.replace(pos, old_value.length(), new_value); - else - break; - } - - return str; -} - -#endif +#include +#include +#include + +char* ex_strcpy(char* target, size_t size, const char* source) +{ + if (target == source) + return target; + +#ifdef EX_OS_WIN32 + if (SUCCEEDED(StringCchCopyA(target, size, source))) + return target; + else + return NULL; +#else + size_t len = strlen(source); + if (size > len) + { + return strcpy(target, source); + } + else + { + memmove(target, source, size - 1); + return NULL; + } +#endif +} + +wchar_t* ex_wcscpy(wchar_t* target, size_t size, const wchar_t* source) +{ + if (target == source) + return target; + +#ifdef EX_OS_WIN32 + if (SUCCEEDED(StringCchCopyW(target, size, source))) + return target; + else + return NULL; +#else + size_t len = wcslen(source); + if (size > len) + { + return wcscpy(target, source); + } + else + { + memmove(target, source, (size - 1)*sizeof(wchar_t)); + return NULL; + } +#endif +} + +char* ex_strdup(const char* src) +{ + if (NULL == src) + return NULL; + size_t len = strlen(src) + 1; + char* ret = (char*)calloc(1, len); + memcpy(ret, src, len); + return ret; +} + +wchar_t* ex_wcsdup(const wchar_t* src) +{ + if (NULL == src) + return NULL; + size_t len = wcslen(src) + 1; + wchar_t* ret = (wchar_t*)calloc(sizeof(wchar_t), len); + memcpy(ret, src, sizeof(wchar_t)*len); + return ret; +} + +wchar_t* ex_str2wcs_alloc(const char* in_buffer, int code_page) +{ + wchar_t* out_buffer = NULL; +#ifdef EX_OS_WIN32 + int wlen = 0; + UINT _cp = 0; + if (code_page == EX_CODEPAGE_ACP) + _cp = CP_ACP; + else if (code_page == EX_CODEPAGE_UTF8) + _cp = CP_UTF8; + + wlen = MultiByteToWideChar(_cp, 0, in_buffer, -1, NULL, 0); + if (0 == wlen) + return NULL; + + out_buffer = (wchar_t*)calloc(wlen + 1, sizeof(wchar_t)); + if (NULL == out_buffer) + return NULL; + + wlen = MultiByteToWideChar(_cp, 0, in_buffer, -1, out_buffer, wlen); + if (0 == wlen) + { + free(out_buffer); + return NULL; + } + +#else + size_t wlen = 0; + wlen = mbstowcs(NULL, in_buffer, 0); + if (wlen < 0) + return NULL; + + out_buffer = (wchar_t*)calloc(wlen + 1, sizeof(wchar_t)); + if (NULL == out_buffer) + return NULL; + + wlen = mbstowcs(out_buffer, in_buffer, wlen); + if (wlen < 0) + { + free(out_buffer); + return NULL; + } + +#endif + + return out_buffer; +} + + +char* ex_wcs2str_alloc(const wchar_t* in_buffer, int code_page) +{ + char* out_buffer = NULL; + + if(NULL == in_buffer) + return NULL; + +#ifdef EX_OS_WIN32 + int len = 0; + UINT _cp = 0; + if (code_page == EX_CODEPAGE_ACP) + _cp = CP_ACP; + else if (code_page == EX_CODEPAGE_UTF8) + _cp = CP_UTF8; + + len = WideCharToMultiByte(_cp, 0, in_buffer, -1, NULL, 0, NULL, NULL); + if (0 == len) + return NULL; + + out_buffer = (char*)calloc(len + 1, sizeof(char)); + if (NULL == out_buffer) + return NULL; + + len = WideCharToMultiByte(_cp, 0, in_buffer, -1, out_buffer, len, NULL, NULL); + if (0 == len) + { + free(out_buffer); + return NULL; + } + +#else + size_t len = 0; + len = wcstombs(NULL, in_buffer, 0); + if (len < 0) + return NULL; + + out_buffer = (char*)calloc(len + 1, sizeof(char)); + if (NULL == out_buffer) + return NULL; + + len = wcstombs(out_buffer, in_buffer, len); + if (len < 0) + { + free(out_buffer); + return NULL; + } + +#endif + + return out_buffer; +} + +wchar_t** ex_make_wargv(int argc, char** argv) +{ + int i = 0; + wchar_t** ret = NULL; + + ret = (wchar_t**)calloc(argc + 1, sizeof(wchar_t*)); + if (!ret) + { + return NULL; + } + + for (i = 0; i < argc; ++i) + { + ret[i] = ex_str2wcs_alloc(argv[i], EX_CODEPAGE_DEFAULT); + if (NULL == ret[i]) + goto err; + } + + return ret; + +err: + ex_free_wargv(argc, ret); + return NULL; +} + +void ex_free_wargv(int argc, wchar_t** argv) +{ + int i = 0; + for (i = 0; i < argc; ++i) + free(argv[i]); + + free(argv); +} + +EX_BOOL ex_str_only_white_space(const wchar_t* src) +{ + if (ex_only_white_space(src)) + return EX_TRUE; + else + return EX_FALSE; +} + +EX_BOOL ex_wcs_only_white_space(const char* src) +{ + if (ex_only_white_space(src)) + return EX_TRUE; + else + return EX_FALSE; +} + +int ex_strformat(char* out_buf, size_t buf_size, const char* fmt, ...) +{ + int ret = 0; + va_list valist; + va_start(valist, fmt); + //_ts_printf_a(level, EX_COLOR_BLACK, fmt, valist); +#ifdef EX_OS_WIN32 + ret = vsnprintf(out_buf, buf_size, fmt, valist); +#else + ret = vsprintf(out_buf, fmt, valist); +#endif + va_end(valist); + return ret; +} + +int ex_wcsformat(wchar_t* out_buf, size_t buf_size, const wchar_t* fmt, ...) +{ + int ret = 0; + va_list valist; + va_start(valist, fmt); + //_ts_printf_a(level, EX_COLOR_BLACK, fmt, valist); +#ifdef EX_OS_WIN32 + //ret = vsnprintf(out_buf, buf_size, fmt, valist); + ret = _vsnwprintf_s(out_buf, buf_size, buf_size, fmt, valist); +#else + //ret = vsprintf(out_buf, fmt, valist); + ret = vswprintf(out_buf, buf_size, fmt, valist); +#endif + va_end(valist); + return ret; +} + + +#ifdef __cplusplus +bool ex_wstr2astr(const ex_wstr& in_str, ex_astr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) +{ + return ex_wstr2astr(in_str.c_str(), out_str, code_page); +} + +bool ex_wstr2astr(const wchar_t* in_str, ex_astr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) +{ + char* astr = ex_wcs2str_alloc(in_str, code_page); + if (NULL == astr) + return false; + + out_str = astr; + ex_free(astr); + return true; +} + +bool ex_astr2wstr(const ex_astr& in_str, ex_wstr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) +{ + return ex_astr2wstr(in_str.c_str(), out_str, code_page); +} + +bool ex_astr2wstr(const char* in_str, ex_wstr& out_str, int code_page/* = EX_CODEPAGE_DEFAULT*/) +{ + wchar_t* wstr = ex_str2wcs_alloc(in_str, code_page); + if (NULL == wstr) + return false; + + out_str = wstr; + ex_free(wstr); + return true; +} + +bool ex_only_white_space(const ex_astr& str_check) +{ + ex_astr::size_type pos = 0; + ex_astr strFilter(" \t\r\n"); + pos = str_check.find_first_not_of(strFilter); + if (ex_astr::npos == pos) + return true; + else + return false; +} + +bool ex_only_white_space(const ex_wstr& str_check) +{ + ex_wstr::size_type pos = 0; + ex_wstr strFilter(L" \t\r\n"); + pos = str_check.find_first_not_of(strFilter); + if (ex_wstr::npos == pos) + return true; + else + return false; +} + +void ex_remove_white_space(ex_astr& str_fix, int ulFlag /*= EX_RSC_ALL*/) +{ + ex_astr::size_type pos = 0; + ex_astr strFilter(" \t\r\n"); + + if (ulFlag & EX_RSC_BEGIN) + { + pos = str_fix.find_first_not_of(strFilter); + if (ex_astr::npos != pos) + str_fix.erase(0, pos); + // FIXME + } + if (ulFlag & EX_RSC_END) + { + pos = str_fix.find_last_not_of(strFilter); + if (ex_astr::npos != pos) + str_fix.erase(pos + 1); + // FIXME + } +} + +void ex_remove_white_space(ex_wstr& str_fix, int ulFlag /*= EX_RSC_ALL*/) +{ + ex_wstr::size_type pos = 0; + ex_wstr strFilter(L" \t\r\n"); + + if (ulFlag & EX_RSC_BEGIN) + { + pos = str_fix.find_first_not_of(strFilter); + if (ex_wstr::npos != pos) + str_fix.erase(0, pos); + // FIXME + } + if (ulFlag & EX_RSC_END) + { + pos = str_fix.find_last_not_of(strFilter); + if (ex_wstr::npos != pos) + str_fix.erase(pos + 1); + // FIXME + } +} + +ex_astr& ex_replace_all(ex_astr& str, const ex_astr& old_value, const ex_astr& new_value) +{ + for (ex_astr::size_type pos(0); pos != ex_astr::npos; pos += new_value.length()) + { + if ((pos = str.find(old_value, pos)) != ex_astr::npos) + str.replace(pos, old_value.length(), new_value); + else + break; + } + + return str; +} + +ex_wstr& ex_replace_all(ex_wstr& str, const ex_wstr& old_value, const ex_wstr& new_value) +{ + for (ex_wstr::size_type pos(0); pos != ex_wstr::npos; pos += new_value.length()) + { + if ((pos = str.find(old_value, pos)) != ex_wstr::npos) + str.replace(pos, old_value.length(), new_value); + else + break; + } + + return str; +} + + + +#ifndef EX_OS_WIN32 + +#define BYTE ex_u8 +#define DWORD ex_u32 +#define WCHAR ex_i16 +#define LPWSTR WCHAR* +#define BOOL int +#define TRUE 1 +#define FALSE 0 +#define UINT unsigned int +#define LPCSTR const char* +#define CP_UTF8 1 + +typedef enum +{ + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +typedef enum +{ + strictConversion = 0, + lenientConversion +} ConversionFlags; + +static const char trailingBytesForUTF8[256] = +{ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; + +static const DWORD offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL +}; + +static const BYTE firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + +static const int halfShift = 10; /* used for shifting by 10 bits */ + +static const DWORD halfBase = 0x0010000UL; +static const DWORD halfMask = 0x3FFUL; + +#define UNI_SUR_HIGH_START (DWORD)0xD800 +#define UNI_SUR_HIGH_END (DWORD)0xDBFF +#define UNI_SUR_LOW_START (DWORD)0xDC00 +#define UNI_SUR_LOW_END (DWORD)0xDFFF + +#define UNI_REPLACEMENT_CHAR (DWORD)0x0000FFFD +#define UNI_MAX_BMP (DWORD)0x0000FFFF +#define UNI_MAX_UTF16 (DWORD)0x0010FFFF +#define UNI_MAX_UTF32 (DWORD)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (DWORD)0x0010FFFF + + +static ConversionResult ConvertUTF16toUTF8(const WCHAR** sourceStart, const WCHAR* sourceEnd, BYTE** targetStart, BYTE* targetEnd, ConversionFlags flags) +{ + BYTE* target; + const WCHAR* source; + BOOL computeLength; + ConversionResult result; + computeLength = (!targetEnd) ? TRUE : FALSE; + source = *sourceStart; + target = *targetStart; + result = conversionOK; + + while (source < sourceEnd) + { + DWORD ch; + unsigned short bytesToWrite = 0; + const DWORD byteMask = 0xBF; + const DWORD byteMark = 0x80; + const WCHAR* oldSource = source; /* In case we have to back up because of target overflow. */ + ch = *source++; + + /* If we have a surrogate pair, convert to UTF32 first. */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) + { + /* If the 16 bits following the high surrogate are in the source buffer... */ + if (source < sourceEnd) + { + DWORD ch2 = *source; + + /* If it's a low surrogate, convert to UTF32. */ + if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) + { + ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + + (ch2 - UNI_SUR_LOW_START) + halfBase; + ++source; + } + else if (flags == strictConversion) + { + /* it's an unpaired high surrogate */ + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + else + { + /* We don't have the 16 bits following the high surrogate. */ + --source; /* return to the high surrogate */ + result = sourceExhausted; + break; + } + } + else if (flags == strictConversion) + { + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) + { + --source; /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + } + + /* Figure out how many bytes the result will require */ + if (ch < (DWORD)0x80) + { + bytesToWrite = 1; + } + else if (ch < (DWORD)0x800) + { + bytesToWrite = 2; + } + else if (ch < (DWORD)0x10000) + { + bytesToWrite = 3; + } + else if (ch < (DWORD)0x110000) + { + bytesToWrite = 4; + } + else + { + bytesToWrite = 3; + ch = UNI_REPLACEMENT_CHAR; + } + + target += bytesToWrite; + + if ((target > targetEnd) && (!computeLength)) + { + source = oldSource; /* Back up source pointer! */ + target -= bytesToWrite; + result = targetExhausted; + break; + } + + if (!computeLength) + { + switch (bytesToWrite) + { + /* note: everything falls through. */ + case 4: + *--target = (BYTE)((ch | byteMark) & byteMask); + ch >>= 6; + + case 3: + *--target = (BYTE)((ch | byteMark) & byteMask); + ch >>= 6; + + case 2: + *--target = (BYTE)((ch | byteMark) & byteMask); + ch >>= 6; + + case 1: + *--target = (BYTE)(ch | firstByteMark[bytesToWrite]); + } + } + else + { + switch (bytesToWrite) + { + /* note: everything falls through. */ + case 4: + --target; + ch >>= 6; + + case 3: + --target; + ch >>= 6; + + case 2: + --target; + ch >>= 6; + + case 1: + --target; + } + } + + target += bytesToWrite; + } + + *sourceStart = source; + *targetStart = target; + return result; +} + + +static BOOL isLegalUTF8(const BYTE* source, int length) +{ + BYTE a; + const BYTE* srcptr = source + length; + + switch (length) + { + default: + return FALSE; + + /* Everything else falls through when "TRUE"... */ + case 4: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return FALSE; + + case 3: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return FALSE; + + case 2: + if ((a = (*--srcptr)) > 0xBF) return FALSE; + + switch (*source) + { + /* no fall-through in this inner switch */ + case 0xE0: + if (a < 0xA0) return FALSE; + + break; + + case 0xED: + if (a > 0x9F) return FALSE; + + break; + + case 0xF0: + if (a < 0x90) return FALSE; + + break; + + case 0xF4: + if (a > 0x8F) return FALSE; + + break; + + default: + if (a < 0x80) return FALSE; + } + + case 1: + if (*source >= 0x80 && *source < 0xC2) return FALSE; + } + + if (*source > 0xF4) + return FALSE; + + return TRUE; +} + +static ConversionResult _ConvertUTF8toUTF16(const BYTE** sourceStart, const BYTE* sourceEnd, WCHAR** targetStart, WCHAR* targetEnd, ConversionFlags flags) +{ + WCHAR* target; + const BYTE* source; + BOOL computeLength; + ConversionResult result; + computeLength = (!targetEnd) ? TRUE : FALSE; + result = conversionOK; + source = *sourceStart; + target = *targetStart; + + while (source < sourceEnd) + { + DWORD ch = 0; + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; + + if ((source + extraBytesToRead) >= sourceEnd) + { + result = sourceExhausted; + break; + } + + /* Do this check whether lenient or strict */ + if (!isLegalUTF8(source, extraBytesToRead + 1)) + { + result = sourceIllegal; + break; + } + + /* + * The cases all fall through. See "Note A" below. + */ + switch (extraBytesToRead) + { + case 5: + ch += *source++; + ch <<= 6; /* remember, illegal UTF-8 */ + + case 4: + ch += *source++; + ch <<= 6; /* remember, illegal UTF-8 */ + + case 3: + ch += *source++; + ch <<= 6; + + case 2: + ch += *source++; + ch <<= 6; + + case 1: + ch += *source++; + ch <<= 6; + + case 0: + ch += *source++; + } + + ch -= offsetsFromUTF8[extraBytesToRead]; + + if ((target >= targetEnd) && (!computeLength)) + { + source -= (extraBytesToRead + 1); /* Back up source pointer! */ + result = targetExhausted; + break; + } + + if (ch <= UNI_MAX_BMP) + { + /* Target is a character <= 0xFFFF */ + /* UTF-16 surrogate values are illegal in UTF-32 */ + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + { + if (flags == strictConversion) + { + source -= (extraBytesToRead + 1); /* return to the illegal value itself */ + result = sourceIllegal; + break; + } + else + { + if (!computeLength) + *target++ = UNI_REPLACEMENT_CHAR; + else + target++; + } + } + else + { + if (!computeLength) + *target++ = (WCHAR)ch; /* normal case */ + else + target++; + } + } + else if (ch > UNI_MAX_UTF16) + { + if (flags == strictConversion) + { + result = sourceIllegal; + source -= (extraBytesToRead + 1); /* return to the start */ + break; /* Bail out; shouldn't continue */ + } + else + { + if (!computeLength) + *target++ = UNI_REPLACEMENT_CHAR; + else + target++; + } + } + else + { + /* target is a character in range 0xFFFF - 0x10FFFF. */ + if ((target + 1 >= targetEnd) && (!computeLength)) + { + source -= (extraBytesToRead + 1); /* Back up source pointer! */ + result = targetExhausted; + break; + } + + ch -= halfBase; + + if (!computeLength) + { + *target++ = (WCHAR)((ch >> halfShift) + UNI_SUR_HIGH_START); + *target++ = (WCHAR)((ch & halfMask) + UNI_SUR_LOW_START); + } + else + { + target++; + target++; + } + } + } + + *sourceStart = source; + *targetStart = target; + return result; +} + +static int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar) +{ + int length; + LPWSTR targetStart; + const BYTE* sourceStart; + ConversionResult result; + + /* If cbMultiByte is 0, the function fails */ + + if (cbMultiByte == 0) + return 0; + + /* If cbMultiByte is -1, the string is null-terminated */ + + if (cbMultiByte == -1) + cbMultiByte = (int)strlen((char*)lpMultiByteStr) + 1; + + /* + * if cchWideChar is 0, the function returns the required buffer size + * in characters for lpWideCharStr and makes no use of the output parameter itself. + */ + + if (cchWideChar == 0) + { + sourceStart = (const BYTE*)lpMultiByteStr; + targetStart = (WCHAR*)NULL; + + result = _ConvertUTF8toUTF16(&sourceStart, &sourceStart[cbMultiByte], + &targetStart, NULL, strictConversion); + + length = (int)(targetStart - ((WCHAR*)NULL)); + cchWideChar = length; + } + else + { + sourceStart = (const BYTE*)lpMultiByteStr; + targetStart = lpWideCharStr; + + result = _ConvertUTF8toUTF16(&sourceStart, &sourceStart[cbMultiByte], + &targetStart, &targetStart[cchWideChar], strictConversion); + + length = (int)(targetStart - ((WCHAR*)lpWideCharStr)); + cchWideChar = length; + } + + return cchWideChar; +} + +#endif + + + +bool ex_utf8_to_utf16le(const std::string& from, ex_str_utf16le& to) +{ + int iSize = MultiByteToWideChar(CP_UTF8, 0, from.c_str(), -1, NULL, 0); + if (iSize <= 0) + return false; + + //++iSize; + to.resize(iSize); + memset(&to[0], 0, sizeof(ex_utf16)); + + MultiByteToWideChar(CP_UTF8, 0, from.c_str(), -1, &to[0], iSize); + + return true; +} + +#endif diff --git a/common/libex/src/ex_util.cpp b/common/libex/src/ex_util.cpp index 81bd035..4c6c297 100644 --- a/common/libex/src/ex_util.cpp +++ b/common/libex/src/ex_util.cpp @@ -1,251 +1,264 @@ -#include -#include -#include -#include - -EX_BOOL ex_initialize(const char* lc_ctype) -{ -#ifdef EX_OS_UNIX - const char* _lc_default = "en_US.UTF-8"; - const char* _lc_ctype = NULL; - char* _loc = NULL; - if(NULL == lc_ctype) - _lc_ctype = _lc_default; - else - _lc_ctype = lc_ctype; - - _loc = setlocale(LC_CTYPE, _lc_ctype); - - if(NULL == _loc) - return EX_FALSE; -// if(0 != strcmp(_loc, _lc_ctype)) -// return EX_FALSE; - return EX_TRUE; - -#else - return EX_TRUE; -#endif -} - - -void ex_free(void* buffer) -{ - if (NULL == buffer) - return; - free(buffer); -} - -const ex_u8* ex_memmem(const ex_u8* haystack, size_t haystacklen, const ex_u8* needle, size_t needlelen) -{ - const ex_u8* cursor = NULL; - const ex_u8* last_possible_needle_location = haystack + haystacklen - needlelen; - - /** Easy answers */ - if (needlelen > haystacklen) return(NULL); - if (needle == NULL) return(NULL); - if (haystack == NULL) return(NULL); - if (needlelen == 0) return(NULL); - if (haystacklen == 0) return(NULL); - - for (cursor = haystack; cursor <= last_possible_needle_location; cursor++) - { - if (memcmp(needle, cursor, needlelen) == 0) - return cursor; - } - return(NULL); -} - -void ex_printf(const char* fmt, ...) -{ - if (NULL == fmt || 0 == strlen(fmt)) - return; - - va_list valist; - va_start(valist, fmt); - //_ts_printf_a(TS_COLOR_GRAY, TS_COLOR_BLACK, fmt, valist); - - char _tmp[4096] = { 0 }; -#ifdef EX_OS_WIN32 - vsnprintf_s(_tmp, 4096, 4095, fmt, valist); - printf_s("%s", _tmp); - fflush(stdout); -#else - vsnprintf(_tmp, 4095, fmt, valist); - printf("%s", _tmp); - fflush(stdout); -#endif - - va_end(valist); -} - -void ex_wprintf(const wchar_t* fmt, ...) -{ - if (NULL == fmt || 0 == wcslen(fmt)) - return; - - va_list valist; - va_start(valist, fmt); - - wchar_t _tmp[4096] = { 0 }; -#ifdef EX_OS_WIN32 - _vsnwprintf_s(_tmp, 4096, 4095, fmt, valist); - wprintf_s(L"%s", _tmp); - fflush(stdout); -#else - vswprintf(_tmp, 4095, fmt, valist); - - ex_astr _astr_tmp; - ex_wstr2astr(_tmp, _astr_tmp); - printf("%s", _astr_tmp.c_str()); - - fflush(stdout); -#endif - - va_end(valist); -} - -ex_u64 ex_get_tick_count(void) -{ -#ifdef EX_OS_WIN32 -# if (_WIN32_WINNT >= 0x0600) - return GetTickCount64(); -# else - LARGE_INTEGER TicksPerSecond = { 0 }; - LARGE_INTEGER Tick; - if (!TicksPerSecond.QuadPart) - QueryPerformanceFrequency(&TicksPerSecond); - QueryPerformanceCounter(&Tick); - ex_u64 Seconds = Tick.QuadPart / TicksPerSecond.QuadPart; - ex_u64 LeftPart = Tick.QuadPart - (TicksPerSecond.QuadPart*Seconds); - ex_u64 MillSeconds = LeftPart * 1000 / TicksPerSecond.QuadPart; - ex_u64 Ret = Seconds * 1000 + MillSeconds; - return Ret; -# endif -#else - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return ((ex_u64)ts.tv_sec * 1000 + (ex_u64)ts.tv_nsec / 1000000); -#endif -} - -void ex_sleep_ms(int ms) -{ -#ifdef EX_OS_WIN32 - Sleep(ms); -#else - usleep(ms * 1000); -#endif -} - -EX_BOOL ex_localtime_now(int* t, struct tm* dt) -{ -// if (NULL == dt) -// return EX_FALSE; - - //struct tm *_tmp; - -#ifdef EX_OS_WIN32 - struct tm _tmp; - __time32_t timep; - _time32(&timep); - if (0 != _localtime32_s(&_tmp, &timep)) - return EX_FALSE; - if(NULL != dt) - memcpy(dt, &_tmp, sizeof(struct tm)); -#else - struct tm *_tmp; - time_t timep; - time(&timep); - _tmp = localtime(&timep); //get server's time - if (_tmp == NULL) - return NULL; - if(NULL != dt) - memcpy(dt, _tmp, sizeof(struct tm)); -#endif - - if (NULL != t) - *t = (int)timep; - - return EX_TRUE; -} - -FILE* ex_fopen(const ex_wstr& filename, const wchar_t* mode) -{ - FILE* f = NULL; -#ifdef EX_OS_WIN32 - errno_t err = 0; - err = _wfopen_s(&f, filename.c_str(), mode); - if (0 == err) - return f; - else - return NULL; -#else - ex_astr _fname; - ex_wstr2astr(filename, _fname); - ex_astr _mode; - ex_wstr2astr(mode, _mode); - f = fopen(_fname.c_str(), _mode.c_str()); - return f; -#endif -} - - -EX_DYLIB_HANDLE ex_dlopen(const wchar_t* dylib_path) -{ - EX_DYLIB_HANDLE handle = NULL; - -#ifdef EX_OS_WIN32 - handle = LoadLibraryExW(dylib_path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); - if (NULL == handle) - { - EXLOGE_WIN(L"LoadLibraryEx('%ls') failed.\n", dylib_path); - return NULL; - } -#else - ex_astr path; - if (!ex_wstr2astr(dylib_path, path, EX_CODEPAGE_UTF8)) - { - EXLOGE("convert dylib_path failed.\n"); - return NULL; - } - - handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); - - if (NULL == handle) - { - EXLOGE("dlopen() failed: %s.\n", dlerror()); - return NULL; - } -#endif - - return handle; -} - -void ex_dlclose(EX_DYLIB_HANDLE dylib) -{ -#ifdef EX_OS_WIN32 - FreeLibrary(dylib); -#else - dlclose(dylib); -#endif -} - -static int _inet_ntop4(const unsigned char *src, char *dst, size_t size) { - static const char fmt[] = "%u.%u.%u.%u"; - char tmp[32]; - int l; - - l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); - if (l <= 0 || (size_t)l >= size) { - return -1; - } - ex_strcpy(dst, size, tmp); - dst[size - 1] = '\0'; - return 0; -} - -int ex_ip4_name(const struct sockaddr_in* src, char* dst, size_t size) -{ - return _inet_ntop4((const unsigned char*)&(src->sin_addr), dst, size); -} - +#include +#include +#include +#include + +EX_BOOL ex_initialize(const char* lc_ctype) +{ +#ifdef EX_OS_UNIX + const char* _lc_default = "en_US.UTF-8"; + const char* _lc_ctype = NULL; + char* _loc = NULL; + if(NULL == lc_ctype) + _lc_ctype = _lc_default; + else + _lc_ctype = lc_ctype; + + _loc = setlocale(LC_CTYPE, _lc_ctype); + + if(NULL == _loc) + return EX_FALSE; +// if(0 != strcmp(_loc, _lc_ctype)) +// return EX_FALSE; + return EX_TRUE; + +#else + return EX_TRUE; +#endif +} + + +void ex_free(void* buffer) +{ + if (NULL == buffer) + return; + free(buffer); +} + +const ex_u8* ex_memmem(const ex_u8* haystack, size_t haystacklen, const ex_u8* needle, size_t needlelen) +{ + const ex_u8* cursor = NULL; + const ex_u8* last_possible_needle_location = haystack + haystacklen - needlelen; + + /** Easy answers */ + if (needlelen > haystacklen) return(NULL); + if (needle == NULL) return(NULL); + if (haystack == NULL) return(NULL); + if (needlelen == 0) return(NULL); + if (haystacklen == 0) return(NULL); + + for (cursor = haystack; cursor <= last_possible_needle_location; cursor++) + { + if (memcmp(needle, cursor, needlelen) == 0) + return cursor; + } + return(NULL); +} + +void ex_mem_reverse(ex_u8* p, size_t l) +{ + ex_u8 temp = 0; + size_t i = 0, j = 0; + + for (i = 0, j = l - 1; i < j; i++, j--) + { + temp = p[i]; + p[i] = p[j]; + p[j] = temp; + } +} + +void ex_printf(const char* fmt, ...) +{ + if (NULL == fmt || 0 == strlen(fmt)) + return; + + va_list valist; + va_start(valist, fmt); + //_ts_printf_a(TS_COLOR_GRAY, TS_COLOR_BLACK, fmt, valist); + + char _tmp[4096] = { 0 }; +#ifdef EX_OS_WIN32 + vsnprintf_s(_tmp, 4096, 4095, fmt, valist); + printf_s("%s", _tmp); + fflush(stdout); +#else + vsnprintf(_tmp, 4095, fmt, valist); + printf("%s", _tmp); + fflush(stdout); +#endif + + va_end(valist); +} + +void ex_wprintf(const wchar_t* fmt, ...) +{ + if (NULL == fmt || 0 == wcslen(fmt)) + return; + + va_list valist; + va_start(valist, fmt); + + wchar_t _tmp[4096] = { 0 }; +#ifdef EX_OS_WIN32 + _vsnwprintf_s(_tmp, 4096, 4095, fmt, valist); + wprintf_s(L"%s", _tmp); + fflush(stdout); +#else + vswprintf(_tmp, 4095, fmt, valist); + + ex_astr _astr_tmp; + ex_wstr2astr(_tmp, _astr_tmp); + printf("%s", _astr_tmp.c_str()); + + fflush(stdout); +#endif + + va_end(valist); +} + +ex_u64 ex_get_tick_count(void) +{ +#ifdef EX_OS_WIN32 +# if (_WIN32_WINNT >= 0x0600) + return GetTickCount64(); +# else + LARGE_INTEGER TicksPerSecond = { 0 }; + LARGE_INTEGER Tick; + if (!TicksPerSecond.QuadPart) + QueryPerformanceFrequency(&TicksPerSecond); + QueryPerformanceCounter(&Tick); + ex_u64 Seconds = Tick.QuadPart / TicksPerSecond.QuadPart; + ex_u64 LeftPart = Tick.QuadPart - (TicksPerSecond.QuadPart*Seconds); + ex_u64 MillSeconds = LeftPart * 1000 / TicksPerSecond.QuadPart; + ex_u64 Ret = Seconds * 1000 + MillSeconds; + return Ret; +# endif +#else + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ((ex_u64)ts.tv_sec * 1000 + (ex_u64)ts.tv_nsec / 1000000); +#endif +} + +void ex_sleep_ms(int ms) +{ +#ifdef EX_OS_WIN32 + Sleep(ms); +#else + usleep(ms * 1000); +#endif +} + +EX_BOOL ex_localtime_now(int* t, struct tm* dt) +{ +// if (NULL == dt) +// return EX_FALSE; + + //struct tm *_tmp; + +#ifdef EX_OS_WIN32 + struct tm _tmp; + __time32_t timep; + _time32(&timep); + if (0 != _localtime32_s(&_tmp, &timep)) + return EX_FALSE; + if(NULL != dt) + memcpy(dt, &_tmp, sizeof(struct tm)); +#else + struct tm *_tmp; + time_t timep; + time(&timep); + _tmp = localtime(&timep); //get server's time + if (_tmp == NULL) + return NULL; + if(NULL != dt) + memcpy(dt, _tmp, sizeof(struct tm)); +#endif + + if (NULL != t) + *t = (int)timep; + + return EX_TRUE; +} + +FILE* ex_fopen(const ex_wstr& filename, const wchar_t* mode) +{ + FILE* f = NULL; +#ifdef EX_OS_WIN32 + errno_t err = 0; + err = _wfopen_s(&f, filename.c_str(), mode); + if (0 == err) + return f; + else + return NULL; +#else + ex_astr _fname; + ex_wstr2astr(filename, _fname); + ex_astr _mode; + ex_wstr2astr(mode, _mode); + f = fopen(_fname.c_str(), _mode.c_str()); + return f; +#endif +} + + +EX_DYLIB_HANDLE ex_dlopen(const wchar_t* dylib_path) +{ + EX_DYLIB_HANDLE handle = NULL; + +#ifdef EX_OS_WIN32 + handle = LoadLibraryExW(dylib_path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (NULL == handle) + { + EXLOGE_WIN(L"LoadLibraryEx('%ls') failed.\n", dylib_path); + return NULL; + } +#else + ex_astr path; + if (!ex_wstr2astr(dylib_path, path, EX_CODEPAGE_UTF8)) + { + EXLOGE("convert dylib_path failed.\n"); + return NULL; + } + + handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); + + if (NULL == handle) + { + EXLOGE("dlopen() failed: %s.\n", dlerror()); + return NULL; + } +#endif + + return handle; +} + +void ex_dlclose(EX_DYLIB_HANDLE dylib) +{ +#ifdef EX_OS_WIN32 + FreeLibrary(dylib); +#else + dlclose(dylib); +#endif +} + +static int _inet_ntop4(const unsigned char *src, char *dst, size_t size) { + static const char fmt[] = "%u.%u.%u.%u"; + char tmp[32]; + int l; + + l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); + if (l <= 0 || (size_t)l >= size) { + return -1; + } + ex_strcpy(dst, size, tmp); + dst[size - 1] = '\0'; + return 0; +} + +int ex_ip4_name(const struct sockaddr_in* src, char* dst, size_t size) +{ + return _inet_ntop4((const unsigned char*)&(src->sin_addr), dst, size); +} + diff --git a/common/teleport/teleport_const.h b/common/teleport/teleport_const.h index 852d887..dd29680 100644 --- a/common/teleport/teleport_const.h +++ b/common/teleport/teleport_const.h @@ -27,22 +27,22 @@ #define TPE_UNKNOWN_CMD 124 // δ֪ #define TPE_JSON_FORMAT 125 // JSONʽҪJSONʽݣȴ޷JSONʽ룩 -#define TPE_PARAM 126 // -#define TPE_DATA 127 // ݴ +#define TPE_PARAM 126 // +#define TPE_DATA 127 // ݴ // #define TPE_OPENFILE_ERROR 0x1007 // ޷ļ // #define TPE_GETTEMPPATH_ERROR 0x1007 - +#define TPE_OPENFILE 300 //------------------------------------------------------- // ֳרôֵ //------------------------------------------------------- -#define TPE_NO_ASSIST 100000 // δܼ⵽ֳ +#define TPE_NO_ASSIST 100000 // δܼ⵽ֳ #define TPE_OLD_ASSIST 100001 // ֳ汾̫ -#define TPE_START_CLIENT 100002 // ޷ͻ˳޷̣ +#define TPE_START_CLIENT 100002 // ޷ͻ˳޷̣ diff --git a/config.ini.in b/config.ini.in index d10b8ee..f327296 100644 --- a/config.ini.in +++ b/config.ini.in @@ -33,7 +33,7 @@ cmake = /opt/cmake/bin/cmake [external_ver] openssl = 1.0.2h,1000208f -libuv = 1.9.1 +libuv = 1.11.0 mbedtls = 2.3.0 sqlite = 3170000 libssh = 0.7.4 diff --git a/dist/client/windows/assist/installer.nsi b/dist/client/windows/assist/installer.nsi index f6372e3..c80252e 100644 Binary files a/dist/client/windows/assist/installer.nsi and b/dist/client/windows/assist/installer.nsi differ diff --git a/dist/client/windows/assist/main.nsh b/dist/client/windows/assist/main.nsh index 1b4626a..5775e17 100644 Binary files a/dist/client/windows/assist/main.nsh and b/dist/client/windows/assist/main.nsh differ diff --git a/dist/client/windows/assist/setup.nsh b/dist/client/windows/assist/setup.nsh index 9e8a951..6464078 100644 Binary files a/dist/client/windows/assist/setup.nsh and b/dist/client/windows/assist/setup.nsh differ diff --git a/external/fix-external/mbedtls/include/mbedtls/config.h b/external/fix-external/mbedtls/include/mbedtls/config.h new file mode 100644 index 0000000..c59998a --- /dev/null +++ b/external/fix-external/mbedtls/include/mbedtls/config.h @@ -0,0 +1,2587 @@ +/** + * \file config.h + * + * \brief Configuration options (set of defines) + * + * This set of compile-time options may be used to enable + * or disable features selectively, and reduce the global + * memory footprint. + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CONFIG_H +#define MBEDTLS_CONFIG_H + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +/** + * \name SECTION: System support + * + * This section sets system specific settings. + * \{ + */ + +/** + * \def MBEDTLS_HAVE_ASM + * + * The compiler has support for asm(). + * + * Requires support for asm() in compiler. + * + * Used in: + * library/timing.c + * library/padlock.c + * include/mbedtls/bn_mul.h + * + * Comment to disable the use of assembly code. + */ +#define MBEDTLS_HAVE_ASM + +/** + * \def MBEDTLS_HAVE_SSE2 + * + * CPU supports SSE2 instruction set. + * + * Uncomment if the CPU supports SSE2 (IA-32 specific). + */ +//#define MBEDTLS_HAVE_SSE2 + +/** + * \def MBEDTLS_HAVE_TIME + * + * System has time.h and time(). + * The time does not need to be correct, only time differences are used, + * by contrast with MBEDTLS_HAVE_TIME_DATE + * + * Comment if your system does not support time functions + */ +#define MBEDTLS_HAVE_TIME + +/** + * \def MBEDTLS_HAVE_TIME_DATE + * + * System has time.h and time(), gmtime() and the clock is correct. + * The time needs to be correct (not necesarily very accurate, but at least + * the date should be correct). This is used to verify the validity period of + * X.509 certificates. + * + * Comment if your system does not have a correct clock. + */ +#define MBEDTLS_HAVE_TIME_DATE + +/** + * \def MBEDTLS_PLATFORM_MEMORY + * + * Enable the memory allocation layer. + * + * By default mbed TLS uses the system-provided calloc() and free(). + * This allows different allocators (self-implemented or provided) to be + * provided to the platform abstraction layer. + * + * Enabling MBEDTLS_PLATFORM_MEMORY without the + * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide + * "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and + * free() function pointer at runtime. + * + * Enabling MBEDTLS_PLATFORM_MEMORY and specifying + * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the + * alternate function at compile time. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Enable this layer to allow use of alternative memory allocators. + */ +//#define MBEDTLS_PLATFORM_MEMORY + +/** + * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + * + * Do not assign standard functions in the platform layer (e.g. calloc() to + * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF) + * + * This makes sure there are no linking errors on platforms that do not support + * these functions. You will HAVE to provide alternatives, either at runtime + * via the platform_set_xxx() functions or at compile time by setting + * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a + * MBEDTLS_PLATFORM_XXX_MACRO. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Uncomment to prevent default assignment of standard functions in the + * platform layer. + */ +//#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + +/** + * \def MBEDTLS_PLATFORM_EXIT_ALT + * + * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let mbed TLS support the + * function in the platform abstraction layer. + * + * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, mbed TLS will + * provide a function "mbedtls_platform_set_printf()" that allows you to set an + * alternative printf function pointer. + * + * All these define require MBEDTLS_PLATFORM_C to be defined! + * + * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows; + * it will be enabled automatically by check_config.h + * + * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as + * MBEDTLS_PLATFORM_XXX_MACRO! + * + * Uncomment a macro to enable alternate implementation of specific base + * platform function + */ +//#define MBEDTLS_PLATFORM_EXIT_ALT +//#define MBEDTLS_PLATFORM_TIME_ALT +//#define MBEDTLS_PLATFORM_FPRINTF_ALT +//#define MBEDTLS_PLATFORM_PRINTF_ALT +//#define MBEDTLS_PLATFORM_SNPRINTF_ALT +//#define MBEDTLS_PLATFORM_NV_SEED_ALT + +/** + * \def MBEDTLS_DEPRECATED_WARNING + * + * Mark deprecated functions so that they generate a warning if used. + * Functions deprecated in one version will usually be removed in the next + * version. You can enable this to help you prepare the transition to a new + * major version by making sure your code is not using these functions. + * + * This only works with GCC and Clang. With other compilers, you may want to + * use MBEDTLS_DEPRECATED_REMOVED + * + * Uncomment to get warnings on using deprecated functions. + */ +//#define MBEDTLS_DEPRECATED_WARNING + +/** + * \def MBEDTLS_DEPRECATED_REMOVED + * + * Remove deprecated functions so that they generate an error if used. + * Functions deprecated in one version will usually be removed in the next + * version. You can enable this to help you prepare the transition to a new + * major version by making sure your code is not using these functions. + * + * Uncomment to get errors on using deprecated functions. + */ +//#define MBEDTLS_DEPRECATED_REMOVED + +/* \} name SECTION: System support */ + +/** + * \name SECTION: mbed TLS feature support + * + * This section sets support for features that are or are not needed + * within the modules that are enabled. + * \{ + */ + +/** + * \def MBEDTLS_TIMING_ALT + * + * Uncomment to provide your own alternate implementation for mbedtls_timing_hardclock(), + * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay() + * + * Only works if you have MBEDTLS_TIMING_C enabled. + * + * You will need to provide a header "timing_alt.h" and an implementation at + * compile time. + */ +//#define MBEDTLS_TIMING_ALT + +/** + * \def MBEDTLS_AES_ALT + * + * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let mbed TLS use your + * alternate core implementation of a symmetric crypto or hash module (e.g. + * platform specific assembly optimized implementations). Keep in mind that + * the function prototypes should remain the same. + * + * This replaces the whole module. If you only want to replace one of the + * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_AES_ALT, mbed TLS will no longer + * provide the "struct mbedtls_aes_context" definition and omit the base function + * declarations and implementations. "aes_alt.h" will be included from + * "aes.h" to include the new function definitions. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * module. + */ +//#define MBEDTLS_AES_ALT +//#define MBEDTLS_ARC4_ALT +//#define MBEDTLS_BLOWFISH_ALT +//#define MBEDTLS_CAMELLIA_ALT +//#define MBEDTLS_DES_ALT +//#define MBEDTLS_XTEA_ALT +//#define MBEDTLS_MD2_ALT +//#define MBEDTLS_MD4_ALT +//#define MBEDTLS_MD5_ALT +//#define MBEDTLS_RIPEMD160_ALT +//#define MBEDTLS_SHA1_ALT +//#define MBEDTLS_SHA256_ALT +//#define MBEDTLS_SHA512_ALT + +/** + * \def MBEDTLS_MD2_PROCESS_ALT + * + * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you + * alternate core implementation of symmetric crypto or hash function. Keep in + * mind that function prototypes should remain the same. + * + * This replaces only one function. The header file from mbed TLS is still + * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will + * no longer provide the mbedtls_sha1_process() function, but it will still provide + * the other function (using your mbedtls_sha1_process() function) and the definition + * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible + * with this definition. + * + * Note: if you use the AES_xxx_ALT macros, then is is recommended to also set + * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES + * tables. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * function. + */ +//#define MBEDTLS_MD2_PROCESS_ALT +//#define MBEDTLS_MD4_PROCESS_ALT +//#define MBEDTLS_MD5_PROCESS_ALT +//#define MBEDTLS_RIPEMD160_PROCESS_ALT +//#define MBEDTLS_SHA1_PROCESS_ALT +//#define MBEDTLS_SHA256_PROCESS_ALT +//#define MBEDTLS_SHA512_PROCESS_ALT +//#define MBEDTLS_DES_SETKEY_ALT +//#define MBEDTLS_DES_CRYPT_ECB_ALT +//#define MBEDTLS_DES3_CRYPT_ECB_ALT +//#define MBEDTLS_AES_SETKEY_ENC_ALT +//#define MBEDTLS_AES_SETKEY_DEC_ALT +//#define MBEDTLS_AES_ENCRYPT_ALT +//#define MBEDTLS_AES_DECRYPT_ALT + +/** + * \def MBEDTLS_TEST_NULL_ENTROPY + * + * Enables testing and use of mbed TLS without any configured entropy sources. + * This permits use of the library on platforms before an entropy source has + * been integrated (see for example the MBEDTLS_ENTROPY_HARDWARE_ALT or the + * MBEDTLS_ENTROPY_NV_SEED switches). + * + * WARNING! This switch MUST be disabled in production builds, and is suitable + * only for development. + * Enabling the switch negates any security provided by the library. + * + * Requires MBEDTLS_ENTROPY_C, MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + * + */ +//#define MBEDTLS_TEST_NULL_ENTROPY + +/** + * \def MBEDTLS_ENTROPY_HARDWARE_ALT + * + * Uncomment this macro to let mbed TLS use your own implementation of a + * hardware entropy collector. + * + * Your function must be called \c mbedtls_hardware_poll(), have the same + * prototype as declared in entropy_poll.h, and accept NULL as first argument. + * + * Uncomment to use your own hardware entropy collector. + */ +//#define MBEDTLS_ENTROPY_HARDWARE_ALT + +/** + * \def MBEDTLS_AES_ROM_TABLES + * + * Store the AES tables in ROM. + * + * Uncomment this macro to store the AES tables in ROM. + */ +//#define MBEDTLS_AES_ROM_TABLES + +/** + * \def MBEDTLS_CAMELLIA_SMALL_MEMORY + * + * Use less ROM for the Camellia implementation (saves about 768 bytes). + * + * Uncomment this macro to use less memory for Camellia. + */ +//#define MBEDTLS_CAMELLIA_SMALL_MEMORY + +/** + * \def MBEDTLS_CIPHER_MODE_CBC + * + * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CBC + +/** + * \def MBEDTLS_CIPHER_MODE_CFB + * + * Enable Cipher Feedback mode (CFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CFB + +/** + * \def MBEDTLS_CIPHER_MODE_CTR + * + * Enable Counter Block Cipher mode (CTR) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CTR + +/** + * \def MBEDTLS_CIPHER_NULL_CIPHER + * + * Enable NULL cipher. + * Warning: Only do so when you know what you are doing. This allows for + * encryption or channels without any security! + * + * Requires MBEDTLS_ENABLE_WEAK_CIPHERSUITES as well to enable + * the following ciphersuites: + * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_MD5 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA + * + * Uncomment this macro to enable the NULL cipher and ciphersuites + */ +//#define MBEDTLS_CIPHER_NULL_CIPHER + +/** + * \def MBEDTLS_CIPHER_PADDING_PKCS7 + * + * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for + * specific padding modes in the cipher layer with cipher modes that support + * padding (e.g. CBC) + * + * If you disable all padding modes, only full blocks can be used with CBC. + * + * Enable padding modes in the cipher layer. + */ +#define MBEDTLS_CIPHER_PADDING_PKCS7 +#define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS +#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN +#define MBEDTLS_CIPHER_PADDING_ZEROS + +/** + * \def MBEDTLS_ENABLE_WEAK_CIPHERSUITES + * + * Enable weak ciphersuites in SSL / TLS. + * Warning: Only do so when you know what you are doing. This allows for + * channels with virtually no security at all! + * + * This enables the following ciphersuites: + * MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA + * + * Uncomment this macro to enable weak ciphersuites + */ +//#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES + +/** + * \def MBEDTLS_REMOVE_ARC4_CIPHERSUITES + * + * Remove RC4 ciphersuites by default in SSL / TLS. + * This flag removes the ciphersuites based on RC4 from the default list as + * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible to + * enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including them + * explicitly. + * + * Uncomment this macro to remove RC4 ciphersuites by default. + */ +#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES + +/** + * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED + * + * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve + * module. By default all supported curves are enabled. + * + * Comment macros to disable the curve and functions for it + */ +#define MBEDTLS_ECP_DP_SECP192R1_ENABLED +#define MBEDTLS_ECP_DP_SECP224R1_ENABLED +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_DP_SECP384R1_ENABLED +#define MBEDTLS_ECP_DP_SECP521R1_ENABLED +#define MBEDTLS_ECP_DP_SECP192K1_ENABLED +#define MBEDTLS_ECP_DP_SECP224K1_ENABLED +#define MBEDTLS_ECP_DP_SECP256K1_ENABLED +#define MBEDTLS_ECP_DP_BP256R1_ENABLED +#define MBEDTLS_ECP_DP_BP384R1_ENABLED +#define MBEDTLS_ECP_DP_BP512R1_ENABLED +#define MBEDTLS_ECP_DP_CURVE25519_ENABLED + +/** + * \def MBEDTLS_ECP_NIST_OPTIM + * + * Enable specific 'modulo p' routines for each NIST prime. + * Depending on the prime and architecture, makes operations 4 to 8 times + * faster on the corresponding curve. + * + * Comment this macro to disable NIST curves optimisation. + */ +#define MBEDTLS_ECP_NIST_OPTIM + +/** + * \def MBEDTLS_ECDSA_DETERMINISTIC + * + * Enable deterministic ECDSA (RFC 6979). + * Standard ECDSA is "fragile" in the sense that lack of entropy when signing + * may result in a compromise of the long-term signing key. This is avoided by + * the deterministic variant. + * + * Requires: MBEDTLS_HMAC_DRBG_C + * + * Comment this macro to disable deterministic ECDSA. + */ +#define MBEDTLS_ECDSA_DETERMINISTIC + +/** + * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + * + * Enable the PSK based ciphersuite modes in SSL / TLS. + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + * + * Enable the DHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + * + * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + * + * Enable the RSA-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + * + * Enable the RSA-only based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 + */ +#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + * + * Enable the DHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + * + * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + * + * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C, + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + * + * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + * + * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + * + * Enable the ECJPAKE based ciphersuite modes in SSL / TLS. + * + * \warning This is currently experimental. EC J-PAKE support is based on the + * Thread v1.0.0 specification; incompatible changes to the specification + * might still happen. For this reason, this is disabled by default. + * + * Requires: MBEDTLS_ECJPAKE_C + * MBEDTLS_SHA256_C + * MBEDTLS_ECP_DP_SECP256R1_ENABLED + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + +/** + * \def MBEDTLS_PK_PARSE_EC_EXTENDED + * + * Enhance support for reading EC keys using variants of SEC1 not allowed by + * RFC 5915 and RFC 5480. + * + * Currently this means parsing the SpecifiedECDomain choice of EC + * parameters (only known groups are supported, not arbitrary domains, to + * avoid validation issues). + * + * Disable if you only need to support RFC 5915 + 5480 key formats. + */ +#define MBEDTLS_PK_PARSE_EC_EXTENDED + +/** + * \def MBEDTLS_ERROR_STRERROR_DUMMY + * + * Enable a dummy error function to make use of mbedtls_strerror() in + * third party libraries easier when MBEDTLS_ERROR_C is disabled + * (no effect when MBEDTLS_ERROR_C is enabled). + * + * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're + * not using mbedtls_strerror() or error_strerror() in your application. + * + * Disable if you run into name conflicts and want to really remove the + * mbedtls_strerror() + */ +#define MBEDTLS_ERROR_STRERROR_DUMMY + +/** + * \def MBEDTLS_GENPRIME + * + * Enable the prime-number generation code. + * + * Requires: MBEDTLS_BIGNUM_C + */ +#define MBEDTLS_GENPRIME + +/** + * \def MBEDTLS_FS_IO + * + * Enable functions that use the filesystem. + */ +#define MBEDTLS_FS_IO + +/** + * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + * + * Do not add default entropy sources. These are the platform specific, + * mbedtls_timing_hardclock and HAVEGE based poll functions. + * + * This is useful to have more control over the added entropy sources in an + * application. + * + * Uncomment this macro to prevent loading of default entropy functions. + */ +//#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + +/** + * \def MBEDTLS_NO_PLATFORM_ENTROPY + * + * Do not use built-in platform entropy functions. + * This is useful if your platform does not support + * standards like the /dev/urandom or Windows CryptoAPI. + * + * Uncomment this macro to disable the built-in platform entropy functions. + */ +//#define MBEDTLS_NO_PLATFORM_ENTROPY + +/** + * \def MBEDTLS_ENTROPY_FORCE_SHA256 + * + * Force the entropy accumulator to use a SHA-256 accumulator instead of the + * default SHA-512 based one (if both are available). + * + * Requires: MBEDTLS_SHA256_C + * + * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option + * if you have performance concerns. + * + * This option is only useful if both MBEDTLS_SHA256_C and + * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used. + */ +//#define MBEDTLS_ENTROPY_FORCE_SHA256 + +/** + * \def MBEDTLS_ENTROPY_NV_SEED + * + * Enable the non-volatile (NV) seed file-based entropy source. + * (Also enables the NV seed read/write functions in the platform layer) + * + * This is crucial (if not required) on systems that do not have a + * cryptographic entropy source (in hardware or kernel) available. + * + * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C + * + * \note The read/write functions that are used by the entropy source are + * determined in the platform layer, and can be modified at runtime and/or + * compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used. + * + * \note If you use the default implementation functions that read a seedfile + * with regular fopen(), please make sure you make a seedfile with the + * proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at + * least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from + * and written to or you will get an entropy source error! The default + * implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE + * bytes from the file. + * + * \note The entropy collector will write to the seed file before entropy is + * given to an external source, to update it. + */ +//#define MBEDTLS_ENTROPY_NV_SEED + +/** + * \def MBEDTLS_MEMORY_DEBUG + * + * Enable debugging of buffer allocator memory issues. Automatically prints + * (to stderr) all (fatal) messages on memory allocation issues. Enables + * function for 'debug output' of allocated memory. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Uncomment this macro to let the buffer allocator print out error messages. + */ +//#define MBEDTLS_MEMORY_DEBUG + +/** + * \def MBEDTLS_MEMORY_BACKTRACE + * + * Include backtrace information with each allocated block. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * GLIBC-compatible backtrace() an backtrace_symbols() support + * + * Uncomment this macro to include backtrace information + */ +//#define MBEDTLS_MEMORY_BACKTRACE + +/** + * \def MBEDTLS_PK_RSA_ALT_SUPPORT + * + * Support external private RSA keys (eg from a HSM) in the PK layer. + * + * Comment this macro to disable support for external private RSA keys. + */ +#define MBEDTLS_PK_RSA_ALT_SUPPORT + +/** + * \def MBEDTLS_PKCS1_V15 + * + * Enable support for PKCS#1 v1.5 encoding. + * + * Requires: MBEDTLS_RSA_C + * + * This enables support for PKCS#1 v1.5 operations. + */ +#define MBEDTLS_PKCS1_V15 + +/** + * \def MBEDTLS_PKCS1_V21 + * + * Enable support for PKCS#1 v2.1 encoding. + * + * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C + * + * This enables support for RSAES-OAEP and RSASSA-PSS operations. + */ +#define MBEDTLS_PKCS1_V21 + +/** + * \def MBEDTLS_RSA_NO_CRT + * + * Do not use the Chinese Remainder Theorem for the RSA private operation. + * + * Uncomment this macro to disable the use of CRT in RSA. + * + */ +#define MBEDTLS_RSA_NO_CRT + +/** + * \def MBEDTLS_SELF_TEST + * + * Enable the checkup functions (*_self_test). + */ +#define MBEDTLS_SELF_TEST + +/** + * \def MBEDTLS_SHA256_SMALLER + * + * Enable an implementation of SHA-256 that has lower ROM footprint but also + * lower performance. + * + * The default implementation is meant to be a reasonnable compromise between + * performance and size. This version optimizes more aggressively for size at + * the expense of performance. Eg on Cortex-M4 it reduces the size of + * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about + * 30%. + * + * Uncomment to enable the smaller implementation of SHA256. + */ +//#define MBEDTLS_SHA256_SMALLER + +/** + * \def MBEDTLS_SSL_AEAD_RANDOM_IV + * + * Generate a random IV rather than using the record sequence number as a + * nonce for ciphersuites using and AEAD algorithm (GCM or CCM). + * + * Using the sequence number is generally recommended. + * + * Uncomment this macro to always use random IVs with AEAD ciphersuites. + */ +//#define MBEDTLS_SSL_AEAD_RANDOM_IV + +/** + * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES + * + * Enable sending of alert messages in case of encountered errors as per RFC. + * If you choose not to send the alert messages, mbed TLS can still communicate + * with other servers, only debugging of failures is harder. + * + * The advantage of not sending alert messages, is that no information is given + * about reasons for failures thus preventing adversaries of gaining intel. + * + * Enable sending of all alert messages + */ +#define MBEDTLS_SSL_ALL_ALERT_MESSAGES + +/** + * \def MBEDTLS_SSL_DEBUG_ALL + * + * Enable the debug messages in SSL module for all issues. + * Debug messages have been disabled in some places to prevent timing + * attacks due to (unbalanced) debugging function calls. + * + * If you need all error reporting you should enable this during debugging, + * but remove this for production servers that should log as well. + * + * Uncomment this macro to report all debug messages on errors introducing + * a timing side-channel. + * + */ +//#define MBEDTLS_SSL_DEBUG_ALL + +/** \def MBEDTLS_SSL_ENCRYPT_THEN_MAC + * + * Enable support for Encrypt-then-MAC, RFC 7366. + * + * This allows peers that both support it to use a more robust protection for + * ciphersuites using CBC, providing deep resistance against timing attacks + * on the padding or underlying cipher. + * + * This only affects CBC ciphersuites, and is useless if none is defined. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1 or + * MBEDTLS_SSL_PROTO_TLS1_1 or + * MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Encrypt-then-MAC + */ +#define MBEDTLS_SSL_ENCRYPT_THEN_MAC + +/** \def MBEDTLS_SSL_EXTENDED_MASTER_SECRET + * + * Enable support for Extended Master Secret, aka Session Hash + * (draft-ietf-tls-session-hash-02). + * + * This was introduced as "the proper fix" to the Triple Handshake familiy of + * attacks, but it is recommended to always use it (even if you disable + * renegotiation), since it actually fixes a more fundamental issue in the + * original SSL/TLS design, and has implications beyond Triple Handshake. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1 or + * MBEDTLS_SSL_PROTO_TLS1_1 or + * MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Extended Master Secret. + */ +#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET + +/** + * \def MBEDTLS_SSL_FALLBACK_SCSV + * + * Enable support for FALLBACK_SCSV (draft-ietf-tls-downgrade-scsv-00). + * + * For servers, it is recommended to always enable this, unless you support + * only one version of TLS, or know for sure that none of your clients + * implements a fallback strategy. + * + * For clients, you only need this if you're using a fallback strategy, which + * is not recommended in the first place, unless you absolutely need it to + * interoperate with buggy (version-intolerant) servers. + * + * Comment this macro to disable support for FALLBACK_SCSV + */ +#define MBEDTLS_SSL_FALLBACK_SCSV + +/** + * \def MBEDTLS_SSL_HW_RECORD_ACCEL + * + * Enable hooking functions in SSL module for hardware acceleration of + * individual records. + * + * Uncomment this macro to enable hooking functions. + */ +//#define MBEDTLS_SSL_HW_RECORD_ACCEL + +/** + * \def MBEDTLS_SSL_CBC_RECORD_SPLITTING + * + * Enable 1/n-1 record splitting for CBC mode in SSLv3 and TLS 1.0. + * + * This is a countermeasure to the BEAST attack, which also minimizes the risk + * of interoperability issues compared to sending 0-length records. + * + * Comment this macro to disable 1/n-1 record splitting. + */ +#define MBEDTLS_SSL_CBC_RECORD_SPLITTING + +/** + * \def MBEDTLS_SSL_RENEGOTIATION + * + * Disable support for TLS renegotiation. + * + * The two main uses of renegotiation are (1) refresh keys on long-lived + * connections and (2) client authentication after the initial handshake. + * If you don't need renegotiation, it's probably better to disable it, since + * it has been associated with security issues in the past and is easy to + * misuse/misunderstand. + * + * Comment this to disable support for renegotiation. + */ +//#define MBEDTLS_SSL_RENEGOTIATION + +/** + * \def MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO + * + * Enable support for receiving and parsing SSLv2 Client Hello messages for the + * SSL Server module (MBEDTLS_SSL_SRV_C). + * + * Uncomment this macro to enable support for SSLv2 Client Hello messages. + */ +//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO + +/** + * \def MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE + * + * Pick the ciphersuite according to the client's preferences rather than ours + * in the SSL Server module (MBEDTLS_SSL_SRV_C). + * + * Uncomment this macro to respect client's ciphersuite order + */ +//#define MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE + +/** + * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + * + * Enable support for RFC 6066 max_fragment_length extension in SSL. + * + * Comment this macro to disable support for the max_fragment_length extension + */ +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + +/** + * \def MBEDTLS_SSL_PROTO_SSL3 + * + * Enable support for SSL 3.0. + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for SSL 3.0 + */ +#define MBEDTLS_SSL_PROTO_SSL3 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1 + * + * Enable support for TLS 1.0. + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for TLS 1.0 + */ +#define MBEDTLS_SSL_PROTO_TLS1 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_1 + * + * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled). + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for TLS 1.1 / DTLS 1.0 + */ +#define MBEDTLS_SSL_PROTO_TLS1_1 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_2 + * + * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). + * + * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C + * (Depends on ciphersuites) + * + * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 + */ +#define MBEDTLS_SSL_PROTO_TLS1_2 + +/** + * \def MBEDTLS_SSL_PROTO_DTLS + * + * Enable support for DTLS (all available versions). + * + * Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0, + * and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_1 + * or MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for DTLS + */ +#define MBEDTLS_SSL_PROTO_DTLS + +/** + * \def MBEDTLS_SSL_ALPN + * + * Enable support for RFC 7301 Application Layer Protocol Negotiation. + * + * Comment this macro to disable support for ALPN. + */ +#define MBEDTLS_SSL_ALPN + +/** + * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY + * + * Enable support for the anti-replay mechanism in DTLS. + * + * Requires: MBEDTLS_SSL_TLS_C + * MBEDTLS_SSL_PROTO_DTLS + * + * \warning Disabling this is often a security risk! + * See mbedtls_ssl_conf_dtls_anti_replay() for details. + * + * Comment this to disable anti-replay in DTLS. + */ +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY + +/** + * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Enable support for HelloVerifyRequest on DTLS servers. + * + * This feature is highly recommended to prevent DTLS servers being used as + * amplifiers in DoS attacks against other hosts. It should always be enabled + * unless you know for sure amplification cannot be a problem in the + * environment in which your server operates. + * + * \warning Disabling this can ba a security risk! (see above) + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + * + * Comment this to disable support for HelloVerifyRequest. + */ +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY + +/** + * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + * + * Enable server-side support for clients that reconnect from the same port. + * + * Some clients unexpectedly close the connection and try to reconnect using the + * same source port. This needs special support from the server to handle the + * new connection securely, as described in section 4.2.8 of RFC 6347. This + * flag enables that support. + * + * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Comment this to disable support for clients reusing the source port. + */ +#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + +/** + * \def MBEDTLS_SSL_DTLS_BADMAC_LIMIT + * + * Enable support for a limit of records with bad MAC. + * + * See mbedtls_ssl_conf_dtls_badmac_limit(). + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + */ +#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT + +/** + * \def MBEDTLS_SSL_SESSION_TICKETS + * + * Enable support for RFC 5077 session tickets in SSL. + * Client-side, provides full support for session tickets (maintainance of a + * session store remains the responsibility of the application, though). + * Server-side, you also need to provide callbacks for writing and parsing + * tickets, including authenticated encryption and key management. Example + * callbacks are provided by MBEDTLS_SSL_TICKET_C. + * + * Comment this macro to disable support for SSL session tickets + */ +#define MBEDTLS_SSL_SESSION_TICKETS + +/** + * \def MBEDTLS_SSL_EXPORT_KEYS + * + * Enable support for exporting key block and master secret. + * This is required for certain users of TLS, e.g. EAP-TLS. + * + * Comment this macro to disable support for key export + */ +#define MBEDTLS_SSL_EXPORT_KEYS + +/** + * \def MBEDTLS_SSL_SERVER_NAME_INDICATION + * + * Enable support for RFC 6066 server name indication (SNI) in SSL. + * + * Requires: MBEDTLS_X509_CRT_PARSE_C + * + * Comment this macro to disable support for server name indication in SSL + */ +#define MBEDTLS_SSL_SERVER_NAME_INDICATION + +/** + * \def MBEDTLS_SSL_TRUNCATED_HMAC + * + * Enable support for RFC 6066 truncated HMAC in SSL. + * + * Comment this macro to disable support for truncated HMAC in SSL + */ +#define MBEDTLS_SSL_TRUNCATED_HMAC + +/** + * \def MBEDTLS_THREADING_ALT + * + * Provide your own alternate threading implementation. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to allow your own alternate threading implementation. + */ +//#define MBEDTLS_THREADING_ALT + +/** + * \def MBEDTLS_THREADING_PTHREAD + * + * Enable the pthread wrapper layer for the threading layer. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to enable pthread mutexes. + */ +//#define MBEDTLS_THREADING_PTHREAD + +/** + * \def MBEDTLS_VERSION_FEATURES + * + * Allow run-time checking of compile-time enabled features. Thus allowing users + * to check at run-time if the library is for instance compiled with threading + * support via mbedtls_version_check_feature(). + * + * Requires: MBEDTLS_VERSION_C + * + * Comment this to disable run-time checking and save ROM space + */ +//#define MBEDTLS_VERSION_FEATURES + +/** + * \def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 + * + * If set, the X509 parser will not break-off when parsing an X509 certificate + * and encountering an extension in a v1 or v2 certificate. + * + * Uncomment to prevent an error. + */ +//#define MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 + +/** + * \def MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION + * + * If set, the X509 parser will not break-off when parsing an X509 certificate + * and encountering an unknown critical extension. + * + * \warning Depending on your PKI use, enabling this can be a security risk! + * + * Uncomment to prevent an error. + */ +//#define MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION + +/** + * \def MBEDTLS_X509_CHECK_KEY_USAGE + * + * Enable verification of the keyUsage extension (CA and leaf certificates). + * + * Disabling this avoids problems with mis-issued and/or misused + * (intermediate) CA and leaf certificates. + * + * \warning Depending on your PKI use, disabling this can be a security risk! + * + * Comment to skip keyUsage checking for both CA and leaf certificates. + */ +#define MBEDTLS_X509_CHECK_KEY_USAGE + +/** + * \def MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + * + * Enable verification of the extendedKeyUsage extension (leaf certificates). + * + * Disabling this avoids problems with mis-issued and/or misused certificates. + * + * \warning Depending on your PKI use, disabling this can be a security risk! + * + * Comment to skip extendedKeyUsage checking for certificates. + */ +#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + +/** + * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT + * + * Enable parsing and verification of X.509 certificates, CRLs and CSRS + * signed with RSASSA-PSS (aka PKCS#1 v2.1). + * + * Comment this macro to disallow using RSASSA-PSS in certificates. + */ +#define MBEDTLS_X509_RSASSA_PSS_SUPPORT + +/** + * \def MBEDTLS_ZLIB_SUPPORT + * + * If set, the SSL/TLS module uses ZLIB to support compression and + * decompression of packet data. + * + * \warning TLS-level compression MAY REDUCE SECURITY! See for example the + * CRIME attack. Before enabling this option, you should examine with care if + * CRIME or similar exploits may be a applicable to your use case. + * + * \note Currently compression can't be used with DTLS. + * + * Used in: library/ssl_tls.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * This feature requires zlib library and headers to be present. + * + * Uncomment to enable use of ZLIB + */ +//#define MBEDTLS_ZLIB_SUPPORT +/* \} name SECTION: mbed TLS feature support */ + +/** + * \name SECTION: mbed TLS modules + * + * This section enables or disables entire modules in mbed TLS + * \{ + */ + +/** + * \def MBEDTLS_AESNI_C + * + * Enable AES-NI support on x86-64. + * + * Module: library/aesni.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM + * + * This modules adds support for the AES-NI instructions on x86-64 + */ +#define MBEDTLS_AESNI_C + +/** + * \def MBEDTLS_AES_C + * + * Enable the AES block cipher. + * + * Module: library/aes.c + * Caller: library/ssl_tls.c + * library/pem.c + * library/ctr_drbg.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * + * PEM_PARSE uses AES for decrypting encrypted keys. + */ +#define MBEDTLS_AES_C + +/** + * \def MBEDTLS_ARC4_C + * + * Enable the ARCFOUR stream cipher. + * + * Module: library/arc4.c + * Caller: library/ssl_tls.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 + * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_ARC4_C + +/** + * \def MBEDTLS_ASN1_PARSE_C + * + * Enable the generic ASN1 parser. + * + * Module: library/asn1.c + * Caller: library/x509.c + * library/dhm.c + * library/pkcs12.c + * library/pkcs5.c + * library/pkparse.c + */ +#define MBEDTLS_ASN1_PARSE_C + +/** + * \def MBEDTLS_ASN1_WRITE_C + * + * Enable the generic ASN1 writer. + * + * Module: library/asn1write.c + * Caller: library/ecdsa.c + * library/pkwrite.c + * library/x509_create.c + * library/x509write_crt.c + * library/mbedtls_x509write_csr.c + */ +//#define MBEDTLS_ASN1_WRITE_C + +/** + * \def MBEDTLS_BASE64_C + * + * Enable the Base64 module. + * + * Module: library/base64.c + * Caller: library/pem.c + * + * This module is required for PEM support (required by X.509). + */ +#define MBEDTLS_BASE64_C + +/** + * \def MBEDTLS_BIGNUM_C + * + * Enable the multi-precision integer library. + * + * Module: library/bignum.c + * Caller: library/dhm.c + * library/ecp.c + * library/ecdsa.c + * library/rsa.c + * library/ssl_tls.c + * + * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. + */ +#define MBEDTLS_BIGNUM_C + +/** + * \def MBEDTLS_BLOWFISH_C + * + * Enable the Blowfish block cipher. + * + * Module: library/blowfish.c + */ +#define MBEDTLS_BLOWFISH_C + +/** + * \def MBEDTLS_CAMELLIA_C + * + * Enable the Camellia block cipher. + * + * Module: library/camellia.c + * Caller: library/ssl_tls.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +//#define MBEDTLS_CAMELLIA_C + +/** + * \def MBEDTLS_CCM_C + * + * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher. + * + * Module: library/ccm.c + * + * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C + * + * This module enables the AES-CCM ciphersuites, if other requisites are + * enabled as well. + */ +//#define MBEDTLS_CCM_C + +/** + * \def MBEDTLS_CERTS_C + * + * Enable the test certificates. + * + * Module: library/certs.c + * Caller: + * + * This module is used for testing (ssl_client/server). + */ +#define MBEDTLS_CERTS_C + +/** + * \def MBEDTLS_CIPHER_C + * + * Enable the generic cipher layer. + * + * Module: library/cipher.c + * Caller: library/ssl_tls.c + * + * Uncomment to enable generic cipher wrappers. + */ +#define MBEDTLS_CIPHER_C + +/** + * \def MBEDTLS_CTR_DRBG_C + * + * Enable the CTR_DRBG AES-256-based random generator. + * + * Module: library/ctr_drbg.c + * Caller: + * + * Requires: MBEDTLS_AES_C + * + * This module provides the CTR_DRBG AES-256 random number generator. + */ +#define MBEDTLS_CTR_DRBG_C + +/** + * \def MBEDTLS_DEBUG_C + * + * Enable the debug functions. + * + * Module: library/debug.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * This module provides debugging functions. + */ +#define MBEDTLS_DEBUG_C + +/** + * \def MBEDTLS_DES_C + * + * Enable the DES block cipher. + * + * Module: library/des.c + * Caller: library/pem.c + * library/ssl_tls.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA + * + * PEM_PARSE uses DES/3DES for decrypting encrypted keys. + */ +#define MBEDTLS_DES_C + +/** + * \def MBEDTLS_DHM_C + * + * Enable the Diffie-Hellman-Merkle module. + * + * Module: library/dhm.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * This module is used by the following key exchanges: + * DHE-RSA, DHE-PSK + */ +#define MBEDTLS_DHM_C + +/** + * \def MBEDTLS_ECDH_C + * + * Enable the elliptic curve Diffie-Hellman library. + * + * Module: library/ecdh.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK + * + * Requires: MBEDTLS_ECP_C + */ +//#define MBEDTLS_ECDH_C + +/** + * \def MBEDTLS_ECDSA_C + * + * Enable the elliptic curve DSA library. + * + * Module: library/ecdsa.c + * Caller: + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA + * + * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C + */ +//#define MBEDTLS_ECDSA_C + +/** + * \def MBEDTLS_ECJPAKE_C + * + * Enable the elliptic curve J-PAKE library. + * + * \warning This is currently experimental. EC J-PAKE support is based on the + * Thread v1.0.0 specification; incompatible changes to the specification + * might still happen. For this reason, this is disabled by default. + * + * Module: library/ecjpake.c + * Caller: + * + * This module is used by the following key exchanges: + * ECJPAKE + * + * Requires: MBEDTLS_ECP_C, MBEDTLS_MD_C + */ +//#define MBEDTLS_ECJPAKE_C + +/** + * \def MBEDTLS_ECP_C + * + * Enable the elliptic curve over GF(p) library. + * + * Module: library/ecp.c + * Caller: library/ecdh.c + * library/ecdsa.c + * library/ecjpake.c + * + * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED + */ +//#define MBEDTLS_ECP_C + +/** + * \def MBEDTLS_ENTROPY_C + * + * Enable the platform-specific entropy code. + * + * Module: library/entropy.c + * Caller: + * + * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C + * + * This module provides a generic entropy pool + */ +#define MBEDTLS_ENTROPY_C + +/** + * \def MBEDTLS_ERROR_C + * + * Enable error code to error string conversion. + * + * Module: library/error.c + * Caller: + * + * This module enables mbedtls_strerror(). + */ +#define MBEDTLS_ERROR_C + +/** + * \def MBEDTLS_GCM_C + * + * Enable the Galois/Counter Mode (GCM) for AES. + * + * Module: library/gcm.c + * + * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C + * + * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other + * requisites are enabled as well. + */ +//#define MBEDTLS_GCM_C + +/** + * \def MBEDTLS_HAVEGE_C + * + * Enable the HAVEGE random generator. + * + * Warning: the HAVEGE random generator is not suitable for virtualized + * environments + * + * Warning: the HAVEGE random generator is dependent on timing and specific + * processor traits. It is therefore not advised to use HAVEGE as + * your applications primary random generator or primary entropy pool + * input. As a secondary input to your entropy pool, it IS able add + * the (limited) extra entropy it provides. + * + * Module: library/havege.c + * Caller: + * + * Requires: MBEDTLS_TIMING_C + * + * Uncomment to enable the HAVEGE random generator. + */ +//#define MBEDTLS_HAVEGE_C + +/** + * \def MBEDTLS_HMAC_DRBG_C + * + * Enable the HMAC_DRBG random generator. + * + * Module: library/hmac_drbg.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * Uncomment to enable the HMAC_DRBG random number geerator. + */ +#define MBEDTLS_HMAC_DRBG_C + +/** + * \def MBEDTLS_MD_C + * + * Enable the generic message digest layer. + * + * Module: library/mbedtls_md.c + * Caller: + * + * Uncomment to enable generic message digest wrappers. + */ +#define MBEDTLS_MD_C + +/** + * \def MBEDTLS_MD2_C + * + * Enable the MD2 hash algorithm. + * + * Module: library/mbedtls_md2.c + * Caller: + * + * Uncomment to enable support for (rare) MD2-signed X.509 certs. + */ +//#define MBEDTLS_MD2_C + +/** + * \def MBEDTLS_MD4_C + * + * Enable the MD4 hash algorithm. + * + * Module: library/mbedtls_md4.c + * Caller: + * + * Uncomment to enable support for (rare) MD4-signed X.509 certs. + */ +//#define MBEDTLS_MD4_C + +/** + * \def MBEDTLS_MD5_C + * + * Enable the MD5 hash algorithm. + * + * Module: library/mbedtls_md5.c + * Caller: library/mbedtls_md.c + * library/pem.c + * library/ssl_tls.c + * + * This module is required for SSL/TLS and X.509. + * PEM_PARSE uses MD5 for decrypting encrypted keys. + */ +#define MBEDTLS_MD5_C + +/** + * \def MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Enable the buffer allocator implementation that makes use of a (stack) + * based buffer to 'allocate' dynamic memory. (replaces calloc() and free() + * calls) + * + * Module: library/memory_buffer_alloc.c + * + * Requires: MBEDTLS_PLATFORM_C + * MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS) + * + * Enable this module to enable the buffer memory allocator. + */ +//#define MBEDTLS_MEMORY_BUFFER_ALLOC_C + +/** + * \def MBEDTLS_NET_C + * + * Enable the TCP and UDP over IPv6/IPv4 networking routines. + * + * \note This module only works on POSIX/Unix (including Linux, BSD and OS X) + * and Windows. For other platforms, you'll want to disable it, and write your + * own networking callbacks to be passed to \c mbedtls_ssl_set_bio(). + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/net.c + * + * This module provides networking routines. + */ +// #define MBEDTLS_NET_C + +/** + * \def MBEDTLS_OID_C + * + * Enable the OID database. + * + * Module: library/oid.c + * Caller: library/asn1write.c + * library/pkcs5.c + * library/pkparse.c + * library/pkwrite.c + * library/rsa.c + * library/x509.c + * library/x509_create.c + * library/mbedtls_x509_crl.c + * library/mbedtls_x509_crt.c + * library/mbedtls_x509_csr.c + * library/x509write_crt.c + * library/mbedtls_x509write_csr.c + * + * This modules translates between OIDs and internal values. + */ +#define MBEDTLS_OID_C + +/** + * \def MBEDTLS_PADLOCK_C + * + * Enable VIA Padlock support on x86. + * + * Module: library/padlock.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM + * + * This modules adds support for the VIA PadLock on x86. + */ +#define MBEDTLS_PADLOCK_C + +/** + * \def MBEDTLS_PEM_PARSE_C + * + * Enable PEM decoding / parsing. + * + * Module: library/pem.c + * Caller: library/dhm.c + * library/pkparse.c + * library/mbedtls_x509_crl.c + * library/mbedtls_x509_crt.c + * library/mbedtls_x509_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for decoding / parsing PEM files. + */ +#define MBEDTLS_PEM_PARSE_C + +/** + * \def MBEDTLS_PEM_WRITE_C + * + * Enable PEM encoding / writing. + * + * Module: library/pem.c + * Caller: library/pkwrite.c + * library/x509write_crt.c + * library/mbedtls_x509write_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for encoding / writing PEM files. + */ +//#define MBEDTLS_PEM_WRITE_C + +/** + * \def MBEDTLS_PK_C + * + * Enable the generic public (asymetric) key layer. + * + * Module: library/pk.c + * Caller: library/ssl_tls.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C + * + * Uncomment to enable generic public key wrappers. + */ +#define MBEDTLS_PK_C + +/** + * \def MBEDTLS_PK_PARSE_C + * + * Enable the generic public (asymetric) key parser. + * + * Module: library/pkparse.c + * Caller: library/mbedtls_x509_crt.c + * library/mbedtls_x509_csr.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key parse functions. + */ +#define MBEDTLS_PK_PARSE_C + +/** + * \def MBEDTLS_PK_WRITE_C + * + * Enable the generic public (asymetric) key writer. + * + * Module: library/pkwrite.c + * Caller: library/x509write.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key write functions. + */ +//#define MBEDTLS_PK_WRITE_C + +/** + * \def MBEDTLS_PKCS5_C + * + * Enable PKCS#5 functions. + * + * Module: library/pkcs5.c + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the PKCS#5 functions. + */ +#define MBEDTLS_PKCS5_C + +/** + * \def MBEDTLS_PKCS11_C + * + * Enable wrapper for PKCS#11 smartcard support. + * + * Module: library/pkcs11.c + * Caller: library/pk.c + * + * Requires: MBEDTLS_PK_C + * + * This module enables SSL/TLS PKCS #11 smartcard support. + * Requires the presence of the PKCS#11 helper library (libpkcs11-helper) + */ +//#define MBEDTLS_PKCS11_C + +/** + * \def MBEDTLS_PKCS12_C + * + * Enable PKCS#12 PBE functions. + * Adds algorithms for parsing PKCS#8 encrypted private keys + * + * Module: library/pkcs12.c + * Caller: library/pkparse.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C, MBEDTLS_MD_C + * Can use: MBEDTLS_ARC4_C + * + * This module enables PKCS#12 functions. + */ +#define MBEDTLS_PKCS12_C + +/** + * \def MBEDTLS_PLATFORM_C + * + * Enable the platform abstraction layer that allows you to re-assign + * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit(). + * + * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT + * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned + * above to be specified at runtime or compile time respectively. + * + * \note This abstraction layer must be enabled on Windows (including MSYS2) + * as other module rely on it for a fixed snprintf implementation. + * + * Module: library/platform.c + * Caller: Most other .c files + * + * This module enables abstraction of common (libc) functions. + */ +#define MBEDTLS_PLATFORM_C + +/** + * \def MBEDTLS_RIPEMD160_C + * + * Enable the RIPEMD-160 hash algorithm. + * + * Module: library/mbedtls_ripemd160.c + * Caller: library/mbedtls_md.c + * + */ +//#define MBEDTLS_RIPEMD160_C + +/** + * \def MBEDTLS_RSA_C + * + * Enable the RSA public-key cryptosystem. + * + * Module: library/rsa.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * library/x509.c + * + * This module is used by the following key exchanges: + * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C + */ +#define MBEDTLS_RSA_C + +/** + * \def MBEDTLS_SHA1_C + * + * Enable the SHA1 cryptographic hash algorithm. + * + * Module: library/mbedtls_sha1.c + * Caller: library/mbedtls_md.c + * library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * library/x509write_crt.c + * + * This module is required for SSL/TLS and SHA1-signed certificates. + */ +#define MBEDTLS_SHA1_C + +/** + * \def MBEDTLS_SHA256_C + * + * Enable the SHA-224 and SHA-256 cryptographic hash algorithms. + * + * Module: library/mbedtls_sha256.c + * Caller: library/entropy.c + * library/mbedtls_md.c + * library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * This module adds support for SHA-224 and SHA-256. + * This module is required for the SSL/TLS 1.2 PRF function. + */ +#define MBEDTLS_SHA256_C + +/** + * \def MBEDTLS_SHA512_C + * + * Enable the SHA-384 and SHA-512 cryptographic hash algorithms. + * + * Module: library/mbedtls_sha512.c + * Caller: library/entropy.c + * library/mbedtls_md.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * This module adds support for SHA-384 and SHA-512. + */ +#define MBEDTLS_SHA512_C + +/** + * \def MBEDTLS_SSL_CACHE_C + * + * Enable simple SSL cache implementation. + * + * Module: library/ssl_cache.c + * Caller: + * + * Requires: MBEDTLS_SSL_CACHE_C + */ +#define MBEDTLS_SSL_CACHE_C + +/** + * \def MBEDTLS_SSL_COOKIE_C + * + * Enable basic implementation of DTLS cookies for hello verification. + * + * Module: library/ssl_cookie.c + * Caller: + */ +#define MBEDTLS_SSL_COOKIE_C + +/** + * \def MBEDTLS_SSL_TICKET_C + * + * Enable an implementation of TLS server-side callbacks for session tickets. + * + * Module: library/ssl_ticket.c + * Caller: + * + * Requires: MBEDTLS_CIPHER_C + */ +#define MBEDTLS_SSL_TICKET_C + +/** + * \def MBEDTLS_SSL_CLI_C + * + * Enable the SSL/TLS client code. + * + * Module: library/ssl_cli.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS client support. + */ +#define MBEDTLS_SSL_CLI_C + +/** + * \def MBEDTLS_SSL_SRV_C + * + * Enable the SSL/TLS server code. + * + * Module: library/ssl_srv.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS server support. + */ +#define MBEDTLS_SSL_SRV_C + +/** + * \def MBEDTLS_SSL_TLS_C + * + * Enable the generic SSL/TLS code. + * + * Module: library/ssl_tls.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C + * and at least one of the MBEDTLS_SSL_PROTO_XXX defines + * + * This module is required for SSL/TLS. + */ +#define MBEDTLS_SSL_TLS_C + +/** + * \def MBEDTLS_THREADING_C + * + * Enable the threading abstraction layer. + * By default mbed TLS assumes it is used in a non-threaded environment or that + * contexts are not shared between threads. If you do intend to use contexts + * between threads, you will need to enable this layer to prevent race + * conditions. See also our Knowledge Base article about threading: + * https://tls.mbed.org/kb/development/thread-safety-and-multi-threading + * + * Module: library/threading.c + * + * This allows different threading implementations (self-implemented or + * provided). + * + * You will have to enable either MBEDTLS_THREADING_ALT or + * MBEDTLS_THREADING_PTHREAD. + * + * Enable this layer to allow use of mutexes within mbed TLS + */ +//#define MBEDTLS_THREADING_C + +/** + * \def MBEDTLS_TIMING_C + * + * Enable the semi-portable timing interface. + * + * \note The provided implementation only works on POSIX/Unix (including Linux, + * BSD and OS X) and Windows. On other platforms, you can either disable that + * module and provide your own implementations of the callbacks needed by + * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide + * your own implementation of the whole module by setting + * \c MBEDTLS_TIMING_ALT in the current file. + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/timing.c + * Caller: library/havege.c + * + * This module is used by the HAVEGE random number generator. + */ +#define MBEDTLS_TIMING_C + +/** + * \def MBEDTLS_VERSION_C + * + * Enable run-time version information. + * + * Module: library/version.c + * + * This module provides run-time version information. + */ +//#define MBEDTLS_VERSION_C + +/** + * \def MBEDTLS_X509_USE_C + * + * Enable X.509 core for using certificates. + * + * Module: library/x509.c + * Caller: library/mbedtls_x509_crl.c + * library/mbedtls_x509_crt.c + * library/mbedtls_x509_csr.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, + * MBEDTLS_PK_PARSE_C + * + * This module is required for the X.509 parsing modules. + */ +#define MBEDTLS_X509_USE_C + +/** + * \def MBEDTLS_X509_CRT_PARSE_C + * + * Enable X.509 certificate parsing. + * + * Module: library/mbedtls_x509_crt.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 certificate parsing. + */ +#define MBEDTLS_X509_CRT_PARSE_C + +/** + * \def MBEDTLS_X509_CRL_PARSE_C + * + * Enable X.509 CRL parsing. + * + * Module: library/mbedtls_x509_crl.c + * Caller: library/mbedtls_x509_crt.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 CRL parsing. + */ +#define MBEDTLS_X509_CRL_PARSE_C + +/** + * \def MBEDTLS_X509_CSR_PARSE_C + * + * Enable X.509 Certificate Signing Request (CSR) parsing. + * + * Module: library/mbedtls_x509_csr.c + * Caller: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is used for reading X.509 certificate request. + */ +//#define MBEDTLS_X509_CSR_PARSE_C + +/** + * \def MBEDTLS_X509_CREATE_C + * + * Enable X.509 core for creating certificates. + * + * Module: library/x509_create.c + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_WRITE_C + * + * This module is the basis for creating X.509 certificates and CSRs. + */ +//#define MBEDTLS_X509_CREATE_C + +/** + * \def MBEDTLS_X509_CRT_WRITE_C + * + * Enable creating X.509 certificates. + * + * Module: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate creation. + */ +//#define MBEDTLS_X509_CRT_WRITE_C + +/** + * \def MBEDTLS_X509_CSR_WRITE_C + * + * Enable creating X.509 Certificate Signing Requests (CSR). + * + * Module: library/x509_csr_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate request writing. + */ +//#define MBEDTLS_X509_CSR_WRITE_C + +/** + * \def MBEDTLS_XTEA_C + * + * Enable the XTEA block cipher. + * + * Module: library/xtea.c + * Caller: + */ +#define MBEDTLS_XTEA_C + +/* \} name SECTION: mbed TLS modules */ + +/** + * \name SECTION: Module configuration options + * + * This section allows for the setting of module specific sizes and + * configuration options. The default values are already present in the + * relevant header files and should suffice for the regular use cases. + * + * Our advice is to enable options and change their values here + * only if you have a good reason and know the consequences. + * + * Please check the respective header file for documentation on these + * parameters (to prevent duplicate documentation). + * \{ + */ + +/* MPI / BIGNUM options */ +//#define MBEDTLS_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ +//#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ + +/* CTR_DRBG options */ +//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ +//#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ + +/* HMAC_DRBG options */ +//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ + +/* ECP options */ +//#define MBEDTLS_ECP_MAX_BITS 521 /**< Maximum bit size of groups */ +//#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< Maximum window size used */ +//#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ + +/* Entropy options */ +//#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ +//#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ + +/* Memory buffer allocator options */ +//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ + +/* Platform options */ +//#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */ +//#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ +/* Note: your snprintf must correclty zero-terminate the buffer! */ +//#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default implementation */ + +/* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */ +/* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */ +//#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */ +/* Note: your snprintf must correclty zero-terminate the buffer! */ +#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ + +/* SSL Cache options */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ + +/* SSL options */ +//#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */ +//#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ +//#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ +//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ + +/** + * Complete list of ciphersuites to use, in order of preference. + * + * \warning No dependency checking is done on that field! This option can only + * be used to restrict the set of available ciphersuites. It is your + * responsibility to make sure the needed modules are active. + * + * Use this to save a few hundred bytes of ROM (default ordering of all + * available ciphersuites) and a few to a few hundred bytes of RAM. + * + * The value below is only an example, not the default. + */ +//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + +/* X509 options */ +//#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */ + +/* \} name SECTION: Customisation configuration options */ + +/* Target and application specific configurations */ +//#define YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE "target_config.h" + +/* + * Allow user to override any previous default. + * + * Use two macro names for that, as: + * - with yotta the prefix YOTTA_CFG_ is forced + * - without yotta is looks weird to have a YOTTA prefix. + */ +#if defined(YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE) +#include YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE +#elif defined(MBEDTLS_USER_CONFIG_FILE) +#include MBEDTLS_USER_CONFIG_FILE +#endif + +#include "check_config.h" + +#endif /* MBEDTLS_CONFIG_H */ diff --git a/external/fix-external/mbedtls/library/rsa.c b/external/fix-external/mbedtls/library/rsa.c index 80535cd..0ff55f6 100644 --- a/external/fix-external/mbedtls/library/rsa.c +++ b/external/fix-external/mbedtls/library/rsa.c @@ -19,10 +19,16 @@ * This file is part of mbed TLS (https://tls.mbed.org) */ /* - * RSA was designed by Ron Rivest, Adi Shamir and Len Adleman. + * The following sources were referenced in the design of this implementation + * of the RSA algorithm: + * + * [1] A method for obtaining digital signatures and public-key cryptosystems + * R Rivest, A Shamir, and L Adleman + * http://people.csail.mit.edu/rivest/pubs.html#RSA78 + * + * [2] Handbook of Applied Cryptography - 1997, Chapter 8 + * Menezes, van Oorschot and Vanstone * - * http://theory.lcs.mit.edu/~rivest/rsapaper.pdf - * http://www.cacr.math.uwaterloo.ca/hac/about/chap8.pdf */ #if !defined(MBEDTLS_CONFIG_FILE) @@ -96,7 +102,8 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, if( f_rng == NULL || nbits < 128 || exponent < 3 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); - mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); + mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); + mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); /* * find primes P and Q with Q < P so that: @@ -106,14 +113,19 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, do { - MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, ( nbits + 1 ) >> 1, 0, + MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, ( nbits + 1 ) >> 1, 0, + if( nbits % 2 ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, ( nbits >> 1 ) + 1, 0, f_rng, p_rng ) ); - - if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 ) - mbedtls_mpi_swap( &ctx->P, &ctx->Q ); + } + else + { + MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0, + f_rng, p_rng ) ); + } if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 ) continue; @@ -366,7 +378,7 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, #else if (ctx->N.p == NULL || ctx->P.p == NULL || ctx->Q.p == NULL || ctx->D.p == NULL) #endif - //if (ctx->P.p == NULL || ctx->Q.p == NULL || ctx->D.p == NULL) + /*if (ctx->P.p == NULL || ctx->Q.p == NULL || ctx->D.p == NULL)*/ return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); @@ -471,8 +483,7 @@ static void mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src, hlen = mbedtls_md_get_size( md_ctx->md_info ); - // Generate and apply dbMask - // + /* Generate and apply dbMask */ p = dst; while( dlen > 0 ) @@ -529,22 +540,21 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, olen = ctx->len; hlen = mbedtls_md_get_size( md_info ); - if( olen < ilen + 2 * hlen + 2 ) + /* first comparison checks for overflow */ + if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); memset( output, 0, olen ); *p++ = 0; - // Generate a random octet string seed - // + /* Generate a random octet string seed */ if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); p += hlen; - // Construct DB - // + /* Construct DB */ mbedtls_md( md_info, label, label_len, p ); p += hlen; p += olen - 2 * hlen - 2 - ilen; @@ -552,15 +562,17 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, memcpy( p, input, ilen ); mbedtls_md_init( &md_ctx ); - mbedtls_md_setup( &md_ctx, md_info, 0 ); + if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) + { + mbedtls_md_free( &md_ctx ); + return( ret ); + } - // maskedDB: Apply dbMask to DB - // + /* maskedDB: Apply dbMask to DB */ mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen, &md_ctx ); - // maskedSeed: Apply seedMask to seed - // + /* maskedSeed: Apply seedMask to seed */ mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1, &md_ctx ); @@ -590,12 +602,14 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); - if( f_rng == NULL ) + // We don't check p_rng because it won't be dereferenced here + if( f_rng == NULL || input == NULL || output == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; - if( olen < ilen + 11 ) + /* first comparison checks for overflow */ + if( ilen + 11 < ilen || olen < ilen + 11 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad = olen - 3 - ilen; @@ -613,8 +627,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, ret = f_rng( p_rng, p, 1 ); } while( *p == 0 && --rng_dl && ret == 0 ); - // Check if RNG failed to generate data - // + /* Check if RNG failed to generate data */ if( rng_dl == 0 || ret != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); @@ -705,6 +718,12 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + hlen = mbedtls_md_get_size( md_info ); + + // checking for integer underflow + if( 2 * hlen + 2 > ilen ) + return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + /* * RSA operation */ @@ -718,10 +737,13 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, /* * Unmask data and generate lHash */ - hlen = mbedtls_md_get_size( md_info ); - mbedtls_md_init( &md_ctx ); - mbedtls_md_setup( &md_ctx, md_info, 0 ); + if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) + { + mbedtls_md_free( &md_ctx ); + return( ret ); + } + /* Generate lHash */ mbedtls_md( md_info, label, label_len, lhash ); @@ -854,6 +876,8 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, bad |= *p++; /* Must be zero */ } + bad |= ( pad_count < 8 ); + if( bad ) return( MBEDTLS_ERR_RSA_INVALID_PADDING ); @@ -930,8 +954,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, if( md_alg != MBEDTLS_MD_NONE ) { - // Gather length of hash to sign - // + /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -951,13 +974,11 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, memset( sig, 0, olen ); - // Generate salt of length slen - // + /* Generate salt of length slen */ if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); - // Note: EMSA-PSS encoding is over the length of N - 1 bits - // + /* Note: EMSA-PSS encoding is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; p += olen - hlen * 2 - 2; *p++ = 0x01; @@ -965,23 +986,24 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, p += slen; mbedtls_md_init( &md_ctx ); - mbedtls_md_setup( &md_ctx, md_info, 0 ); + if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) + { + mbedtls_md_free( &md_ctx ); + return( ret ); + } - // Generate H = Hash( M' ) - // + /* Generate H = Hash( M' ) */ mbedtls_md_starts( &md_ctx ); mbedtls_md_update( &md_ctx, p, 8 ); mbedtls_md_update( &md_ctx, hash, hashlen ); mbedtls_md_update( &md_ctx, salt, slen ); mbedtls_md_finish( &md_ctx, p ); - // Compensate for boundary condition when applying mask - // + /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) offset = 1; - // maskedDB: Apply dbMask to DB - // + /* maskedDB: Apply dbMask to DB */ mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx ); mbedtls_md_free( &md_ctx ); @@ -1175,13 +1197,13 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int ret; size_t siglen; unsigned char *p; - unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; unsigned char result[MBEDTLS_MD_MAX_SIZE]; unsigned char zeros[8]; unsigned int hlen; size_t slen, msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; + unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -1205,8 +1227,7 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, if( md_alg != MBEDTLS_MD_NONE ) { - // Gather length of hash to sign - // + /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( md_info == NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -1223,12 +1244,12 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, memset( zeros, 0, 8 ); - // Note: EMSA-PSS verification is over the length of N - 1 bits - // + /* + * Note: EMSA-PSS verification is over the length of N - 1 bits + */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; - // Compensate for boundary condition when applying mask - // + /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) { p++; @@ -1238,7 +1259,11 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); mbedtls_md_init( &md_ctx ); - mbedtls_md_setup( &md_ctx, md_info, 0 ); + if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) + { + mbedtls_md_free( &md_ctx ); + return( ret ); + } mgf_mask( p, siglen - hlen - 1, p + siglen - hlen - 1, hlen, &md_ctx ); @@ -1264,8 +1289,9 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } - // Generate H = Hash( M' ) - // + /* + * Generate H = Hash( M' ) + */ mbedtls_md_starts( &md_ctx ); mbedtls_md_update( &md_ctx, zeros, 8 ); mbedtls_md_update( &md_ctx, hash, hashlen ); @@ -1320,10 +1346,10 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int ret; size_t len, siglen, asn1_len; unsigned char *p, *end; - unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; mbedtls_md_type_t msg_md_alg; const mbedtls_md_info_t *md_info; mbedtls_asn1_buf oid; + unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -1370,8 +1396,9 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, end = p + len; - // Parse the ASN.1 structure inside the PKCS#1 v1.5 structure - // + /* + * Parse the ASN.1 structure inside the PKCS#1 v1.5 structure + */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &asn1_len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_RSA_VERIFY_FAILED ); @@ -1666,7 +1693,7 @@ int mbedtls_rsa_self_test( int verbose ) #if defined(MBEDTLS_SHA1_C) if( verbose != 0 ) - mbedtls_printf( "PKCS#1 data sign : " ); + mbedtls_printf( " PKCS#1 data sign : " ); mbedtls_sha1( rsa_plaintext, PT_LEN, sha1sum ); diff --git a/external/readme.md b/external/readme.md index 696f92a..7236dcc 100644 --- a/external/readme.md +++ b/external/readme.md @@ -31,5 +31,13 @@ teleport项目用到的第三方库 https://git.libssh.org/projects/libssh.git/snapshot libssh-0.7.4.zip Windows平台使用预制的libssh-static工程进行编译。 +- libuv + https://github.com/libuv/libuv + v1.11.0.zip + 注意:teleport项目使用源代码直接编译,因此解压缩源代码到此即可。 + + + + diff --git a/server/.idea/encodings.xml b/server/.idea/encodings.xml index 2f77846..e2ddfa7 100644 --- a/server/.idea/encodings.xml +++ b/server/.idea/encodings.xml @@ -8,15 +8,22 @@ + + + + - + + + + diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 2b60b04..5733eb9 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -10,3 +10,5 @@ cmake_minimum_required(VERSION 3.5) add_subdirectory(tp_web/src) add_subdirectory(tp_core/core) add_subdirectory(tp_core/protocol/ssh) +add_subdirectory(tp_core/protocol/rdp) + diff --git a/server/share/etc/core.ini.in b/server/share/etc/core.ini.in index 5311287..38b1169 100644 --- a/server/share/etc/core.ini.in +++ b/server/share/etc/core.ini.in @@ -13,6 +13,8 @@ # LOG_LEVEL_ERROR 4 log error message only. log-level=2 +debug=0 + ; 'replay-path' define the replay file location. if not set, default location ; to $INSTDIR%/data/replay/ ;replay-path=/var/lib/teleport/data/replay @@ -32,14 +34,14 @@ bind-ip=0.0.0.0 bind-port=52189 [protocol-rdp] -enabled=false -lib=rdp +enabled=true +lib=tprdp bind-ip=0.0.0.0 bind-port=52089 [protocol-telnet] enabled=false -lib=telnet +lib=tptelnet bind-ip=0.0.0.0 bind-port=52389 diff --git a/server/tp_core/common/base_env.cpp b/server/tp_core/common/base_env.cpp index 4755eea..7c8aa92 100644 --- a/server/tp_core/common/base_env.cpp +++ b/server/tp_core/common/base_env.cpp @@ -21,10 +21,11 @@ bool TppEnvBase::init(TPP_INIT_ARGS* args) replay_path = args->replay_path; take_session = args->func_take_session; + free_session = args->func_free_session; session_begin = args->func_session_begin; session_end = args->func_session_end; - if (NULL == take_session || NULL == session_begin || NULL == session_end) + if (NULL == take_session || NULL == free_session || NULL == session_begin || NULL == session_end) { EXLOGE("invalid init args(2).\n"); return false; @@ -36,19 +37,6 @@ bool TppEnvBase::init(TPP_INIT_ARGS* args) return false; } -// ExIniSection* ps = args->cfg->GetSection(L"common"); -// if (NULL == ps) -// { -// EXLOGE("invalid config(1).\n"); -// return false; -// } -// -// if (!ps->GetStr(L"replay-path", replay_path)) -// { -// replay_path = exec_path; -// ex_path_join(replay_path, true, L"..", L"data", L"replay", NULL); -// } - if (!_on_init(args)) { EXLOGE("invalid init args(4).\n"); diff --git a/server/tp_core/common/base_env.h b/server/tp_core/common/base_env.h index 96241ac..49fa6b7 100644 --- a/server/tp_core/common/base_env.h +++ b/server/tp_core/common/base_env.h @@ -17,6 +17,7 @@ public: ex_wstr replay_path; TPP_TAKE_SESSION_FUNC take_session; + TPP_FREE_SESSION_FUNC free_session; TPP_SESSION_BEGIN_FUNC session_begin; TPP_SESSION_END_FUNC session_end; diff --git a/server/tp_core/common/base_record.cpp b/server/tp_core/common/base_record.cpp index 38ae8e3..7f974fe 100644 --- a/server/tp_core/common/base_record.cpp +++ b/server/tp_core/common/base_record.cpp @@ -5,238 +5,6 @@ #include "base_record.h" -#if 0 -base_record::base_record() -{ - //g_env.m_record_ssh_path - m_buf = new unsigned char[MAX_SIZE_PER_FILE]; - memset(m_buf, 0, MAX_SIZE_PER_FILE); - m_buf_offset = 0; - m_begin_time = 0; - m_last_time = 0; - m_file_current_index = 0; - m_current_file = 0; - m_totol_size = 0; -} - - -base_record::~base_record() -{ - if (NULL != m_buf) - { - delete[] m_buf; - m_buf = NULL; - } -} - -void base_record::begin(int record_id, int record_type) -{ - char szPath[1024] = { 0 }; - ex_astr ssh_path; - - m_begin_time = ex_get_tick_count(); - m_last_time = m_begin_time; - m_file_current_index = 0; - m_current_file = 0; - if (record_type == 2) - { - //ex_mkdirs() - -#ifdef EX_OS_WIN32 - ts_str2astr(g_env.m_record_ssh_path, ssh_path); - sprintf_s(szPath, "%s\\%d\\", ssh_path.c_str(), record_id); - int ret = _mkdir(szPath); -#else - ssh_path = g_env.m_record_ssh_path; - snprintf(szPath, 1024, "%s/%d", ssh_path.c_str(), record_id); - EXLOGV("try to create folder for record: [%s]\n", szPath); - int status = mkdir(szPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); - EXLOGV("create folder for record return %d, errno=%d.\n", status, errno); -#endif - m_current_path = szPath; - open_next_file(); - } -} -void base_record::end() -{ - ex_u64 current_time = ex_get_tick_count(); - ex_u64 internal_time = m_last_time - m_begin_time; - - save_buffer_to_file(int(internal_time)); - - if (m_buf) - { - delete[] m_buf; - m_buf = NULL; - } - if (m_current_file) - { - fclose(m_current_file); - } - - ts_replay_header header = {0}; - ex_strcpy(header.ID, 16, "teleport"); - ex_strcpy(header.version, 16, "1.0.0.1"); - header.total_time = (ex_u32)internal_time; - header.total_file_count = (ex_u8)m_file_current_index; - header.total_size = (ex_u8)m_totol_size; - int ts_replay_header_len = sizeof(ts_replay_header); - char szPath[1024] = { 0 }; -#ifdef EX_OS_WIN32 - sprintf_s(szPath, "%s\\head.init", m_current_path.c_str()); -#else - snprintf(szPath, 1024, "%s/head.init", m_current_path.c_str()); -#endif - FILE* f = NULL; - if ((f = fopen(szPath, "wb")) == NULL) /* open file TEST.$$$ */ - { - return; - } - - int ret = fwrite(&header, sizeof(ts_replay_header), 1, f); - ret = fwrite(&m_timelist[0], m_timelist.size() * sizeof(int), 1, f); - fclose(f); - - char szTermPath[1024] = { 0 }; -#ifdef EX_OS_WIN32 - sprintf_s(szTermPath, "%s\\term.init", m_current_path.c_str()); -#else - snprintf(szTermPath, 1024, "%s/term.init", m_current_path.c_str()); -#endif - - if ((f = fopen(szTermPath, "wb")) == NULL) - { - return; - } - ssh_terms_data_header terms_header = { 0 }; - ex_strcpy(terms_header.ID, 16,"teleport"); - ex_strcpy(terms_header.version, 16,"1.0.0.1"); - terms_header.term_count = (ex_u32)m_windows_size_list.size(); - ret = fwrite(&terms_header,sizeof(ssh_terms_data_header), 1, f); - if (m_windows_size_list.size() > 0) - { - ret = fwrite(&m_windows_size_list[0], m_windows_size_list.size() * sizeof(ssh_terms_data), 1, f); - } - - fclose(f); -} - -void base_record::windows_size(ssh_terms_data size_info) -{ - ex_u64 internal_time = ex_get_tick_count() - m_begin_time; - size_info.time = (ex_u32)internal_time; - m_windows_size_list.push_back(size_info); -} - -void base_record::record(unsigned char* buf, int len, int cmd) -{ - ex_u64 current_time = ex_get_tick_count(); - ex_u64 internal_time = current_time - m_begin_time; - m_last_time = current_time; - - //bool bSwitchFile = false; - //bool bWriteFile = false; - - ts_replay_data_header replay_header = {0}; - replay_header.action = (ex_u8)cmd; - replay_header.time = (ex_u32)internal_time; - replay_header.size = (ex_u32)len; - //int header_len = sizeof(ts_replay_data_header); - - bool bRet = cached_buffer(&replay_header, buf, len); - if (!bRet) - { - //ѻļջ - save_buffer_to_file(int(internal_time)); - - //¸ļ - open_next_file(); - - bRet = cached_buffer(&replay_header, buf, len); - - if (!bRet) - { - //̫󣬲ܻ棬ֱӴļ - save_to_file(ex_u32(internal_time), &replay_header, buf, len); - open_next_file(); - } - } -} - -bool base_record::cached_buffer(ts_replay_data_header* header, unsigned char* buf, int len) -{ - size_t header_len = sizeof(ts_replay_data_header); - if ((m_buf_offset + len + header_len) > MAX_SIZE_PER_FILE) - { - return false; - } - - //ȹֱӴ滺 - memcpy(m_buf + m_buf_offset, header, header_len); - m_buf_offset += header_len; - - memcpy(m_buf + m_buf_offset, buf, len); - m_buf_offset += len; - - return true; -} - -bool base_record::open_next_file() -{ - char szPath[1024] = { 0 }; -#ifdef EX_OS_WIN32 - sprintf_s(szPath, "%s\\%d.ts", m_current_path.c_str(), m_file_current_index); -#else - snprintf(szPath, 1024, "%s/%d.ts", m_current_path.c_str(), m_file_current_index); -#endif - if (NULL != m_current_file) - { - fclose(m_current_file); - } - if ((m_current_file = fopen(szPath, "wb")) == NULL) /* open file TEST.$$$ */ - { - return false; - } - - m_file_current_index++; - - return true; -} - -bool base_record::save_buffer_to_file(int internal_time) -{ - if(NULL == m_current_file) - return false; - - int ret = fwrite(m_buf, m_buf_offset, 1, m_current_file); /* дstructļ*/ - m_totol_size += m_buf_offset; - - m_buf_offset = 0; - m_timelist.push_back(ex_u32(internal_time)); - return true; -} - -bool base_record::save_to_file(int internal_time,ts_replay_data_header* header, unsigned char* buf, int len) -{ - if(NULL == m_current_file) - return false; - - int ret = fwrite(header, sizeof(ts_replay_data_header), 1, m_current_file); - ret = fwrite(buf, len, 1, m_current_file); - - m_totol_size += sizeof(ts_replay_data_header); - m_totol_size += len; - m_timelist.push_back(ex_u32(internal_time)); - return true; -} -#endif - -//==================================================== -// NEW INTERFACE -//==================================================== - - - TppRecBase::TppRecBase() { m_cache.reserve(MAX_SIZE_PER_FILE); @@ -248,7 +16,7 @@ TppRecBase::~TppRecBase() { } -void TppRecBase::begin(const wchar_t* base_path, const wchar_t* base_fname, int record_id, const TS_SESSION_INFO& info) +void TppRecBase::begin(const wchar_t* base_path, const wchar_t* base_fname, int record_id, const TPP_SESSION_INFO* info) { m_start_time = ex_get_tick_count(); diff --git a/server/tp_core/common/base_record.h b/server/tp_core/common/base_record.h index b3833b7..8306a59 100644 --- a/server/tp_core/common/base_record.h +++ b/server/tp_core/common/base_record.h @@ -8,133 +8,43 @@ #include #define MAX_SIZE_PER_FILE 4194304 // 4M = 1024*1024*4 -//#define MAX_SIZE_PER_FILE 40*1024 -// #define SSH_DATA 1 -// #define SSH_WINDOWS_SIZE 2 -#if 0 #pragma pack(push,1) -struct ts_replay_data_header +// ¼ļͷ +typedef struct TS_RECORD_HEADER { - ex_u8 action; - ex_u32 time; - ex_u32 size; - //char* buf; -}; -struct ts_replay_header + ex_u32 magic; // "TPPR" ־ TelePort Protocol Record + ex_u16 ver; // ¼ļ汾ĿǰΪ2 + ex_u16 protocol; // Э飺1=RDP, 2=SSH, 3=Telnet + ex_u64 timestamp; // ¼ʼʱ䣨UTCʱ + ex_u32 packages; // ܰ + ex_u32 time_ms; // ܺʱ룩 + ex_u16 width; // ʼĻߴ磺 + ex_u16 height; // ʼĻߴ磺 + ex_u16 file_count; // ļ + ex_u32 file_size; // ļܴСÿļͷ4ֽڵÿļС + char account[16]; // teleport˺ + char username[16]; // Զû + char ip[18]; + ex_u16 port; + + // RDPר + ex_u8 rdp_security; // 0 = RDP, 1 = TLS + + ex_u8 reserve[128 - 4 - 2 - 2 - 8 - 4 - 4 - 2 - 2 - 2 - 4 - 16 - 16 - 18 - 2 - 1]; // +}TS_RECORD_HEADER; + +// һݰͷ +typedef struct TS_RECORD_PKG { - char ID[16]; - char version[16]; - ex_u8 total_size; - ex_u8 total_file_count; - ex_u32 total_time; - //飬ÿԪصÿļIJʱ -}; -struct ssh_terms_data_header -{ - char ID[16]; - char version[16]; - ex_u32 term_count; - //飬ÿԪصÿļIJʱ -}; -struct ssh_terms_data { - //char term[16]; - ex_u32 time; - ex_u32 w; - ex_u32 h; - //ex_u32 px; - //ex_u32 py; -}; + ex_u8 type; // + ex_u32 size; // ܴСͷ + ex_u32 time_ms; // ʼʱʱ룬ζһӲܳ49죩 + ex_u8 reserve[3]; // +}TS_RECORD_PKG; + #pragma pack(pop) -typedef std::vector file_time_list; - -typedef std::vector windows_size_list; - -class base_record -{ -public: - base_record(); - ~base_record(); -public: - void begin(int record_id, int record_type); - void record(unsigned char* buf, int len, int cmd); - void windows_size(ssh_terms_data size_info); - void end(); - ex_astr get_replay_path() { - return m_current_path; - } -protected: - bool open_next_file(); - bool cached_buffer(ts_replay_data_header* header, unsigned char* buf,int len); - bool save_buffer_to_file(int internal_time); - bool save_to_file(int internal_time, ts_replay_data_header* header, unsigned char* buf, int len); -protected: - ex_u64 m_begin_time; - ex_u64 m_last_time; - - int m_file_current_index; - - ex_astr m_current_path; - FILE* m_current_file; - unsigned char* m_buf; - int m_buf_offset; - - file_time_list m_timelist; - windows_size_list m_windows_size_list; - - int m_totol_size; - //Json::Value m_ts_replay; - -}; -#endif - -//==================================================== -// NEW INTERFACE -//==================================================== - -// #define TS_RECORD_TYPE_RDP_CURSOR_POS 0x10 // λøı䣬ڻ -// #define TS_RECORD_TYPE_RDP_SERVER_PKG 0x11 // ˷صݰչʾ - -// #pragma pack(push,1) -// -// // ¼ļͷ -// typedef struct TS_RECORD_HEADER -// { -// ex_u32 magic; // "TPPR" ־ TelePort Protocol Record -// ex_u32 timestamp; // ¼ʼʱ䣨UTCʱ -// ex_u32 packages; // ܰ -// ex_u32 time_ms; // ܺʱ룩 -// ex_u16 width; // ʼĻߴ磺 -// ex_u16 height; // ʼĻߴ磺 -// ex_u8 security; // 0 = RDP, 1 = SSL -// ex_u16 file_count; // ļ -// ex_u32 file_size; // ļܴСÿļͷ4ֽڵÿļС -// char account[16]; // teleport˺ -// char username[16]; // Զû -// char ip[18]; -// ex_u16 port; -// -// ex_u8 reserve[128 - 20 - 1 - 2 - 4 - 16 - 16 - 18 - 2]; // -// }TS_RECORD_HEADER; -// -// // һݰͷ -// typedef struct TS_RECORD_PKG -// { -// ex_u8 type; // ͣĿǰʱδʹãΪ0 -// ex_u32 size; // ܴС -// ex_u32 time_ms; // ʼʱʱ룬ζһӲܳ49죩 -// ex_u8 reserve[3]; // -// }TS_RECORD_PKG; -// -// RDPƶ -// typedef struct TS_RECORD_RDP_MOUSE_POS -// { -// ex_u16 x; -// ex_u16 y; -// }TS_RECORD_RDP_MOUSE_POS; - -// #pragma pack(pop) class TppRecBase { @@ -142,13 +52,13 @@ public: TppRecBase(); virtual ~TppRecBase(); - void begin(const wchar_t* base_path, const wchar_t* base_fname, int record_id, const TS_SESSION_INFO& info); + void begin(const wchar_t* base_path, const wchar_t* base_fname, int record_id, const TPP_SESSION_INFO* info); void end(void); virtual void record(ex_u8 type, const ex_u8* data, size_t size) = 0; protected: - virtual void _on_begin(const TS_SESSION_INFO& info) = 0; + virtual void _on_begin(const TPP_SESSION_INFO* info) = 0; virtual void _on_end(void) = 0; protected: diff --git a/server/tp_core/common/protocol_interface.h b/server/tp_core/common/protocol_interface.h index 9b0608a..f47fcca 100644 --- a/server/tp_core/common/protocol_interface.h +++ b/server/tp_core/common/protocol_interface.h @@ -14,28 +14,26 @@ # define TPP_API #endif -typedef struct TS_SESSION_INFO +typedef struct TPP_SESSION_INFO { - ex_astr sid; - ex_astr account_name; // 뱾ӵû - - int auth_id; - ex_astr host_ip; + char* sid; + char* account_name; // 뱾ӵû + char* host_ip; + char* user_name; + char* user_auth; + char* user_param; int host_port; int protocol; - ex_astr user_name; - ex_astr user_auth; - ex_astr user_param; + int auth_id; int auth_mode; int sys_type; - int ref_count; // sessionԱtake_session()ٴ ex_u64 ticket_start; -}TS_SESSION_INFO; +}TPP_SESSION_INFO; - -typedef bool(*TPP_TAKE_SESSION_FUNC)(const ex_astr& sid, TS_SESSION_INFO& info); -typedef bool(*TPP_SESSION_BEGIN_FUNC)(TS_SESSION_INFO& info, int& db_id); +typedef TPP_SESSION_INFO* (*TPP_TAKE_SESSION_FUNC)(const char* sid); +typedef void(*TPP_FREE_SESSION_FUNC)(TPP_SESSION_INFO* info); +typedef bool(*TPP_SESSION_BEGIN_FUNC)(const TPP_SESSION_INFO* info, int* db_id); typedef bool(*TPP_SESSION_END_FUNC)(int db_id, int ret); @@ -48,6 +46,7 @@ typedef struct TPP_INIT_ARGS ExIniFile* cfg; TPP_TAKE_SESSION_FUNC func_take_session; + TPP_FREE_SESSION_FUNC func_free_session; TPP_SESSION_BEGIN_FUNC func_session_begin; TPP_SESSION_END_FUNC func_session_end; }TPP_INIT_ARGS; diff --git a/server/tp_core/common/ts_const.h b/server/tp_core/common/ts_const.h index daf5398..db4e21e 100644 --- a/server/tp_core/common/ts_const.h +++ b/server/tp_core/common/ts_const.h @@ -1,67 +1,68 @@ -#ifndef __TS_ERRNO_H__ -#define __TS_ERRNO_H__ - -//#include "ts_types.h" - -// #define TS_RDP_PROXY_PORT 3389 -// #define TS_RDP_PROXY_HOST "0.0.0.0" - -#define TS_SSH_PROXY_PORT 22 -#define TS_SSH_PROXY_HOST "0.0.0.0" -// -// #define TS_TELNET_PROXY_PORT 23 -// #define TS_TELNET_PROXY_HOST "0.0.0.0" - -#define TS_HTTP_RPC_PORT 52080 -//#define TS_HTTP_RPC_HOST "127.0.0.1" -#define TS_HTTP_RPC_HOST "0.0.0.0" - - -#define TS_RDP_PROTOCOL_RDP 0 -#define TS_RDP_PROTOCOL_SSL 1 -#define TS_RDP_PROTOCOL_HYBRID 2 -#define TS_RDP_PROTOCOL_HYBRID_EX 8 - -#define TS_AUTH_MODE_NONE 0 -#define TS_AUTH_MODE_PASSWORD 1 -#define TS_AUTH_MODE_PRIVATE_KEY 2 - -#define TS_PROXY_PROTOCOL_RDP 1 -#define TS_PROXY_PROTOCOL_SSH 2 -#define TS_PROXY_PROTOCOL_TELNET 3 - -//typedef ex_u32 ts_rv; - -#define TSR_OK 0x0000 -#define TSR_INVALID_DATA 0x0001 -#define TSR_SEND_ERROR 0x0002 -#define TSR_NEED_MORE_DATA 0x0005 -#define TSR_FAILED 0x0006 -#define TSR_DATA_LEN_ZERO 0x0007 - -#define TSR_MAX_CONN_REACHED 0x0010 -#define TSR_MAX_HOST_REACHED 0x0011 - -#define TSR_INVALID_REQUEST 0x1000 -#define TSR_INVALID_URI 0x1001 -#define TSR_INVALID_URL_ENCODE 0x1002 -#define TSR_NO_SUCH_METHOD 0x1003 -#define TSR_INVALID_JSON_FORMAT 0x1004 -#define TSR_INVALID_JSON_PARAM 0x1005 -#define TSR_GETAUTH_INFO_ERROR 0x1006 -#define TSR_HOST_LOCK_ERROR 0x1007 -#define TSR_ACCOUNT_LOCK_ERROR 0x1008 - -//================================================ -#define SESS_STAT_RUNNING 0 // Ựʼˣδ -#define SESS_STAT_END 9999 // Ựɹ -#define SESS_STAT_ERR_AUTH_DENIED 1 // ỰΪ֤ʧ -#define SESS_STAT_ERR_CONNECT 2 // ỰΪ޷ӵԶ -#define SESS_STAT_ERR_BAD_SSH_KEY 3 // ỰΪ޷ʶSSH˽Կ -#define SESS_STAT_ERR_INTERNAL 4 // ỰΪڲ -#define SESS_STAT_ERR_UNSUPPORT_PROTOCOL 5 // ỰΪЭ鲻֧(RDP) -#define SESS_STAT_ERR_BAD_PKG 6 // ỰΪյı -#define SESS_STAT_ERR_RESET 7 // ỰΪteleportķ - - -#endif // __TS_ERRNO_H__ +#ifndef __TS_ERRNO_H__ +#define __TS_ERRNO_H__ + +//#include "ts_types.h" + +#define TS_RDP_PROXY_PORT 3389 +#define TS_RDP_PROXY_HOST "0.0.0.0" + +#define TS_SSH_PROXY_PORT 22 +#define TS_SSH_PROXY_HOST "0.0.0.0" + +#define TS_TELNET_PROXY_PORT 23 +#define TS_TELNET_PROXY_HOST "0.0.0.0" + +#define TS_HTTP_RPC_PORT 52080 +#define TS_HTTP_RPC_HOST "127.0.0.1" +//#define TS_HTTP_RPC_HOST "0.0.0.0" + + +#define TS_RDP_PROTOCOL_RDP 0 +#define TS_RDP_PROTOCOL_TLS 1 +#define TS_RDP_PROTOCOL_HYBRID 2 +#define TS_RDP_PROTOCOL_RDSTLS 4 +#define TS_RDP_PROTOCOL_HYBRID_EX 8 + +#define TS_AUTH_MODE_NONE 0 +#define TS_AUTH_MODE_PASSWORD 1 +#define TS_AUTH_MODE_PRIVATE_KEY 2 + +#define TS_PROXY_PROTOCOL_RDP 1 +#define TS_PROXY_PROTOCOL_SSH 2 +#define TS_PROXY_PROTOCOL_TELNET 3 + +//typedef ex_u32 ts_rv; + +#define TSR_OK 0x0000 +#define TSR_INVALID_DATA 0x0001 +#define TSR_SEND_ERROR 0x0002 +#define TSR_NEED_MORE_DATA 0x0005 +#define TSR_FAILED 0x0006 +#define TSR_DATA_LEN_ZERO 0x0007 + +#define TSR_MAX_CONN_REACHED 0x0010 +#define TSR_MAX_HOST_REACHED 0x0011 + +#define TSR_INVALID_REQUEST 0x1000 +#define TSR_INVALID_URI 0x1001 +#define TSR_INVALID_URL_ENCODE 0x1002 +#define TSR_NO_SUCH_METHOD 0x1003 +#define TSR_INVALID_JSON_FORMAT 0x1004 +#define TSR_INVALID_JSON_PARAM 0x1005 +#define TSR_GETAUTH_INFO_ERROR 0x1006 +#define TSR_HOST_LOCK_ERROR 0x1007 +#define TSR_ACCOUNT_LOCK_ERROR 0x1008 + +//================================================ +#define SESS_STAT_RUNNING 0 // Ựʼˣδ +#define SESS_STAT_END 9999 // Ựɹ +#define SESS_STAT_ERR_AUTH_DENIED 1 // ỰΪ֤ʧ +#define SESS_STAT_ERR_CONNECT 2 // ỰΪ޷ӵԶ +#define SESS_STAT_ERR_BAD_SSH_KEY 3 // ỰΪ޷ʶSSH˽Կ +#define SESS_STAT_ERR_INTERNAL 4 // ỰΪڲ +#define SESS_STAT_ERR_UNSUPPORT_PROTOCOL 5 // ỰΪЭ鲻֧(RDP) +#define SESS_STAT_ERR_BAD_PKG 6 // ỰΪյı +#define SESS_STAT_ERR_RESET 7 // ỰΪteleportķ + + +#endif // __TS_ERRNO_H__ diff --git a/server/tp_core/common/ts_membuf.cpp b/server/tp_core/common/ts_membuf.cpp index 13a3b79..c5f063f 100644 --- a/server/tp_core/common/ts_membuf.cpp +++ b/server/tp_core/common/ts_membuf.cpp @@ -1,8 +1,12 @@ #include "ts_membuf.h" #include -MemBuffer::MemBuffer() : m_buffer(NULL), m_data_size(0), m_buffer_size(0) +MemBuffer::MemBuffer()// : m_buffer(NULL), m_data_size(0), m_buffer_size(0) { + m_buffer = NULL; + m_data_size = 0; + m_buffer_size = 0; + //EXLOGI("[mbuf:%p] create new instance.\n", this); } MemBuffer::~MemBuffer() @@ -16,16 +20,19 @@ MemBuffer::~MemBuffer() m_buffer_size = 0; //TSLOGD("[mbuf] #%d destroied with buffer-size: %d, data-size: %d.\n", m_index, m_buffer_size, m_data_size); + //EXLOGI("[mbuf:%p] destroy instance\n", this); } void MemBuffer::append(const ex_u8* data, size_t size) { + //EXLOGD("[mbuf:%p] call reserve() in append()\n", this); reserve(m_data_size + size); // TODO: should return boolean. if(NULL == m_buffer) return; + //EXLOGD("[mbuf:%p] append(): buffer: %p, m_buf_size: %d, m_data_size: %d, data: %p, size: %d\n", this, m_buffer, m_buffer_size, m_data_size, data, size); memcpy(m_buffer+m_data_size, data, size); m_data_size += size; } @@ -33,26 +40,42 @@ void MemBuffer::append(const ex_u8* data, size_t size) void MemBuffer::reserve(size_t size) { if (size <= m_buffer_size) + { + //EXLOGD("[mbuf:%p] reserve(1): m_buf: %p, m_buf_size: %d, need size: %d, skip.\n", this, m_buffer, m_buffer_size, size); return; + } // µĻСȡ MEMBUF_BLOCK_SIZE - int new_size = (size + MEMBUF_BLOCK_SIZE - 1) & ~(MEMBUF_BLOCK_SIZE - 1); + size_t new_size = (size + MEMBUF_BLOCK_SIZE - 1) & ~(MEMBUF_BLOCK_SIZE - 1); + //EXLOGD("[mbuf:%p] reserve(2): m_buf: %p, m_buf_size: %d, size: %d, new size: %d.\n", this, m_buffer, m_buffer_size, size, new_size); if (NULL == m_buffer) + { + //EXLOGD("[mbuf:%p] calloc(%d).\n", this, new_size); m_buffer = (ex_u8*)calloc(1, new_size); + } else + { + //EXLOGD("[mbuf:%p] realloc(%d).\n", this, new_size); m_buffer = (ex_u8*)realloc(m_buffer, new_size); + } m_buffer_size = new_size; // TODO: reserve() should return boolean. if(NULL == m_buffer) { + //EXLOGD("[mbuf:%p] ----- m_buffer == NULL.\n", this); m_buffer_size = 0; m_data_size = 0; } + //else + //{ + //EXLOGD("[mbuf:%p] m_buffer == %p.\n", this, m_buffer); + //} //TSLOGD("[mbuf] reserve(): #%d, buffer-size: %d, data-size: %d\n", m_index, m_buffer_size, m_data_size); + //EXLOGD("[mbuf:%p] reserve(3): m_buf: %p, buffer-size: %d, data-size: %d\n", this, m_buffer, m_buffer_size, m_data_size); } void MemBuffer::concat(const MemBuffer& m) diff --git a/server/tp_core/common/ts_memstream.cpp b/server/tp_core/common/ts_memstream.cpp new file mode 100644 index 0000000..3b41e2b --- /dev/null +++ b/server/tp_core/common/ts_memstream.cpp @@ -0,0 +1,219 @@ +#include "ts_memstream.h" + +MemStream::MemStream(MemBuffer& mbuf) : m_mbuf(mbuf) +{ + m_offset = 0; +} + +MemStream::~MemStream() +{} + +void MemStream::reset(void) +{ + m_mbuf.empty(); + rewind(); +} + + +bool MemStream::seek(size_t offset) +{ + if (offset >= m_mbuf.size()) + return false; + + m_offset = offset; + return true; +} + +bool MemStream::skip(size_t n) +{ + if (m_offset + n >= m_mbuf.size()) + return false; + m_offset += n; + return true; +} + +bool MemStream::rewind(size_t n) +{ + if (m_offset < n) + return false; + + if (0 == n) + m_offset = 0; + else + m_offset -= n; + return true; +} + +ex_u8 MemStream::get_u8(void) +{ + ASSERT(m_offset + 1 <= m_mbuf.size()); + + ex_u8 v = (m_mbuf.data() + m_offset)[0]; + m_offset++; + return v; +} + +ex_u16 MemStream::get_u16_le(void) +{ + ASSERT(m_offset + 2 <= m_mbuf.size()); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ex_u16 v = (ex_u16)(p[0] | (p[1] << 8)); +#else + ex_u16 v = ((ex_u16*)p)[0]; +#endif + m_offset += 2; + return v; +} + +ex_u16 MemStream::get_u16_be(void) +{ + ASSERT(m_offset + 2 <= m_mbuf.size()); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ex_u16 v = ((ex_u16*)p)[0]; +#else + ex_u16 v = (ex_u16)((p[0] << 8) | p[1]); +#endif + m_offset += 2; + return v; +} + + +ex_u32 MemStream::get_u32_le(void) +{ + ASSERT(m_offset + 4 <= m_mbuf.size()); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ex_u32 v = (ex_u32)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)); +#else + ex_u32 v = ((ex_u32*)p)[0]; +#endif + m_offset += 4; + return v; +} + +ex_u32 MemStream::get_u32_be(void) +{ + ASSERT(m_offset + 4 <= m_mbuf.size()); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ex_u32 v = ((ex_u32*)p)[0]; +#else + ex_u32 v = (ex_u32)((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); +#endif + m_offset += 4; + return v; +} + +ex_u8* MemStream::get_bin(size_t n) +{ + ASSERT(m_offset + 4 <= m_mbuf.size()); + ex_u8* p = m_mbuf.data() + m_offset; + m_offset += n; + return p; +} + + +void MemStream::put_zero(size_t n) +{ + m_mbuf.reserve(m_mbuf.size() + n); + memset(m_mbuf.data() + m_offset, 0, n); + m_offset += n; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_u8(ex_u8 v) +{ + m_mbuf.reserve(m_mbuf.size() + 1); + + (m_mbuf.data() + m_offset)[0] = v; + m_offset++; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_u16_le(ex_u16 v) +{ + m_mbuf.reserve(m_mbuf.size() + 2); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + p[0] = (ex_u8)v; + p[1] = (ex_u8)(v >> 8); +#else + ((ex_u16*)p)[0] = v; +#endif + m_offset += 2; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_u16_be(ex_u16 v) +{ + m_mbuf.reserve(m_mbuf.size() + 2); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ((ex_u16*)p)[0] = v; +#else + ex_u8* _v = (ex_u8*)&v; + p[0] = _v[1]; + p[1] = _v[0]; +#endif + m_offset += 2; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_u32_le(ex_u32 v) +{ + m_mbuf.reserve(m_mbuf.size() + 4); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + p[0] = (ex_u8)v; + p[1] = (ex_u8)(v >> 8); + p[2] = (ex_u8)(v >> 16); + p[3] = (ex_u8)(v >> 24); +#else + ((ex_u32*)p)[0] = v; +#endif + m_offset += 4; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_u32_be(ex_u32 v) +{ + m_mbuf.reserve(m_mbuf.size() + 4); + + ex_u8* p = m_mbuf.data() + m_offset; +#if defined(B_ENDIAN) + ((ex_u32*)p)[0] = v; +#else + ex_u8* _v = (ex_u8*)&v; + p[0] = _v[3]; + p[1] = _v[2]; + p[2] = _v[1]; + p[3] = _v[0]; +#endif + m_offset += 4; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + +void MemStream::put_bin(const ex_u8* p, size_t n) +{ + m_mbuf.reserve(m_mbuf.size() + n); + memcpy(m_mbuf.data() + m_offset, p, n); + m_offset += n; + if (m_mbuf.size() < m_offset) + m_mbuf.size(m_offset); +} + diff --git a/server/tp_core/common/ts_memstream.h b/server/tp_core/common/ts_memstream.h new file mode 100644 index 0000000..9ab425c --- /dev/null +++ b/server/tp_core/common/ts_memstream.h @@ -0,0 +1,45 @@ +#ifndef __TS_MEMSTREAM_H__ +#define __TS_MEMSTREAM_H__ + +#include "ts_membuf.h" + +class MemStream +{ +public: + MemStream(MemBuffer& mbuf); + ~MemStream(); + + void reset(void); // ջݣͷڴ棩ָƶͷ + + bool seek(size_t offset); // ƶָ뵽ָƫƣԽ磬򷵻ش + bool rewind(size_t n = 0); // nֽڣԽ磬شnΪ0˵ʼ + bool skip(size_t n); // nֽڣԽ磬򷵻ش + + ex_u8* ptr(void) { return m_mbuf.data() + m_offset; } // صǰָ + size_t offset(void) { return m_offset; } // صǰָʼƫ + + size_t left(void) { return m_mbuf.size() - m_offset; } // ʣݵĴСӵǰָ뵽β + + ex_u8 get_u8(void); + ex_u16 get_u16_le(void); + ex_u16 get_u16_be(void); + ex_u32 get_u32_le(void); + ex_u32 get_u32_be(void); + ex_u8* get_bin(size_t n); // صǰָݵָ룬ڲƫƻƶnֽ + + void put_zero(size_t n); // nֽڵ0 + void put_u8(ex_u8 v); + void put_u16_le(ex_u16 v); + void put_u16_be(ex_u16 v); + void put_u32_le(ex_u32 v); + void put_u32_be(ex_u32 v); + void put_bin(const ex_u8* p, size_t n); // pָnֽ + + size_t size(void) { return m_mbuf.size(); } + +private: + MemBuffer& m_mbuf; + size_t m_offset; +}; + +#endif // __TS_MEMSTREAM_H__ diff --git a/server/tp_core/core/tp_core.rc b/server/tp_core/core/tp_core.rc index 263f296..9cd0fbc 100644 Binary files a/server/tp_core/core/tp_core.rc and b/server/tp_core/core/tp_core.rc differ diff --git a/server/tp_core/core/tp_core.vs2015.vcxproj b/server/tp_core/core/tp_core.vs2015.vcxproj index 0a42984..08568d1 100644 --- a/server/tp_core/core/tp_core.vs2015.vcxproj +++ b/server/tp_core/core/tp_core.vs2015.vcxproj @@ -1,229 +1,229 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {6548CB1D-A7BA-4A68-9B3F-A5129F77868B} - Win32Proj - tp_core - 8.1 - tp_core - - - - Application - true - v140_xp - Unicode - - - Application - false - v140_xp - true - Unicode - - - Application - true - v140 - Unicode - - - Application - false - v140 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - ..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ - ..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - D:\apps\vld\include;$(IncludePath) - D:\apps\vld\lib\Win32;$(LibraryPath) - - - true - ..\..\out\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - false - ..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ - ..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - false - ..\..\out\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) - true - ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose - MultiThreadedDebug - - - Console - - - libcmt.lib - Debug - - - - - - - Level3 - Disabled - _DEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - ../../external/windows/libuv/include;../../external/windows/openssl/include;../../external/windows/zlib/include;../../external/windows/mbedtls/include;../../external/windows/libssh/include;../../external/common/jsoncpp/include;../../external/common/sqlite;d:/apps/vld/include - - - Windows - true - ../../external/windows/openssl/lib;../../external/windows/zlib/lib;../../external/windows/libssh/lib - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) - true - ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose - MultiThreaded - - - Console - true - true - - - - - - - Level3 - - - MaxSpeed - true - true - NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - true - ../../external/windows/libuv/include;../../external/windows/openssl/include;../../external/windows/zlib/include;../../external/windows/mbedtls/include;../../external/windows/libssh/include;../../external/common/jsoncpp/include;../../external/common/sqlite - - - Windows - true - true - true - ../../external/windows/openssl/lib;../../external/windows/zlib/lib;../../external/windows/libssh/lib - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {6548CB1D-A7BA-4A68-9B3F-A5129F77868B} + Win32Proj + tp_core + 8.1 + tp_core + + + + Application + true + v140_xp + Unicode + + + Application + false + v140_xp + true + Unicode + + + Application + true + v140 + Unicode + + + Application + false + v140 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + ..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ + ..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files %28x86%29\Visual Leak Detector\lib\Win32;$(LibraryPath) + + + true + ..\..\out\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + false + ..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ + ..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + false + ..\..\out\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + ..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) + true + ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose + MultiThreadedDebug + + + Console + + + libcmt.lib + Debug + + + + + + + Level3 + Disabled + _DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + ../../external/windows/libuv/include;../../external/windows/openssl/include;../../external/windows/zlib/include;../../external/windows/mbedtls/include;../../external/windows/libssh/include;../../external/common/jsoncpp/include;../../external/common/sqlite;d:/apps/vld/include + + + Windows + true + ../../external/windows/openssl/lib;../../external/windows/zlib/lib;../../external/windows/libssh/lib + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) + true + ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose + MultiThreaded + + + Console + true + true + + + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + ../../external/windows/libuv/include;../../external/windows/openssl/include;../../external/windows/zlib/include;../../external/windows/mbedtls/include;../../external/windows/libssh/include;../../external/common/jsoncpp/include;../../external/common/sqlite + + + Windows + true + true + true + ../../external/windows/openssl/lib;../../external/windows/zlib/lib;../../external/windows/libssh/lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/server/tp_core/core/ts_env.cpp b/server/tp_core/core/ts_env.cpp index 78b79b9..51b976c 100644 --- a/server/tp_core/core/ts_env.cpp +++ b/server/tp_core/core/ts_env.cpp @@ -63,11 +63,13 @@ bool TsEnv::init(bool load_config) #else m_etc_path = L"/etc/teleport"; conf_file = L"/etc/teleport/core.ini"; - m_replay_path = L"/var/lib/teleport/data/replay"; + m_replay_path = L"/var/lib/teleport/replay"; log_path = L"/var/log/teleport"; #endif } + //EXLOGW(L"[core] load config file: %ls.\n", conf_file.c_str()); + if (!m_ini.LoadFromFile(conf_file)) { EXLOGE(L"[core] can not load %ls.\n", conf_file.c_str()); @@ -109,6 +111,11 @@ bool TsEnv::init(bool load_config) EXLOG_LEVEL(log_level); } + int debug_mode = 0; + ps->GetInt(L"debug", debug_mode, 0); + if (debug_mode == 1) + EXLOG_DEBUG(true); + ex_wstr tmp; ps = m_ini.GetSection(L"rpc"); if (!ps->GetStr(L"bind-ip", tmp)) diff --git a/server/tp_core/core/ts_main.cpp b/server/tp_core/core/ts_main.cpp index ba8436d..db58208 100644 --- a/server/tp_core/core/ts_main.cpp +++ b/server/tp_core/core/ts_main.cpp @@ -9,14 +9,74 @@ bool g_exit_flag = false; -bool tpp_take_session(const ex_astr& sid, TS_SESSION_INFO& info) +TPP_SESSION_INFO* tpp_take_session(const char* sid) { - return g_session_mgr.take_session(sid, info); + TS_SESSION_INFO sinfo; + bool ret = g_session_mgr.take_session(sid, sinfo); + if (!ret) + return NULL; + + TPP_SESSION_INFO* info = (TPP_SESSION_INFO*)calloc(1, sizeof(TPP_SESSION_INFO)); + + info->sid = (char*)calloc(1, sinfo.sid.length() + 1); + ex_strcpy(info->sid, sinfo.sid.length() + 1, sinfo.sid.c_str()); + info->account_name = (char*)calloc(1, sinfo.account_name.length() + 1); + ex_strcpy(info->account_name, sinfo.account_name.length() + 1, sinfo.account_name.c_str()); + info->host_ip = (char*)calloc(1, sinfo.host_ip.length() + 1); + ex_strcpy(info->host_ip, sinfo.host_ip.length() + 1, sinfo.host_ip.c_str()); + info->user_name = (char*)calloc(1, sinfo.user_name.length() + 1); + ex_strcpy(info->user_name, sinfo.user_name.length() + 1, sinfo.user_name.c_str()); + info->user_auth = (char*)calloc(1, sinfo.user_auth.length() + 1); + ex_strcpy(info->user_auth, sinfo.user_auth.length() + 1, sinfo.user_auth.c_str()); + info->user_param = (char*)calloc(1, sinfo.user_param.length() + 1); + ex_strcpy(info->user_param, sinfo.user_param.length() + 1, sinfo.user_param.c_str()); + + info->auth_id = sinfo.auth_id; + info->host_port = sinfo.host_port; + info->protocol = sinfo.protocol; + info->auth_mode = sinfo.auth_mode; + info->sys_type = sinfo.sys_type; + info->ref_count = sinfo.ref_count; + info->ticket_start = sinfo.ticket_start; + + return info; } -bool tpp_session_begin(TS_SESSION_INFO& info, int& db_id) +void tpp_free_session(TPP_SESSION_INFO* info) { - return ts_web_rpc_session_begin(info, db_id); + if (NULL == info) + return; + + free(info->sid); + free(info->account_name); + free(info->host_ip); + free(info->user_name); + free(info->user_auth); + free(info->user_param); + free(info); +} + +bool tpp_session_begin(const TPP_SESSION_INFO* info, int* db_id) +{ + if (NULL == info || NULL == db_id) + return false; + + TS_SESSION_INFO sinfo; + sinfo.sid = info->sid; + sinfo.account_name = info->account_name; + sinfo.auth_id = info->auth_id; + sinfo.host_ip = info->host_ip; + sinfo.host_port = info->host_port; + sinfo.protocol = info->protocol; + sinfo.user_name = info->user_name; + sinfo.user_auth = info->user_auth; + sinfo.user_param = info->user_param; + sinfo.auth_mode = info->auth_mode; + sinfo.sys_type = info->sys_type; + sinfo.ref_count = info->ref_count; + sinfo.ticket_start = info->ticket_start; + + return ts_web_rpc_session_begin(sinfo, *db_id); } bool tpp_session_end(int db_id, int ret) @@ -88,7 +148,7 @@ bool TppManager::load_tpp(const ex_wstr& libname) ex_path_join(libfile, false, filename.c_str(), NULL); EXLOGV(L"[core] load protocol lib: %ls\n", libfile.c_str()); - TPP_LIB* lib = new TPP_LIB; + TPP_LIB* lib = new TPP_LIB; lib->dylib = ex_dlopen(libfile.c_str()); if (NULL == lib->dylib) @@ -122,6 +182,7 @@ bool TppManager::load_tpp(const ex_wstr& libname) init_args.replay_path = g_env.m_replay_path; init_args.cfg = &g_env.get_ini(); init_args.func_take_session = tpp_take_session; + init_args.func_free_session = tpp_free_session; init_args.func_session_begin = tpp_session_begin; init_args.func_session_end = tpp_session_end; @@ -153,11 +214,13 @@ void TppManager::stop_all(void) int ts_main(void) { - EXLOGI("\n"); - EXLOGI("###############################################################\n"); - EXLOGI("Teleport Core Server starting ...\n"); - ExIniFile& ini = g_env.get_ini(); + + EXLOGI(L"\n"); + EXLOGI(L"###############################################################\n"); + EXLOGI(L"Load config file: %ls.\n", ini.get_filename().c_str()); + EXLOGI(L"Teleport Core Server starting ...\n"); + ex_ini_sections& secs = ini.GetAllSections(); TsHttpRpc rpc; @@ -167,14 +230,14 @@ int ts_main(void) do { if (!g_session_mgr.start()) { - EXLOGE("[core] failed to start session-id manager.\n"); + EXLOGE(L"[core] failed to start session-id manager.\n"); all_ok = false; break; } if (!rpc.init() || !rpc.start()) { - EXLOGE("[core] rpc init/start failed.\n"); + EXLOGE(L"[core] rpc init/start failed.\n"); all_ok = false; break; } diff --git a/server/tp_core/core/ts_session.cpp b/server/tp_core/core/ts_session.cpp index ac41cf4..9fdf380 100644 --- a/server/tp_core/core/ts_session.cpp +++ b/server/tp_core/core/ts_session.cpp @@ -113,16 +113,19 @@ bool TsSessionManager::take_session(const ex_astr& sid, TS_SESSION_INFO& info) return false; info.sid = it->second->sid; + info.account_name = it->second->account_name; info.auth_id = it->second->auth_id; info.host_ip = it->second->host_ip; info.host_port = it->second->host_port; info.protocol = it->second->protocol; - info.account_name = it->second->account_name; - info.sys_type = it->second->sys_type; info.user_name = it->second->user_name; - info.user_param = it->second->user_param; + info.user_auth = it->second->user_auth; + + info.user_param = it->second->user_param; info.auth_mode = it->second->auth_mode; + info.sys_type = it->second->sys_type; + info.ref_count = it->second->ref_count; info.ticket_start = it->second->ticket_start; it->second->ref_count--; @@ -145,7 +148,7 @@ bool TsSessionManager::_add_session(ex_astr& sid, TS_SESSION_INFO* info) for (;;) { _gen_session_id(_sid, info, 6); - it = m_sessions.find(sid); + it = m_sessions.find(_sid); if (it == m_sessions.end()) break; diff --git a/server/tp_core/core/ts_session.h b/server/tp_core/core/ts_session.h index 68f13b2..76d3dc6 100644 --- a/server/tp_core/core/ts_session.h +++ b/server/tp_core/core/ts_session.h @@ -6,6 +6,25 @@ #include +typedef struct TS_SESSION_INFO +{ + ex_astr sid; + ex_astr account_name; // 뱾ӵû + + int auth_id; + ex_astr host_ip; + int host_port; + int protocol; + ex_astr user_name; + ex_astr user_auth; + ex_astr user_param; + int auth_mode; + int sys_type; + + int ref_count; // sessionԱtake_session()ٴ + ex_u64 ticket_start; +}TS_SESSION_INFO; + typedef std::map ts_sessiones; class TsSessionManager : public ExThreadBase diff --git a/server/tp_core/core/ts_ver.h b/server/tp_core/core/ts_ver.h index 834c7c4..afb273e 100644 --- a/server/tp_core/core/ts_ver.h +++ b/server/tp_core/core/ts_ver.h @@ -1,6 +1,6 @@ #ifndef __TS_SERVER_VER_H__ #define __TS_SERVER_VER_H__ -#define TP_SERVER_VER L"2.1.2.1" +#define TP_SERVER_VER L"2.2.5.1" #endif // __TS_SERVER_VER_H__ diff --git a/server/tp_core/protocol/ssh/CMakeLists.txt b/server/tp_core/protocol/ssh/CMakeLists.txt index b0e8604..1ffc4de 100644 --- a/server/tp_core/protocol/ssh/CMakeLists.txt +++ b/server/tp_core/protocol/ssh/CMakeLists.txt @@ -7,22 +7,19 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${Project_SOURCE_DIR}/../out/server/x64/bin") -aux_source_directory(. DIR_SRCS) -aux_source_directory(../../common DIR_SRCS) -aux_source_directory(../../../../common/libex/src DIR_SRCS) -aux_source_directory(../../../../external/jsoncpp/src/lib_json DIR_SRCS) +aux_source_directory(. DIR_SSH_SRCS) +aux_source_directory(../../common DIR_SSH_SRCS) +aux_source_directory(../../../../common/libex/src DIR_SSH_SRCS) -list(REMOVE_ITEM DIR_SRCS "./dllmain.cpp") -list(REMOVE_ITEM DIR_SRCS "./stdafx.cpp") +list(REMOVE_ITEM DIR_SSH_SRCS "./dllmain.cpp") +list(REMOVE_ITEM DIR_SSH_SRCS "./stdafx.cpp") include_directories( ../../../../common/libex/include - ../../../../external/jsoncpp/include ../../../../external/linux/release/include ) link_directories(../../../../external/linux/release/lib) -add_library(tpssh SHARED ${DIR_SRCS}) +add_library(tpssh SHARED ${DIR_SSH_SRCS}) target_link_libraries(tpssh ssh ssl crypto mbedx509 mbedtls mbedcrypto dl pthread rt util) -#target_link_libraries(tpssh ssh mbedx509 mbedtls mbedcrypto dl pthread rt util) diff --git a/server/tp_core/protocol/ssh/ssh_proxy.cpp b/server/tp_core/protocol/ssh/ssh_proxy.cpp index 04a248c..9b579cf 100644 --- a/server/tp_core/protocol/ssh/ssh_proxy.cpp +++ b/server/tp_core/protocol/ssh/ssh_proxy.cpp @@ -1,255 +1,255 @@ -#include "ssh_proxy.h" -#include "tpp_env.h" - -SshProxy g_ssh_proxy; - -SshProxy::SshProxy() : - ExThreadBase("ssh-proxy-thread"), - m_bind(NULL) -{ -} - -SshProxy::~SshProxy() -{ - if (NULL != m_bind) - ssh_bind_free(m_bind); - - ssh_finalize(); - - ts_sftp_sessions::iterator it = m_sftp_sessions.begin(); - for (; it != m_sftp_sessions.end(); ++it) - { - delete it->second; - } - m_sftp_sessions.clear(); -} - -bool SshProxy::init(void) -{ - m_host_ip = g_ssh_env.bind_ip; - m_host_port = g_ssh_env.bind_port; - - - m_bind = ssh_bind_new(); - if (NULL == m_bind) - { - EXLOGE("[ssh] can not create bind.\n"); - return false; - } - - if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_BINDADDR, m_host_ip.c_str())) - { - EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_BINDADDR.\n"); - return false; - } - if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_BINDPORT, &m_host_port)) - { - EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_BINDPORT.\n"); - return false; - } - - ex_wstr _key_file = g_ssh_env.etc_path; - ex_path_join(_key_file, false, L"tp_ssh_server.key", NULL); - ex_astr key_file; - ex_wstr2astr(_key_file, key_file); - - EXLOGV("[ssh] try to load ssh-server-key: %s\n", key_file.c_str()); - if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_RSAKEY, key_file.c_str())) - { - EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_RSAKEY.\n"); - return false; - } - - if (ssh_bind_listen(m_bind) < 0) - { - EXLOGE("[ssh] listening to socket: %s\n", ssh_get_error(m_bind)); - return false; - } - - return true; -} - -void SshProxy::_thread_loop(void) -{ - EXLOGV("[ssh] TeleportServer-SSH ready on %s:%d\n", m_host_ip.c_str(), m_host_port); - _run(); - EXLOGV("[ssh] main-loop end.\n"); -} - -void SshProxy::_set_stop_flag(void) -{ - m_stop_flag = true; - - if (m_is_running) - { - // һͨķʽеļһ - ex_astr host_ip = m_host_ip; - if (host_ip == "0.0.0.0") - host_ip = "127.0.0.1"; - - ssh_session _session = ssh_new(); - ssh_options_set(_session, SSH_OPTIONS_HOST, host_ip.c_str()); - ssh_options_set(_session, SSH_OPTIONS_PORT, &m_host_port); - - int _timeout_us = 100000; - ssh_options_set(_session, SSH_OPTIONS_TIMEOUT_USEC, &_timeout_us); - ssh_connect(_session); - ssh_free(_session); - } - - m_thread_mgr.stop_all(); -} - -void SshProxy::_run(void) -{ - for (;;) - { - // ע⣬ssh_new()ָ룬ֹͣ־ڲͷˣָ뽻SshSessionʵʱͷš - ssh_session sess_to_client = ssh_new(); - - struct sockaddr_storage sock_client; - char ip[32] = { 0 }; - int len = sizeof(ip); - - if (ssh_bind_accept(m_bind, sess_to_client) != SSH_OK) - { - EXLOGE("[ssh] accepting a connection failed: %s.\n", ssh_get_error(m_bind)); - continue; - } - EXLOGD("[ssh] ssh_bind_accept() returned...\n"); - - if (m_stop_flag) - { - ssh_free(sess_to_client); - break; - } - - SshSession* sess = new SshSession(this, sess_to_client); - -#ifdef EX_OS_WIN32 - getpeername(ssh_get_fd(sess_to_client), (struct sockaddr*)&sock_client, &len); -#else - getpeername(ssh_get_fd(sess_to_client), (struct sockaddr*)&sock_client, (unsigned int*)&len); -#endif - sockaddr_in* addrin = (sockaddr_in*)&sock_client; - - if (0 == ex_ip4_name(addrin, ip, sizeof(ip))) - { - sess->client_ip(ip); - sess->client_port(addrin->sin_port); - } - - - EXLOGV("[ssh] ------ NEW SSH CLIENT [%s:%d] ------\n", sess->client_ip(), sess->client_port()); - - - { - ExThreadSmartLock locker(m_lock); - m_sessions.insert(std::make_pair(sess, 0)); - } - - sess->start(); - } - - // ȴй߳˳ - m_thread_mgr.stop_all(); -} - -void SshProxy::_dump_sftp_sessions(void) -{ - ts_sftp_sessions::iterator it = m_sftp_sessions.begin(); - for (; it != m_sftp_sessions.end(); ++it) - { - EXLOGD("ssh-proxy session: sid: %s\n", it->first.c_str()); - } -} - -void SshProxy::add_sftp_session_info(const ex_astr& sid, const ex_astr& host_ip, int host_port, const ex_astr& user_name, const ex_astr& user_auth, int auth_mode) -{ - ExThreadSmartLock locker(m_lock); - EXLOGD("[ssh] add sftp session-id: %s\n", sid.c_str()); - ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); - if (it != m_sftp_sessions.end()) - { - EXLOGD("[ssh] sftp-session-id '%s' already exists.\n", sid.c_str()); - it->second->ref_count++; - return; - } - - TS_SFTP_SESSION_INFO* info = new TS_SFTP_SESSION_INFO; - info->host_ip = host_ip; - info->host_port = host_port; - info->user_name = user_name; - info->user_auth = user_auth; - info->auth_mode = auth_mode; - info->ref_count = 1; - - if (!m_sftp_sessions.insert(std::make_pair(sid, info)).second) - { - EXLOGE("[ssh] ssh-proxy can not insert a sftp-session-id.\n"); - } - - _dump_sftp_sessions(); -} - -bool SshProxy::get_sftp_session_info(const ex_astr& sid, TS_SFTP_SESSION_INFO& info) -{ - ExThreadSmartLock locker(m_lock); - EXLOGD("[ssh] try to get info by sftp session-id: %s\n", sid.c_str()); - - _dump_sftp_sessions(); - - ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); - if (it == m_sftp_sessions.end()) - { - EXLOGD("sftp-session '%s' not exists.\n", sid.c_str()); - return false; - } - - info.host_ip = it->second->host_ip; - info.host_port = it->second->host_port; - info.user_name = it->second->user_name; - info.user_auth = it->second->user_auth; - info.auth_mode = it->second->auth_mode; - info.ref_count = it->second->ref_count; - - return true; -} - -void SshProxy::remove_sftp_sid(const ex_astr& sid) -{ - EXLOGD("[ssh] try to remove sftp session-id: %s\n", sid.c_str()); - - ExThreadSmartLock locker(m_lock); - ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); - if (it == m_sftp_sessions.end()) - { - EXLOGE("[ssh] ssh-proxy when remove sftp sid, it not in charge.\n"); - return; - } - - it->second->ref_count--; - if (it->second->ref_count <= 0) - { - delete it->second; - m_sftp_sessions.erase(it); - EXLOGD("[ssh] sftp session-id '%s' removed.\n", sid.c_str()); - } -} - -void SshProxy::session_finished(SshSession* sess) -{ - ExThreadSmartLock locker(m_lock); - ts_ssh_sessions::iterator it = m_sessions.find(sess); - if (it != m_sessions.end()) - { - m_sessions.erase(it); - EXLOGV("[ssh] client %s:%d session removed.\n", sess->client_ip(), sess->client_port()); - } - else - { - EXLOGW("[ssh] when session %s:%d end, it not in charge.\n", sess->client_ip(), sess->client_port()); - } - - delete sess; -} +#include "ssh_proxy.h" +#include "tpp_env.h" + +SshProxy g_ssh_proxy; + +SshProxy::SshProxy() : + ExThreadBase("ssh-proxy-thread"), + m_bind(NULL) +{ +} + +SshProxy::~SshProxy() +{ + if (NULL != m_bind) + ssh_bind_free(m_bind); + + ssh_finalize(); + + ts_sftp_sessions::iterator it = m_sftp_sessions.begin(); + for (; it != m_sftp_sessions.end(); ++it) + { + delete it->second; + } + m_sftp_sessions.clear(); +} + +bool SshProxy::init(void) +{ + m_host_ip = g_ssh_env.bind_ip; + m_host_port = g_ssh_env.bind_port; + + + m_bind = ssh_bind_new(); + if (NULL == m_bind) + { + EXLOGE("[ssh] can not create bind.\n"); + return false; + } + + if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_BINDADDR, m_host_ip.c_str())) + { + EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_BINDADDR.\n"); + return false; + } + if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_BINDPORT, &m_host_port)) + { + EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_BINDPORT.\n"); + return false; + } + + ex_wstr _key_file = g_ssh_env.etc_path; + ex_path_join(_key_file, false, L"tp_ssh_server.key", NULL); + ex_astr key_file; + ex_wstr2astr(_key_file, key_file); + + EXLOGV("[ssh] try to load ssh-server-key: %s\n", key_file.c_str()); + if (SSH_OK != ssh_bind_options_set(m_bind, SSH_BIND_OPTIONS_RSAKEY, key_file.c_str())) + { + EXLOGE("[ssh] can not set bind option: SSH_BIND_OPTIONS_RSAKEY.\n"); + return false; + } + + if (ssh_bind_listen(m_bind) < 0) + { + EXLOGE("[ssh] listening to socket: %s\n", ssh_get_error(m_bind)); + return false; + } + + return true; +} + +void SshProxy::_thread_loop(void) +{ + EXLOGV("[ssh] TeleportServer-SSH ready on %s:%d\n", m_host_ip.c_str(), m_host_port); + _run(); + EXLOGV("[ssh] main-loop end.\n"); +} + +void SshProxy::_set_stop_flag(void) +{ + m_stop_flag = true; + + if (m_is_running) + { + // һͨķʽеļһ + ex_astr host_ip = m_host_ip; + if (host_ip == "0.0.0.0") + host_ip = "127.0.0.1"; + + ssh_session _session = ssh_new(); + ssh_options_set(_session, SSH_OPTIONS_HOST, host_ip.c_str()); + ssh_options_set(_session, SSH_OPTIONS_PORT, &m_host_port); + + int _timeout_us = 100000; + ssh_options_set(_session, SSH_OPTIONS_TIMEOUT_USEC, &_timeout_us); + ssh_connect(_session); + ssh_free(_session); + } + + m_thread_mgr.stop_all(); +} + +void SshProxy::_run(void) +{ + for (;;) + { + // ע⣬ssh_new()ָ룬ֹͣ־ڲͷˣָ뽻SshSessionʵʱͷš + ssh_session sess_to_client = ssh_new(); + + struct sockaddr_storage sock_client; + char ip[32] = { 0 }; + int len = sizeof(ip); + + if (ssh_bind_accept(m_bind, sess_to_client) != SSH_OK) + { + EXLOGE("[ssh] accepting a connection failed: %s.\n", ssh_get_error(m_bind)); + continue; + } + EXLOGD("[ssh] ssh_bind_accept() returned...\n"); + + if (m_stop_flag) + { + ssh_free(sess_to_client); + break; + } + + SshSession* sess = new SshSession(this, sess_to_client); + +#ifdef EX_OS_WIN32 + getpeername(ssh_get_fd(sess_to_client), (struct sockaddr*)&sock_client, &len); +#else + getpeername(ssh_get_fd(sess_to_client), (struct sockaddr*)&sock_client, (unsigned int*)&len); +#endif + sockaddr_in* addrin = (sockaddr_in*)&sock_client; + + if (0 == ex_ip4_name(addrin, ip, sizeof(ip))) + { + sess->client_ip(ip); + sess->client_port(addrin->sin_port); + } + + + EXLOGV("[ssh] ------ NEW SSH CLIENT [%s:%d] ------\n", sess->client_ip(), sess->client_port()); + + + { + ExThreadSmartLock locker(m_lock); + m_sessions.insert(std::make_pair(sess, 0)); + } + + sess->start(); + } + + // ȴй߳˳ + m_thread_mgr.stop_all(); +} + +void SshProxy::_dump_sftp_sessions(void) +{ + ts_sftp_sessions::iterator it = m_sftp_sessions.begin(); + for (; it != m_sftp_sessions.end(); ++it) + { + EXLOGD("ssh-proxy session: sid: %s\n", it->first.c_str()); + } +} + +void SshProxy::add_sftp_session_info(const ex_astr& sid, const ex_astr& host_ip, int host_port, const ex_astr& user_name, const ex_astr& user_auth, int auth_mode) +{ + ExThreadSmartLock locker(m_lock); + EXLOGD("[ssh] add sftp session-id: %s\n", sid.c_str()); + ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); + if (it != m_sftp_sessions.end()) + { + EXLOGD("[ssh] sftp-session-id '%s' already exists.\n", sid.c_str()); + it->second->ref_count++; + return; + } + + TS_SFTP_SESSION_INFO* info = new TS_SFTP_SESSION_INFO; + info->host_ip = host_ip; + info->host_port = host_port; + info->user_name = user_name; + info->user_auth = user_auth; + info->auth_mode = auth_mode; + info->ref_count = 1; + + if (!m_sftp_sessions.insert(std::make_pair(sid, info)).second) + { + EXLOGE("[ssh] ssh-proxy can not insert a sftp-session-id.\n"); + } + + _dump_sftp_sessions(); +} + +bool SshProxy::get_sftp_session_info(const ex_astr& sid, TS_SFTP_SESSION_INFO& info) +{ + ExThreadSmartLock locker(m_lock); + EXLOGD("[ssh] try to get info by sftp session-id: %s\n", sid.c_str()); + + _dump_sftp_sessions(); + + ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); + if (it == m_sftp_sessions.end()) + { + EXLOGD("sftp-session '%s' not exists.\n", sid.c_str()); + return false; + } + + info.host_ip = it->second->host_ip; + info.host_port = it->second->host_port; + info.user_name = it->second->user_name; + info.user_auth = it->second->user_auth; + info.auth_mode = it->second->auth_mode; + info.ref_count = it->second->ref_count; + + return true; +} + +void SshProxy::remove_sftp_sid(const ex_astr& sid) +{ + EXLOGD("[ssh] try to remove sftp session-id: %s\n", sid.c_str()); + + ExThreadSmartLock locker(m_lock); + ts_sftp_sessions::iterator it = m_sftp_sessions.find(sid); + if (it == m_sftp_sessions.end()) + { + EXLOGE("[ssh] ssh-proxy when remove sftp sid, it not in charge.\n"); + return; + } + + it->second->ref_count--; + if (it->second->ref_count <= 0) + { + delete it->second; + m_sftp_sessions.erase(it); + EXLOGD("[ssh] sftp session-id '%s' removed.\n", sid.c_str()); + } +} + +void SshProxy::session_finished(SshSession* sess) +{ + ExThreadSmartLock locker(m_lock); + ts_ssh_sessions::iterator it = m_sessions.find(sess); + if (it != m_sessions.end()) + { + m_sessions.erase(it); + EXLOGV("[ssh] client %s:%d session removed.\n", sess->client_ip(), sess->client_port()); + } + else + { + EXLOGW("[ssh] when session %s:%d end, it not in charge.\n", sess->client_ip(), sess->client_port()); + } + + delete sess; +} diff --git a/server/tp_core/protocol/ssh/ssh_recorder.cpp b/server/tp_core/protocol/ssh/ssh_recorder.cpp index 0fa5e23..b245a0c 100644 --- a/server/tp_core/protocol/ssh/ssh_recorder.cpp +++ b/server/tp_core/protocol/ssh/ssh_recorder.cpp @@ -1,29 +1,38 @@ #include "ssh_recorder.h" -static ex_u8 TPP_RECORD_MAGIC[4] = { 'T', 'P', 'R', 'R' }; +static ex_u8 TPP_RECORD_MAGIC[4] = { 'T', 'P', 'P', 'R' }; -TppRec::TppRec() +TppSshRec::TppSshRec() { m_cmd_cache.reserve(MAX_SIZE_PER_FILE); memset(&m_head, 0, sizeof(TS_RECORD_HEADER)); memcpy((ex_u8*)(&m_head.magic), TPP_RECORD_MAGIC, sizeof(ex_u32)); + m_head.ver = 0x02; + m_head.protocol = TS_PROXY_PROTOCOL_SSH; } -TppRec::~TppRec() +TppSshRec::~TppSshRec() { end(); } -void TppRec::_on_begin(const TS_SESSION_INFO& info) +void TppSshRec::_on_begin(const TPP_SESSION_INFO* info) { - m_head.port = info.host_port; - memcpy(m_head.account, info.account_name.c_str(), info.account_name.length() > 15 ? 15 : info.account_name.length()); - memcpy(m_head.username, info.user_name.c_str(), info.user_name.length() > 15 ? 15 : info.user_name.length()); - memcpy(m_head.ip, info.host_ip.c_str(), info.host_ip.length() > 17 ? 17 : info.host_ip.length()); + if (NULL == info) + return; + m_head.timestamp = time(NULL); + m_head.port = info->host_port; + // memcpy(m_head.account, info.account_name.c_str(), info.account_name.length() > 15 ? 15 : info.account_name.length()); + // memcpy(m_head.username, info.user_name.c_str(), info.user_name.length() > 15 ? 15 : info.user_name.length()); + // memcpy(m_head.ip, info.host_ip.c_str(), info.host_ip.length() > 17 ? 17 : info.host_ip.length()); + + memcpy(m_head.account, info->account_name, strlen(info->account_name) > 15 ? 15 : strlen(info->account_name)); + memcpy(m_head.username, info->user_name, strlen(info->user_name) > 15 ? 15 : strlen(info->user_name)); + memcpy(m_head.ip, info->host_ip, strlen(info->host_ip) > 17 ? 17 : strlen(info->host_ip)); } -void TppRec::_on_end(void) +void TppSshRec::_on_end(void) { // ʣδдݣдļС if (m_cache.size() > 0) @@ -32,7 +41,7 @@ void TppRec::_on_end(void) _save_to_cmd_file(); // ͷϢ - m_head.timestamp = m_start_time; + //m_head.timestamp = m_start_time; m_head.time_ms = (ex_u32)(m_last_time - m_start_time); ex_wstr fname = m_base_path; @@ -51,7 +60,7 @@ void TppRec::_on_end(void) fclose(f); } -void TppRec::record(ex_u8 type, const ex_u8* data, size_t size) +void TppSshRec::record(ex_u8 type, const ex_u8* data, size_t size) { if (data == NULL || 0 == size) return; @@ -75,13 +84,13 @@ void TppRec::record(ex_u8 type, const ex_u8* data, size_t size) m_cache.append(data, size); } -void TppRec::record_win_size_startup(int width, int height) +void TppSshRec::record_win_size_startup(int width, int height) { m_head.width = width; m_head.height = height; } -void TppRec::record_win_size_change(int width, int height) +void TppSshRec::record_win_size_change(int width, int height) { TS_RECORD_WIN_SIZE pkg; pkg.width = (ex_u16)width; @@ -89,7 +98,7 @@ void TppRec::record_win_size_change(int width, int height) record(TS_RECORD_TYPE_SSH_TERM_SIZE, (ex_u8*)&pkg, sizeof(TS_RECORD_WIN_SIZE)); } -void TppRec::record_command(const ex_astr cmd) +void TppSshRec::record_command(const ex_astr cmd) { char szTime[100] = { 0 }; #ifdef EX_OS_WIN32 @@ -115,7 +124,7 @@ void TppRec::record_command(const ex_astr cmd) m_cmd_cache.append((ex_u8*)cmd.c_str(), cmd.length()); } -bool TppRec::_save_to_data_file(void) +bool TppSshRec::_save_to_data_file(void) { wchar_t _str_file_id[24] = { 0 }; ex_wcsformat(_str_file_id, 24, L".%03d", m_head.file_count); @@ -146,7 +155,7 @@ bool TppRec::_save_to_data_file(void) return true; } -bool TppRec::_save_to_cmd_file(void) +bool TppSshRec::_save_to_cmd_file(void) { ex_wstr fname = m_base_path; ex_path_join(fname, false, m_base_fname.c_str(), NULL); diff --git a/server/tp_core/protocol/ssh/ssh_recorder.h b/server/tp_core/protocol/ssh/ssh_recorder.h index 624fd1a..08d52a8 100644 --- a/server/tp_core/protocol/ssh/ssh_recorder.h +++ b/server/tp_core/protocol/ssh/ssh_recorder.h @@ -9,32 +9,32 @@ #pragma pack(push,1) // ¼ļͷ -typedef struct TS_RECORD_HEADER -{ - ex_u32 magic; // "TPPR" ־ TelePort Protocol Record - ex_u64 timestamp; // ¼ʼʱ䣨UTCʱ - ex_u32 packages; // ܰ - ex_u32 time_ms; // ܺʱ룩 - ex_u16 width; // ʼĻߴ磺 - ex_u16 height; // ʼĻߴ磺 - ex_u16 file_count; // ļ - ex_u32 file_size; // ļܴСÿļͷ4ֽڵÿļС - char account[16]; // teleport˺ - char username[16]; // Զû - char ip[18]; - ex_u16 port; - - ex_u8 reserve[128 - 4 - 8 - 4 - 4 - 2 - 2 - 2 - 4 - 16 - 16 - 18 - 2]; // -}TS_RECORD_HEADER; - -// һݰͷ -typedef struct TS_RECORD_PKG -{ - ex_u8 type; // - ex_u32 size; // ܴСͷ - ex_u32 time_ms; // ʼʱʱ룬ζһӲܳ49죩 - ex_u8 reserve[3]; // -}TS_RECORD_PKG; +// typedef struct TS_RECORD_HEADER +// { +// ex_u32 magic; // "TPPR" ־ TelePort Protocol Record +// ex_u64 timestamp; // ¼ʼʱ䣨UTCʱ +// ex_u32 packages; // ܰ +// ex_u32 time_ms; // ܺʱ룩 +// ex_u16 width; // ʼĻߴ磺 +// ex_u16 height; // ʼĻߴ磺 +// ex_u16 file_count; // ļ +// ex_u32 file_size; // ļܴСÿļͷ4ֽڵÿļС +// char account[16]; // teleport˺ +// char username[16]; // Զû +// char ip[18]; +// ex_u16 port; +// +// ex_u8 reserve[128 - 4 - 8 - 4 - 4 - 2 - 2 - 2 - 4 - 16 - 16 - 18 - 2]; // +// }TS_RECORD_HEADER; +// +// // һݰͷ +// typedef struct TS_RECORD_PKG +// { +// ex_u8 type; // +// ex_u32 size; // ܴСͷ +// ex_u32 time_ms; // ʼʱʱ룬ζһӲܳ49죩 +// ex_u8 reserve[3]; // +// }TS_RECORD_PKG; // ¼ڴСıݰ typedef struct TS_RECORD_WIN_SIZE @@ -45,11 +45,11 @@ typedef struct TS_RECORD_WIN_SIZE #pragma pack(pop) -class TppRec : public TppRecBase +class TppSshRec : public TppRecBase { public: - TppRec(); - virtual ~TppRec(); + TppSshRec(); + virtual ~TppSshRec(); void record(ex_u8 type, const ex_u8* data, size_t size); void record_win_size_startup(int width, int height); @@ -57,7 +57,7 @@ public: void record_command(const ex_astr cmd); protected: - void _on_begin(const TS_SESSION_INFO& info); + void _on_begin(const TPP_SESSION_INFO* info); void _on_end(void); bool _save_to_data_file(void); diff --git a/server/tp_core/protocol/ssh/ssh_session.cpp b/server/tp_core/protocol/ssh/ssh_session.cpp index 592e724..00a82a1 100644 --- a/server/tp_core/protocol/ssh/ssh_session.cpp +++ b/server/tp_core/protocol/ssh/ssh_session.cpp @@ -71,9 +71,9 @@ void SshSession::_set_stop_flag(void) { } } -bool SshSession::_on_session_begin(TS_SESSION_INFO& info) +bool SshSession::_on_session_begin(const TPP_SESSION_INFO* info) { - if (!g_ssh_env.session_begin(info, m_db_id)) + if (!g_ssh_env.session_begin(info, &m_db_id)) { EXLOGD("[ssh] session_begin error. %d\n", m_db_id); return false; @@ -229,12 +229,11 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, _this->m_sid = user; EXLOGV("[ssh] authenticating, session-id: %s\n", _this->m_sid.c_str()); - bool bRet = true; - TS_SESSION_INFO sess_info; - //bRet = _this->m_proxy->get_session_mgr()->take_session(_this->m_sid, sess_info); - bRet = g_ssh_env.take_session(_this->m_sid, sess_info); + //bool bRet = true; + int protocol = 0; + TPP_SESSION_INFO* sess_info = g_ssh_env.take_session(_this->m_sid.c_str()); - if (!bRet) { + if (NULL == sess_info) { EXLOGW("[ssh] try to get login-info from ssh-sftp-session.\n"); // ԴsftpӼ¼лȡϢһsshỰΪsftpỰڲὫϢ¼ã TS_SFTP_SESSION_INFO sftp_info; @@ -251,25 +250,28 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, _this->m_user_name = sftp_info.user_name; _this->m_user_auth = sftp_info.user_auth; - sess_info.host_ip = sftp_info.host_ip; - sess_info.host_port = sftp_info.host_port; - sess_info.auth_mode = sftp_info.auth_mode; - sess_info.user_name = sftp_info.user_name; - sess_info.user_auth = sftp_info.user_auth; - sess_info.protocol = TS_PROXY_PROTOCOL_SSH; +// sess_info.host_ip = sftp_info.host_ip; +// sess_info.host_port = sftp_info.host_port; +// sess_info.auth_mode = sftp_info.auth_mode; +// sess_info.user_name = sftp_info.user_name; +// sess_info.user_auth = sftp_info.user_auth; +// sess_info.protocol = TS_PROXY_PROTOCOL_SSH; + protocol = TS_PROXY_PROTOCOL_SSH; // ΪǴsftpỰĵ¼ݣƱỰֻsftpʹshellˡ _this->_enter_sftp_mode(); } else { - _this->m_server_ip = sess_info.host_ip; - _this->m_server_port = sess_info.host_port; - _this->m_auth_mode = sess_info.auth_mode; - _this->m_user_name = sess_info.user_name; - _this->m_user_auth = sess_info.user_auth; + _this->m_server_ip = sess_info->host_ip; + _this->m_server_port = sess_info->host_port; + _this->m_auth_mode = sess_info->auth_mode; + _this->m_user_name = sess_info->user_name; + _this->m_user_auth = sess_info->user_auth; + protocol = sess_info->protocol; } //EXLOGE("[ssh---------1] auth info [password:%s:%s:%d]\n", _this->m_user_name.c_str(),_this->m_user_auth.c_str(), _this->m_auth_mode); - if (sess_info.protocol != TS_PROXY_PROTOCOL_SSH) { + if (protocol != TS_PROXY_PROTOCOL_SSH) { + g_ssh_env.free_session(sess_info); EXLOGE("[ssh] session '%s' is not for SSH.\n", _this->m_sid.c_str()); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_AUTH_DENIED; @@ -278,19 +280,23 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, if (!_this->_on_session_begin(sess_info)) { + g_ssh_env.free_session(sess_info); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_AUTH_DENIED; return SSH_AUTH_DENIED; } - // ڳԸsession-idȡõϢӲ¼SSH - EXLOGV("[ssh] try to connect to real SSH server %s:%d\n", sess_info.host_ip.c_str(), sess_info.host_port); - _this->m_srv_session = ssh_new(); - ssh_options_set(_this->m_srv_session, SSH_OPTIONS_HOST, sess_info.host_ip.c_str()); - ssh_options_set(_this->m_srv_session, SSH_OPTIONS_PORT, &sess_info.host_port); + g_ssh_env.free_session(sess_info); + sess_info = NULL; - if (sess_info.auth_mode != TS_AUTH_MODE_NONE) - ssh_options_set(_this->m_srv_session, SSH_OPTIONS_USER, sess_info.user_name.c_str()); + // ڳԸsession-idȡõϢӲ¼SSH + EXLOGV("[ssh] try to connect to real SSH server %s:%d\n", _this->m_server_ip.c_str(), _this->m_server_port); + _this->m_srv_session = ssh_new(); + ssh_options_set(_this->m_srv_session, SSH_OPTIONS_HOST, _this->m_server_ip.c_str()); + ssh_options_set(_this->m_srv_session, SSH_OPTIONS_PORT, &_this->m_server_port); + + if (_this->m_auth_mode != TS_AUTH_MODE_NONE) + ssh_options_set(_this->m_srv_session, SSH_OPTIONS_USER, _this->m_user_name.c_str()); int _timeout_us = 30000000; // 30 sec. ssh_options_set(_this->m_srv_session, SSH_OPTIONS_TIMEOUT_USEC, &_timeout_us); @@ -298,25 +304,24 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, int rc = 0; rc = ssh_connect(_this->m_srv_session); if (rc != SSH_OK) { - EXLOGE("[ssh] can not connect to real SSH server %s:%d.\n", sess_info.host_ip.c_str(), sess_info.host_port); + EXLOGE("[ssh] can not connect to real SSH server %s:%d.\n", _this->m_server_ip.c_str(), _this->m_server_port); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_CONNECT; return SSH_AUTH_DENIED; } - if (sess_info.auth_mode == TS_AUTH_MODE_PASSWORD) { - rc = ssh_userauth_password(_this->m_srv_session, NULL, sess_info.user_auth.c_str()); + if (_this->m_auth_mode == TS_AUTH_MODE_PASSWORD) { + rc = ssh_userauth_password(_this->m_srv_session, NULL, _this->m_user_auth.c_str()); if (rc != SSH_OK) { - EXLOGE("[ssh] can not use user/name login to real SSH server %s:%d.\n", sess_info.host_ip.c_str(), - sess_info.host_port); + EXLOGE("[ssh] can not use user/name login to real SSH server %s:%d.\n", _this->m_server_ip.c_str(), _this->m_server_port); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_AUTH_DENIED; return SSH_AUTH_DENIED; } } - else if (sess_info.auth_mode == TS_AUTH_MODE_PRIVATE_KEY) { + else if (_this->m_auth_mode == TS_AUTH_MODE_PRIVATE_KEY) { ssh_key key = NULL; - if (SSH_OK != ssh_pki_import_privkey_base64(sess_info.user_auth.c_str(), NULL, NULL, NULL, &key)) { + if (SSH_OK != ssh_pki_import_privkey_base64(_this->m_user_auth.c_str(), NULL, NULL, NULL, &key)) { EXLOGE("[ssh] can not import private-key for auth.\n"); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_BAD_SSH_KEY; @@ -326,8 +331,7 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, rc = ssh_userauth_publickey(_this->m_srv_session, NULL, key); if (rc != SSH_OK) { ssh_key_free(key); - EXLOGE("[ssh] can not use private-key login to real SSH server %s:%d.\n", sess_info.host_ip.c_str(), - sess_info.host_port); + EXLOGE("[ssh] can not use private-key login to real SSH server %s:%d.\n", _this->m_server_ip.c_str(), _this->m_server_port); _this->m_have_error = true; _this->m_retcode = SESS_STAT_ERR_AUTH_DENIED; return SSH_AUTH_DENIED; @@ -335,7 +339,7 @@ int SshSession::_on_auth_password_request(ssh_session session, const char *user, ssh_key_free(key); } - else if (sess_info.auth_mode == TS_AUTH_MODE_NONE) + else if (_this->m_auth_mode == TS_AUTH_MODE_NONE) { // do nothing. return SSH_AUTH_DENIED; diff --git a/server/tp_core/protocol/ssh/ssh_session.h b/server/tp_core/protocol/ssh/ssh_session.h index 4a928a9..c69f2a8 100644 --- a/server/tp_core/protocol/ssh/ssh_session.h +++ b/server/tp_core/protocol/ssh/ssh_session.h @@ -55,7 +55,7 @@ public: protected: // ̳ TppSessionBase - bool _on_session_begin(TS_SESSION_INFO& info); + bool _on_session_begin(const TPP_SESSION_INFO* info); bool _on_session_end(void); @@ -89,7 +89,7 @@ private: int m_retcode; int m_db_id; - TppRec m_rec; + TppSshRec m_rec; SshProxy* m_proxy; ssh_session m_cli_session; diff --git a/server/tp_core/protocol/ssh/tpp_env.cpp b/server/tp_core/protocol/ssh/tpp_env.cpp index db9977e..a5594b3 100644 --- a/server/tp_core/protocol/ssh/tpp_env.cpp +++ b/server/tp_core/protocol/ssh/tpp_env.cpp @@ -1,14 +1,14 @@ #include "tpp_env.h" -TppEnv g_ssh_env; +TppSshEnv g_ssh_env; -TppEnv::TppEnv() +TppSshEnv::TppSshEnv() {} -TppEnv::~TppEnv() +TppSshEnv::~TppSshEnv() {} -bool TppEnv::_on_init(TPP_INIT_ARGS* args) +bool TppSshEnv::_on_init(TPP_INIT_ARGS* args) { ex_path_join(replay_path, false, L"ssh", NULL); @@ -28,11 +28,13 @@ bool TppEnv::_on_init(TPP_INIT_ARGS* args) { ex_wstr2astr(tmp, bind_ip); } + EXLOGW("[ssh] bind-ip: %s\n", bind_ip.c_str()); if (!ps->GetInt(L"bind-port", bind_port)) { bind_port = TS_SSH_PROXY_PORT; } + EXLOGW(L"[ssh] bind-port: %d\n", bind_port); return true; } diff --git a/server/tp_core/protocol/ssh/tpp_env.h b/server/tp_core/protocol/ssh/tpp_env.h index 25e2e0a..65e4d9b 100644 --- a/server/tp_core/protocol/ssh/tpp_env.h +++ b/server/tp_core/protocol/ssh/tpp_env.h @@ -3,11 +3,11 @@ #include "../../common/base_env.h" -class TppEnv : public TppEnvBase +class TppSshEnv : public TppEnvBase { public: - TppEnv(); - ~TppEnv(); + TppSshEnv(); + ~TppSshEnv(); public: ex_astr bind_ip; @@ -17,6 +17,6 @@ private: bool _on_init(TPP_INIT_ARGS* args); }; -extern TppEnv g_ssh_env; +extern TppSshEnv g_ssh_env; #endif // __TPP_ENV_H__ diff --git a/server/tp_core/protocol/ssh/tpssh.vs2015.vcxproj b/server/tp_core/protocol/ssh/tpssh.vs2015.vcxproj index 6e6f5cc..eac2a2f 100644 --- a/server/tp_core/protocol/ssh/tpssh.vs2015.vcxproj +++ b/server/tp_core/protocol/ssh/tpssh.vs2015.vcxproj @@ -1,218 +1,157 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {FDA16D20-09B7-45AF-ADF1-DAF3EF2C0531} - Win32Proj - tpssh - 8.1 - tpssh - - - - DynamicLibrary - true - v140_xp - Unicode - - - DynamicLibrary - false - v140_xp - true - Unicode - - - DynamicLibrary - true - v140 - Unicode - - - DynamicLibrary - false - v140 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - ..\..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ - ..\..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - true - - - false - ..\..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ - ..\..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ - - - false - - - - - - Level3 - Disabled - WIN32;_DEBUG;_WINDOWS;_USRDLL;TPP_EXPORTS;LIBSSH_STATIC;%(PreprocessorDefinitions) - ..\..\..\..\common\libex\include;..\..\..\..\external\libssh-win-static\include;%(AdditionalIncludeDirectories) - MultiThreadedDebug - - - Windows - true - ..\..\..\..\external\libssh-win-static\lib;..\..\..\..\external\openssl\out32;%(AdditionalLibraryDirectories) - - - - - - - Level3 - Disabled - _DEBUG;_WINDOWS;_USRDLL;TPSSH_EXPORTS;%(PreprocessorDefinitions) - - - Windows - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_WINDOWS;_USRDLL;TPP_EXPORTS;LIBSSH_STATIC;%(PreprocessorDefinitions) - ..\..\..\..\common\libex\include;..\..\..\..\external\libssh-win-static\include;%(AdditionalIncludeDirectories) - MultiThreaded - - - Windows - true - true - true - ..\..\..\..\external\libssh-win-static\lib;..\..\..\..\external\openssl\out32;%(AdditionalLibraryDirectories) - - - - - Level3 - - - MaxSpeed - true - true - NDEBUG;_WINDOWS;_USRDLL;TPSSH_EXPORTS;%(PreprocessorDefinitions) - - - Windows - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - false - - - false - - - false - - - - - - - - - - - - - + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {FDA16D20-09B7-45AF-ADF1-DAF3EF2C0531} + Win32Proj + tpssh + 8.1 + tpssh + + + + DynamicLibrary + true + v140_xp + Unicode + + + DynamicLibrary + false + v140_xp + true + Unicode + + + + + + + + + + + + + + + true + ..\..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ + ..\..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + false + ..\..\..\..\out\server\$(PlatformTarget)\$(Configuration)\ + ..\..\..\..\out\_tmp_\$(ProjectName)\$(PlatformTarget)\$(Configuration)\ + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;TPP_EXPORTS;LIBSSH_STATIC;%(PreprocessorDefinitions) + ..\..\..\..\common\libex\include;..\..\..\..\external\libssh-win-static\include;%(AdditionalIncludeDirectories) + MultiThreadedDebug + + + Windows + Debug + ..\..\..\..\external\libssh-win-static\lib;..\..\..\..\external\openssl\out32;%(AdditionalLibraryDirectories) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;TPP_EXPORTS;LIBSSH_STATIC;%(PreprocessorDefinitions) + ..\..\..\..\common\libex\include;..\..\..\..\external\libssh-win-static\include;%(AdditionalIncludeDirectories) + MultiThreaded + + + Windows + true + true + true + ..\..\..\..\external\libssh-win-static\lib;..\..\..\..\external\openssl\out32;%(AdditionalLibraryDirectories) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + false + + + + + + + + + + + + + \ No newline at end of file diff --git a/server/tp_web/src/tp_web.rc b/server/tp_web/src/tp_web.rc index f11ae9d..d8d1646 100644 Binary files a/server/tp_web/src/tp_web.rc and b/server/tp_web/src/tp_web.rc differ diff --git a/server/tp_web/src/ts_ver.h b/server/tp_web/src/ts_ver.h index 834c7c4..afb273e 100644 --- a/server/tp_web/src/ts_ver.h +++ b/server/tp_web/src/ts_ver.h @@ -1,6 +1,6 @@ #ifndef __TS_SERVER_VER_H__ #define __TS_SERVER_VER_H__ -#define TP_SERVER_VER L"2.1.2.1" +#define TP_SERVER_VER L"2.2.5.1" #endif // __TS_SERVER_VER_H__ diff --git a/server/www/teleport/.idea/teleport.iml b/server/www/teleport/.idea/teleport.iml index 9044667..0eaa135 100644 --- a/server/www/teleport/.idea/teleport.iml +++ b/server/www/teleport/.idea/teleport.iml @@ -11,7 +11,7 @@ - + diff --git a/server/www/teleport/app/eom_app/app/db.py b/server/www/teleport/app/eom_app/app/db.py index 19530f4..0d2be09 100644 --- a/server/www/teleport/app/eom_app/app/db.py +++ b/server/www/teleport/app/eom_app/app/db.py @@ -57,7 +57,8 @@ class TPDatabase: return False # 看看数据库中是否存在指定的数据表(如果不存在,可能是一个空数据库文件),则可能是一个新安装的系统 - ret = self.is_table_exists('{}group'.format(self._table_prefix)) + # ret = self.query('SELECT COUNT(*) FROM `sqlite_master` WHERE `type`="table" AND `name`="{}account";'.format(self._table_prefix)) + ret = self.is_table_exists('{}group'.format(self._table_prefix)) if ret is None or not ret: log.w('database need create.\n') self.need_create = True @@ -75,9 +76,9 @@ class TPDatabase: self.need_upgrade = True return True - # DO TEST - # self.alter_table('ts_account', [['account_id', 'id'], ['account_type', 'type']]) - + # DO TEST + # self.alter_table('ts_account', [['account_id', 'id'], ['account_type', 'type']]) + return True def is_table_exists(self, table_name): @@ -158,49 +159,49 @@ class TPDatabase: log.w('nothing to do.\n') return False - if isinstance(table_names, str): - old_table_name = table_names - new_table_name = table_names - elif isinstance(table_names, list) and len(table_names) == 2: - old_table_name = table_names[0] - new_table_name = table_names[1] - else: - log.w('invalid param.\n') - return False - - if isinstance(field_names, list): - for i in field_names: - if not isinstance(i, list) or 2 != len(i): - log.w('invalid param.\n') - return False - - if field_names is None: - # 仅数据表改名 - return self.exec('ALTER TABLE `{}` RENAME TO `{}`;'.format(old_table_name, new_table_name)) - else: - # sqlite不支持字段改名,所以需要通过临时表中转一下 - - # 先获取数据表的字段名列表 - ret = self.query('SELECT * FROM `sqlite_master` WHERE `type`="table" AND `name`="{}";'.format(old_table_name)) - log.w('-----\n') - log.w(ret[0][4]) - log.w('\n') - - # 先将数据表改名,成为一个临时表 - # tmp_table_name = '{}_sqlite_tmp'.format(old_table_name) - # ret = self.exec('ALTER TABLE `{}` RENAME TO `{}`;'.format(old_table_name, tmp_table_name)) - # if ret is None or not ret: - # return ret - - pass - elif self.db_source['type'] == self.DB_TYPE_MYSQL: - log.e('mysql not supported yet.\n') - return False - else: - log.e('Unknown database type.\n') - return False - - + if isinstance(table_names, str): + old_table_name = table_names + new_table_name = table_names + elif isinstance(table_names, list) and len(table_names) == 2: + old_table_name = table_names[0] + new_table_name = table_names[1] + else: + log.w('invalid param.\n') + return False + + if isinstance(field_names, list): + for i in field_names: + if not isinstance(i, list) or 2 != len(i): + log.w('invalid param.\n') + return False + + if field_names is None: + # 仅数据表改名 + return self.exec('ALTER TABLE `{}` RENAME TO `{}`;'.format(old_table_name, new_table_name)) + else: + # sqlite不支持字段改名,所以需要通过临时表中转一下 + + # 先获取数据表的字段名列表 + ret = self.query('SELECT * FROM `sqlite_master` WHERE `type`="table" AND `name`="{}";'.format(old_table_name)) + log.w('-----\n') + log.w(ret[0][4]) + log.w('\n') + + # 先将数据表改名,成为一个临时表 + # tmp_table_name = '{}_sqlite_tmp'.format(old_table_name) + # ret = self.exec('ALTER TABLE `{}` RENAME TO `{}`;'.format(old_table_name, tmp_table_name)) + # if ret is None or not ret: + # return ret + + pass + elif self.db_source['type'] == self.DB_TYPE_MYSQL: + log.e('mysql not supported yet.\n') + return False + else: + log.e('Unknown database type.\n') + return False + + class TPDatabasePool: def __init__(self): self._locker = threading.RLock() diff --git a/server/www/teleport/app/eom_app/controller/__init__.py b/server/www/teleport/app/eom_app/controller/__init__.py index 7819a5c..08416ba 100644 --- a/server/www/teleport/app/eom_app/controller/__init__.py +++ b/server/www/teleport/app/eom_app/controller/__init__.py @@ -53,7 +53,8 @@ controllers = [ # add another path to static-path # todo: 重放数据路径是动态从core服务的json-rpc接口获取的,因此这里的数据获取方式需要改变 - (r"/log/replay/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(cfg.data_path, 'replay')}), + #(r"/log/replay/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(cfg.data_path, 'replay')}), + (r"/log/replay/(.*)", record.ReplayStaticFileHandler, {"path": os.path.join(cfg.data_path, 'replay')}), (r'/log/list', record.LogList), (r'/log/record/(.*)/(.*)', record.RecordHandler), @@ -113,6 +114,8 @@ controllers = [ (r'/set/', set.IndexHandler), (r'/set', set.IndexHandler), - # 通过访问一个特殊URL来停止WEB服务,仅用于开发阶段,生产系统中请删除下一行 - (r'/EXIT-4E581FEFD7AB497D833D71A51C61D898', index.ExitHandler), + (r'/uidesign', index.UIDesignHandler), + (r'/uidesign/without-sidebar', index.UIDesignWithoutSidebarHandler), + (r'/uidesign/table', index.UIDesignTableHandler) + ] diff --git a/server/www/teleport/app/eom_app/controller/auth.py b/server/www/teleport/app/eom_app/controller/auth.py index cd4f6ab..f88c4a9 100644 --- a/server/www/teleport/app/eom_app/controller/auth.py +++ b/server/www/teleport/app/eom_app/controller/auth.py @@ -58,12 +58,14 @@ class VerifyUser(TPBaseJsonHandler): return try: - user_id, account_type, nickname = user.verify_user(username, userpwd) + user_id, account_type, nickname, locked = user.verify_user(username, userpwd) + if locked == 1: + return self.write_json(-1, '账号被锁定,请联系管理员!') if user_id == 0: if cfg.app_mode == APP_MODE_MAINTENANCE: - self.write_json(-2, '系统维护中,请稍候再试') + self.write_json(-2, '系统维护中,请稍候再试!') else: - self.write_json(-1, '用户名/密码错误') + self.write_json(-1, '用户名/密码错误!') return _user = self.get_session('user') @@ -92,7 +94,7 @@ class VerifyUser(TPBaseJsonHandler): except: log.e('can not set session.') - self.write_json(-1, '无法记录用户登录状态') + self.write_json(-1, '无法记录用户登录状态!') class LogoutHandler(TPBaseUserAuthHandler): diff --git a/server/www/teleport/app/eom_app/controller/host.py b/server/www/teleport/app/eom_app/controller/host.py index 449484e..812f11b 100644 --- a/server/www/teleport/app/eom_app/controller/host.py +++ b/server/www/teleport/app/eom_app/controller/host.py @@ -1,977 +1,974 @@ -# -*- coding: utf-8 -*- - -import time -import csv -import os -import json -import threading -import tornado.gen -import tornado.httpclient - -from eom_app.app.configs import app_cfg -from eom_app.app.util import * -from eom_app.module import host -from eom_common.eomcore.logger import * -from eom_app.app.session import web_session -from .base import TPBaseUserAuthHandler, TPBaseAdminAuthHandler, TPBaseUserAuthJsonHandler, TPBaseAdminAuthJsonHandler - -cfg = app_cfg() - -# 临时认证ID的基数,每次使用时均递减 -tmp_auth_id_base = -1 -tmp_auth_id_lock = threading.RLock() - - -class IndexHandler(TPBaseUserAuthHandler): - def get(self): - _user = self.get_session('user') - if _user is None: - return self.write(-1) - - param = dict() - - param['core'] = { - 'ssh_port': cfg.core.ssh.port, - 'rdp_port': cfg.core.telnet.port, - 'telnet_port': cfg.core.telnet.port - } - - param['group_list'] = host.get_group_list() - - if _user['type'] >= 100: - param['cert_list'] = host.get_cert_list() - self.render('host/admin_index.mako', page_param=json.dumps(param)) - else: - self.render('host/common_index.mako', page_param=json.dumps(param)) - - -class UploadAndImportHandler(TPBaseAdminAuthJsonHandler): - # TODO: 导入操作可能会比较耗时,应该分离导入和获取导入状态两个过程,在页面上可以呈现导入进度,并列出导出成功/失败的项 - - @tornado.gen.coroutine - def post(self): - """ - csv导入规则: - 每一行的数据格式: 分组ID,操作系统,IP地址,端口,系统用户,系统密码,协议,密钥ID,状态,认证类型,描述 - 因为主机的唯一性在于 `IP地址 + 端口`,且允许一个 `IP地址 + 端口` 对应多个系统用户,因此,每一行的数据几乎没有限制。 - 在导入时: - 1. 对每一个第一次遇到的 `IP地址 + 端口` 组合,就在 ts_host_info 表中加一个条目,并在 ts_auth_info 表中加入一个用户。 - 2. 对于非第一次遇到的 `IP地址 + 端口` 组合,则仅仅在 ts_auth_info 表中加一个用户,不更改 ts_host_info 表中的现有数据。 - 3. `IP地址 + 端口 + 用户` 的组合不能重复。 - 4. 空行跳过,数据格式不正确的跳过。 - """ - ret = dict() - ret['code'] = 0 - ret['msg'] = list() # 记录跳过的行(格式不正确,或者数据重复等) - csv_filename = '' - - try: - # upload_path = os.path.join(os.path.dirname(__file__), 'csv-files') # 文件的暂存路径 - upload_path = os.path.join(cfg.data_path, 'tmp') # 文件的暂存路径 - if not os.path.exists(upload_path): - os.mkdir(upload_path) - file_metas = self.request.files['csvfile'] # 提取表单中‘name’为‘file’的文件元数据 - for meta in file_metas: - now = time.localtime(time.time()) - tmp_name = 'upload-{:04d}{:02d}{:02d}{:02d}{:02d}{:02d}.csv'.format(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) - csv_filename = os.path.join(upload_path, tmp_name) - with open(csv_filename, 'wb') as up: - up.write(meta['body']) - - # file encode maybe utf8 or gbk... check it out. - file_encode = None - with open(csv_filename, encoding='gbk') as up: - try: - up.readlines() - file_encode = 'gbk' - except: - log.e('open file:{} -1\n'.format(csv_filename)) - - if file_encode is None: - with open(csv_filename, encoding='utf8') as up: - try: - up.readlines() - file_encode = 'utf8' - except: - log.e('open file:{} -2\n'.format(csv_filename)) - - if file_encode is None: - os.remove(csv_filename) - self.write_json(-2) - log.e('file {} unknown encode.\n'.format(csv_filename)) - return - - with open(csv_filename, encoding=file_encode) as up: - csv_reader = csv.reader(up) - is_first_line = True - for csv_recorder in csv_reader: - # 跳过第一行,那是格式说明 - if is_first_line: - is_first_line = False - continue - - # 空行则忽略 - if len(csv_recorder) <= 1: - continue - - # 格式错误则记录在案,然后继续 - if len(csv_recorder) != 13: - ret['msg'].append({'reason': '格式错误', 'line': ', '.join(csv_recorder)}) - continue - - # pro_type = int(line[6]) - # host_port = int(line[3]) - - host_args = dict() - user_args = dict() - # 分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密,附加参数, 密钥ID, 认证类型 - - host_args['group_id'] = int(csv_recorder[0]) - host_args['host_sys_type'] = int(csv_recorder[1]) - host_args['host_ip'] = csv_recorder[2] - host_args['host_port'] = csv_recorder[3] - host_args['protocol'] = csv_recorder[4] - host_args['host_lock'] = csv_recorder[5] - host_args['host_desc'] = csv_recorder[6] - # 加入一个主机(如果已经存在,则直接返回已存在的条目的host_id) - host_id = host.add_host(host_args, must_not_exists=False) - if host_id < 0: - ret['msg'].append({'reason': '添加主机失败,操作数据库失败', 'line': ', '.join(csv_recorder)}) - continue - - user_args['host_id'] = host_id - user_args['user_name'] = csv_recorder[7] - user_pswd = csv_recorder[8] - is_encrpty = int(csv_recorder[9]) - user_args['user_param'] = csv_recorder[10].replace('\\n', '\n') - user_args['cert_id'] = int(csv_recorder[11]) - auth_mode = int(csv_recorder[12]) - user_args['auth_mode'] = auth_mode - user_args['user_pswd'] = '' - ret_code = 0 - if auth_mode == 0: - pass - elif auth_mode == 1: - try: - if is_encrpty == 0: - # ret_code, tmp_pswd = get_enc_data(user_pswd) - _yr = async_enc(user_pswd) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - tmp_pswd = return_data['data'] - - else: - tmp_pswd = user_pswd - - user_args['user_pswd'] = tmp_pswd - - except Exception: - ret_code = -1 - log.e('get_enc_data() failed.\n') - - if 0 != ret_code: - ret['msg'].append({'reason': '加密用户密码失败,可能原因:Teleport核心服务未启动', 'line': ', '.join(csv_recorder)}) - log.e('get_enc_data() failed, error={}\n'.format(ret_code)) - continue - - elif auth_mode == 2: - pass - # user_args['cert_id'] = int(csv_recorder[7]) - else: - ret['msg'].append({'reason': '未知的认证模式', 'line': ', '.join(csv_recorder)}) - log.e('auth_mode unknown\n') - continue - - uid = host.sys_user_add(user_args) - if uid < 0: - if uid == -100: - ret['msg'].append({'reason': '添加登录账号失败,账号已存在', 'line': ', '.join(csv_recorder)}) - else: - ret['msg'].append({'reason': '添加登录账号失败,操作数据库失败', 'line': ', '.join(csv_recorder)}) - # log.e('sys_user_add() failed.\n') - - ret = json.dumps(ret).encode('utf8') - self.write(ret) - except: - log.e('error\n') - ret['code'] = -1 - ret = json.dumps(ret).encode('utf8') - self.write(ret) - - finally: - if os.path.exists(csv_filename): - os.remove(csv_filename) - - -class GetListHandler(TPBaseUserAuthJsonHandler): - def post(self): - _user = self.get_session('user') - if _user is None: - return self.write(-1) - - _type = _user['type'] - _uname = _user['name'] - - filter = dict() - user = self.get_current_user() - order = dict() - order['name'] = 'host_id' - order['asc'] = True - limit = dict() - limit['page_index'] = 0 - limit['per_page'] = 25 - - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - - tmp = list() - _filter = args['filter'] - for i in _filter: - if i == 'host_sys_type' and _filter[i] == 0: - tmp.append(i) - continue - if i == 'host_group' and _filter[i] == 0: - tmp.append(i) - continue - if i == 'search': - _x = _filter[i].strip() - if len(_x) == 0: - tmp.append(i) - continue - - for i in tmp: - del _filter[i] - - filter.update(_filter) - - _limit = args['limit'] - if _limit['page_index'] < 0: - _limit['page_index'] = 0 - if _limit['per_page'] < 10: - _limit['per_page'] = 10 - if _limit['per_page'] > 100: - _limit['per_page'] = 100 - - limit.update(_limit) - - _order = args['order'] - if _order is not None: - order['name'] = _order['k'] - order['asc'] = _order['v'] - if _type == 100: - _total, _hosts = host.get_all_host_info_list(filter, order, limit) - else: - filter['account_name'] = _uname - _total, _hosts = host.get_host_info_list_by_user(filter, order, limit) - # print(_hosts) - - ret = dict() - ret['page_index'] = limit['page_index'] - ret['total'] = _total - ret['data'] = _hosts - self.write_json(0, data=ret) - # self.write(json_encode(data)) - - -class GetGrouplist(TPBaseUserAuthJsonHandler): - def post(self): - group_list = host.get_group_list() - self.write_json(0, data=group_list) - - -class UpdateHandler(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - - if 'host_id' not in args or 'kv' not in args: - # ret = {'code':-2} - self.write_json(-2) - return - - # _host_id = args['host_id'] - - _ret = host.update(args['host_id'], args['kv']) - - if _ret: - self.write_json(0) - else: - self.write_json(-1) - - -class AddHost(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - - try: - ret = host.add_host(args) - if ret > 0: - self.write_json(0) - else: - self.write_json(ret) - return - except: - self.write_json(-1) - return - - -class LockHost(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - - host_id = args['host_id'] - lock = args['lock'] - try: - ret = host.lock_host(host_id, lock) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class DeleteHost(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - host_list = args['host_list'] - try: - ret = host.delete_host(host_list) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class ExportHostHandler(TPBaseAdminAuthHandler): - def get(self): - self.set_header('Content-Type', 'application/octet-stream') - self.set_header('Content-Disposition', 'attachment; filename=teleport-host-export.csv') - - order = dict() - order['name'] = 'host_id' - order['asc'] = True - limit = dict() - limit['page_index'] = 0 - limit['per_page'] = 999999 - _total, _hosts = host.get_all_host_info_list(dict(), order, limit, True) - - self.write("分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密, 附加参数, 密钥ID, 认证类型\n".encode('gbk')) - - try: - - for h in _hosts: - auth_list = h['auth_list'] - # 分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密,附加参数, 密钥ID, 认证类型 - for j in auth_list: - row_string = '' - # row_string = str(h['host_id']) - # row_string += ',' - row_string += str(h['group_id']) - row_string += ',' - row_string += str(h['host_sys_type']) - row_string += ',' - row_string += h['host_ip'] - row_string += ',' - row_string += str(h['host_port']) - row_string += ',' - row_string += str(h['protocol']) - row_string += ',' - row_string += str(h['host_lock']) - row_string += ',' - row_string += h['host_desc'] - row_string += ',' - - # row_string += str(j['host_auth_id']) - # row_string += ',' - row_string += j['user_name'] - row_string += ',' - row_string += j['user_pswd'] - row_string += ',' - row_string += '1' - row_string += ',' - user_param = j['user_param'] - if len(user_param) > 0: - user_param = user_param.replace('\n', '\\n') - row_string += user_param - row_string += ',' - row_string += str(j['cert_id']) - row_string += ',' - row_string += str(j['auth_mode']) - - self.write(row_string.encode('gbk')) - self.write('\n') - - except IndexError: - self.write('**********************************************\n'.encode('gbk')) - self.write('!!错误!!\n'.encode('gbk')) - self.write('导出过程中发生了错误!!\n'.encode('gbk')) - self.write('**********************************************\n'.encode('gbk')) - log.e('') - - self.finish() - - -class GetCertList(TPBaseUserAuthJsonHandler): - def post(self): - # args = self.get_argument('args', None) - # if args is not None: - # args = json.loads(args) - # # print('args', args) - # else: - # # ret = {'code':-1} - # self.write_json(-1) - # return - _certs = host.get_cert_list() - if _certs is None: - self.write_json(-1) - return - else: - self.write_json(0, data=_certs) - return - - -class AddCert(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - self.write_json(-1) - return - - cert_pub = args['cert_pub'] - cert_pri = args['cert_pri'] - cert_name = args['cert_name'] - - if len(cert_pri) == 0: - self.write_json(-1) - return - - _yr = async_enc(cert_pri) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - cert_pri = return_data['data'] - - try: - ret = host.add_cert(cert_pub, cert_pri, cert_name) - if ret: - return self.write_json(0) - else: - return self.write_json(-1) - except: - return self.write_json(-1) - - -class DeleteCert(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - cert_id = args['cert_id'] - try: - ret = host.delete_cert(cert_id) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class UpdateCert(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - cert_id = args['cert_id'] - cert_pub = args['cert_pub'] - cert_pri = args['cert_pri'] - cert_name = args['cert_name'] - - if len(cert_pri) > 0: - _yr = async_enc(cert_pri) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - cert_pri = return_data['data'] - - try: - ret = host.update_cert(cert_id, cert_pub, cert_pri, cert_name) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class AddGroup(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - group_name = args['group_name'] - try: - ret = host.add_group(group_name) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class UpdateGroup(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - group_id = args['group_id'] - group_name = args['group_name'] - try: - ret = host.update_group(group_id, group_name) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class DeleteGroup(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - group_id = args['group_id'] - try: - ret = host.delete_group(group_id) - if ret == 0: - self.write_json(0) - else: - self.write_json(ret) - return - except: - self.write_json(-1) - return - - -class AddHostToGroup(TPBaseUserAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - host_list = args['host_list'] - group_id = args['group_id'] - try: - ret = host.add_host_to_group(host_list, group_id) - if ret: - self.write_json(0) - else: - self.write_json(-1) - return - except: - self.write_json(-1) - return - - -class GetSessionId(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - if 'auth_id' not in args: - self.write_json(-1) - return - auth_id = args['auth_id'] - - req = {'method': 'request_session', 'param': {'authid': auth_id}} - _yr = async_post_http(req) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data: - return self.write_json(-1) - - _code = return_data['code'] - if _code != 0: - return self.write_json(_code) - - try: - session_id = return_data['data']['sid'] - except IndexError: - return self.write_json(-1) - - data = dict() - data['session_id'] = session_id - - return self.write_json(0, data=data) - - -class AdminGetSessionId(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - self.write_json(-1) - return - - if 'host_auth_id' not in args: - self.write_json(-1) - return - - _host_auth_id = int(args['host_auth_id']) - - user = self.get_current_user() - - # host_auth_id 对应的是 ts_auth_info 表中的某个条目,含有具体的认证数据,因为管理员无需授权即可访问所有远程主机,因此 - # 直接给出 host_auth_id,且account直接指明是当前登录用户(其必然是管理员) - - tmp_auth_info = host.get_host_auth_info(_host_auth_id) - if tmp_auth_info is None: - self.write_json(-1) - return - - tmp_auth_info['account_lock'] = 0 - tmp_auth_info['account_name'] = user['name'] - - with tmp_auth_id_lock: - global tmp_auth_id_base - tmp_auth_id_base -= 1 - auth_id = tmp_auth_id_base - - # 将这个临时认证信息放到session中备后续查找使用(10秒内有效) - web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) - - req = {'method': 'request_session', 'param': {'authid': auth_id}} - _yr = async_post_http(req) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data: - return self.write_json(-1) - - _code = return_data['code'] - if _code != 0: - return self.write_json(_code) - - try: - session_id = return_data['data']['sid'] - except IndexError: - return self.write_json(-1) - - data = dict() - data['session_id'] = session_id - - return self.write_json(0, data=data) - - -class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler): - @tornado.gen.coroutine - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - self.write_json(-1) - return - - user = self.get_current_user() - - tmp_auth_info = dict() - - try: - _host_auth_id = int(args['host_auth_id']) - _user_pswd = args['user_pswd'] - _cert_id = int(args['cert_id']) - - tmp_auth_info['host_ip'] = args['host_ip'] - tmp_auth_info['host_port'] = int(args['host_port']) - tmp_auth_info['sys_type'] = int(args['sys_type']) - tmp_auth_info['protocol'] = int(args['protocol']) - tmp_auth_info['user_name'] = args['user_name'] - tmp_auth_info['auth_mode'] = int(args['auth_mode']) - tmp_auth_info['user_param'] = args['user_param'] - tmp_auth_info['encrypt'] = 1 - tmp_auth_info['account_lock'] = 0 - tmp_auth_info['account_name'] = user['name'] - except IndexError: - self.write_json(-2) - return - - if tmp_auth_info['auth_mode'] == 1: - if len(_user_pswd) == 0: # 修改登录用户信息时可能不会修改密码,因此页面上可能不会传来密码,需要从数据库中直接读取 - h = host.get_host_auth_info(_host_auth_id) - tmp_auth_info['user_auth'] = h['user_auth'] - else: # 如果页面上修改了密码或者新建账号时设定了密码,那么需要先交给core服务进行加密 - req = {'method': 'enc', 'param': {'p': _user_pswd}} - _yr = async_post_http(req) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - tmp_auth_info['user_auth'] = return_data['data']['c'] - - elif tmp_auth_info['auth_mode'] == 2: - tmp_auth_info['user_auth'] = host.get_cert_info(_cert_id) - if tmp_auth_info['user_auth'] is None: - self.write_json(-100) - return - elif tmp_auth_info['auth_mode'] == 0: - tmp_auth_info['user_auth'] = '' - else: - self.write_json(-101) - return - - with tmp_auth_id_lock: - global tmp_auth_id_base - tmp_auth_id_base -= 1 - auth_id = tmp_auth_id_base - - web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) - - req = {'method': 'request_session', 'param': {'authid': auth_id}} - _yr = async_post_http(req) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data: - return self.write_json(-1) - - _code = return_data['code'] - if _code != 0: - return self.write_json(_code) - - try: - session_id = return_data['data']['sid'] - except IndexError: - return self.write_json(-1) - - data = dict() - data['session_id'] = session_id - - return self.write_json(0, data=data) - - -class SysUserList(TPBaseUserAuthJsonHandler): - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - self.write_json(-1) - return - try: - host_id = args['host_id'] - except Exception as e: - self.write_json(-2) - return - - data = host.sys_user_list(host_id) - return self.write_json(0, data=data) - - -class SysUserAdd(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - return self.write_json(-1) - - try: - auth_mode = args['auth_mode'] - user_pswd = args['user_pswd'] - cert_id = args['cert_id'] - except IndexError: - return self.write_json(-2) - - if auth_mode == 1: - if 0 == len(args['user_pswd']): - return self.write_json(-1) - - _yr = async_enc(user_pswd) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - args['user_pswd'] = return_data['data'] - - if host.sys_user_add(args) < 0: - return self.write_json(-1) - - return self.write_json(0) - - -class SysUserUpdate(TPBaseUserAuthJsonHandler): - @tornado.gen.coroutine - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - - if 'host_auth_id' not in args or 'kv' not in args: - # ret = {'code':-2} - self.write_json(-2) - return - - kv = args['kv'] - if 'auth_mode' not in kv or 'user_pswd' not in kv or 'cert_id' not in kv: - self.write_json(-3) - return - - auth_mode = kv['auth_mode'] - if 'user_pswd' in kv: - user_pswd = kv['user_pswd'] - if 0 == len(user_pswd): - args['kv'].pop('user_pswd') - user_pswd = None - else: - user_pswd = None - - cert_id = kv['cert_id'] - if auth_mode == 1 and user_pswd is not None: - _yr = async_enc(user_pswd) - return_data = yield _yr - if return_data is None: - return self.write_json(-1) - - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - - args['kv']['user_pswd'] = return_data['data'] - - if host.sys_user_update(args['host_auth_id'], args['kv']): - return self.write_json(0) - - return self.write_json(-1) - - -class SysUserDelete(TPBaseUserAuthJsonHandler): - def post(self, *args, **kwargs): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - else: - self.write_json(-2) - return - try: - host_auth_id = args['host_auth_id'] - except IndexError: - self.write_json(-2) - return - - if host.sys_user_delete(host_auth_id): - return self.write_json(0) - - return self.write_json(-1) +# -*- coding: utf-8 -*- + +import time +import csv +import os +import json +import threading +import tornado.gen +import tornado.httpclient + +from eom_app.app.configs import app_cfg +from eom_app.app.util import * +from eom_app.module import host +from eom_common.eomcore.logger import * +from eom_app.app.session import web_session +from .base import TPBaseUserAuthHandler, TPBaseAdminAuthHandler, TPBaseUserAuthJsonHandler, TPBaseAdminAuthJsonHandler + +cfg = app_cfg() + +# 临时认证ID的基数,每次使用时均递减 +tmp_auth_id_base = -1 +tmp_auth_id_lock = threading.RLock() + + +class IndexHandler(TPBaseUserAuthHandler): + def get(self): + _user = self.get_session('user') + if _user is None: + return self.write(-1) + + param = dict() + + param['core'] = { + 'ssh_port': cfg.core.ssh.port, + 'rdp_port': cfg.core.rdp.port, + 'telnet_port': cfg.core.telnet.port + } + + param['group_list'] = host.get_group_list() + + if _user['type'] >= 100: + param['cert_list'] = host.get_cert_list() + self.render('host/admin_index.mako', page_param=json.dumps(param)) + else: + self.render('host/common_index.mako', page_param=json.dumps(param)) + + +class UploadAndImportHandler(TPBaseAdminAuthJsonHandler): + # TODO: 导入操作可能会比较耗时,应该分离导入和获取导入状态两个过程,在页面上可以呈现导入进度,并列出导出成功/失败的项 + + @tornado.gen.coroutine + def post(self): + """ + csv导入规则: + 每一行的数据格式: 分组ID,操作系统,IP地址,端口,系统用户,系统密码,协议,密钥ID,状态,认证类型,描述 + 因为主机的唯一性在于 `IP地址 + 端口`,且允许一个 `IP地址 + 端口` 对应多个系统用户,因此,每一行的数据几乎没有限制。 + 在导入时: + 1. 对每一个第一次遇到的 `IP地址 + 端口` 组合,就在 ts_host_info 表中加一个条目,并在 ts_auth_info 表中加入一个用户。 + 2. 对于非第一次遇到的 `IP地址 + 端口` 组合,则仅仅在 ts_auth_info 表中加一个用户,不更改 ts_host_info 表中的现有数据。 + 3. `IP地址 + 端口 + 用户` 的组合不能重复。 + 4. 空行跳过,数据格式不正确的跳过。 + """ + ret = dict() + ret['code'] = 0 + ret['msg'] = list() # 记录跳过的行(格式不正确,或者数据重复等) + csv_filename = '' + + try: + # upload_path = os.path.join(os.path.dirname(__file__), 'csv-files') # 文件的暂存路径 + upload_path = os.path.join(cfg.data_path, 'tmp') # 文件的暂存路径 + if not os.path.exists(upload_path): + os.mkdir(upload_path) + file_metas = self.request.files['csvfile'] # 提取表单中‘name’为‘file’的文件元数据 + for meta in file_metas: + now = time.localtime(time.time()) + tmp_name = 'upload-{:04d}{:02d}{:02d}{:02d}{:02d}{:02d}.csv'.format(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) + csv_filename = os.path.join(upload_path, tmp_name) + with open(csv_filename, 'wb') as up: + up.write(meta['body']) + + # file encode maybe utf8 or gbk... check it out. + file_encode = None + with open(csv_filename, encoding='gbk') as up: + try: + up.readlines() + file_encode = 'gbk' + except: + log.e('open file:{} -1\n'.format(csv_filename)) + + if file_encode is None: + with open(csv_filename, encoding='utf8') as up: + try: + up.readlines() + file_encode = 'utf8' + except: + log.e('open file:{} -2\n'.format(csv_filename)) + + if file_encode is None: + os.remove(csv_filename) + self.write_json(-2) + log.e('file {} unknown encode.\n'.format(csv_filename)) + return + + with open(csv_filename, encoding=file_encode) as up: + csv_reader = csv.reader(up) + is_first_line = True + for csv_recorder in csv_reader: + # 跳过第一行,那是格式说明 + if is_first_line: + is_first_line = False + continue + + # 空行则忽略 + if len(csv_recorder) <= 1: + continue + + # 格式错误则记录在案,然后继续 + if len(csv_recorder) != 13: + ret['msg'].append({'reason': '格式错误', 'line': ', '.join(csv_recorder)}) + continue + + # pro_type = int(line[6]) + # host_port = int(line[3]) + + host_args = dict() + user_args = dict() + # 分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密,附加参数, 密钥ID, 认证类型 + + host_args['group_id'] = int(csv_recorder[0]) + host_args['host_sys_type'] = int(csv_recorder[1]) + host_args['host_ip'] = csv_recorder[2] + host_args['host_port'] = csv_recorder[3] + host_args['protocol'] = csv_recorder[4] + host_args['host_lock'] = csv_recorder[5] + host_args['host_desc'] = csv_recorder[6] + # 加入一个主机(如果已经存在,则直接返回已存在的条目的host_id) + host_id = host.add_host(host_args, must_not_exists=False) + if host_id < 0: + ret['msg'].append({'reason': '添加主机失败,操作数据库失败', 'line': ', '.join(csv_recorder)}) + continue + + user_args['host_id'] = host_id + user_args['user_name'] = csv_recorder[7] + user_pswd = csv_recorder[8] + is_encrpty = int(csv_recorder[9]) + user_args['user_param'] = csv_recorder[10].replace('\\n', '\n') + user_args['cert_id'] = int(csv_recorder[11]) + auth_mode = int(csv_recorder[12]) + user_args['auth_mode'] = auth_mode + user_args['user_pswd'] = '' + ret_code = 0 + if auth_mode == 0: + pass + elif auth_mode == 1: + try: + if is_encrpty == 0: + # ret_code, tmp_pswd = get_enc_data(user_pswd) + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + tmp_pswd = return_data['data'] + + else: + tmp_pswd = user_pswd + + user_args['user_pswd'] = tmp_pswd + + except Exception: + ret_code = -1 + log.e('get_enc_data() failed.\n') + + if 0 != ret_code: + ret['msg'].append({'reason': '加密用户密码失败,可能原因:Teleport核心服务未启动', 'line': ', '.join(csv_recorder)}) + log.e('get_enc_data() failed, error={}\n'.format(ret_code)) + continue + + elif auth_mode == 2: + pass + # user_args['cert_id'] = int(csv_recorder[7]) + else: + ret['msg'].append({'reason': '未知的认证模式', 'line': ', '.join(csv_recorder)}) + log.e('auth_mode unknown\n') + continue + + uid = host.sys_user_add(user_args) + if uid < 0: + if uid == -100: + ret['msg'].append({'reason': '添加登录账号失败,账号已存在', 'line': ', '.join(csv_recorder)}) + else: + ret['msg'].append({'reason': '添加登录账号失败,操作数据库失败', 'line': ', '.join(csv_recorder)}) + # log.e('sys_user_add() failed.\n') + + ret = json.dumps(ret).encode('utf8') + self.write(ret) + except: + log.e('error\n') + ret['code'] = -1 + ret = json.dumps(ret).encode('utf8') + self.write(ret) + + finally: + if os.path.exists(csv_filename): + os.remove(csv_filename) + + +class GetListHandler(TPBaseUserAuthJsonHandler): + def post(self): + _user = self.get_session('user') + if _user is None: + return self.write(-1) + + _type = _user['type'] + _uname = _user['name'] + + filter = dict() + user = self.get_current_user() + order = dict() + order['name'] = 'host_id' + order['asc'] = True + limit = dict() + limit['page_index'] = 0 + limit['per_page'] = 25 + + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + + tmp = list() + _filter = args['filter'] + for i in _filter: + if i == 'host_sys_type' and _filter[i] == 0: + tmp.append(i) + continue + if i == 'host_group' and _filter[i] == 0: + tmp.append(i) + continue + if i == 'search': + _x = _filter[i].strip() + if len(_x) == 0: + tmp.append(i) + continue + + for i in tmp: + del _filter[i] + + filter.update(_filter) + + _limit = args['limit'] + if _limit['page_index'] < 0: + _limit['page_index'] = 0 + if _limit['per_page'] < 10: + _limit['per_page'] = 10 + if _limit['per_page'] > 100: + _limit['per_page'] = 100 + + limit.update(_limit) + + _order = args['order'] + if _order is not None: + order['name'] = _order['k'] + order['asc'] = _order['v'] + if _type == 100: + _total, _hosts = host.get_all_host_info_list(filter, order, limit) + else: + filter['account_name'] = _uname + _total, _hosts = host.get_host_info_list_by_user(filter, order, limit) + # print(_hosts) + + ret = dict() + ret['page_index'] = limit['page_index'] + ret['total'] = _total + ret['data'] = _hosts + self.write_json(0, data=ret) + # self.write(json_encode(data)) + + +class GetGrouplist(TPBaseUserAuthJsonHandler): + def post(self): + group_list = host.get_group_list() + self.write_json(0, data=group_list) + + +class UpdateHandler(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + + if 'host_id' not in args or 'kv' not in args: + # ret = {'code':-2} + self.write_json(-2) + return + + # _host_id = args['host_id'] + + _ret = host.update(args['host_id'], args['kv']) + + if _ret: + self.write_json(0) + else: + self.write_json(-1) + + +class AddHost(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + + try: + ret = host.add_host(args) + if ret > 0: + self.write_json(0) + else: + self.write_json(ret) + return + except: + self.write_json(-1) + return + + +class LockHost(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + + host_id = args['host_id'] + lock = args['lock'] + try: + ret = host.lock_host(host_id, lock) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class DeleteHost(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + host_list = args['host_list'] + try: + ret = host.delete_host(host_list) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class ExportHostHandler(TPBaseAdminAuthHandler): + def get(self): + self.set_header('Content-Type', 'application/octet-stream') + self.set_header('Content-Disposition', 'attachment; filename=teleport-host-export.csv') + + order = dict() + order['name'] = 'host_id' + order['asc'] = True + limit = dict() + limit['page_index'] = 0 + limit['per_page'] = 999999 + _total, _hosts = host.get_all_host_info_list(dict(), order, limit, True) + + self.write("分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密, 附加参数, 密钥ID, 认证类型\n".encode('gbk')) + + try: + + for h in _hosts: + auth_list = h['auth_list'] + # 分组ID, 操作系统, IP地址, 端口, 协议, 状态, 描述, 系统用户, 系统密码, 是否加密,附加参数, 密钥ID, 认证类型 + for j in auth_list: + row_string = '' + # row_string = str(h['host_id']) + # row_string += ',' + row_string += str(h['group_id']) + row_string += ',' + row_string += str(h['host_sys_type']) + row_string += ',' + row_string += h['host_ip'] + row_string += ',' + row_string += str(h['host_port']) + row_string += ',' + row_string += str(h['protocol']) + row_string += ',' + row_string += str(h['host_lock']) + row_string += ',' + row_string += h['host_desc'] + row_string += ',' + + # row_string += str(j['host_auth_id']) + # row_string += ',' + row_string += j['user_name'] + row_string += ',' + row_string += j['user_pswd'] + row_string += ',' + row_string += '1' + row_string += ',' + user_param = j['user_param'] + if len(user_param) > 0: + user_param = user_param.replace('\n', '\\n') + row_string += user_param + row_string += ',' + row_string += str(j['cert_id']) + row_string += ',' + row_string += str(j['auth_mode']) + + self.write(row_string.encode('gbk')) + self.write('\n') + + except IndexError: + self.write('**********************************************\n'.encode('gbk')) + self.write('!!错误!!\n'.encode('gbk')) + self.write('导出过程中发生了错误!!\n'.encode('gbk')) + self.write('**********************************************\n'.encode('gbk')) + log.e('') + + self.finish() + + +class GetCertList(TPBaseUserAuthJsonHandler): + def post(self): + # args = self.get_argument('args', None) + # if args is not None: + # args = json.loads(args) + # # print('args', args) + # else: + # # ret = {'code':-1} + # self.write_json(-1) + # return + _certs = host.get_cert_list() + if _certs is None: + self.write_json(-1) + return + else: + self.write_json(0, data=_certs) + return + + +class AddCert(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + self.write_json(-1) + return + + cert_pub = args['cert_pub'] + cert_pri = args['cert_pri'] + cert_name = args['cert_name'] + + if len(cert_pri) == 0: + self.write_json(-1) + return + + _yr = async_enc(cert_pri) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + cert_pri = return_data['data'] + + try: + ret = host.add_cert(cert_pub, cert_pri, cert_name) + if ret: + return self.write_json(0) + else: + return self.write_json(-1) + except: + return self.write_json(-1) + + +class DeleteCert(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + return self.write_json(-1) + + cert_id = args['cert_id'] + + try: + ret = host.delete_cert(cert_id) + if ret: + return self.write_json(0) + else: + return self.write_json(-2) + except: + return self.write_json(-3) + + +class UpdateCert(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + cert_id = args['cert_id'] + cert_pub = args['cert_pub'] + cert_pri = args['cert_pri'] + cert_name = args['cert_name'] + + if len(cert_pri) > 0: + _yr = async_enc(cert_pri) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + cert_pri = return_data['data'] + + try: + ret = host.update_cert(cert_id, cert_pub, cert_pri, cert_name) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class AddGroup(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + group_name = args['group_name'] + try: + ret = host.add_group(group_name) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class UpdateGroup(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + group_id = args['group_id'] + group_name = args['group_name'] + try: + ret = host.update_group(group_id, group_name) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class DeleteGroup(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + group_id = args['group_id'] + try: + ret = host.delete_group(group_id) + if ret == 0: + self.write_json(0) + else: + self.write_json(ret) + return + except: + self.write_json(-1) + return + + +class AddHostToGroup(TPBaseUserAuthJsonHandler): + def post(self): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + host_list = args['host_list'] + group_id = args['group_id'] + try: + ret = host.add_host_to_group(host_list, group_id) + if ret: + self.write_json(0) + else: + self.write_json(-1) + return + except: + self.write_json(-1) + return + + +class GetSessionId(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + # print('args', args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + if 'auth_id' not in args: + self.write_json(-1) + return + auth_id = args['auth_id'] + + req = {'method': 'request_session', 'param': {'authid': auth_id}} + _yr = async_post_http(req) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data: + return self.write_json(-1) + + _code = return_data['code'] + if _code != 0: + return self.write_json(_code) + + try: + session_id = return_data['data']['sid'] + except IndexError: + return self.write_json(-1) + + data = dict() + data['session_id'] = session_id + + return self.write_json(0, data=data) + + +class AdminGetSessionId(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + self.write_json(-1) + return + + if 'host_auth_id' not in args: + self.write_json(-1) + return + + _host_auth_id = int(args['host_auth_id']) + + user = self.get_current_user() + + # host_auth_id 对应的是 ts_auth_info 表中的某个条目,含有具体的认证数据,因为管理员无需授权即可访问所有远程主机,因此 + # 直接给出 host_auth_id,且account直接指明是当前登录用户(其必然是管理员) + + tmp_auth_info = host.get_host_auth_info(_host_auth_id) + if tmp_auth_info is None: + self.write_json(-1) + return + + tmp_auth_info['account_lock'] = 0 + tmp_auth_info['account_name'] = user['name'] + + with tmp_auth_id_lock: + global tmp_auth_id_base + tmp_auth_id_base -= 1 + auth_id = tmp_auth_id_base + + # 将这个临时认证信息放到session中备后续查找使用(10秒内有效) + web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) + + req = {'method': 'request_session', 'param': {'authid': auth_id}} + _yr = async_post_http(req) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data: + return self.write_json(-1) + + _code = return_data['code'] + if _code != 0: + return self.write_json(_code) + + try: + session_id = return_data['data']['sid'] + except IndexError: + return self.write_json(-1) + + data = dict() + data['session_id'] = session_id + + return self.write_json(0, data=data) + + +class AdminFastGetSessionId(TPBaseAdminAuthJsonHandler): + @tornado.gen.coroutine + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + self.write_json(-1) + return + + user = self.get_current_user() + + tmp_auth_info = dict() + + try: + _host_auth_id = int(args['host_auth_id']) + _user_pswd = args['user_pswd'] + _cert_id = int(args['cert_id']) + + tmp_auth_info['host_ip'] = args['host_ip'] + tmp_auth_info['host_port'] = int(args['host_port']) + tmp_auth_info['sys_type'] = int(args['sys_type']) + tmp_auth_info['protocol'] = int(args['protocol']) + tmp_auth_info['user_name'] = args['user_name'] + tmp_auth_info['auth_mode'] = int(args['auth_mode']) + tmp_auth_info['user_param'] = args['user_param'] + tmp_auth_info['encrypt'] = 1 + tmp_auth_info['account_lock'] = 0 + tmp_auth_info['account_name'] = user['name'] + except IndexError: + self.write_json(-2) + return + + if tmp_auth_info['auth_mode'] == 1: + if len(_user_pswd) == 0: # 修改登录用户信息时可能不会修改密码,因此页面上可能不会传来密码,需要从数据库中直接读取 + h = host.get_host_auth_info(_host_auth_id) + tmp_auth_info['user_auth'] = h['user_auth'] + else: # 如果页面上修改了密码或者新建账号时设定了密码,那么需要先交给core服务进行加密 + req = {'method': 'enc', 'param': {'p': _user_pswd}} + _yr = async_post_http(req) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + tmp_auth_info['user_auth'] = return_data['data']['c'] + + elif tmp_auth_info['auth_mode'] == 2: + tmp_auth_info['user_auth'] = host.get_cert_info(_cert_id) + if tmp_auth_info['user_auth'] is None: + self.write_json(-100) + return + elif tmp_auth_info['auth_mode'] == 0: + tmp_auth_info['user_auth'] = '' + else: + self.write_json(-101) + return + + with tmp_auth_id_lock: + global tmp_auth_id_base + tmp_auth_id_base -= 1 + auth_id = tmp_auth_id_base + + web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) + + req = {'method': 'request_session', 'param': {'authid': auth_id}} + _yr = async_post_http(req) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data: + return self.write_json(-1) + + _code = return_data['code'] + if _code != 0: + return self.write_json(_code) + + try: + session_id = return_data['data']['sid'] + except IndexError: + return self.write_json(-1) + + data = dict() + data['session_id'] = session_id + + return self.write_json(0, data=data) + + +class SysUserList(TPBaseUserAuthJsonHandler): + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + self.write_json(-1) + return + try: + host_id = args['host_id'] + except Exception as e: + self.write_json(-2) + return + + data = host.sys_user_list(host_id) + return self.write_json(0, data=data) + + +class SysUserAdd(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + return self.write_json(-1) + + try: + auth_mode = args['auth_mode'] + user_pswd = args['user_pswd'] + cert_id = args['cert_id'] + except IndexError: + return self.write_json(-2) + + if auth_mode == 1: + if 0 == len(args['user_pswd']): + return self.write_json(-1) + + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + args['user_pswd'] = return_data['data'] + + if host.sys_user_add(args) < 0: + return self.write_json(-1) + + return self.write_json(0) + + +class SysUserUpdate(TPBaseUserAuthJsonHandler): + @tornado.gen.coroutine + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + # ret = {'code':-1} + self.write_json(-1) + return + + if 'host_auth_id' not in args or 'kv' not in args: + # ret = {'code':-2} + self.write_json(-2) + return + + kv = args['kv'] + if 'auth_mode' not in kv or 'user_pswd' not in kv or 'cert_id' not in kv: + self.write_json(-3) + return + + auth_mode = kv['auth_mode'] + if 'user_pswd' in kv: + user_pswd = kv['user_pswd'] + if 0 == len(user_pswd): + args['kv'].pop('user_pswd') + user_pswd = None + else: + user_pswd = None + + cert_id = kv['cert_id'] + if auth_mode == 1 and user_pswd is not None: + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + args['kv']['user_pswd'] = return_data['data'] + + if host.sys_user_update(args['host_auth_id'], args['kv']): + return self.write_json(0) + + return self.write_json(-1) + + +class SysUserDelete(TPBaseUserAuthJsonHandler): + def post(self, *args, **kwargs): + args = self.get_argument('args', None) + if args is not None: + args = json.loads(args) + else: + self.write_json(-2) + return + try: + host_auth_id = args['host_auth_id'] + except IndexError: + self.write_json(-2) + return + + if host.sys_user_delete(host_auth_id): + return self.write_json(0) + + return self.write_json(-1) diff --git a/server/www/teleport/app/eom_app/controller/index.py b/server/www/teleport/app/eom_app/controller/index.py index cf01a81..65950cb 100644 --- a/server/www/teleport/app/eom_app/controller/index.py +++ b/server/www/teleport/app/eom_app/controller/index.py @@ -1,15 +1,30 @@ -# -*- coding: utf-8 -*- -import sys -import tornado.ioloop -from .base import TPBaseHandler, TPBaseUserAuthHandler - - -class IndexHandler(TPBaseUserAuthHandler): - def get(self): - self.redirect('/host') - - -class ExitHandler(TPBaseHandler): - def get(self): - self.write('exit ok') - tornado.ioloop.IOLoop.instance().stop() +# -*- coding: utf-8 -*- +import sys +import tornado.ioloop +from .base import TPBaseHandler, TPBaseUserAuthHandler + + +class IndexHandler(TPBaseUserAuthHandler): + def get(self): + self.redirect('/host') + + +class ExitHandler(TPBaseHandler): + def get(self): + self.write('exit ok') + tornado.ioloop.IOLoop.instance().stop() + + +class UIDesignHandler(TPBaseHandler): + def get(self): + self.render('uidesign/index.mako') + + +class UIDesignWithoutSidebarHandler(TPBaseHandler): + def get(self): + self.render('uidesign/without-sidebar.mako') + + +class UIDesignTableHandler(TPBaseHandler): + def get(self): + self.render('uidesign/table.mako') diff --git a/server/www/teleport/app/eom_app/controller/record.py b/server/www/teleport/app/eom_app/controller/record.py index ad39ecc..a8f8573 100644 --- a/server/www/teleport/app/eom_app/controller/record.py +++ b/server/www/teleport/app/eom_app/controller/record.py @@ -9,6 +9,7 @@ from eom_app.app.configs import app_cfg from eom_app.module import record from eom_app.module import user from .base import TPBaseAdminAuthHandler, TPBaseAdminAuthJsonHandler +import tornado.web def get_free_space_bytes(folder): @@ -61,6 +62,12 @@ class RecordHandler(TPBaseAdminAuthHandler): # # pass # filename = os.path.join(cfg.core.replay_path, 'replay', 'rdp', '{}'.format(record_id), 'tp-rdp.tpr') +class ReplayStaticFileHandler(tornado.web.StaticFileHandler): + def initialize(self, path, default_filename=None): + super().initialize(path, default_filename) + self.root = app_cfg().core.replay_path + # self.default_filename = default_filename + class ComandLogHandler(TPBaseAdminAuthHandler): def get(self, protocol, record_id): diff --git a/server/www/teleport/app/eom_app/module/host.py b/server/www/teleport/app/eom_app/module/host.py index a46ed05..8546662 100644 --- a/server/www/teleport/app/eom_app/module/host.py +++ b/server/www/teleport/app/eom_app/module/host.py @@ -414,7 +414,7 @@ def add_cert(cert_pub, cert_pri, cert_name): def delete_cert(cert_id): db = get_db() - sql = 'DELETE FROM `{}key` WHERE `cert_id`={};'.format(int(cert_id)) + sql = 'DELETE FROM `{}key` WHERE `cert_id`={};'.format(db.table_prefix, int(cert_id)) return db.exec(sql) diff --git a/server/www/teleport/app/eom_app/module/record.py b/server/www/teleport/app/eom_app/module/record.py index c249135..fd0c63c 100644 --- a/server/www/teleport/app/eom_app/module/record.py +++ b/server/www/teleport/app/eom_app/module/record.py @@ -19,8 +19,12 @@ def read_record_head(record_id): data = file.read() offset = 0 - magic, = struct.unpack_from('I', data, offset) # magic must be 1381126228, 'TPRR' + magic, = struct.unpack_from('I', data, offset) # magic must be 1381126228, 'TPPR' offset += 4 + ver, = struct.unpack_from('H', data, offset) + offset += 2 + protocol, = struct.unpack_from('H', data, offset) + offset += 2 time_start, = struct.unpack_from('Q', data, offset) offset += 8 pkg_count, = struct.unpack_from('I', data, offset) @@ -42,6 +46,11 @@ def read_record_head(record_id): user_name, = struct.unpack_from('16s', data, offset) user_name = user_name.decode() offset += 16 + ip, = struct.unpack_from('18s', data, offset) + ip = ip.decode() + offset += 18 + port, = struct.unpack_from('H', data, offset) + offset += 2 except Exception as e: return None @@ -50,81 +59,19 @@ def read_record_head(record_id): file.close() header = dict() + header['start'] = time_start header['file_count'] = file_count header['time_used'] = time_used header['width'] = width header['height'] = height + header['account'] = account + header['user_name'] = user_name + header['ip'] = ip + header['port'] = port + return header -# def read_record_term(record_id): -# record_path = os.path.join(cfg.core.replay_path, 'ssh', '{}'.format(record_id)) -# term_file_path = os.path.join(record_path, 'term.init') -# # term_file_path = r"E:\GitWork\teleport\share\data\replay\ssh\103\term.init" -# -# file = None -# try: -# file = open(term_file_path, 'rb') -# data = file.read() -# x = len(data) -# offset = 0 -# # data = data.decode() -# ID, = struct.unpack_from('16s', data, offset) -# ID = ID.decode() -# offset += 16 -# -# Version, = struct.unpack_from('16s', data, offset) -# Version = Version.decode() -# offset += 16 -# -# t_count, = struct.unpack_from('I', data, offset) -# offset += 4 -# term_list = list() -# for i in range(t_count): -# # _term, = struct.unpack_from('16s', data, offset) -# # _term = _term.decode() -# # offset += 16 -# _time, = struct.unpack_from('I', data, offset) -# offset += 4 -# -# x, = struct.unpack_from('I', data, offset) -# offset += 4 -# -# y, = struct.unpack_from('I', data, offset) -# offset += 4 -# -# # px, = struct.unpack_from('I', data, offset) -# # offset += 4 -# # -# # py, = struct.unpack_from('I', data, offset) -# # offset += 4 -# # -# # _time, = struct.unpack_from('I', data, offset) -# # offset += 4 -# temp = dict() -# # temp['term'] = _term -# temp['t'] = _time -# temp['w'] = x -# temp['h'] = y -# # temp['px'] = px -# # temp['py'] = py -# -# term_list.append(temp) -# -# except Exception as e: -# return None -# finally: -# if file is not None: -# file.close() -# -# header = dict() -# header['id'] = ID -# header['ver'] = Version -# header['count'] = t_count -# header['term_list'] = term_list -# return header - - def read_record_info(record_id, file_id): record_path = os.path.join(app_cfg().core.replay_path, 'ssh', '{:06d}'.format(int(record_id))) file_info = os.path.join(record_path, 'tp-ssh.{:03d}'.format(int(file_id))) diff --git a/server/www/teleport/app/eom_app/module/user.py b/server/www/teleport/app/eom_app/module/user.py index 3c6c27a..5c615c6 100644 --- a/server/www/teleport/app/eom_app/module/user.py +++ b/server/www/teleport/app/eom_app/module/user.py @@ -12,7 +12,7 @@ def verify_user(name, password): cfg = app_cfg() db = get_db() - sql = 'SELECT `account_id`, `account_type`, `account_name`, `account_pwd` FROM `{}account` WHERE `account_name`="{}";'.format(db.table_prefix, name) + sql = 'SELECT `account_id`, `account_type`, `account_name`, `account_pwd`, `account_lock` FROM `{}account` WHERE `account_name`="{}";'.format(db.table_prefix, name) db_ret = db.query(sql) if db_ret is None: # 特别地,如果无法取得数据库连接,有可能是新安装的系统,尚未建立数据库,此时应该处于维护模式 @@ -20,25 +20,29 @@ def verify_user(name, password): if cfg.app_mode == APP_MODE_MAINTENANCE: if name == 'admin' and password == 'admin': return 1, 100, 'admin' - return 0, 0, '' + return 0, 0, '', 0 if len(db_ret) != 1: - return 0, 0, '' + return 0, 0, '', 0 user_id = db_ret[0][0] account_type = db_ret[0][1] name = db_ret[0][2] + locked = db_ret[0][4] + if locked == 1: + return 0, 0, '', locked + if not sec_verify_password(password, db_ret[0][3]): # 按新方法验证密码失败,可能是旧版本的密码散列格式,再尝试一下 if db_ret[0][3] != hashlib.sha256(password.encode()).hexdigest(): - return 0, 0, '' + return 0, 0, '', locked else: # 发现此用户的密码散列格式还是旧的,更新成新的吧! _new_sec_password = sec_generate_password(password) sql = 'UPDATE `{}account` SET `account_pwd`="{}" WHERE `account_id`={}'.format(db.table_prefix, _new_sec_password, int(user_id)) db.exec(sql) - return user_id, account_type, name + return user_id, account_type, name, locked def modify_pwd(old_pwd, new_pwd, user_id): diff --git a/server/www/teleport/app/eom_ver.py b/server/www/teleport/app/eom_ver.py index 587f864..625508a 100644 --- a/server/www/teleport/app/eom_ver.py +++ b/server/www/teleport/app/eom_ver.py @@ -1,4 +1,4 @@ # -*- coding: utf8 -*- -TS_VER = "2.1.2.1" -TP_ASSIST_LAST_VER = "2.1.2.1" +TS_VER = "2.2.5.1" +TP_ASSIST_LAST_VER = "2.2.5.1" TP_ASSIST_REQUIRE = "2.0.0.1" diff --git a/server/www/teleport/static/css/auth.css b/server/www/teleport/static/css/auth.css index ab14080..882cdaa 100644 --- a/server/www/teleport/static/css/auth.css +++ b/server/www/teleport/static/css/auth.css @@ -1 +1 @@ -@charset "utf-8";body{padding-top:70px;padding-bottom:24px;background-color:#ececed}#head nav.navbar{height:70px;line-height:70px;background-color:#333;color:#fff}#head .logo .desc{display:block;float:right;color:#ccc;margin-top:10px;font-size:18px}#foot nav.navbar{min-height:24px;height:24px;line-height:24px;background-color:#ddd;color:#fff;font-size:12px;border-top:1px solid #ccc}#foot nav.navbar .container{height:24px}#foot nav.navbar p{margin:0 auto;text-align:center;color:#333}#content{margin:10px 0 50px 0}.auth-box{margin-top:30px;min-height:120px;border:1px solid #ccc;border-radius:8px;background-color:rgba(255,255,255,0.6)}.auth-box .header{min-height:50px;height:50px;border:none;box-shadow:none;border-bottom:1px solid #ccc}.auth-box .header .title{display:inline-block;float:left;margin-left:60px;height:24px;margin-top:25px;line-height:16px;font-size:20px;color:#999}.auth-box .header .selected{border-bottom:1px solid #69c;color:#555}.auth-box .header .title:hover{border-bottom:1px solid #999}.auth-box .inputarea{margin:30px}.auth-box .inputarea .input-group-addon{padding:0 5px 0 5px}.auth-box .inputarea p.input-addon-desc{text-align:right;padding:0 5px 0 5px;color:#999}#leftside{width:560px;height:560px;padding-top:60px;background:url(../img/login/side-001.jpg) 0 0 no-repeat}#leftside h1{font-size:24px;color:#888}#leftside p{font-size:18px;color:#888;padding-left:24px}.auth-box .inputbox{margin-bottom:10px}.auth-box-lg .inputbox{margin-bottom:20px}.auth-box .op_box{display:block;padding:5px;border-radius:3px;text-align:center;margin:5px 20px 10px 20px}.auth-box .op_error{background:#fbb}.auth-box .op_wait{background:#ccc}.auth-box .quick-area{padding:80px 0 80px 0}.auth-box .quick-area .quick-disc{text-align:center;margin-bottom:20px}.auth-box .quick-area .quick-no{padding-top:80px;padding-bottom:100px}.auth-box .quick-area .quick-yes{text-align:center}.auth-box .quick-area .quick-yes .quick-account{display:inline-block;margin:auto;margin-bottom:20px}.auth-box .quick-area .quick-yes .quick-account:hover .quick-image{box-shadow:0 0 8px #00c2f6}.auth-box .quick-area .quick-yes .quick-image{display:block;width:82px;height:82px;line-height:80px;font-size:64px;margin:auto;border:1px solid #a4cdf6;box-shadow:0 0 6px #a7d1fb}.auth-box .quick-area .quick-yes .quick-name{display:block;margin-top:5px} \ No newline at end of file +@charset "utf-8";body{padding-top:70px;padding-bottom:24px;background-color:#ececed}#head nav.navbar{height:70px;line-height:70px;background-color:#333;color:#fff}#head .logo .desc{display:block;float:right;color:#ccc;margin-top:10px;font-size:18px}#foot nav.navbar{min-height:24px;height:24px;line-height:24px;background-color:#ddd;color:#fff;font-size:12px;border-top:1px solid #ccc}#foot nav.navbar .container{height:24px}#foot nav.navbar p{margin:0 auto;text-align:center;color:#333}#content{margin:10px 0 50px 0}.auth-box{margin-top:30px;min-height:120px;border:1px solid #ccc;border-radius:8px;background-color:rgba(255,255,255,0.6)}.auth-box .header{min-height:50px;height:50px;border:none;box-shadow:none;border-bottom:1px solid #ccc}.auth-box .header .title{display:inline-block;float:left;margin-left:60px;height:24px;margin-top:25px;line-height:16px;font-size:20px;color:#999}.auth-box .header .selected{border-bottom:1px solid #69c;color:#555}.auth-box .header .title:hover{border-bottom:1px solid #999}.auth-box .inputarea{margin:30px}.auth-box .inputarea .input-group-addon{padding:0 5px 0 5px}.auth-box .inputarea p.input-addon-desc{text-align:right;padding:0 5px 0 5px;color:#999}#leftside{width:560px;height:560px;padding-top:60px;background:url(../img/login/side-001.jpg) 0 0 no-repeat}@media screen and (max-width:990px){#leftside{display:none}}#leftside h1{font-size:24px;color:#888}#leftside p{font-size:18px;color:#888;padding-left:24px}.auth-box .inputbox{margin-bottom:10px}.auth-box-lg .inputbox{margin-bottom:20px}.auth-box .op_box{display:block;padding:5px;border-radius:3px;text-align:center;margin:5px 20px 10px 20px}.auth-box .op_error{background:#fbb}.auth-box .op_wait{background:#ccc}.auth-box .quick-area{padding:80px 0 80px 0}.auth-box .quick-area .quick-disc{text-align:center;margin-bottom:20px}.auth-box .quick-area .quick-no{padding-top:80px;padding-bottom:100px}.auth-box .quick-area .quick-yes{text-align:center}.auth-box .quick-area .quick-yes .quick-account{display:inline-block;margin:auto;margin-bottom:20px}.auth-box .quick-area .quick-yes .quick-account:hover .quick-image{box-shadow:0 0 8px #00c2f6}.auth-box .quick-area .quick-yes .quick-image{display:block;width:82px;height:82px;line-height:80px;font-size:64px;margin:auto;border:1px solid #a4cdf6;box-shadow:0 0 6px #a7d1fb}.auth-box .quick-area .quick-yes .quick-name{display:block;margin-top:5px} \ No newline at end of file diff --git a/server/www/teleport/static/js/ui/admin_host.js b/server/www/teleport/static/js/ui/admin_host.js index 19eb10d..9d44f66 100644 --- a/server/www/teleport/static/js/ui/admin_host.js +++ b/server/www/teleport/static/js/ui/admin_host.js @@ -1,13 +1,13 @@ "use strict"; -var OS_TYPE_WINDOWS = 1; -var OS_TYPE_LINUX = 2; -var PROTOCOL_TYPE_RDP = 1; -var PROTOCOL_TYPE_SSH = 2; -var PROTOCOL_TYPE_TELNET = 3; -var AUTH_TYPE_PASSWORD = 1; -var AUTH_TYPE_SSHKEY = 2; -var AUTH_NONE = 0; +//var OS_TYPE_WINDOWS = 1; +//var OS_TYPE_LINUX = 2; +//var PROTOCOL_TYPE_RDP = 1; +//var PROTOCOL_TYPE_SSH = 2; +//var PROTOCOL_TYPE_TELNET = 3; +//var AUTH_TYPE_PASSWORD = 1; +//var AUTH_TYPE_SSHKEY = 2; +//var AUTH_NONE = 0; var g_assist = null; var g_host_table = null; @@ -19,231 +19,231 @@ var g_dlg_sys_user = null; var g_join_group_dlg = null; ywl.do_upload_file = function () { - var param = {}; - $.ajaxFileUpload({ - url: "/host/upload-import",// 需要链接到服务器地址 - secureuri: false, - fileElementId: "upload-file", // 文件选择框的id属性 - dataType: 'text', // 服务器返回的格式,可以是json - data: param, - success: function (data) { - $('#upload-file').remove(); - var obj = JSON.parse(data); - if (obj.code == 0) { - g_host_table.reload(); - ywl.notify_success('批量导入主机成功!'); - console.log('msg', obj); - if (obj.msg.length > 0) { - console.log(obj.msg); - var html = []; - html.push('
    '); - for (var i = 0, cnt = obj.msg.length; i < cnt; ++i) { - html.push('
  • '); - html.push('' + obj.msg[i].reason + '
    '); - html.push(obj.msg[i].line); - html.push('
  • '); - } - html.push('
'); + var param = {}; + $.ajaxFileUpload({ + url: "/host/upload-import",// 需要链接到服务器地址 + secureuri: false, + fileElementId: "upload-file", // 文件选择框的id属性 + dataType: 'text', // 服务器返回的格式,可以是json + data: param, + success: function (data) { + $('#upload-file').remove(); + var obj = JSON.parse(data); + if (obj.code === TPE_OK) { + g_host_table.reload(); + ywl.notify_success('批量导入主机成功!'); + console.log('msg', obj); + if (obj.msg.length > 0) { + console.log(obj.msg); + var html = []; + html.push('
    '); + for (var i = 0, cnt = obj.msg.length; i < cnt; ++i) { + html.push('
  • '); + html.push('' + obj.msg[i].reason + '
    '); + html.push(obj.msg[i].line); + html.push('
  • '); + } + html.push('
'); - $('#batch_add_host_result').html(html.join('')); - $('#dialog_batch_add_host').modal({backdrop: 'static'}); - } - } else { - ywl.notify_error('批量导入主机失败! 错误号:' + obj.code); - } - }, - error: function (data, status, e) { // 相当于java中catch语句块的用法 - $('#upload-file').remove(); - ywl.notify_error('网络故障,批量导入主机失败!'); - } - }); + $('#batch_add_host_result').html(html.join('')); + $('#dialog_batch_add_host').modal({backdrop: 'static'}); + } + } else { + ywl.notify_error('批量导入主机失败! 错误号:' + obj.code); + } + }, + error: function (data, status, e) { // 相当于java中catch语句块的用法 + $('#upload-file').remove(); + ywl.notify_error('网络故障,批量导入主机失败!'); + } + }); }; ywl.on_init = function (cb_stack, cb_args) { - g_assist = ywl.create_assist(); + g_assist = ywl.create_assist(); - var _ver_obj = $("#tp-assist-version"); - var last_version = _ver_obj.text(); - var req_version = _ver_obj.attr("req-version"); + var _ver_obj = $("#tp-assist-version"); + var last_version = _ver_obj.text(); + var req_version = _ver_obj.attr("req-version"); - teleport_init(last_version, req_version, - function (ret) { - $("#tp-assist-current-version").text("当前助手版本:" + ret.version); - }, - function (ret, code, error) { - if (code == TPE_NO_ASSIST) { - $("#tp-assist-current-version").text("未能检测到TP助手,请您下载并启动TP助手!"); - g_assist.alert_assist_not_found(); - } else if (code == TPE_OLD_ASSIST) { - ywl.notify_error(error); - $('#tp-assist-current-version').html('当前助手版本太低(v' + ret.version + '),请下载最新版本!'); - } else { - $("#tp-assist-current-version").text('检测TP助手版本时发生错误!'); - ywl.notify_error(error); - } - }); + teleport_init(last_version, req_version, + function (ret) { + $("#tp-assist-current-version").text("当前助手版本:" + ret.version); + }, + function (ret, code, error) { + if (code === TPE_NO_ASSIST) { + $("#tp-assist-current-version").text("未能检测到TP助手,请您下载并启动TP助手!"); + g_assist.alert_assist_not_found(); + } else if (code === TPE_OLD_ASSIST) { + ywl.notify_error(error); + $('#tp-assist-current-version').html('当前助手版本太低(v' + ret.version + '),请下载最新版本!'); + } else { + $("#tp-assist-current-version").text('检测TP助手版本时发生错误!'); + ywl.notify_error(error); + } + }); - //=================================== - // 创建页面控件对象 - //=================================== - var tbl_dom_id = '#ywl_host_list'; - // 表格数据 - var host_table_options = { - selector: tbl_dom_id + " [ywl-table='host-list']", - data_source: { - type: 'ajax-post', - url: '/host/list' - }, - //render: ywl.create_table_render(ywl.on_host_table_render_created),//ywl_TableRender.create(); - column_default: {sort: false, header_align: 'center', cell_align: 'center'}, - columns: [ - { - title: '', - key: 'select_all', - sort: false, - width: 24, - render: 'make_check_box', - fields: {id: 'host_id'} - }, - {title: "主机", key: "host_id", width: 200, render: 'host_id', fields: {id: 'host_ip', host_port: 'host_port', host_desc: 'host_desc'}}, - {title: "分组", key: "group_name"}, - {title: "系统", key: "host_sys_type", width: 36, render: 'sys_type', fields: {sys_type: 'host_sys_type'}}, - // {title: "协议", key: "protocol", width: 40, render: 'protocol', fields: {protocol: 'protocol', host_port: 'host_port'}}, - {title: "状态", key: "host_lock", render: 'host_lock', fields: {host_lock: 'host_lock'}}, - {title: "远程连接", key: "auth_list", width: 390, header_align: 'left', cell_align: 'left', render: 'auth_list', fields: {id: 'host_id', protocol: 'protocol', auth_list: 'auth_list'}}, - { - title: "系统用户", - sort: false, - key: "action", - //width: 60, - render: 'make_user_btn', - fields: {id: 'host_id'} - }, - { - title: "操作", - sort: false, - key: "action", - width: 150, - render: 'make_action_btn', - fields: {id: 'host_id', host_lock: 'host_lock'} - } - ], - paging: {selector: tbl_dom_id + " [ywl-paging='host-list']", per_page: paging_normal}, + //=================================== + // 创建页面控件对象 + //=================================== + var tbl_dom_id = '#ywl_host_list'; + // 表格数据 + var host_table_options = { + selector: tbl_dom_id + " [ywl-table='host-list']", + data_source: { + type: 'ajax-post', + url: '/host/list' + }, + //render: ywl.create_table_render(ywl.on_host_table_render_created),//ywl_TableRender.create(); + column_default: {sort: false, header_align: 'center', cell_align: 'center'}, + columns: [ + { + title: '', + key: 'select_all', + sort: false, + width: 24, + render: 'make_check_box', + fields: {id: 'host_id'} + }, + {title: "主机", key: "host_id", width: 200, render: 'host_id', fields: {id: 'host_ip', host_port: 'host_port', host_desc: 'host_desc'}}, + {title: "分组", key: "group_name"}, + {title: "系统", key: "host_sys_type", width: 36, render: 'sys_type', fields: {sys_type: 'host_sys_type'}}, + // {title: "协议", key: "protocol", width: 40, render: 'protocol', fields: {protocol: 'protocol', host_port: 'host_port'}}, + {title: "状态", key: "host_lock", render: 'host_lock', fields: {host_lock: 'host_lock'}}, + {title: "远程连接", key: "auth_list", width: 390, header_align: 'left', cell_align: 'left', render: 'auth_list', fields: {id: 'host_id', protocol: 'protocol', auth_list: 'auth_list'}}, + { + title: "系统用户", + sort: false, + key: "action", + //width: 60, + render: 'make_user_btn', + fields: {id: 'host_id'} + }, + { + title: "操作", + sort: false, + key: "action", + width: 150, + render: 'make_action_btn', + fields: {id: 'host_id', host_lock: 'host_lock'} + } + ], + paging: {selector: tbl_dom_id + " [ywl-paging='host-list']", per_page: paging_normal}, - // 可用的属性设置 - //have_header: true or false + // 可用的属性设置 + //have_header: true or false - // 可用的回调函数 - on_created: ywl.on_host_table_created, - on_header_created: ywl.on_host_table_header_created + // 可用的回调函数 + on_created: ywl.on_host_table_created, + on_header_created: ywl.on_host_table_header_created - // 可重载的函数(在on_created回调函数中重载) - // on_render_created - // on_header_created - // on_paging_created - // on_data_loaded - // on_row_rendered - // on_table_rendered - // on_cell_created - // on_begin_load - // on_after_load + // 可重载的函数(在on_created回调函数中重载) + // on_render_created + // on_header_created + // on_paging_created + // on_data_loaded + // on_row_rendered + // on_table_rendered + // on_cell_created + // on_begin_load + // on_after_load - // 可用的函数 - // load_data - // cancel_load - // set_data - // add_row - // remove_row - // get_row - // update_row - // clear - // reset_filter - }; + // 可用的函数 + // load_data + // cancel_load + // set_data + // add_row + // remove_row + // get_row + // update_row + // clear + // reset_filter + }; - var host_table = ywl.create_table(host_table_options); - g_host_table = host_table; - // 主机分组过滤器 - g_cert_list = ywl.page_options.cert_list; - g_group_list = ywl.page_options.group_list; - ywl.create_table_filter_host_group(host_table, tbl_dom_id + " [ywl-filter='host-group']", g_group_list); + var host_table = ywl.create_table(host_table_options); + g_host_table = host_table; + // 主机分组过滤器 + g_cert_list = ywl.page_options.cert_list; + g_group_list = ywl.page_options.group_list; + ywl.create_table_filter_host_group(host_table, tbl_dom_id + " [ywl-filter='host-group']", g_group_list); - ywl.create_table_filter_system_type(host_table, tbl_dom_id + " [ywl-filter='system-type']"); - // 搜索框 - ywl.create_table_filter_search_box(host_table, tbl_dom_id + " [ywl-filter='search']"); + ywl.create_table_filter_system_type(host_table, tbl_dom_id + " [ywl-filter='system-type']"); + // 搜索框 + ywl.create_table_filter_search_box(host_table, tbl_dom_id + " [ywl-filter='search']"); - g_dlg_edit_host = ywl.create_host_edit_dlg(host_table); - g_dlg_edit_host.init(); + g_dlg_edit_host = ywl.create_host_edit_dlg(host_table); + g_dlg_edit_host.init(); - g_dlg_edit_host_user = ywl.create_host_user_edit_dlg(host_table); - g_dlg_edit_host_user.init(); + g_dlg_edit_host_user = ywl.create_host_user_edit_dlg(host_table); + g_dlg_edit_host_user.init(); - g_dlg_sys_user = ywl.create_sys_user(host_table); - g_dlg_sys_user.init(); + g_dlg_sys_user = ywl.create_sys_user(host_table); + g_dlg_sys_user.init(); - g_join_group_dlg = ywl.create_batch_join_group_dlg(host_table); - g_join_group_dlg.init(); + g_join_group_dlg = ywl.create_batch_join_group_dlg(host_table); + g_join_group_dlg.init(); - //====================================================== - // 事件绑定 - //====================================================== - $("#btn-add-host").click(function () { - g_dlg_edit_host.create_show(); - }); + //====================================================== + // 事件绑定 + //====================================================== + $("#btn-add-host").click(function () { + g_dlg_edit_host.create_show(); + }); - $("#btn-delete-host").click(function () { - var host_list = []; - var _objs = $(host_table.selector + " tbody tr td [data-check-box]"); - $.each(_objs, function (i, _obj) { - if ($(_obj).is(':checked')) { - var _row_data = host_table.get_row(_obj); - host_list.push(_row_data.host_id); - } - }); + $("#btn-delete-host").click(function () { + var host_list = []; + var _objs = $(host_table.selector + " tbody tr td [data-check-box]"); + $.each(_objs, function (i, _obj) { + if ($(_obj).is(':checked')) { + var _row_data = host_table.get_row(_obj); + host_list.push(_row_data.host_id); + } + }); - if (host_list.length === 0) { - ywl.notify_error('请选择要批量删除的主机!'); - return; - } + if (host_list.length === 0) { + ywl.notify_error('请选择要批量删除的主机!'); + return; + } - var _fn_sure = function (cb_stack, cb_args) { - ywl.ajax_post_json('/host/delete-host', {host_list: host_list}, - function (ret) { - g_host_table.reload(); - ywl.notify_success('删除主机操作成功!'); - }, - function () { - ywl.notify_error('网络故障,删除主机操作失败!'); - } - ); - }; + var _fn_sure = function (cb_stack, cb_args) { + ywl.ajax_post_json('/host/delete-host', {host_list: host_list}, + function (ret) { + g_host_table.reload(); + ywl.notify_success('删除主机操作成功!'); + }, + function () { + ywl.notify_error('网络故障,删除主机操作失败!'); + } + ); + }; - var cb_stack = CALLBACK_STACK.create(); - ywl.dlg_confirm(cb_stack, { - msg: '

注意:移除操作不可恢复!!

如果您只是希望临时禁用某个远程主机,可对其进行“锁定”操作!

您确定要移除所有选定的远程主机吗?

', - fn_yes: _fn_sure - }); - }); + var cb_stack = CALLBACK_STACK.create(); + ywl.dlg_confirm(cb_stack, { + msg: '

注意:移除操作不可恢复!!

如果您只是希望临时禁用某个远程主机,可对其进行“锁定”操作!

您确定要移除所有选定的远程主机吗?

', + fn_yes: _fn_sure + }); + }); - $('#btn-batch-add-host').click(function (e) { - var html = ''; - $(this).after($(html)); - var update_file = $("#upload-file"); + $('#btn-batch-add-host').click(function (e) { + var html = ''; + $(this).after($(html)); + var update_file = $("#upload-file"); - update_file.change(function () { - var file_path = $(this).val(); - if (file_path === null || file_path === undefined || file_path === '') { - return; - } - ywl.do_upload_file(); - }); + update_file.change(function () { + var file_path = $(this).val(); + if (file_path === null || file_path === undefined || file_path === '') { + return; + } + ywl.do_upload_file(); + }); - update_file.trigger('click'); - }); + update_file.trigger('click'); + }); - $('#btn-batch-export-host').click(function (e) { + $('#btn-batch-export-host').click(function (e) { window.location.href = '/host/export-host'; // ywl.ajax_post_json('/host/export-host', {}, // function (ret) { @@ -260,352 +260,352 @@ ywl.on_init = function (cb_stack, cb_args) { // ywl.notify_error('操作失败'); // } // ); - }); + }); - $("#btn-apply-group").click(function () { - var _data_list = []; - var _objs = $(host_table.selector + " tbody tr td [data-check-box]"); - $.each(_objs, function (i, _obj) { - if ($(_obj).is(':checked')) { - var _row_data = host_table.get_row(_obj); - var data = {host_id: _row_data.host_id, row_id: _row_data.ywl_row_id}; - _data_list.push(data); - } - }); - if (_data_list.length === 0) { - ywl.notify_error('请选择要批量设置分组的主机!'); - return; - } - g_join_group_dlg.show(_data_list); - }); + $("#btn-apply-group").click(function () { + var _data_list = []; + var _objs = $(host_table.selector + " tbody tr td [data-check-box]"); + $.each(_objs, function (i, _obj) { + if ($(_obj).is(':checked')) { + var _row_data = host_table.get_row(_obj); + var data = {host_id: _row_data.host_id, row_id: _row_data.ywl_row_id}; + _data_list.push(data); + } + }); + if (_data_list.length === 0) { + ywl.notify_error('请选择要批量设置分组的主机!'); + return; + } + g_join_group_dlg.show(_data_list); + }); - // 将刷新按钮点击事件绑定到表格的重新加载函数上,这样,点击刷新就导致表格数据重新加载。 - $(tbl_dom_id + " [ywl-filter='reload']").click(host_table.reload); + // 将刷新按钮点击事件绑定到表格的重新加载函数上,这样,点击刷新就导致表格数据重新加载。 + $(tbl_dom_id + " [ywl-filter='reload']").click(host_table.reload); - cb_stack - .add(host_table.load_data) - .add(host_table.init) - .exec(); + cb_stack + .add(host_table.load_data) + .add(host_table.init) + .exec(); }; // 扩展/重载表格的功能 ywl.on_host_table_created = function (tbl) { - tbl.on_cell_created = function (row_id, col_key, cell_obj) { - var row_data; + tbl.on_cell_created = function (row_id, col_key, cell_obj) { + var row_data; - if (col_key == 'select_all') { - // 选择 - $('#host-select-' + row_id).click(function () { - var _all_checked = true; - var _objs = $(tbl.selector + ' tbody').find('[data-check-box]'); - $.each(_objs, function (i, _obj) { - if (!$(_obj).is(':checked')) { - _all_checked = false; - return false; - } - }); + if (col_key == 'select_all') { + // 选择 + $('#host-select-' + row_id).click(function () { + var _all_checked = true; + var _objs = $(tbl.selector + ' tbody').find('[data-check-box]'); + $.each(_objs, function (i, _obj) { + if (!$(_obj).is(':checked')) { + _all_checked = false; + return false; + } + }); - var select_all_dom = $('#host-select-all'); - if (_all_checked) { - select_all_dom.prop('checked', true); - } else { - select_all_dom.prop('checked', false); - } - }); + var select_all_dom = $('#host-select-all'); + if (_all_checked) { + select_all_dom.prop('checked', true); + } else { + select_all_dom.prop('checked', false); + } + }); - } else if (col_key == 'host_id') { - // 为主机描述绑定点击事件 - var _link = $(cell_obj).find(" [ywl-host-desc]"); - _link.click(function () { - var row_data = tbl.get_row(row_id); - ywl.create_dlg_modify_host_desc(tbl, row_data.ywl_row_id, row_data.host_id, row_data.host_ip, row_data.host_desc).show(_link); - }); - } else if (col_key == 'action') { - row_data = tbl.get_row(row_id); - //console.log('row_data', row_data); - $(cell_obj).find('[ywl-btn-edit]').click(function () { - g_dlg_edit_host.update_show(row_id, row_data); - }); - $(cell_obj).find('[ywl-btn-user-edit]').click(function () { - g_dlg_edit_host_user.update_show(row_id, row_data); - }); + } else if (col_key == 'host_id') { + // 为主机描述绑定点击事件 + var _link = $(cell_obj).find(" [ywl-host-desc]"); + _link.click(function () { + var row_data = tbl.get_row(row_id); + ywl.create_dlg_modify_host_desc(tbl, row_data.ywl_row_id, row_data.host_id, row_data.host_ip, row_data.host_desc).show(_link); + }); + } else if (col_key == 'action') { + row_data = tbl.get_row(row_id); + //console.log('row_data', row_data); + $(cell_obj).find('[ywl-btn-edit]').click(function () { + g_dlg_edit_host.update_show(row_id, row_data); + }); + $(cell_obj).find('[ywl-btn-user-edit]').click(function () { + g_dlg_edit_host_user.update_show(row_id, row_data); + }); - $(cell_obj).find('[ywl-btn-lock]').click(function () { - var host_id = row_data.host_id; - var host_lock = row_data.host_lock; - var message = ''; - if (host_lock === 0) { - host_lock = 1; - message = '确认要锁定该主机吗?'; - } else { - host_lock = 0; - message = '确认要解锁该主机吗?'; - } - var _fn_sure = function (cb_stack, cb_args) { - ywl.ajax_post_json('/host/lock-host', {host_id: host_id, lock: host_lock}, - function (ret) { - var update_args = {host_lock: host_lock}; - tbl.update_row(row_id, update_args); - ywl.notify_success('操作成功'); - }, - function () { - ywl.notify_error('操作失败'); - } - ); - }; - var cb_stack = CALLBACK_STACK.create(); + $(cell_obj).find('[ywl-btn-lock]').click(function () { + var host_id = row_data.host_id; + var host_lock = row_data.host_lock; + var message = ''; + if (host_lock === 0) { + host_lock = 1; + message = '确认要锁定该主机吗?'; + } else { + host_lock = 0; + message = '确认要解锁该主机吗?'; + } + var _fn_sure = function (cb_stack, cb_args) { + ywl.ajax_post_json('/host/lock-host', {host_id: host_id, lock: host_lock}, + function (ret) { + var update_args = {host_lock: host_lock}; + tbl.update_row(row_id, update_args); + ywl.notify_success('操作成功'); + }, + function () { + ywl.notify_error('操作失败'); + } + ); + }; + var cb_stack = CALLBACK_STACK.create(); - ywl.dlg_confirm(cb_stack, - { - msg: '

' + message + '

', - fn_yes: _fn_sure - }); + ywl.dlg_confirm(cb_stack, + { + msg: '

' + message + '

', + fn_yes: _fn_sure + }); - }); + }); - $(cell_obj).find('[ywl-btn-delete]').click(function () { - var host_id = row_data.host_id; - var _fn_sure = function (cb_stack, cb_args) { - var host_list = []; - host_list.push(host_id); - ywl.ajax_post_json('/host/delete-host', {host_list: host_list}, - function (ret) { - tbl.remove_row(row_id); - ywl.notify_success('操作成功'); - }, - function () { - ywl.notify_error('操作失败'); - } - ); - }; - var cb_stack = CALLBACK_STACK.create(); + $(cell_obj).find('[ywl-btn-delete]').click(function () { + var host_id = row_data.host_id; + var _fn_sure = function (cb_stack, cb_args) { + var host_list = []; + host_list.push(host_id); + ywl.ajax_post_json('/host/delete-host', {host_list: host_list}, + function (ret) { + tbl.remove_row(row_id); + ywl.notify_success('操作成功'); + }, + function () { + ywl.notify_error('操作失败'); + } + ); + }; + var cb_stack = CALLBACK_STACK.create(); - ywl.dlg_confirm(cb_stack, - { - msg: '

注意:移除操作不可恢复!!

如果您只是希望临时禁用此主机,可以执行“锁定”操作!

您确定要移除此远程主机吗?

', - fn_yes: _fn_sure - }); + ywl.dlg_confirm(cb_stack, + { + msg: '

注意:移除操作不可恢复!!

如果您只是希望临时禁用此主机,可以执行“锁定”操作!

您确定要移除此远程主机吗?

', + fn_yes: _fn_sure + }); - }); + }); - } else if (col_key == 'auth_list') { - row_data = tbl.get_row(row_id); - $(cell_obj).find('[data-action="remote"]').click(function () { - var ts_rdp_port = ywl.page_options.core.rdp_port; - var ts_ssh_port = ywl.page_options.core.ssh_port; - var ts_telnet_port = ywl.page_options.core.telnet_port; - var host_ip = row_data.host_ip; - var host_port = 0; - var pro_type = parseInt($(this).attr('data-protocol')); - var pro_sub = parseInt($(this).attr('data-sub-protocol')); - var host_auth_id = parseInt($(this).attr('host-auth-id')); - var size = 0; - var rdp_console = 0; - var pro_port; - if (typeof row_data.pro_port === 'string') { - pro_port = $.parseJSON(row_data.pro_port); - } else { - pro_port = row_data.pro_port; - } + } else if (col_key === 'auth_list') { + row_data = tbl.get_row(row_id); + $(cell_obj).find('[data-action="remote"]').click(function () { + var ts_rdp_port = ywl.page_options.core.rdp_port; + var ts_ssh_port = ywl.page_options.core.ssh_port; + var ts_telnet_port = ywl.page_options.core.telnet_port; + var host_ip = row_data.host_ip; + var host_port = 0; + var pro_type = parseInt($(this).attr('data-protocol')); + var pro_sub = parseInt($(this).attr('data-sub-protocol')); + var host_auth_id = parseInt($(this).attr('host-auth-id')); + var size = 0; + var rdp_console = 0; + var pro_port; + if (typeof row_data.pro_port === 'string') { + pro_port = $.parseJSON(row_data.pro_port); + } else { + pro_port = row_data.pro_port; + } - if (pro_type == 1) { - host_port = ts_rdp_port; - size = parseInt($(this).parent().parent().find('#dlg-rdp-size select').val()) - if ($(this).parent().parent().find('#dlg-action-rdp-console').is(':checked')) { - rdp_console = 1; - } else { - rdp_console = 0; - } - } else if (pro_type == 2) { - host_port = ts_ssh_port; - } else if (pro_type == 3) { - host_port = ts_telnet_port; - } else { - ywl.notify_error("未知的服务器端口号" + pro_port); - return; - } - var args = {}; - args.host_auth_id = host_auth_id; - args.server_ip = ywl.server_ip; - args.server_port = host_port; - args.pro_type = pro_type; - args.pro_sub = pro_sub; - args.host_ip = host_ip; - args.console = rdp_console; - args.size = size; - to_admin_teleport( - '/host/admin-get-session-id', - args, - function () { - console.log('远程连接建立成功!') - }, - function (code, error) { - if (code == TPE_NO_ASSIST) - g_assist.alert_assist_not_found(); - else { - ywl.notify_error(error); - console.log('error:', error) - } - } - ); - }); + if (pro_type === PROTOCOL_TYPE_RDP) { + host_port = ts_rdp_port; + size = parseInt($(this).parent().parent().find('#dlg-rdp-size select').val()) + if ($(this).parent().parent().find('#dlg-action-rdp-console').is(':checked')) { + rdp_console = 1; + } else { + rdp_console = 0; + } + } else if (pro_type === PROTOCOL_TYPE_SSH) { + host_port = ts_ssh_port; + } else if (pro_type === PROTOCOL_TYPE_TELNET) { + host_port = ts_telnet_port; + } else { + ywl.notify_error("未知的服务器端口号" + pro_port); + return; + } + var args = {}; + args.host_auth_id = host_auth_id; + args.server_ip = ywl.server_ip; + args.server_port = host_port; + args.pro_type = pro_type; + args.pro_sub = pro_sub; + args.host_ip = host_ip; + args.console = rdp_console; + args.size = size; + to_admin_teleport( + '/host/admin-get-session-id', + args, + function () { + console.log('远程连接建立成功!') + }, + function (code, error) { + if (code === TPE_NO_ASSIST) + g_assist.alert_assist_not_found(); + else { + ywl.notify_error(error); + console.log('error:', error) + } + } + ); + }); - $(cell_obj).find('[data-action="remote-rdp-advance"]').click(function () { - ywl.create_dlg_show_rdp_advance(row_data).show($(this)); - }); - } - }; + $(cell_obj).find('[data-action="remote-rdp-advance"]').click(function () { + ywl.create_dlg_show_rdp_advance(row_data).show($(this)); + }); + } + }; - // 重载表格渲染器的部分渲染方式,加入本页面相关特殊操作 - tbl.on_render_created = function (render) { + // 重载表格渲染器的部分渲染方式,加入本页面相关特殊操作 + tbl.on_render_created = function (render) { - render.host_id = function (row_id, fields) { - var ret = []; + render.host_id = function (row_id, fields) { + var ret = []; // ret.push('' + fields.id + '' + fields.host_port + ''); - ret.push('' + fields.id + ':' + fields.host_port + ''); - ret.push('' + fields.host_desc + ''); - return ret.join(''); - }; + ret.push('' + fields.id + ':' + fields.host_port + ''); + ret.push('' + fields.host_desc + ''); + return ret.join(''); + }; - render.protocol = function (row_id, fields) { - var ret = []; - switch (fields.protocol) { - case 1: - return 'RDP:' + fields.host_port + ''; - case 2: - return 'SSH:' + fields.host_port + ''; - case 3: - return 'TELNET:' + fields.host_port + ''; - default: - return '未知'; - } - }; - render.auth_list = function (row_id, fields) { + render.protocol = function (row_id, fields) { + var ret = []; + switch (fields.protocol) { + case 1: + return 'RDP:' + fields.host_port + ''; + case 2: + return 'SSH:' + fields.host_port + ''; + case 3: + return 'TELNET:' + fields.host_port + ''; + default: + return '未知'; + } + }; + render.auth_list = function (row_id, fields) { - var auth_list = fields.auth_list; - var ret = []; - if (auth_list.length == 0) { - ret.push('尚未添加系统用户'); - return ret.join(''); - } - var protocol = fields.protocol; - for (var i = 0; i < auth_list.length; i++) { - var auth = auth_list[i]; + var auth_list = fields.auth_list; + var ret = []; + if (auth_list.length === 0) { + ret.push('尚未添加系统用户'); + return ret.join(''); + } + var protocol = fields.protocol; + for (var i = 0; i < auth_list.length; i++) { + var auth = auth_list[i]; - ret.push('
'); - ret.push('
    '); + ret.push('
    '); + ret.push('
      '); - if (auth.user_name.length > 0) - ret.push('
    • ' + auth.user_name + '
    • '); - else - ret.push('
    • - 未指定 -
    • '); + if (auth.user_name.length > 0) + ret.push('
    • ' + auth.user_name + '
    • '); + else + ret.push('
    • - 未指定 -
    • '); - if (auth.auth_mode == AUTH_TYPE_PASSWORD) { - ret.push('
    • 密码
    • '); - } else if (auth.auth_mode == AUTH_TYPE_SSHKEY) { - ret.push('
    • 私钥
    • '); - } else if (auth.auth_mode == AUTH_NONE) { - ret.push('
    • '); - } else { - ret.push('
    • 未知
    • '); - } + if (auth.auth_mode === AUTH_TYPE_PASSWORD) { + ret.push('
    • 密码
    • '); + } else if (auth.auth_mode === AUTH_TYPE_SSHKEY) { + ret.push('
    • 私钥
    • '); + } else if (auth.auth_mode === AUTH_NONE) { + ret.push('
    • '); + } else { + ret.push('
    • 未知
    • '); + } - switch (protocol) { - case PROTOCOL_TYPE_RDP: - ret.push('
    • RDP
    • '); - ret.push('
    • '); - ret.push('
    • '); - break; - case PROTOCOL_TYPE_SSH: - ret.push('
    • SSH
    • '); - ret.push('
    • SFTP
    • '); - break; - case PROTOCOL_TYPE_TELNET: - ret.push('
    • TELNET
    • '); - break; - default: - ret.push('
    • 未知协议类型
    • '); - } + switch (protocol) { + case PROTOCOL_TYPE_RDP: + ret.push('
    • RDP
    • '); + ret.push('
    • '); + ret.push('
    • '); + break; + case PROTOCOL_TYPE_SSH: + ret.push('
    • SSH
    • '); + ret.push('
    • SFTP
    • '); + break; + case PROTOCOL_TYPE_TELNET: + ret.push('
    • TELNET
    • '); + break; + default: + ret.push('
    • 未知协议类型
    • '); + } - ret.push('
    '); - ret.push('
    '); - } + ret.push('
'); + ret.push('
'); + } - return ret.join(''); - }; - render.host_lock = function (row_id, fields) { - switch (fields.host_lock) { - case 0: - return '正常'; - case 1: - return '禁止连接'; - default: - return '未知'; - } - }; - render.make_check_box = function (row_id, fields) { - return ''; - }; - render.make_action_btn = function (row_id, fields) { - var ret = []; - ret.push('
'); - ret.push(' 编辑'); + return ret.join(''); + }; + render.host_lock = function (row_id, fields) { + switch (fields.host_lock) { + case 0: + return '正常'; + case 1: + return '禁止连接'; + default: + return '未知'; + } + }; + render.make_check_box = function (row_id, fields) { + return ''; + }; + render.make_action_btn = function (row_id, fields) { + var ret = []; + ret.push('
'); + ret.push(' 编辑'); // if (fields.host_lock === 0) // ret.push(' 锁定'); // else // ret.push(' 解锁'); - ret.push(' 移除'); + ret.push(' 移除'); // ret.push(' 远程'); - ret.push('
'); - return ret.join(''); - }; - render.make_user_btn = function (row_id, fields) { - var ret = []; - ret.push('
'); - ret.push('用户管理'); - ret.push('
'); - return ret.join(''); - } - }; + ret.push('
'); + return ret.join(''); + }; + render.make_user_btn = function (row_id, fields) { + var ret = []; + ret.push('
'); + ret.push('用户管理'); + ret.push('
'); + return ret.join(''); + } + }; }; ywl.on_host_table_header_created = function (tbl) { - $('#host-select-all').click(function () { - var _is_selected = $(this).is(':checked'); - $(tbl.selector + ' tbody').find('[data-check-box]').prop('checked', _is_selected); - }); + $('#host-select-all').click(function () { + var _is_selected = $(this).is(':checked'); + $(tbl.selector + ' tbody').find('[data-check-box]').prop('checked', _is_selected); + }); }; ywl.create_host_edit_dlg = function (tbl) { - var dlg_edit_host = {}; - dlg_edit_host.dom_id = "#dialog-host-edit"; - dlg_edit_host.update = 0; - dlg_edit_host.tbl = tbl; - dlg_edit_host.host_id = 0; - dlg_edit_host.row_id = ""; - dlg_edit_host.sys_type = 1; - dlg_edit_host.group_id = 0; - dlg_edit_host.group_name = '默认分组'; - dlg_edit_host.host_desc = ''; - dlg_edit_host.ip = ''; - dlg_edit_host.protocol = 0; - dlg_edit_host.host_port = 0; + var dlg_edit_host = {}; + dlg_edit_host.dom_id = "#dialog-host-edit"; + dlg_edit_host.update = 0; + dlg_edit_host.tbl = tbl; + dlg_edit_host.host_id = 0; + dlg_edit_host.row_id = ""; + dlg_edit_host.sys_type = 1; + dlg_edit_host.group_id = 0; + dlg_edit_host.group_name = '默认分组'; + dlg_edit_host.host_desc = ''; + dlg_edit_host.ip = ''; + dlg_edit_host.protocol = 0; + dlg_edit_host.host_port = 0; // dlg_edit_host.pro_port = {}; - dlg_edit_host.init = function () { - $('#auth-sys-type').change(dlg_edit_host.on_sys_type_change); - $('#host-protocol-type').change(dlg_edit_host.on_protocol_change); + dlg_edit_host.init = function () { + $('#auth-sys-type').change(dlg_edit_host.on_sys_type_change); + $('#host-protocol-type').change(dlg_edit_host.on_protocol_change); // $('#auth-protocol-type').change(dlg_edit_host.on_protocol_change); // $('#auth-auth-type').change(dlg_edit_host.on_auth_type_change); @@ -616,30 +616,30 @@ ywl.create_host_edit_dlg = function (tbl) { // $("#dlg-edit-host-rdp-port").change(dlg_edit_host.on_rdp_port); - var obj_group = $('#dlg-edit-host-group'); - $('#dlg-edit-host-group').change(dlg_edit_host.on_group_change); + var obj_group = $('#dlg-edit-host-group'); + obj_group.change(dlg_edit_host.on_group_change); - var i, cnt; - // 分组选择 - var html_group = []; - html_group.push(''); - for (i = 0, cnt = g_group_list.length; i < cnt; ++i) { - html_group.push(''); - } - obj_group.append($(html_group.join(''))); - // 对话框按钮事件绑定 + var i, cnt; + // 分组选择 + var html_group = []; + html_group.push(''); + for (i = 0, cnt = g_group_list.length; i < cnt; ++i) { + html_group.push(''); + } + obj_group.append($(html_group.join(''))); + // 对话框按钮事件绑定 - $("#host-btn-save").click(function () { - if (!dlg_edit_host.check_args()) - return; - //console.log("dlg_edit_host"); - if (dlg_edit_host.update == 1) { - dlg_edit_host.update_post(); - } else { - dlg_edit_host.create_post(); - } + $("#host-btn-save").click(function () { + if (!dlg_edit_host.check_args()) + return; + //console.log("dlg_edit_host"); + if (dlg_edit_host.update === 1) { + dlg_edit_host.update_post(); + } else { + dlg_edit_host.create_post(); + } // - }); + }); // // SSH密钥选择 // var html_sshkey = []; @@ -666,837 +666,828 @@ ywl.create_host_edit_dlg = function (tbl) { // $('#dialog_test').modal({backdrop: 'static'}); // }); - }; - dlg_edit_host.on_sys_type_change = function () { - dlg_edit_host.sys_type = $('#auth-sys-type').val(); - if (dlg_edit_host.sys_type == OS_TYPE_WINDOWS && dlg_edit_host.protocol == 0) - dlg_edit_host.protocol = PROTOCOL_TYPE_RDP; - else if (dlg_edit_host.sys_type == OS_TYPE_LINUX && dlg_edit_host.protocol == 0) - dlg_edit_host.protocol = PROTOCOL_TYPE_SSH; + }; + dlg_edit_host.on_sys_type_change = function () { + dlg_edit_host.sys_type = parseInt($('#auth-sys-type').val()); + console.log('sys-type', dlg_edit_host.sys_type, 'protocol:', dlg_edit_host.protocol); + if (dlg_edit_host.sys_type === OS_TYPE_WINDOWS) {// && dlg_edit_host.protocol === 0) { + dlg_edit_host.protocol = PROTOCOL_TYPE_RDP; + console.log('--1', dlg_edit_host.protocol); + } + else if (dlg_edit_host.sys_type === OS_TYPE_LINUX) {// && dlg_edit_host.protocol === 0) { + dlg_edit_host.protocol = PROTOCOL_TYPE_SSH; + console.log('--2', dlg_edit_host.protocol); + } - $('#host-protocol-type').val(dlg_edit_host.protocol); + $('#host-protocol-type').val(dlg_edit_host.protocol); - dlg_edit_host.on_protocol_change(); - }; + dlg_edit_host.on_protocol_change(); + }; - dlg_edit_host.on_protocol_change = function () { - dlg_edit_host.protocol = $('#host-protocol-type').val(); - if (dlg_edit_host.protocol == PROTOCOL_TYPE_RDP) - $('#dlg-edit-host-protocol-port').val('3389'); - else if (dlg_edit_host.protocol == PROTOCOL_TYPE_SSH) - $('#dlg-edit-host-protocol-port').val('22'); - else if (dlg_edit_host.protocol == PROTOCOL_TYPE_TELNET) - $('#dlg-edit-host-protocol-port').val('23'); - else - $('#dlg-edit-host-protocol-port').val(0); - }; + dlg_edit_host.on_protocol_change = function () { + dlg_edit_host.protocol = parseInt($('#host-protocol-type').val()); + console.log('xx', dlg_edit_host.protocol); + if (dlg_edit_host.protocol === PROTOCOL_TYPE_RDP) + $('#dlg-edit-host-protocol-port').val('3389'); + else if (dlg_edit_host.protocol === PROTOCOL_TYPE_SSH) + $('#dlg-edit-host-protocol-port').val('22'); + else if (dlg_edit_host.protocol === PROTOCOL_TYPE_TELNET) + $('#dlg-edit-host-protocol-port').val('23'); + else + $('#dlg-edit-host-protocol-port').val(0); + }; - dlg_edit_host.on_group_change = function () { - //console.log('group-change.'); - var obj = $('#group-host-group'); - dlg_edit_host.group_id = parseInt(obj.val()); - dlg_edit_host.group_name = obj.find('option:selected').text(); - }; + dlg_edit_host.on_group_change = function () { + //console.log('group-change.'); + var obj = $('#group-host-group'); + dlg_edit_host.group_id = parseInt(obj.val()); + dlg_edit_host.group_name = obj.find('option:selected').text(); + }; - dlg_edit_host.init_dlg = function (row_id, args) { - if (dlg_edit_host.update === 1) { - dlg_edit_host.sys_type = args.host_sys_type; - dlg_edit_host.ip = args.host_ip; - dlg_edit_host.host_id = args.host_id; - dlg_edit_host.group_id = args.group_id; - dlg_edit_host.host_desc = args.host_desc; - dlg_edit_host.protocol = args.protocol; - dlg_edit_host.host_port = args.host_port; - dlg_edit_host.init_fields(); - dlg_edit_host.row_id = row_id; - } else { - // 新建主机默认设置 - dlg_edit_host.host_id = 0; - dlg_edit_host.row_id = ""; - dlg_edit_host.sys_type = OS_TYPE_LINUX; - dlg_edit_host.ip = ''; - dlg_edit_host.group_id = 0; - dlg_edit_host.group_name = '默认分组'; - dlg_edit_host.host_desc = ''; - dlg_edit_host.protocol = 0; - dlg_edit_host.host_port = 0; - dlg_edit_host.init_fields(); - } - }; + dlg_edit_host.init_dlg = function (row_id, args) { + if (dlg_edit_host.update === 1) { + dlg_edit_host.sys_type = args.host_sys_type; + dlg_edit_host.ip = args.host_ip; + dlg_edit_host.host_id = args.host_id; + dlg_edit_host.group_id = args.group_id; + dlg_edit_host.host_desc = args.host_desc; + dlg_edit_host.protocol = args.protocol; + dlg_edit_host.host_port = args.host_port; + dlg_edit_host.init_fields(); + dlg_edit_host.row_id = row_id; + } else { + // 新建主机默认设置 + dlg_edit_host.host_id = 0; + dlg_edit_host.row_id = ""; + dlg_edit_host.sys_type = OS_TYPE_LINUX; + dlg_edit_host.ip = ''; + dlg_edit_host.group_id = 0; + dlg_edit_host.group_name = '默认分组'; + dlg_edit_host.host_desc = ''; + dlg_edit_host.protocol = 0; + dlg_edit_host.host_port = 0; + dlg_edit_host.init_fields(); + } + }; - dlg_edit_host.clear_fields = function () { - $("#auth-host-ip").val(''); - $("#auth-host-desc").val(''); - $('#auth-sys-type').val(OS_TYPE_LINUX); - }; + dlg_edit_host.clear_fields = function () { + $("#auth-host-ip").val(''); + $("#auth-host-desc").val(''); + $('#auth-sys-type').val(OS_TYPE_LINUX); + }; - dlg_edit_host.init_fields = function () { - dlg_edit_host.clear_fields(); + dlg_edit_host.init_fields = function () { + dlg_edit_host.clear_fields(); - $('#auth-sys-type').val(dlg_edit_host.sys_type); - dlg_edit_host.on_sys_type_change(); + $('#auth-sys-type').val(dlg_edit_host.sys_type); + dlg_edit_host.on_sys_type_change(); - $("#auth-host-ip").val(dlg_edit_host.ip); - $("#auth-host-desc").val(dlg_edit_host.host_desc); + $("#auth-host-ip").val(dlg_edit_host.ip); + $("#auth-host-desc").val(dlg_edit_host.host_desc); - var obj_group = $('#dlg-edit-host-group'); - obj_group.val(dlg_edit_host.group_id); + var obj_group = $('#dlg-edit-host-group'); + obj_group.val(dlg_edit_host.group_id); - if (dlg_edit_host.host_port != 0) { - $("#dlg-edit-host-protocol-port").val(dlg_edit_host.host_port); - } - }; + if (dlg_edit_host.host_port !== 0) { + $("#dlg-edit-host-protocol-port").val(dlg_edit_host.host_port); + } + }; - dlg_edit_host.check_args = function () { - dlg_edit_host.sys_type = parseInt($('#auth-sys-type').val()); - var obj_group = $('#dlg-edit-host-group'); - dlg_edit_host.group_id = parseInt(obj_group.val()); - dlg_edit_host.group_name = obj_group.find('option:selected').text(); - dlg_edit_host.ip = $("#auth-host-ip").val(); + dlg_edit_host.check_args = function () { + dlg_edit_host.sys_type = parseInt($('#auth-sys-type').val()); + var obj_group = $('#dlg-edit-host-group'); + dlg_edit_host.group_id = parseInt(obj_group.val()); + dlg_edit_host.group_name = obj_group.find('option:selected').text(); + dlg_edit_host.ip = $("#auth-host-ip").val(); - dlg_edit_host.host_desc = $("#auth-host-desc").val(); + dlg_edit_host.host_desc = $("#auth-host-desc").val(); - dlg_edit_host.host_port = $("#dlg-edit-host-protocol-port").val(); - if (dlg_edit_host.ip.length == 0) { - ywl.notify_error('请设定远程主机的地址!'); - return false; - } + dlg_edit_host.host_port = $("#dlg-edit-host-protocol-port").val(); + if (dlg_edit_host.ip.length === 0) { + ywl.notify_error('请设定远程主机的地址!'); + return false; + } - if (dlg_edit_host.host_port.length == 0) { - ywl.notify_error('请设定协议端口号!'); - return false; - } - return true; - }; + if (dlg_edit_host.host_port.length === 0) { + ywl.notify_error('请设定协议端口号!'); + return false; + } + return true; + }; - dlg_edit_host.update_show = function (row_id, args) { - dlg_edit_host.update = 1; - dlg_edit_host.init_dlg(row_id, args); - $(dlg_edit_host.dom_id).modal({backdrop: 'static'}); - }; + dlg_edit_host.update_show = function (row_id, args) { + dlg_edit_host.update = 1; + dlg_edit_host.init_dlg(row_id, args); + $(dlg_edit_host.dom_id).modal({backdrop: 'static'}); + }; - dlg_edit_host.create_show = function () { - dlg_edit_host.update = 0; - dlg_edit_host.init_dlg(); - $(dlg_edit_host.dom_id).modal({backdrop: 'static'}); - }; + dlg_edit_host.create_show = function () { + dlg_edit_host.update = 0; + dlg_edit_host.init_dlg(); + $(dlg_edit_host.dom_id).modal({backdrop: 'static'}); + }; - dlg_edit_host.hide = function () { - $(dlg_edit_host.dom_id).modal('hide'); - }; + dlg_edit_host.hide = function () { + $(dlg_edit_host.dom_id).modal('hide'); + }; - dlg_edit_host.update_post = function () { - var host_sys_type = parseInt(dlg_edit_host.sys_type); - var protocol = parseInt(dlg_edit_host.protocol); - var host_port = parseInt(dlg_edit_host.host_port); - var host_ip = dlg_edit_host.ip; - var host_id = dlg_edit_host.host_id; - var args = { - group_id: dlg_edit_host.group_id, - host_sys_type: host_sys_type, - host_ip: host_ip, - protocol: protocol, - host_port: host_port, - host_desc: dlg_edit_host.desc - }; - ywl.ajax_post_json('/host/update', {host_id: host_id, kv: args}, - function (ret) { - var update_args = { - host_ip: dlg_edit_host.ip, - group_name: dlg_edit_host.group_name, - group_id: dlg_edit_host.group_id, - host_desc: dlg_edit_host.host_desc, - host_sys_type: dlg_edit_host.sys_type, - protocol: protocol, - host_port: host_port - }; + dlg_edit_host.update_post = function () { + var host_sys_type = parseInt(dlg_edit_host.sys_type); + var protocol = parseInt(dlg_edit_host.protocol); + var host_port = parseInt(dlg_edit_host.host_port); + var host_ip = dlg_edit_host.ip; + var host_id = dlg_edit_host.host_id; + var args = { + group_id: dlg_edit_host.group_id, + host_sys_type: host_sys_type, + host_ip: host_ip, + protocol: protocol, + host_port: host_port, + host_desc: dlg_edit_host.desc + }; + ywl.ajax_post_json('/host/update', {host_id: host_id, kv: args}, + function (ret) { + var update_args = { + host_ip: dlg_edit_host.ip, + group_name: dlg_edit_host.group_name, + group_id: dlg_edit_host.group_id, + host_desc: dlg_edit_host.host_desc, + host_sys_type: dlg_edit_host.sys_type, + protocol: protocol, + host_port: host_port + }; - dlg_edit_host.tbl.update_row(dlg_edit_host.row_id, update_args); - ywl.notify_success('主机 ' + dlg_edit_host.ip + ' 的认证信息已保存!'); - dlg_edit_host.hide(); - }, - function () { - ywl.notify_error('主机 ' + self.host_ip + ' 更新失败!', ''); - } - ); - }; + dlg_edit_host.tbl.update_row(dlg_edit_host.row_id, update_args); + ywl.notify_success('主机 ' + dlg_edit_host.ip + ' 的认证信息已保存!'); + dlg_edit_host.hide(); + }, + function () { + ywl.notify_error('主机 ' + self.host_ip + ' 更新失败!', ''); + } + ); + }; - dlg_edit_host.create_post = function () { - var protocol = parseInt(dlg_edit_host.protocol); - var host_port = parseInt(dlg_edit_host.host_port); + dlg_edit_host.create_post = function () { + var protocol = parseInt(dlg_edit_host.protocol); + var host_port = parseInt(dlg_edit_host.host_port); - var args = { - host_ip: dlg_edit_host.ip, - host_port: host_port, - protocol: protocol, - host_sys_type: dlg_edit_host.sys_type, - group_id: dlg_edit_host.group_id, - host_desc: dlg_edit_host.host_desc - }; + var args = { + host_ip: dlg_edit_host.ip, + host_port: host_port, + protocol: protocol, + host_sys_type: dlg_edit_host.sys_type, + group_id: dlg_edit_host.group_id, + host_desc: dlg_edit_host.host_desc + }; - ywl.ajax_post_json('/host/add-host', args, - function (ret) { - if (ret.code == 0) { - dlg_edit_host.tbl.reload(); - ywl.notify_success('主机 ' + dlg_edit_host.ip + ' 信息已添加!'); - dlg_edit_host.hide(); - } - else { - if (ret.code == -100) { - ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 已经添加,请不要重复添加主机!', ''); - } else { - ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 信息保存失败!' + ret.code, ''); - } + ywl.ajax_post_json('/host/add-host', args, + function (ret) { + if (ret.code === 0) { + dlg_edit_host.tbl.reload(); + ywl.notify_success('主机 ' + dlg_edit_host.ip + ' 信息已添加!'); + dlg_edit_host.hide(); + } + else { + if (ret.code === -100) { + ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 已经添加,请不要重复添加主机!', ''); + } else { + ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 信息保存失败!' + ret.code, ''); + } - } - }, - function () { - ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 信息保存失败!', ''); - } - ); - }; + } + }, + function () { + ywl.notify_error('主机 ' + dlg_edit_host.ip + ' 信息保存失败!', ''); + } + ); + }; - return dlg_edit_host; + return dlg_edit_host; }; ywl.create_host_user_edit_dlg = function (tbl) { - var dlg_user_edit_host = {}; - dlg_user_edit_host.dom_id = "#dialog-host-user-edit"; - dlg_user_edit_host.update = 0; - dlg_user_edit_host.tbl = tbl; - dlg_user_edit_host.host_id = 0; - dlg_user_edit_host.row_id = ""; - dlg_user_edit_host.host_ip = ''; - dlg_user_edit_host.pro_port = {}; + var dlg_user_edit_host = {}; + dlg_user_edit_host.dom_id = "#dialog-host-user-edit"; + dlg_user_edit_host.update = 0; + dlg_user_edit_host.tbl = tbl; + dlg_user_edit_host.host_id = 0; + dlg_user_edit_host.row_id = ""; + dlg_user_edit_host.host_ip = ''; + dlg_user_edit_host.pro_port = {}; - dlg_user_edit_host.auth_list = []; + dlg_user_edit_host.auth_list = []; - dlg_user_edit_host.init = function () { + dlg_user_edit_host.init = function () { - $("#host-user-btn-save").click(function () { - dlg_user_edit_host.hide(); - }); + $("#host-user-btn-save").click(function () { + dlg_user_edit_host.hide(); + }); - }; + }; - dlg_user_edit_host.create_user_html = function (host_auth_id, index, user_name, pro_name, auth_name) { - if(user_name.length == 0) - user_name = '- 未指定 -'; - var html = ""; - html += '
'; - html += '
    '; - html += '
  • ' + user_name + '
  • '; - html += '
  • ' + pro_name + '
  • '; - html += '
  • ' + auth_name + '
  • '; - html += '
  • '; - html += ' '; - html += '
  • '; - html += '
  • '; - html += ' '; - html += '
  • '; - html += '
'; - html += '
'; - return html; - }; - dlg_user_edit_host.sync_user_info = function (host_id) { - ywl.ajax_post_json('/host/sys-user/list', {host_id: host_id}, - function (ret) { + dlg_user_edit_host.create_user_html = function (host_auth_id, index, user_name, pro_name, auth_name) { + if (user_name.length === 0) + user_name = '- 未指定 -'; + var html = []; + html.push('
    '); + html.push('
  • ' + user_name + '
  • '); + html.push('
  • ' + pro_name + '
  • '); + html.push('
  • ' + auth_name + '
  • '); + html.push('
  • '); + html.push(''); + html.push('
  • '); + html.push(''); + html.push('
'); + return html.join(''); + }; + dlg_user_edit_host.sync_user_info = function (host_id) { + ywl.ajax_post_json('/host/sys-user/list', {host_id: host_id}, + function (ret) { var data = ret.data; - dlg_user_edit_host.auth_list = data; - var update_args = { - auth_list: dlg_user_edit_host.auth_list - }; + dlg_user_edit_host.auth_list = data; + var update_args = { + auth_list: dlg_user_edit_host.auth_list + }; - dlg_user_edit_host.tbl.update_row(dlg_user_edit_host.row_id, update_args); - var row_data = tbl.get_row(dlg_user_edit_host.row_id); - var protocol = row_data.protocol; - var arr = dlg_user_edit_host.auth_list; - var html = ""; + dlg_user_edit_host.tbl.update_row(dlg_user_edit_host.row_id, update_args); + var row_data = tbl.get_row(dlg_user_edit_host.row_id); + var protocol = row_data.protocol; + var arr = dlg_user_edit_host.auth_list; + var html = ""; - for (var i = 0; i < arr.length; i++) { + for (var i = 0; i < arr.length; i++) { - var user_name = arr[i].user_name; - var host_auth_id = arr[i].host_auth_id; - var pro_name = '未知'; - if (protocol == PROTOCOL_TYPE_RDP) { - pro_name = 'RDP'; - } else if (protocol == PROTOCOL_TYPE_SSH) { - pro_name = 'SSH'; - } else if (protocol == PROTOCOL_TYPE_TELNET) { - pro_name = 'TELNET'; - } - var auth_name = "未知"; - if (arr[i].auth_mode == AUTH_NONE) { - auth_name = '无'; - } else if (arr[i].auth_mode == AUTH_TYPE_PASSWORD) { - auth_name = '密码'; - } else if (arr[i].auth_mode == AUTH_TYPE_SSHKEY) { - auth_name = '私钥'; - } - html += dlg_user_edit_host.create_user_html(host_auth_id, i, user_name, pro_name, auth_name); - } - html += ''; - $("#sys-user-list").html(html); + var user_name = arr[i].user_name; + var host_auth_id = arr[i].host_auth_id; + var pro_name = '未知'; + if (protocol === PROTOCOL_TYPE_RDP) { + pro_name = 'RDP'; + } else if (protocol === PROTOCOL_TYPE_SSH) { + pro_name = 'SSH'; + } else if (protocol === PROTOCOL_TYPE_TELNET) { + pro_name = 'TELNET'; + } + var auth_name = "未知"; + if (arr[i].auth_mode === AUTH_NONE) { + auth_name = '无'; + } else if (arr[i].auth_mode === AUTH_TYPE_PASSWORD) { + auth_name = '密码'; + } else if (arr[i].auth_mode === AUTH_TYPE_SSHKEY) { + auth_name = '私钥'; + } + html += dlg_user_edit_host.create_user_html(host_auth_id, i, user_name, pro_name, auth_name); + } + html += ''; + $("#sys-user-list").html(html); - $("#btn-add-sys-user").click(function () { - var row_data = tbl.get_row(dlg_user_edit_host.row_id); - g_dlg_sys_user.create_show(row_data); - }); + $("#btn-add-sys-user").click(function () { + var row_data = tbl.get_row(dlg_user_edit_host.row_id); + g_dlg_sys_user.create_show(row_data); + }); - $('[user-data-action="modify"]').click(function () { - var index = parseInt($(this).attr("index")); - var data = dlg_user_edit_host.auth_list[index]; - var row_data = tbl.get_row(dlg_user_edit_host.row_id); - g_dlg_sys_user.update_show(row_data, data); - }); - $('[user-data-action="delete"]').click(function () { - var host_auth_id = parseInt($(this).attr("auth-id")); - ywl.ajax_post_json('/host/sys-user/delete', {host_auth_id: host_auth_id}, - function (ret) { - //console.log("ret,", ret); - if (ret.code == 0) { - ywl.notify_success('系统用户删除成功'); - // var host_id = parseInt(dlg_user_edit_host.host_id); - g_dlg_edit_host_user.sync_user_info(host_id); + $('[user-data-action="modify"]').click(function () { + var index = parseInt($(this).attr("index")); + var data = dlg_user_edit_host.auth_list[index]; + var row_data = tbl.get_row(dlg_user_edit_host.row_id); + g_dlg_sys_user.update_show(row_data, data); + }); + $('[user-data-action="delete"]').click(function () { + var host_auth_id = parseInt($(this).attr("auth-id")); + ywl.ajax_post_json('/host/sys-user/delete', {host_auth_id: host_auth_id}, + function (ret) { + //console.log("ret,", ret); + if (ret.code === TPE_OK) { + ywl.notify_success('系统用户删除成功'); + // var host_id = parseInt(dlg_user_edit_host.host_id); + g_dlg_edit_host_user.sync_user_info(host_id); - } else { - ywl.notify_error('系统用户删除失败!' + ret.code); - } - }, - function () { - ywl.notify_error('系统用户删除失败!'); - } - ); - }); - }, - function () { - ywl.notify_error('网络故障,无法获取远程主机认证信息!'); - } - ); - }; - dlg_user_edit_host.init_dlg = function (row_id, args) { - dlg_user_edit_host.row_id = row_id; - if (dlg_user_edit_host.update === 1) { - var host_id = args.host_id; - dlg_user_edit_host.host_ip = args.host_ip; - dlg_user_edit_host.pro_port = args.pro_port; + } else { + ywl.notify_error('系统用户删除失败!' + ret.code); + } + }, + function () { + ywl.notify_error('系统用户删除失败!'); + } + ); + }); + }, + function () { + ywl.notify_error('网络故障,无法获取远程主机认证信息!'); + } + ); + }; + dlg_user_edit_host.init_dlg = function (row_id, args) { + dlg_user_edit_host.row_id = row_id; + if (dlg_user_edit_host.update === 1) { + var host_id = args.host_id; + dlg_user_edit_host.host_ip = args.host_ip; + dlg_user_edit_host.pro_port = args.pro_port; - dlg_user_edit_host.sync_user_info(host_id); - } - }; + dlg_user_edit_host.sync_user_info(host_id); + } + }; - dlg_user_edit_host.clear_fields = function () { + dlg_user_edit_host.clear_fields = function () { - }; + }; - dlg_user_edit_host.init_fields = function () { + dlg_user_edit_host.init_fields = function () { - }; + }; - dlg_user_edit_host.check_args = function () { - return true; - }; + dlg_user_edit_host.check_args = function () { + return true; + }; - dlg_user_edit_host.update_show = function (row_id, args) { - dlg_user_edit_host.update = 1; - dlg_user_edit_host.init_dlg(row_id, args); - $(dlg_user_edit_host.dom_id).modal({backdrop: 'static'}); - }; + dlg_user_edit_host.update_show = function (row_id, args) { + dlg_user_edit_host.update = 1; + dlg_user_edit_host.init_dlg(row_id, args); + $(dlg_user_edit_host.dom_id).modal({backdrop: 'static'}); + }; - dlg_user_edit_host.create_show = function () { - dlg_user_edit_host.update = 0; - dlg_user_edit_host.init_dlg(); - $(dlg_user_edit_host.dom_id).modal({backdrop: 'static'}); - }; + dlg_user_edit_host.create_show = function () { + dlg_user_edit_host.update = 0; + dlg_user_edit_host.init_dlg(); + $(dlg_user_edit_host.dom_id).modal({backdrop: 'static'}); + }; - dlg_user_edit_host.hide = function () { - $(dlg_user_edit_host.dom_id).modal('hide'); - }; + dlg_user_edit_host.hide = function () { + $(dlg_user_edit_host.dom_id).modal('hide'); + }; - return dlg_user_edit_host; + return dlg_user_edit_host; }; ywl.create_sys_user = function (tbl) { - var dlg_sys_user = {}; - dlg_sys_user.dom_id = "#dialog_user"; - dlg_sys_user.update = 0; - dlg_sys_user.tbl = tbl; - dlg_sys_user.row_id = ''; - dlg_sys_user.sys_type = 0; - dlg_sys_user.host_id = 0; - dlg_sys_user.host_ip = ''; - dlg_sys_user.auth_mode = 0; - dlg_sys_user.protocol = 0; - dlg_sys_user.host_auth_id = 0; - dlg_sys_user.user_name = ''; - dlg_sys_user.user_pswd = ''; - dlg_sys_user.cert_id = 0; - dlg_sys_user.user_param = ''; + var dlg_sys_user = {}; + dlg_sys_user.dom_id = "#dialog_user"; + dlg_sys_user.update = 0; + dlg_sys_user.tbl = tbl; + dlg_sys_user.row_id = ''; + dlg_sys_user.sys_type = 0; + dlg_sys_user.host_id = 0; + dlg_sys_user.host_ip = ''; + dlg_sys_user.auth_mode = 0; + dlg_sys_user.protocol = 0; + dlg_sys_user.host_auth_id = 0; + dlg_sys_user.user_name = ''; + dlg_sys_user.user_pswd = ''; + dlg_sys_user.cert_id = 0; + dlg_sys_user.user_param = ''; - dlg_sys_user.init = function () { - dlg_sys_user.update = 0; - dlg_sys_user.host_id = 0; - dlg_sys_user.host_ip = ''; - dlg_sys_user.sys_type = 0; - dlg_sys_user.auth_mode = 1; - dlg_sys_user.host_auth_id = 0; - dlg_sys_user.user_name = ''; - dlg_sys_user.user_pswd = ''; - dlg_sys_user.cert_id = 0; - dlg_sys_user.protocol = 0; - dlg_sys_user.host_port = 0; + dlg_sys_user.init = function () { + dlg_sys_user.update = 0; + dlg_sys_user.host_id = 0; + dlg_sys_user.host_ip = ''; + dlg_sys_user.sys_type = 0; + dlg_sys_user.auth_mode = 1; + dlg_sys_user.host_auth_id = 0; + dlg_sys_user.user_name = ''; + dlg_sys_user.user_pswd = ''; + dlg_sys_user.cert_id = 0; + dlg_sys_user.protocol = 0; + dlg_sys_user.host_port = 0; - $("#sys-user-btn-save").click(function () { - if (!dlg_sys_user.check_args()) - return; + $("#sys-user-btn-save").click(function () { + if (!dlg_sys_user.check_args()) + return; - if (dlg_sys_user.update === 1) { - dlg_sys_user.update_post(); - } else { - dlg_sys_user.create_post(); - } - }); - $("#test-btn-connect").click(function () { - if (!dlg_sys_user.check_args()) - return; + if (dlg_sys_user.update === 1) { + dlg_sys_user.update_post(); + } else { + dlg_sys_user.create_post(); + } + }); + $("#test-btn-connect").click(function () { + if (!dlg_sys_user.check_args()) + return; - var ts_rdp_port = ywl.page_options.core.rdp_port; - var ts_ssh_port = ywl.page_options.core.ssh_port; - var ts_telnet_port = ywl.page_options.core.telnet_port; - var server_port = 0; - var host_port = dlg_sys_user.host_port; - var protocol = dlg_sys_user.protocol; - if (protocol === 1) { - server_port = ts_rdp_port; - } else if (protocol === 2) { - server_port = ts_ssh_port; - } else if (protocol === 3) { - server_port = ts_telnet_port; - } else { - ywl.notify_error('未知协议!'); - return; - } + var ts_rdp_port = ywl.page_options.core.rdp_port; + var ts_ssh_port = ywl.page_options.core.ssh_port; + var ts_telnet_port = ywl.page_options.core.telnet_port; + var server_port = 0; + var host_port = dlg_sys_user.host_port; + var protocol = dlg_sys_user.protocol; + if (protocol === PROTOCOL_TYPE_RDP) { + server_port = ts_rdp_port; + } else if (protocol === PROTOCOL_TYPE_SSH) { + server_port = ts_ssh_port; + } else if (protocol === PROTOCOL_TYPE_TELNET) { + server_port = ts_telnet_port; + } else { + ywl.notify_error('未知协议!'); + return; + } - var args = {}; - args.server_ip = ywl.server_ip; - args.server_port = parseInt(server_port); - args.host_port = parseInt(host_port); - args.protocol = parseInt(protocol); - args.protocol_sub = 1; - args.sys_type = parseInt(dlg_sys_user.sys_type); - args.host_ip = dlg_sys_user.host_ip; - args.auth_mode = parseInt(dlg_sys_user.auth_mode); - args.user_name = dlg_sys_user.user_name; - args.user_pswd = dlg_sys_user.user_pswd; - args.cert_id = dlg_sys_user.cert_id; - args.host_auth_id = dlg_sys_user.host_auth_id; - args.user_param = dlg_sys_user.user_param; - args.size = 2; - to_admin_fast_teleport( - '/host/admin-fast-get-session-id', - args, - function () { - console.log('远程连接建立成功!') - }, - function (code, error) { - if (code == TPE_NO_ASSIST) - g_assist.alert_assist_not_found(); - else { - ywl.notify_error(error); - console.log('error:', error) - } - } - ); + var args = {}; + args.server_ip = ywl.server_ip; + args.server_port = parseInt(server_port); + args.host_port = parseInt(host_port); + args.protocol = parseInt(protocol); + args.protocol_sub = 1; + args.sys_type = parseInt(dlg_sys_user.sys_type); + args.host_ip = dlg_sys_user.host_ip; + args.auth_mode = parseInt(dlg_sys_user.auth_mode); + args.user_name = dlg_sys_user.user_name; + args.user_pswd = dlg_sys_user.user_pswd; + args.cert_id = dlg_sys_user.cert_id; + args.host_auth_id = dlg_sys_user.host_auth_id; + args.user_param = dlg_sys_user.user_param; + args.size = 2; + to_admin_fast_teleport( + '/host/admin-fast-get-session-id', + args, + function () { + console.log('远程连接建立成功!') + }, + function (code, error) { + if (code === TPE_NO_ASSIST) + g_assist.alert_assist_not_found(); + else { + ywl.notify_error(error); + console.log('error:', error) + } + } + ); - }); + }); // // SSH密钥选择 - var html_sshkey = []; - var i = 0; - var cnt = 0; - for (i = 0, cnt = g_cert_list.length; i < cnt; ++i) { - html_sshkey.push(''); - } - $('#auth-user-sshkey-list').append($(html_sshkey.join(''))); - }; + var html_sshkey = []; + var i, cnt = 0; + for (i = 0, cnt = g_cert_list.length; i < cnt; ++i) { + html_sshkey.push(''); + } + $('#auth-user-sshkey-list').append($(html_sshkey.join(''))); + }; - dlg_sys_user.init_dlg = function (row_data, args) { - dlg_sys_user.row_id = row_data.row_id; - dlg_sys_user.host_id = row_data.host_id; - dlg_sys_user.host_ip = row_data.host_ip; - dlg_sys_user.sys_type = row_data.host_sys_type; - dlg_sys_user.protocol = row_data.protocol; - dlg_sys_user.host_port = row_data.host_port; - if (dlg_sys_user.update == 1) { - dlg_sys_user.auth_mode = args.auth_mode; - dlg_sys_user.host_auth_id = args.host_auth_id; - dlg_sys_user.user_name = args.user_name; - dlg_sys_user.user_pswd = args.user_pswd; - dlg_sys_user.cert_id = args.cert_id; - dlg_sys_user.user_param = args.user_param; - if(dlg_sys_user.user_param.length == 0) - dlg_sys_user.user_param = 'ogin:\nassword:'; + dlg_sys_user.init_dlg = function (row_data, args) { + dlg_sys_user.row_id = row_data.row_id; + dlg_sys_user.host_id = row_data.host_id; + dlg_sys_user.host_ip = row_data.host_ip; + dlg_sys_user.sys_type = row_data.host_sys_type; + dlg_sys_user.protocol = row_data.protocol; + dlg_sys_user.host_port = row_data.host_port; + if (dlg_sys_user.update === 1) { + dlg_sys_user.auth_mode = args.auth_mode; + dlg_sys_user.host_auth_id = args.host_auth_id; + dlg_sys_user.user_name = args.user_name; + dlg_sys_user.user_pswd = args.user_pswd; + dlg_sys_user.cert_id = args.cert_id; + dlg_sys_user.user_param = args.user_param; + if (dlg_sys_user.user_param.length === 0) + dlg_sys_user.user_param = 'ogin:\nassword:'; - $('#auth-user-host-pswd').attr('placeholder', '不填写则使用已存储的密码'); - } else { - if (dlg_sys_user.sys_type == OS_TYPE_WINDOWS) { - dlg_sys_user.user_name = 'administrator'; - } else if (dlg_sys_user.sys_type == OS_TYPE_LINUX) { - dlg_sys_user.user_name = 'root'; - } else { - dlg_sys_user.user_name = ''; - } - dlg_sys_user.auth_mode = 1; - dlg_sys_user.host_auth_id = 0; - dlg_sys_user.user_pswd = ''; - dlg_sys_user.cert_id = 0; - dlg_sys_user.user_param = 'ogin:\nassword:'; - $('#auth-user-host-pswd').attr('placeholder', '请输入登录远程主机的密码'); - } - dlg_sys_user.init_fields(); - }; + $('#auth-user-host-pswd').attr('placeholder', '不填写则使用已存储的密码'); + } else { + if (dlg_sys_user.sys_type === OS_TYPE_WINDOWS) { + dlg_sys_user.user_name = 'administrator'; + } else if (dlg_sys_user.sys_type === OS_TYPE_LINUX) { + dlg_sys_user.user_name = 'root'; + } else { + dlg_sys_user.user_name = ''; + } + dlg_sys_user.auth_mode = 1; + dlg_sys_user.host_auth_id = 0; + dlg_sys_user.user_pswd = ''; + dlg_sys_user.cert_id = 0; + dlg_sys_user.user_param = 'ogin:\nassword:'; + $('#auth-user-host-pswd').attr('placeholder', '请输入登录远程主机的密码'); + } + dlg_sys_user.init_fields(); + }; - dlg_sys_user.clear_fields = function () { + dlg_sys_user.clear_fields = function () { - }; + }; - dlg_sys_user.init_fields = function () { + dlg_sys_user.init_fields = function () { - var info; - var combox_html = []; - if (dlg_sys_user.protocol == PROTOCOL_TYPE_RDP) { - info = "RDP协议"; - $('#auth-user-block-telnet').hide(); - combox_html.push(''); - } else if (dlg_sys_user.protocol == PROTOCOL_TYPE_SSH) { - info = "SSH协议"; - $('#auth-user-block-telnet').hide(); - combox_html.push(''); - } else if (dlg_sys_user.protocol == PROTOCOL_TYPE_TELNET) { - info = "TELNET协议"; - $('#auth-user-block-telnet').show(); - combox_html.push(''); + var info; + var combox_html = []; + if (dlg_sys_user.protocol === PROTOCOL_TYPE_RDP) { + info = "RDP协议"; + $('#auth-user-block-telnet').hide(); + combox_html.push(''); + } else if (dlg_sys_user.protocol === PROTOCOL_TYPE_SSH) { + info = "SSH协议"; + $('#auth-user-block-telnet').hide(); + combox_html.push(''); + } else if (dlg_sys_user.protocol === PROTOCOL_TYPE_TELNET) { + info = "TELNET协议"; + $('#auth-user-block-telnet').show(); + combox_html.push(''); - var user_param = dlg_sys_user.user_param.split("\n"); - var param1 = ''; - var param2 = ''; - if (user_param.length == 1) { - param1 = user_param[0]; - } else if (user_param.length == 2) { - param1 = user_param[0]; - param2 = user_param[1]; - } + var user_param = dlg_sys_user.user_param.split("\n"); + var param1 = ''; + var param2 = ''; + if (user_param.length === 1) { + param1 = user_param[0]; + } else if (user_param.length === 2) { + param1 = user_param[0]; + param2 = user_param[1]; + } - $('#auth-user-telnet-username-prompt').val(param1); - $('#auth-user-telnet-pswd-prompt').val(param2); - } else { - info = "未知协议"; - } + $('#auth-user-telnet-username-prompt').val(param1); + $('#auth-user-telnet-pswd-prompt').val(param2); + } else { + info = "未知协议"; + } - $('#auth-sys-user-type-combox').html(combox_html.join('')); - $('#auth-user-type').change(dlg_sys_user.on_user_auth_mode_change); - $('#auth-user-protocol-type').text(info); + $('#auth-sys-user-type-combox').html(combox_html.join('')); + $('#auth-user-type').change(dlg_sys_user.on_user_auth_mode_change); + $('#auth-user-protocol-type').text(info); - info = dlg_sys_user.host_ip + ':' + dlg_sys_user.host_port; - $('#add-user-host-ip').text(info); - $('#auth-user-type').val(dlg_sys_user.auth_mode); - $('#auth-user-host-username').val(dlg_sys_user.user_name); + info = dlg_sys_user.host_ip + ':' + dlg_sys_user.host_port; + $('#add-user-host-ip').text(info); + $('#auth-user-type').val(dlg_sys_user.auth_mode); + $('#auth-user-host-username').val(dlg_sys_user.user_name); - if (dlg_sys_user.auth_mode == AUTH_TYPE_PASSWORD) { - $('#auth-user-block-name').show(); - $('#auth-user-block-pswd').show(); - $('#auth-user-block-sshkey').hide(); - $('#auth-user-host-pswd').val(""); - $('#auth-user-host-pswd-confirm').val(""); - } else if (dlg_sys_user.auth_mode == AUTH_TYPE_SSHKEY) { - $('#auth-user-block-name').show(); - $('#auth-user-block-pswd').hide(); - $('#auth-user-block-sshkey').show(); - var cert_id = parseInt(dlg_sys_user.cert_id); - $('#auth-user-sshkey-list').val(cert_id); - } else if (dlg_sys_user.auth_mode == AUTH_NONE) { - $('#auth-user-block-telnet').hide(); - $('#auth-user-block-pswd').hide(); - $('#auth-user-block-name').hide(); - $('#auth-user-block-sshkey').hide(); - } + if (dlg_sys_user.auth_mode === AUTH_TYPE_PASSWORD) { + $('#auth-user-block-name').show(); + $('#auth-user-block-pswd').show(); + $('#auth-user-block-sshkey').hide(); + $('#auth-user-host-pswd').val(""); + $('#auth-user-host-pswd-confirm').val(""); + } else if (dlg_sys_user.auth_mode === AUTH_TYPE_SSHKEY) { + $('#auth-user-block-name').show(); + $('#auth-user-block-pswd').hide(); + $('#auth-user-block-sshkey').show(); + var cert_id = parseInt(dlg_sys_user.cert_id); + $('#auth-user-sshkey-list').val(cert_id); + } else if (dlg_sys_user.auth_mode === AUTH_NONE) { + $('#auth-user-block-telnet').hide(); + $('#auth-user-block-pswd').hide(); + $('#auth-user-block-name').hide(); + $('#auth-user-block-sshkey').hide(); + } + }; + dlg_sys_user.on_user_auth_mode_change = function () { + dlg_sys_user.auth_mode = parseInt($('#auth-user-type').val()); + if (dlg_sys_user.auth_mode === AUTH_TYPE_PASSWORD) { + if (dlg_sys_user.protocol === PROTOCOL_TYPE_RDP) { - }; + } else if (dlg_sys_user.protocol === PROTOCOL_TYPE_SSH) { + } else if (dlg_sys_user.protocol === PROTOCOL_TYPE_TELNET) { + $('#auth-user-block-telnet').show(); + } + $('#auth-user-block-pswd').show(); + $('#auth-user-block-name').show(); + $('#auth-user-block-sshkey').hide(); + } else if (dlg_sys_user.auth_mode === AUTH_TYPE_SSHKEY) { + $('#auth-user-block-telnet').hide(); + $('#auth-user-block-pswd').hide(); + $('#auth-user-block-sshkey').show(); + $('#auth-user-block-name').show(); + } else if (dlg_sys_user.auth_mode === AUTH_NONE) { + $('#auth-user-block-telnet').hide(); + $('#auth-user-block-pswd').hide(); + $('#auth-user-block-name').hide(); + $('#auth-user-block-sshkey').hide(); + } + }; - dlg_sys_user.on_user_auth_mode_change = function () { - dlg_sys_user.auth_mode = $('#auth-user-type').val(); - if (dlg_sys_user.auth_mode == AUTH_TYPE_PASSWORD) { - if (dlg_sys_user.protocol == 1) { + dlg_sys_user.check_args = function () { - } else if (dlg_sys_user.protocol == 2) { + dlg_sys_user.auth_mode = parseInt($('#auth-user-type').val()); + dlg_sys_user.user_name = parseInt($('#auth-user-host-username').val()); + if (dlg_sys_user.auth_mode !== AUTH_NONE && + dlg_sys_user.user_name.length === 0) { + ywl.notify_error('请输入系统用户名!'); + return false; + } - } else if (dlg_sys_user.protocol == 3) { - $('#auth-user-block-telnet').show(); - } - $('#auth-user-block-pswd').show(); - $('#auth-user-block-name').show(); - $('#auth-user-block-sshkey').hide(); - } else if (dlg_sys_user.auth_mode == AUTH_TYPE_SSHKEY) { - $('#auth-user-block-telnet').hide(); - $('#auth-user-block-pswd').hide(); - $('#auth-user-block-sshkey').show(); - $('#auth-user-block-name').show(); - } else if (dlg_sys_user.auth_mode == AUTH_NONE) { - $('#auth-user-block-telnet').hide(); - $('#auth-user-block-pswd').hide(); - $('#auth-user-block-name').hide(); - $('#auth-user-block-sshkey').hide(); - } - }; + if (dlg_sys_user.auth_mode === AUTH_TYPE_PASSWORD) { + if (dlg_sys_user.update !== 1) { + var temp1 = $('#auth-user-host-pswd').val(); + var temp2 = $('#auth-user-host-pswd-confirm').val(); + if (temp1.length === 0) { + ywl.notify_error('请输入密码!'); + return false; + } + if (temp2.length === 0) { + ywl.notify_error('请输入确认密码!'); + return false; + } + if (temp1 !== temp2) { + ywl.notify_error('两次密码输入不一致!'); + return false; + } + dlg_sys_user.user_pswd = temp1; + } else { + var temp1 = $('#auth-user-host-pswd').val(); + var temp2 = $('#auth-user-host-pswd-confirm').val(); + if (temp1 !== temp2) { + ywl.notify_error('两次密码输入不一致!'); + return false; + } + dlg_sys_user.user_pswd = temp1; + } + if (dlg_sys_user.protocol === PROTOCOL_TYPE_TELNET) { + var param1 = $('#auth-user-telnet-username-prompt').val(); + var param2 = $('#auth-user-telnet-pswd-prompt').val(); + dlg_sys_user.user_param = param1 + "\n" + param2; + } - dlg_sys_user.check_args = function () { + } else if (dlg_sys_user.auth_mode === AUTH_TYPE_SSHKEY) { + dlg_sys_user.cert_id = $('#auth-user-sshkey-list').val(); + } else if (dlg_sys_user.auth_mode === AUTH_NONE) { + dlg_sys_user.user_name = ''; + dlg_sys_user.user_pswd = ''; + dlg_sys_user.cert_id = 0; + } else { + ywl.notify_error('未知认证模式!'); + return false; + } + return true; + }; - dlg_sys_user.auth_mode = $('#auth-user-type').val(); - dlg_sys_user.user_name = $('#auth-user-host-username').val(); - if (dlg_sys_user.auth_mode != AUTH_NONE && - dlg_sys_user.user_name.length == 0) { - ywl.notify_error('请输入系统用户名!'); - return false; - } + dlg_sys_user.update_show = function (row_id, args) { + dlg_sys_user.update = 1; + dlg_sys_user.init_dlg(row_id, args); + $(dlg_sys_user.dom_id).modal({backdrop: 'static'}); + }; - if (dlg_sys_user.auth_mode == AUTH_TYPE_PASSWORD) { - if (dlg_sys_user.update != 1) { - var temp1 = $('#auth-user-host-pswd').val(); - var temp2 = $('#auth-user-host-pswd-confirm').val(); - if (temp1.length == 0) { - ywl.notify_error('请输入密码!'); - return false; - } - if (temp2.length == 0) { - ywl.notify_error('请输入确认密码!'); - return false; - } - if (temp1 != temp2) { - ywl.notify_error('两次密码输入不一致!'); - return false; - } - dlg_sys_user.user_pswd = temp1; - } else { - var temp1 = $('#auth-user-host-pswd').val(); - var temp2 = $('#auth-user-host-pswd-confirm').val(); - if (temp1 != temp2) { - ywl.notify_error('两次密码输入不一致!'); - return false; - } - dlg_sys_user.user_pswd = temp1; - } - if (dlg_sys_user.protocol == PROTOCOL_TYPE_TELNET) { - var param1 = $('#auth-user-telnet-username-prompt').val(); - var param2 = $('#auth-user-telnet-pswd-prompt').val(); - dlg_sys_user.user_param = param1 + "\n" + param2; - } + dlg_sys_user.create_show = function (row_data) { + dlg_sys_user.update = 0; + dlg_sys_user.init_dlg(row_data); + $(dlg_sys_user.dom_id).modal({backdrop: 'static'}); + }; - } else if (dlg_sys_user.auth_mode == AUTH_TYPE_SSHKEY) { - dlg_sys_user.cert_id = $('#auth-user-sshkey-list').val(); - } else if (dlg_sys_user.auth_mode == AUTH_NONE) { - dlg_sys_user.user_name = ''; - dlg_sys_user.user_pswd = ''; - dlg_sys_user.cert_id = 0; - } else { - ywl.notify_error('未知认证模式!'); - return false; - } - return true; - }; + dlg_sys_user.hide = function () { + $(dlg_sys_user.dom_id).modal('hide'); + }; - dlg_sys_user.update_show = function (row_id, args) { - dlg_sys_user.update = 1; - dlg_sys_user.init_dlg(row_id, args); - $(dlg_sys_user.dom_id).modal({backdrop: 'static'}); - }; + dlg_sys_user.update_post = function () { + var auth_mode = parseInt(dlg_sys_user.auth_mode); + var user_pswd = ''; + var cert_id = 0; + if (auth_mode === AUTH_TYPE_PASSWORD) { + user_pswd = dlg_sys_user.user_pswd; + } else if (auth_mode === AUTH_TYPE_SSHKEY) { + cert_id = parseInt(dlg_sys_user.cert_id); + } else { - dlg_sys_user.create_show = function (row_data) { - dlg_sys_user.update = 0; - dlg_sys_user.init_dlg(row_data); - $(dlg_sys_user.dom_id).modal({backdrop: 'static'}); - }; + } + var host_id = parseInt(dlg_sys_user.host_id); + var host_auth_id = parseInt(dlg_sys_user.host_auth_id); + var args = { + auth_mode: auth_mode, + host_id: host_id, + user_name: dlg_sys_user.user_name, + user_pswd: user_pswd, + cert_id: cert_id, + user_param: dlg_sys_user.user_param + }; + //console.log("args:", args); + ywl.ajax_post_json('/host/sys-user/update', {host_auth_id: host_auth_id, kv: args}, + function (ret) { + //console.log("ret,", ret); + if (ret.code === 0) { + ywl.notify_success('系统用户信息更新成功'); + g_dlg_edit_host_user.sync_user_info(host_id); + dlg_sys_user.hide(); - dlg_sys_user.hide = function () { - $(dlg_sys_user.dom_id).modal('hide'); - }; + } else { + ywl.notify_error('系统用户信息更新失败' + ret.code); + } + }, + function () { + ywl.notify_error('系统用户信息更新失败'); + } + ); + }; - dlg_sys_user.update_post = function () { - var auth_mode = parseInt(dlg_sys_user.auth_mode); - var user_pswd = ''; - var cert_id = 0; - if (auth_mode == AUTH_TYPE_PASSWORD) { - user_pswd = dlg_sys_user.user_pswd; - } else if (auth_mode == AUTH_TYPE_SSHKEY) { - cert_id = parseInt(dlg_sys_user.cert_id); - } else { + dlg_sys_user.create_post = function () { + if (!dlg_sys_user.check_args()) { + ywl.notify_error("参数输入有错误"); + return; + } + var auth_mode = parseInt(dlg_sys_user.auth_mode); + var user_pswd = ''; + var cert_id = 0; + if (auth_mode === AUTH_TYPE_PASSWORD) { + user_pswd = dlg_sys_user.user_pswd; + } else { + cert_id = parseInt(dlg_sys_user.cert_id); + } + var host_id = parseInt(dlg_sys_user.host_id); + var args = { + host_id: host_id, + auth_mode: auth_mode, + user_name: dlg_sys_user.user_name, + user_pswd: user_pswd, + cert_id: cert_id, + user_param: dlg_sys_user.user_param + }; - } - var host_id = parseInt(dlg_sys_user.host_id); - var host_auth_id = parseInt(dlg_sys_user.host_auth_id); - var args = { - auth_mode: auth_mode, - host_id: host_id, - user_name: dlg_sys_user.user_name, - user_pswd: user_pswd, - cert_id: cert_id, - user_param: dlg_sys_user.user_param - }; - //console.log("args:", args); - ywl.ajax_post_json('/host/sys-user/update', {host_auth_id: host_auth_id, kv: args}, - function (ret) { - //console.log("ret,", ret); - if (ret.code == 0) { - ywl.notify_success('系统用户信息更新成功'); - g_dlg_edit_host_user.sync_user_info(host_id); - dlg_sys_user.hide(); + ywl.ajax_post_json('/host/sys-user/add', args, + function (ret) { + if (ret.code === TPE_OK) { + ywl.notify_success('系统用户添加成功'); + g_dlg_edit_host_user.sync_user_info(host_id); + dlg_sys_user.hide(); + } else { + ywl.notify_error('系统用户添加失败' + ret.code); + } + }, + function () { + ywl.notify_error('系统用户信息更新失败'); + } + ); + }; - } else { - ywl.notify_error('系统用户信息更新失败' + ret.code); - } - }, - function () { - ywl.notify_error('系统用户信息更新失败'); - } - ); - }; - - dlg_sys_user.create_post = function () { - if (!dlg_sys_user.check_args()) { - ywl.notify_error("参数输入有错误"); - return; - } - var auth_mode = parseInt(dlg_sys_user.auth_mode); - var user_pswd = ''; - var cert_id = 0; - if (auth_mode == 1) { - user_pswd = dlg_sys_user.user_pswd; - } else { - cert_id = parseInt(dlg_sys_user.cert_id); - } - var host_id = parseInt(dlg_sys_user.host_id); - var args = { - host_id: host_id, - auth_mode: auth_mode, - user_name: dlg_sys_user.user_name, - user_pswd: user_pswd, - cert_id: cert_id, - user_param: dlg_sys_user.user_param - }; - - ywl.ajax_post_json('/host/sys-user/add', args, - function (ret) { - if (ret.code == 0) { - //console.log("ret,", ret); - if (ret.code == 0) { - ywl.notify_success('系统用户添加成功'); - g_dlg_edit_host_user.sync_user_info(host_id); - dlg_sys_user.hide(); - - } else { - ywl.notify_error('系统用户添加失败' + ret.code); - } - } - else { - ywl.notify_error('系统用户添加失败'); - } - }, - function () { - ywl.notify_error('系统用户信息更新失败'); - } - ); - }; - - return dlg_sys_user; + return dlg_sys_user; }; ywl.create_batch_join_group_dlg = function (tbl) { - var batch_join_dlg = {}; + var batch_join_dlg = {}; - batch_join_dlg.tbl = tbl; - batch_join_dlg.dom_id = "#dialog_batch_join_group"; - batch_join_dlg.host_list = []; + batch_join_dlg.tbl = tbl; + batch_join_dlg.dom_id = "#dialog_batch_join_group"; + batch_join_dlg.host_list = []; - batch_join_dlg.init = function () { - // 分组选择 - var html_group = []; - html_group.push(''); - for (var i = 0, cnt = g_group_list.length; i < cnt; ++i) { - html_group.push(''); - } - $('#group-host-group').append($(html_group.join(''))); + batch_join_dlg.init = function () { + // 分组选择 + var html_group = []; + html_group.push(''); + for (var i = 0, cnt = g_group_list.length; i < cnt; ++i) { + html_group.push(''); + } + $('#group-host-group').append($(html_group.join(''))); - batch_join_dlg.init_dlg(); - }; + batch_join_dlg.init_dlg(); + }; - batch_join_dlg.init_dlg = function () { - }; + batch_join_dlg.init_dlg = function () { + }; - batch_join_dlg.check_args = function () { - return true; - }; + batch_join_dlg.check_args = function () { + return true; + }; - batch_join_dlg.show = function (data_list) { - batch_join_dlg.host_list = data_list; - $(batch_join_dlg.dom_id).modal({backdrop: 'static'}); - }; + batch_join_dlg.show = function (data_list) { + batch_join_dlg.host_list = data_list; + $(batch_join_dlg.dom_id).modal({backdrop: 'static'}); + }; - batch_join_dlg.hide = function () { - $(batch_join_dlg.dom_id).modal('hide'); - }; + batch_join_dlg.hide = function () { + $(batch_join_dlg.dom_id).modal('hide'); + }; - batch_join_dlg.post = function () { + batch_join_dlg.post = function () { - var data_list = []; - for (var i = 0; i < batch_join_dlg.host_list.length; i++) { - var host_id = batch_join_dlg.host_list[i].host_id; - data_list.push(host_id); - } + var data_list = []; + for (var i = 0; i < batch_join_dlg.host_list.length; i++) { + var host_id = batch_join_dlg.host_list[i].host_id; + data_list.push(host_id); + } - var obj = $('#group-host-group'); - var group_id = parseInt(obj.val()); - var group_name = obj.find('option:selected').text(); + var obj = $('#group-host-group'); + var group_id = parseInt(obj.val()); + var group_name = obj.find('option:selected').text(); - ywl.ajax_post_json('/host/add-host-to-group', {host_list: data_list, group_id: group_id}, - function (ret) { - var update_args = {group_name: group_name}; - for (var i = 0; i < batch_join_dlg.host_list.length; i++) { - var row_id = batch_join_dlg.host_list[i].row_id; - batch_join_dlg.tbl.update_row(row_id, update_args); - } + ywl.ajax_post_json('/host/add-host-to-group', {host_list: data_list, group_id: group_id}, + function (ret) { + var update_args = {group_name: group_name}; + for (var i = 0; i < batch_join_dlg.host_list.length; i++) { + var row_id = batch_join_dlg.host_list[i].row_id; + batch_join_dlg.tbl.update_row(row_id, update_args); + } - ywl.notify_success("成功设定分组信息!"); - batch_join_dlg.hide(); - }, - function () { - ywl.notify_error("设定分组信息失败!"); - } - ); - }; + ywl.notify_success("成功设定分组信息!"); + batch_join_dlg.hide(); + }, + function () { + ywl.notify_error("设定分组信息失败!"); + } + ); + }; - $("#group-btn-save").click(function () { - if (!batch_join_dlg.check_args()) { - return; - } - batch_join_dlg.post(); - }); + $("#group-btn-save").click(function () { + if (!batch_join_dlg.check_args()) { + return; + } + batch_join_dlg.post(); + }); - return batch_join_dlg; + return batch_join_dlg; }; diff --git a/server/www/teleport/static/js/ui/auth.js b/server/www/teleport/static/js/ui/auth.js index 76c1806..c75601a 100644 --- a/server/www/teleport/static/js/ui/auth.js +++ b/server/www/teleport/static/js/ui/auth.js @@ -522,10 +522,10 @@ ywl.on_user_host_table_created = function (tbl) { ywl.ajax_post_json('/user/delete-host', {host_list: host_list, user_name: ywl.page_options.user_name}, function (ret) { tbl.remove_row(row_id); - ywl.notify_success('删除用户拥有主机成功'); + ywl.notify_success('回收授权成功!'); }, function () { - ywl.notify_error('删除用户拥有主机失败'); + ywl.notify_error('回收授权失败!'); } ); }; diff --git a/server/www/teleport/static/js/ui/auth/login.js b/server/www/teleport/static/js/ui/auth/login.js index 09ea6c9..c423a7d 100644 --- a/server/www/teleport/static/js/ui/auth/login.js +++ b/server/www/teleport/static/js/ui/auth/login.js @@ -25,23 +25,23 @@ ywl.create_app = function () { $('#captcha_image').click(function () { $(this).attr('src', '/auth/get-captcha?' + Math.random()); - $('#captcha').focus(); + $('#captcha').focus().val(''); }); $('#username_account').keydown(function (event) { $('[data-toggle="popover"]').popover('hide'); - if (event.which == 13) { + if (event.which === 13) { $('#password_account').focus(); } }); $('#password_account').keydown(function (event) { $('[data-toggle="popover"]').popover('hide'); - if (event.which == 13) { + if (event.which === 13) { $('#captcha').focus(); } }); $('#captcha').keydown(function (event) { $('[data-toggle="popover"]').popover('hide'); - if (event.which == 13) { + if (event.which === 13) { _app.login_account(); } }); @@ -64,7 +64,6 @@ ywl.create_app = function () { str_password = dom_password.val(); str_captcha = dom_captcha.val(); is_remember = dom_remember.is(':checked'); - console.log('xxxx', is_remember); if (str_username.length === 0) { show_op_box('error', '缺少账号!'); @@ -92,7 +91,7 @@ ywl.create_app = function () { // 先判断一下captcha是否正确,如果不正确,拒绝登录 ywl.ajax_post_json('/auth/verify-captcha', {captcha: str_captcha}, function (ret) { - if (ret.code === 0) { + if (ret.code === TPE_OK) { // 验证成功 hide_op_box(); show_op_box('wait', ' 正在登录TELEPORT,请稍候...'); @@ -116,14 +115,11 @@ ywl.create_app = function () { }; _app.do_account_login = function (username, userpwd, captcha, is_remember) { - console.log('remember', is_remember); ywl.ajax_post_json('/auth/verify-user', {username: username, userpwd: userpwd, captcha: captcha, remember: is_remember}, function (ret) { - if (ret.code == 0) { - // 验证成功 + if (ret.code === TPE_OK) { window.location.href = ywl.page_options.ref; - } - else { + } else { hide_op_box(); show_op_box('error', '无法登录TELEPORT:' + ret.message); console.log(ret); @@ -137,31 +133,6 @@ ywl.create_app = function () { $('#btn_login').removeAttr('disabled'); } ); - -// $.ajax({ -// type: 'GET', -// url: '/auth/verify-user', -// jsonp: "callback", -// data: {username: username, userpwd: userpwd, captcha: captcha}, -// dataType: 'jsonp', -// success: function (data) { -// if (data.code == 0) { -// // 验证成功 -// window.location.href = ywl.page_options.ref; -// } -// else { -// hide_op_box(); -// show_op_box('error', '无法登录TELEPORT!'); -// } -// -// $('#btn_login').removeAttr('disabled'); -// }, -// error: function () { -// hide_op_box(); -// show_op_box('error', '很抱歉,无法连接服务器!请稍后再试一次!'); -// $('#btn_login').removeAttr('disabled'); -// } -// }); }; return _app; diff --git a/server/www/teleport/static/js/ui/cert.js b/server/www/teleport/static/js/ui/cert.js index ce1c353..f095f84 100644 --- a/server/www/teleport/static/js/ui/cert.js +++ b/server/www/teleport/static/js/ui/cert.js @@ -1,7 +1,7 @@ -/** - * Created by mi on 2016/7/4. - */ +"use strict"; + var g_cert_dlg_info = null; + ywl.on_init = function (cb_stack, cb_args) { var dom_id = '#ywl_cert_list'; @@ -71,7 +71,7 @@ ywl.on_init = function (cb_stack, cb_args) { ywl.on_host_table_created = function (tbl) { tbl.on_cell_created = function (row_id, col_key, cell_obj) { - if (col_key == 'action') { + if (col_key === 'action') { var row_data = tbl.get_row(row_id); //console.log('row_data', row_data); $(cell_obj).find('[ywl-btn-edit]').click(function () { @@ -82,18 +82,18 @@ ywl.on_host_table_created = function (tbl) { var _fn_sure = function (cb_stack, cb_args) { ywl.ajax_post_json('/host/delete-cert', {cert_id: cert_id}, function (ret) { - if (ret.code == 0) { + if (ret.code === TPE_OK) { tbl.remove_row(row_id); ywl.notify_success('删除成功!'); - } else if (ret.code == -2) { + } else if (ret.code === -2) { ywl.notify_error('不能删除,有主机使用了此密钥!'); } else { - ywl.notify_error('删除失败!'); + ywl.notify_error('删除失败!错误代码:'+ret.code); } }, - function (ret) { - ywl.notify_error('删除失败'); + function () { + ywl.notify_error('网络通讯失败!'); } ); }; @@ -189,7 +189,7 @@ ywl.create_cert_info_dlg = function (tbl) { ywl.notify_error('必须填写公钥内容!'); return false; } - if (cert_info_dlg.update == 0 && cert_info_dlg.cert_pri.length == 0) { + if (cert_info_dlg.update === 0 && cert_info_dlg.cert_pri.length === 0) { ywl.notify_error('添加密钥时,必须填写私钥内容!'); return false; } @@ -197,7 +197,7 @@ ywl.create_cert_info_dlg = function (tbl) { }; cert_info_dlg.post = function () { - if (cert_info_dlg.update == 1) { + if (cert_info_dlg.update === 1) { ywl.ajax_post_json('/host/update-cert', {cert_id: cert_info_dlg.cert_id, cert_name: cert_info_dlg.cert_name, cert_pub: cert_info_dlg.cert_pub, cert_pri: cert_info_dlg.cert_pri}, function (ret) { var update_args = {cert_id: cert_info_dlg.cert_id, cert_name: cert_info_dlg.cert_name}; @@ -205,19 +205,19 @@ ywl.create_cert_info_dlg = function (tbl) { ywl.notify_success('密钥更新成功!'); cert_info_dlg.hide(); }, - function (ret) { + function () { ywl.notify_error('密钥更新失败!'); } ); } else { ywl.ajax_post_json('/host/add-cert', {cert_name: cert_info_dlg.cert_name, cert_pub: cert_info_dlg.cert_pub, cert_pri: cert_info_dlg.cert_pri}, function (ret) { - if(ret.code == 0){ + if(ret.code === TPE_OK){ cert_info_dlg.tbl.reload(); ywl.notify_success('密钥添加成功!'); cert_info_dlg.hide(); - }else if(ret.code == -2){ - ywl.notify_error('错误,没有启动核心服务!'); + }else if(ret.code === TPE_NO_CORE_SERVER){ + ywl.notify_error('错误,没有启动核心服务!'); }else{ ywl.notify_error('密钥添加失败!code:' + ret.code); } diff --git a/server/www/teleport/static/js/ui/common.js b/server/www/teleport/static/js/ui/common.js index 9175698..d433627 100644 --- a/server/www/teleport/static/js/ui/common.js +++ b/server/www/teleport/static/js/ui/common.js @@ -68,9 +68,9 @@ function get_system_group_by_id(gid) { } -function get_command_name_by_id(cmd_id) { - return ywl.assist.get_cache_by_id(CACHE_TYPE_COMMAND, cmd_id); -} +//function get_command_name_by_id(cmd_id) { +// return ywl.assist.get_cache_by_id(CACHE_TYPE_COMMAND, cmd_id); +//} //function notify_error(message_, title_) { // var _title = title_ || ''; diff --git a/server/www/teleport/static/js/ui/common_host.js b/server/www/teleport/static/js/ui/common_host.js index ae52447..bb67cdf 100644 --- a/server/www/teleport/static/js/ui/common_host.js +++ b/server/www/teleport/static/js/ui/common_host.js @@ -1,13 +1,13 @@ "use strict"; -var OS_TYPE_WINDOWS = 1; -var OS_TYPE_LINUX = 2; -var PROTOCOL_TYPE_RDP = 1; -var PROTOCOL_TYPE_SSH = 2; -var PROTOCOL_TYPE_TELNET = 3; -var AUTH_TYPE_PASSWORD = 1; -var AUTH_TYPE_SSHKEY = 2; -var AUTH_NONE = 0; +//var OS_TYPE_WINDOWS = 1; +//var OS_TYPE_LINUX = 2; +//var PROTOCOL_TYPE_RDP = 1; +//var PROTOCOL_TYPE_SSH = 2; +//var PROTOCOL_TYPE_TELNET = 3; +//var AUTH_TYPE_PASSWORD = 1; +//var AUTH_TYPE_SSHKEY = 2; +//var AUTH_NONE = 0; var g_assist = null; diff --git a/server/www/teleport/static/js/ui/controls.js b/server/www/teleport/static/js/ui/controls.js index fbe5382..268703d 100644 --- a/server/www/teleport/static/js/ui/controls.js +++ b/server/www/teleport/static/js/ui/controls.js @@ -1003,20 +1003,20 @@ ywl.create_table_render = function (tbl, on_created) { return ret; }; - _tbl_render.host_status = function (row_id, fields) { - if (fields.status == HOST_STAT_ACTIVE) { - switch (fields.online) { - case AGENT_STAT_ONLINE: - return '在线'; - case AGENT_STAT_OFFLINE: - return '离线'; - default: - return '未知'; - } - } else { - return '- 未使用 -'; - } - }; +// _tbl_render.host_status = function (row_id, fields) { +// if (fields.status == HOST_STAT_ACTIVE) { +// switch (fields.online) { +// case AGENT_STAT_ONLINE: +// return '在线'; +// case AGENT_STAT_OFFLINE: +// return '离线'; +// default: +// return '未知'; +// } +// } else { +// return '- 未使用 -'; +// } +// }; _tbl_render.sys_type = function (row_id, fields) { switch (fields.sys_type) { diff --git a/server/www/teleport/static/js/ui/log.js b/server/www/teleport/static/js/ui/log.js index 858a59d..208bb14 100644 --- a/server/www/teleport/static/js/ui/log.js +++ b/server/www/teleport/static/js/ui/log.js @@ -173,9 +173,9 @@ ywl.on_host_table_created = function (tbl) { if (protocol == 1) { $(cell_obj).find('[ywl-btn-record]').click(function () { var ip = window.location.hostname;//ywl.page_options.ts_server.ip; - var port = ywl.page_options.ts_server.port; + var port = parseInt(window.location.port);//ywl.page_options.ts_server.port; var url = 'http://' + ip + ':' + port + '/log/replay/rdp/' + row_data.id; - var tail = 'log/replay/rdp/' + row_data.id; + var tail = 'log/replay/rdp/' + prefixInteger(row_data.id, 6); var args = {}; args.id = parseInt(row_data.id); args.host = ip; diff --git a/server/www/teleport/static/js/ui/record.js b/server/www/teleport/static/js/ui/record.js index aa3c910..a8d7b70 100644 --- a/server/www/teleport/static/js/ui/record.js +++ b/server/www/teleport/static/js/ui/record.js @@ -41,7 +41,7 @@ var speed_offset = 0; ywl.req_record_info = function (record_id, file_id, repeat) { ywl.ajax_post_json_time_out('/log/get-record-file-info', {id: record_id, file_id: file_id}, 30 * 1000, function (ret) { - if (ret.code == 0) { + if (ret.code === TPE_OK) { g_data[file_id] = ret.data; if ((g_down_play_file_id + 1) <= g_total_file_count) { @@ -49,9 +49,7 @@ ywl.req_record_info = function (record_id, file_id, repeat) { ywl.req_record_info(record_id, g_down_play_file_id, true); g_down_play_file_id++; } - } - //console.log('req_record_info successful'); } else { console.log('req_record_info error ', ret.code); } @@ -77,11 +75,13 @@ ywl.on_init = function (cb_stack, cb_args) { ywl.ajax_post_json('/log/get-record-header', {id: record_id}, function (ret) { - if (ret.code == 0) { + if (ret.code === TPE_OK) { g_header = ret.data.header; g_total_file_count = g_header.file_count; g_total_time = g_header.time_used; + $('#recorder-info').html(g_header.account + ' 于 ' + format_datetime(g_header.start) + ' 访问 ' + g_header.user_name + '@' + g_header.ip + ':' + g_header.port); + // 请求第一个录像数据块 g_down_play_file_id = 0; ywl.req_record_info(record_id, g_down_play_file_id, true); diff --git a/server/www/teleport/static/js/ui/teleport.js b/server/www/teleport/static/js/ui/teleport.js index 6be3e51..ba6db61 100644 --- a/server/www/teleport/static/js/ui/teleport.js +++ b/server/www/teleport/static/js/ui/teleport.js @@ -7,19 +7,18 @@ var g_current_version = ""; var g_host_name = window.location.hostname; var error_process = function (ret, func_success, func_error) { -// console.log("ret", ret); var code = ret.code; - if (code == TPE_OK) { + if (code === TPE_OK) { func_success(ret); return; } - if (code == TPE_START_CLIENT) { + if (code === TPE_START_CLIENT) { func_error(TPE_START_CLIENT, '启动本地客户端进程失败,请检查命令行是否正确:' + ret.path); console.log('启动本地进程失败,命令行:', ret.path); - } else if (code == TPE_JSON_FORMAT || code == TPE_PARAM) { + } else if (code === TPE_JSON_FORMAT || code === TPE_PARAM) { func_error(TPE_START_CLIENT, "启动本地客户端进程失败:启动参数错误!"); - } else if (code == TPE_OLD_ASSIST) { + } else if (code === TPE_OLD_ASSIST) { func_error(TPE_OLD_ASSIST, '助手版本太低,请下载最新版本!'); } else { @@ -47,7 +46,7 @@ var teleport_init = function (last_version, req_version, func_success, func_erro func_error(ret, TPE_OLD_ASSIST, '助手版本太低,请下载最新版本!'); } }, - error: function (jqXhr) { + error: function () { func_error({}, TPE_NO_ASSIST, '无法连接到teleport助手,可能尚未启动!'); } }); @@ -60,7 +59,6 @@ var version_compare = function () { }; var to_teleport = function (url, args, func_success, func_error) { - var auth_id = args['auth_id']; // 开始Ajax调用 var args_ = JSON.stringify({auth_id: auth_id}); @@ -94,7 +92,7 @@ var to_teleport = function (url, args, func_success, func_error) { success: function (ret) { error_process(ret, func_success, func_error); }, - error: function (jqXhr) { + error: function () { func_error(TPE_NO_ASSIST, '无法连接到teleport助手,可能尚未启动!'); } }); @@ -109,7 +107,6 @@ var to_teleport = function (url, args, func_success, func_error) { }; var to_admin_teleport = function (url, args, func_success, func_error) { - var host_auth_id = args['host_auth_id']; // 开始Ajax调用 var args_ = JSON.stringify({host_auth_id: host_auth_id}); @@ -124,7 +121,7 @@ var to_admin_teleport = function (url, args, func_success, func_error) { if (ret.code === 0) { var session_id = ret.data.session_id; var data = { - server_ip: g_host_name, // args.server_ip, + server_ip: g_host_name, server_port: parseInt(args.server_port), host_ip: args.host_ip, size: parseInt(args.size), @@ -158,7 +155,6 @@ var to_admin_teleport = function (url, args, func_success, func_error) { }; var to_admin_fast_teleport = function (url, args, func_success, func_error) { - // 开始Ajax调用 var args_ = JSON.stringify(args); $.ajax({ @@ -172,7 +168,7 @@ var to_admin_fast_teleport = function (url, args, func_success, func_error) { if (ret.code === 0) { var session_id = ret.data.session_id; var data = { - server_ip: g_host_name, //args.server_ip, + server_ip: g_host_name, server_port: parseInt(args.server_port), host_ip: args.host_ip, size: parseInt(args.size), @@ -210,7 +206,6 @@ var to_admin_fast_teleport = function (url, args, func_success, func_error) { }; var start_rdp_replay = function (args, func_success, func_error) { - var args_ = encodeURIComponent(JSON.stringify(args)); $.ajax({ type: 'GET', @@ -227,7 +222,7 @@ var start_rdp_replay = function (args, func_success, func_error) { console.log('ret', ret); }, error: function () { - func_error(TPE_NETWORK, '远程网络通讯失败!'); + func_error(TPE_NETWORK, '与助手的络通讯失败!'); } }); }; diff --git a/server/www/teleport/static/js/ywl_common.js b/server/www/teleport/static/js/ywl_common.js index 9cb021e..ae79248 100644 --- a/server/www/teleport/static/js/ywl_common.js +++ b/server/www/teleport/static/js/ywl_common.js @@ -121,6 +121,10 @@ function digital_precision(num, keep) { return Math.round(num * Math.pow(10, keep)) / Math.pow(10, keep); } +function prefixInteger(num, length) { + return (num / Math.pow(10, length)).toFixed(length).substr(2); +} + function size2str(size, precision) { precision = precision || 0; var s = 0; diff --git a/server/www/teleport/static/js/ywl_const.js b/server/www/teleport/static/js/ywl_const.js index aeab26d..9b793c1 100644 --- a/server/www/teleport/static/js/ywl_const.js +++ b/server/www/teleport/static/js/ywl_const.js @@ -1,12 +1,23 @@ "use strict"; -var USER_TYPE_TEAM_MEMBER = 1; -var USER_TYPE_TEAM_LEADER = 9; -var USER_TYPE_SYS_ADMIN = 99; +var PROTOCOL_TYPE_RDP = 1; +var PROTOCOL_TYPE_SSH = 2; +var PROTOCOL_TYPE_TELNET = 3; -var AGENT_STAT_ONLINE = 1; -var AGENT_STAT_OFFLINE = 0; -// var AGENT_STAT_NOT_ACTIVE = 2; +var OS_TYPE_WINDOWS = 1; +var OS_TYPE_LINUX = 2; +var AUTH_TYPE_PASSWORD = 1; +var AUTH_TYPE_SSHKEY = 2; +var AUTH_NONE = 0; + + +//var USER_TYPE_TEAM_MEMBER = 1; +//var USER_TYPE_TEAM_LEADER = 9; +//var USER_TYPE_SYS_ADMIN = 99; + +//var AGENT_STAT_ONLINE = 1; +//var AGENT_STAT_OFFLINE = 0; +//var AGENT_STAT_NOT_ACTIVE = 2; var HOST_STAT_NOT_ACTIVE = 0; var HOST_STAT_ACTIVE = 2; @@ -87,6 +98,7 @@ var TPE_DATA = 127; // 数据错误 // #define TPE_OPENFILE_ERROR 0x1007 // 无法打开文件 // #define TPE_GETTEMPPATH_ERROR 0x1007 +var TPE_OPENFILE = 300; // 无法打开文件 //------------------------------------------------------- @@ -103,4 +115,52 @@ var TPE_START_CLIENT = 100002; // 无法启动客户端程序(无法创建进 var TPE_NO_CORE_SERVER = 200000; // 未能检测到核心服务 +function tp_error_msg(error_code) { + switch (error_code) { + case TPE_FAILED: + return '内部错误'; + case TPE_NETWORK: + return '网络错误'; + +//------------------------------------------------------- +// HTTP请求相关错误 +//------------------------------------------------------- + case TPE_HTTP_METHOD: + return '无效/错误的请求方法'; + case TPE_HTTP_URL_ENCODE: + return 'URL编码错误(无法解码)'; + + case TPE_UNKNOWN_CMD: + return '未知命令'; + case TPE_JSON_FORMAT: + return '错误的JSON格式数据'; + case TPE_PARAM: + return '参数错误'; + case TPE_DATA: + return '数据错误'; + + + case TPE_OPENFILE: + return '无法打开文件'; + +//------------------------------------------------------- +// 助手程序专用错误值 +//------------------------------------------------------- + case TPE_NO_ASSIST: + return '未能检测到助手程序'; + case TPE_OLD_ASSIST: + return '助手程序版本太低'; + case TPE_START_CLIENT: + return '无法启动客户端程序(无法创建进程)'; + +//------------------------------------------------------- +// 核心服务专用错误值 +//------------------------------------------------------- + case TPE_NO_CORE_SERVER: + return '未能检测到核心服务'; + + default: + return '未知错误'; + } +} diff --git a/server/www/teleport/static/less/auth.less b/server/www/teleport/static/less/auth.less index 8b0305a..2fb559f 100644 --- a/server/www/teleport/static/less/auth.less +++ b/server/www/teleport/static/less/auth.less @@ -128,6 +128,12 @@ body { background: url(../img/login/side-001.jpg) 0 0 no-repeat; } +@media screen and (max-width: 990px) { + #leftside { + display: none; + } +} + #leftside h1 { font-size: 24px; color: #888; diff --git a/server/www/teleport/view/auth/page_base.mako b/server/www/teleport/view/auth/page_base.mako index 6baed43..82e7a0d 100644 --- a/server/www/teleport/view/auth/page_base.mako +++ b/server/www/teleport/view/auth/page_base.mako @@ -55,7 +55,7 @@ diff --git a/server/www/teleport/view/cert/index.mako b/server/www/teleport/view/cert/index.mako index 82aa25d..984f630 100644 --- a/server/www/teleport/view/cert/index.mako +++ b/server/www/teleport/view/cert/index.mako @@ -12,7 +12,7 @@ <%block name="breadcrumb"> diff --git a/server/www/teleport/view/common/_sidebar_nav_menu.mako b/server/www/teleport/view/common/_sidebar_nav_menu.mako index 868b13f..a0b0cd6 100644 --- a/server/www/teleport/view/common/_sidebar_nav_menu.mako +++ b/server/www/teleport/view/common/_sidebar_nav_menu.mako @@ -52,27 +52,28 @@ 'name': '日志查询', 'icon': 'fa-database', }, +## { +## 'require_type': 1, +## 'id': 'pwd', +## 'link': '/pwd', +## 'name': '密码修改', +## 'icon': 'fa-pencil-square-o', +## }, +## { +## 'require_type': 1, +## 'id': 'exit', +## 'link': '/exit', +## 'name': '安全退出', +## 'icon': 'fa-sign-out', +## }, { + 'separator': true, 'require_type': 1, 'id': 'assist-config', 'link': 'http://127.0.0.1:50022/config', 'target': '_blank', 'name': '助手配置', - 'icon': 'fa-pencil-square-o', - }, - { - 'require_type': 1, - 'id': 'pwd', - 'link': '/pwd', - 'name': '密码修改', - 'icon': 'fa-pencil-square-o', - }, - { - 'require_type': 1, - 'id': 'exit', - 'link': '/exit', - 'name': '安全退出', - 'icon': 'fa-sign-out', + 'icon': 'fa-cog', }, ] %> @@ -103,7 +104,8 @@
@@ -119,6 +121,10 @@ %for menu in _sidebar: %if menu['require_type'] <= current_user['type']: + %if 'separator' in menu: +
+ %endif + %if 'sub' in menu and len(menu['sub']) > 0:
\ No newline at end of file diff --git a/server/www/teleport/view/group/index.mako b/server/www/teleport/view/group/index.mako index 1406c89..a2613b3 100644 --- a/server/www/teleport/view/group/index.mako +++ b/server/www/teleport/view/group/index.mako @@ -12,7 +12,7 @@ <%block name="breadcrumb"> diff --git a/server/www/teleport/view/host/admin_index.mako b/server/www/teleport/view/host/admin_index.mako index bab22d0..0dce2f3 100644 --- a/server/www/teleport/view/host/admin_index.mako +++ b/server/www/teleport/view/host/admin_index.mako @@ -155,8 +155,8 @@
@@ -173,7 +173,6 @@ -
@@ -200,110 +199,18 @@
-##
-## -##
-## -##
-##
    -##
  • -##
  • 端口号
  • -##
  • -##
-##
-## -##
-##
    -##
  • -##
  • 端口号
  • -##
  • -##
-##
-## -##
-##
    -##
  • -##
  • 端口号
  • -##
  • -##
-##
-##
-##
-
- - ##
- ## - ##
- ## - ##
- ##
- ## - ##
- ## - ##
- ## - ##
- ##
- ## - ##
- ## - ##
- ## - ##
- ##
- ## - ##
- ## - ##
- ## - ##
- ##
- ## - ##
- ##
- ## - ##
- ## - ##
- ##
- ##
- ## - ##
- ## - ##
- ##
- ##
- ## - ## - ## - - + + -