From 881a0b8b0a7f5734dbd9fe2e9f35462f596698f1 Mon Sep 17 00:00:00 2001 From: awkoo <133107732+awkox@users.noreply.github.com> Date: Sun, 13 Sep 2026 08:50:13 +0000 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=E9=9B=86=E6=88=90=20SSH=20?= =?UTF-8?q?=E5=90=8E=E7=AB=AF(libssh=20+=20mbedTLS),=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E5=8C=96=E5=BC=82=E5=B8=B8=E4=B8=8E=E5=BC=82=E6=AD=A5=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E5=BC=95=E6=93=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - JNI sshterm: 6 个导出符号,App 侧 socketpair fd 注入, Connect/Auth/HostKeyMismatch 三类结构化异常 - SshProcess: 构造即返回占位,连接在 IO 协程异步进行, 失败以进程立即退出收敛,期间输入不丢 - SshInfo/SshInfoStore: ProtoBuf + Preferences DataStore 持久化 - CredentialCipher: Android Keystore AES/GCM 不可导出密钥加密凭据 - CMake 引入 libssh 0.12 + mbedTLS 3.6 submodule 全源码现场编译 --- .gitmodules | 6 + app/src/main/cpp/CMakeLists.txt | 48 +- app/src/main/cpp/pty/CMakeLists.txt | 8 + app/src/main/cpp/ssh/CMakeLists.txt | 20 + app/src/main/cpp/ssh/sshterm.cpp | 470 ++++++++++++++++++ app/src/main/cpp/third_party/.gitignore | 4 + app/src/main/cpp/third_party/libssh | 1 + app/src/main/cpp/third_party/mbedtls | 1 + .../cpp/third_party/mbedtls_user_config.h | 2 + .../awkoo/terminal/core/CredentialCipher.kt | 86 ++++ .../com/awkoo/terminal/core/SessionManager.kt | 35 +- .../com/awkoo/terminal/core/SshInfoStore.kt | 126 +++++ .../com/awkoo/terminal/core/SshProcess.kt | 156 ++++++ .../com/awkoo/terminal/ui/MainViewModel.kt | 22 +- 14 files changed, 981 insertions(+), 4 deletions(-) create mode 100644 .gitmodules create mode 100644 app/src/main/cpp/ssh/CMakeLists.txt create mode 100644 app/src/main/cpp/ssh/sshterm.cpp create mode 100644 app/src/main/cpp/third_party/.gitignore create mode 160000 app/src/main/cpp/third_party/libssh create mode 160000 app/src/main/cpp/third_party/mbedtls create mode 100644 app/src/main/cpp/third_party/mbedtls_user_config.h create mode 100644 app/src/main/kotlin/com/awkoo/terminal/core/CredentialCipher.kt create mode 100644 app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt create mode 100644 app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..d3a5d7b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "app/src/main/cpp/third_party/mbedtls"] + path = app/src/main/cpp/third_party/mbedtls + url = https://github.com/Mbed-TLS/mbedtls.git +[submodule "app/src/main/cpp/third_party/libssh"] + path = app/src/main/cpp/third_party/libssh + url = https://github.com/libssh/libssh-mirror.git diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 8b4cf6c..a8f9481 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -1,4 +1,8 @@ cmake_minimum_required(VERSION 4.1) + +# 跳过所有 install (含 EXPORT) 生成, +set(CMAKE_SKIP_INSTALL_RULES ON CACHE BOOL "" FORCE) + project("terminal") set(CMAKE_C_STANDARD 23) @@ -6,14 +10,14 @@ set(CMAKE_CXX_STANDARD 23) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON) -add_compile_options( +set(TERMINAL_COMPILE_OPTIONS -Wall -Wextra -Werror -O3 -fno-stack-protector -flto ) -add_link_options( +set(TERMINAL_LINK_OPTIONS -Wl,--gc-sections -Wl,-s -flto @@ -23,4 +27,44 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/include ) +set(THIRD_PARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party) + +set(MBEDTLS_USER_CONFIG_FILE + "${THIRD_PARTY_DIR}/mbedtls_user_config.h" + CACHE FILEPATH "" FORCE) +set(USE_SHARED_MBEDTLS_LIBRARY OFF CACHE BOOL "" FORCE) +set(USE_STATIC_MBEDTLS_LIBRARY ON CACHE BOOL "" FORCE) +set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE) +set(ENABLE_TESTING OFF CACHE BOOL "" FORCE) +set(GEN_FILES OFF CACHE BOOL "" FORCE) +set(CMAKE_POSITION_INDEPENDENT_CODE ON CACHE BOOL "" FORCE) + +add_subdirectory(${THIRD_PARTY_DIR}/mbedtls mbedtls) + +set(MBEDTLS_INCLUDE_DIR + "${THIRD_PARTY_DIR}/mbedtls/include" + CACHE PATH "" FORCE) +set(MBEDTLS_SSL_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedtls.a" + CACHE FILEPATH "" FORCE) +set(MBEDTLS_CRYPTO_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedcrypto.a" + CACHE FILEPATH "" FORCE) +set(MBEDTLS_X509_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedx509.a" + CACHE FILEPATH "" FORCE) + +set(WITH_MBEDTLS ON CACHE BOOL "" FORCE) +set(WITH_SERVER OFF CACHE BOOL "" FORCE) +set(WITH_ZLIB OFF CACHE BOOL "" FORCE) +set(WITH_EXAMPLES OFF CACHE BOOL "" FORCE) +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(BUILD_STATIC_LIB OFF CACHE BOOL "" FORCE) + +add_subdirectory(${THIRD_PARTY_DIR}/libssh libssh) + +# libssh 的部分平台代码依赖 glibc/bionic 的 BSD 扩展宏 +target_compile_definitions(ssh PRIVATE _BSD_SOURCE=1) + add_subdirectory(pty) +add_subdirectory(ssh) \ No newline at end of file diff --git a/app/src/main/cpp/pty/CMakeLists.txt b/app/src/main/cpp/pty/CMakeLists.txt index 9e45237..1a987b7 100644 --- a/app/src/main/cpp/pty/CMakeLists.txt +++ b/app/src/main/cpp/pty/CMakeLists.txt @@ -1,3 +1,11 @@ add_library(pty SHARED pty.cpp ) + +target_compile_options(pty PRIVATE + ${TERMINAL_COMPILE_OPTIONS} +) + +target_link_options(pty PRIVATE + ${TERMINAL_LINK_OPTIONS} +) \ No newline at end of file diff --git a/app/src/main/cpp/ssh/CMakeLists.txt b/app/src/main/cpp/ssh/CMakeLists.txt new file mode 100644 index 0000000..031cb5a --- /dev/null +++ b/app/src/main/cpp/ssh/CMakeLists.txt @@ -0,0 +1,20 @@ +add_library(sshterm SHARED + sshterm.cpp +) + +target_compile_options(sshterm PRIVATE + ${TERMINAL_COMPILE_OPTIONS} +) + +target_include_directories(sshterm PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../include +) + +target_link_libraries(sshterm PRIVATE + ssh::ssh +) + +target_link_options(sshterm PRIVATE + -Wl,--exclude-libs,ALL + ${TERMINAL_LINK_OPTIONS} +) \ No newline at end of file diff --git a/app/src/main/cpp/ssh/sshterm.cpp b/app/src/main/cpp/ssh/sshterm.cpp new file mode 100644 index 0000000..6245fcc --- /dev/null +++ b/app/src/main/cpp/ssh/sshterm.cpp @@ -0,0 +1,470 @@ +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +struct native_ssh { + ssh_session session = nullptr; + ssh_channel channel = nullptr; + int native_fd = -1; + volatile bool killed = false; + int exit_st = -1; + std::string server_fingerprint; + pthread_t reader = 0; + pthread_t writer = 0; + bool reader_joined = true; + bool writer_joined = true; +}; + +constexpr size_t kIoBuffer = 4096; + +std::string ssh_error_str(ssh_session session, const char* prefix) { + std::string msg(prefix); + msg += ": "; + const char* detail = session != nullptr ? ssh_get_error(session) : "null session"; + msg += detail != nullptr ? detail : "unknown error"; + return msg; +} + +void throw_ssh_exception(JNIEnv* env, const char* class_name, + const std::string& message) { + jclass clazz = env->FindClass(class_name); + if (clazz == nullptr) { + return; + } + jstring jmsg = env->NewStringUTF(message.c_str()); + if (jmsg == nullptr) { + return; + } + jmethodID ctor = env->GetMethodID(clazz, "", "(Ljava/lang/String;)V"); + jobject ex = ctor != nullptr ? env->NewObject(clazz, ctor, jmsg) : nullptr; + if (ex != nullptr) { + env->Throw(static_cast(ex)); + } +} + +void throw_hostkey_mismatch(JNIEnv* env, const std::string& got, + const std::string& expected) { + const std::string msg = "host key verification failed: got " + got + + ", expected " + expected; + jclass clazz = env->FindClass( + "com/awkoo/terminal/core/SshHostKeyMismatchException"); + if (clazz == nullptr) { + return; + } + jstring jmsg = env->NewStringUTF(msg.c_str()); + jstring jgot = env->NewStringUTF(got.c_str()); + jstring jexpected = env->NewStringUTF(expected.c_str()); + if (jmsg == nullptr || jgot == nullptr || jexpected == nullptr) { + return; + } + jmethodID ctor = env->GetMethodID( + clazz, "", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); + jobject ex = ctor != nullptr + ? env->NewObject(clazz, ctor, jmsg, jgot, jexpected) + : nullptr; + if (ex != nullptr) { + env->Throw(static_cast(ex)); + } +} + +void* io_reader(void* arg) { + native_ssh* h = static_cast(arg); + char buf[kIoBuffer]; + for (;;) { + ssize_t n = read(h->native_fd, buf, sizeof(buf)); + if (n <= 0) { + break; + } + size_t off = 0; + while (off < static_cast(n)) { + if (h->killed) { + return nullptr; + } + int written = ssh_channel_write(h->channel, buf + off, + static_cast(n - off)); + if (written == SSH_AGAIN) { + usleep(10000); + continue; + } + if (written < 0) { + return nullptr; + } + off += static_cast(written); + } + } + if (!h->killed) { + ssh_channel_send_eof(h->channel); + } + return nullptr; +} + +void* io_writer(void* arg) { + native_ssh* h = static_cast(arg); + char buf[kIoBuffer]; + for (;;) { + if (h->killed) { + break; + } + // is_blocking=1 在本实现中会立即返回 SSH_AGAIN,必须用非阻塞轮询。 + int n = ssh_channel_read(h->channel, buf, sizeof(buf), 0); + if (n == SSH_AGAIN) { + usleep(10000); + continue; + } + if (n <= 0) { + break; + } + size_t off = 0; + while (off < static_cast(n)) { + ssize_t written = write(h->native_fd, buf + off, + static_cast(n) - off); + if (written <= 0) { + break; + } + off += static_cast(written); + } + } + shutdown(h->native_fd, SHUT_WR); + if (!h->killed) { + // 被 kill 时通道可能已被并发释放,只采集退出状态(正常路径) + uint32_t exit_state = UINT32_MAX; + ssh_channel_get_exit_state(h->channel, &exit_state, nullptr, nullptr); + h->exit_st = exit_state != UINT32_MAX ? static_cast(exit_state) : -1; + } + return nullptr; +} + +void free_channel(native_ssh* h) { + if (h->channel != nullptr) { + ssh_channel_free(h->channel); + h->channel = nullptr; + } +} + +void teardown(native_ssh* h, bool join) { + h->killed = true; + if (join) { + // 先让工作线程自然退出,再动 libssh 对象 + if (!h->writer_joined && h->writer != 0) { + pthread_join(h->writer, nullptr); + h->writer_joined = true; + } + if (!h->reader_joined && h->reader != 0) { + pthread_join(h->reader, nullptr); + h->reader_joined = true; + } + } + // 0.12 的 ssh_disconnect 会 do_free session->channels 里的全部 channel, + // 因此 ssh_channel_free 必须排在 ssh_disconnect 之前,否则构成二次释放。 + free_channel(h); + if (h->session != nullptr) { + ssh_disconnect(h->session); + ssh_free(h->session); + h->session = nullptr; + } + if (h->native_fd >= 0) { + close(h->native_fd); + h->native_fd = -1; + } +} + +void dispose(native_ssh* h) { + if (h == nullptr) { + return; + } + teardown(h, true); + delete h; +} + +std::string jstring_copy(JNIEnv* env, jstring str) { + if (str == nullptr) { + return {}; + } + const char* utf = env->GetStringUTFChars(str, nullptr); + if (utf == nullptr) { + return {}; + } + std::string copy(utf); + env->ReleaseStringUTFChars(str, utf); + return copy; +} + +std::string server_fingerprint_of(ssh_session session) { + if (session == nullptr) { + return {}; + } + ssh_key key = nullptr; + if (ssh_get_server_publickey(session, &key) != SSH_OK || key == nullptr) { + return {}; + } + std::string fp; + unsigned char* hash = nullptr; + size_t hlen = 0; + if (ssh_get_publickey_hash(key, SSH_PUBLICKEY_HASH_SHA256, &hash, &hlen) == SSH_OK) { + char* text = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256, hash, hlen); + if (text != nullptr) { + fp = text; + ssh_string_free_char(text); + } + ssh_clean_pubkey_hash(&hash); + } + ssh_key_free(key); + return fp; +} + +} // namespace + +extern "C" JNIEXPORT jlong JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshConnect( + JNIEnv* env, + jclass, + jstring jhost, + jint jport, + jstring juser, + jstring jpassword, + jstring jprivkey_path, + jstring jpassphrase, + jstring jexpected_fingerprint, + jint jtimeout_ms, + jint jnative_fd, + jint rows, + jint cols) { + const std::string host = jstring_copy(env, jhost); + const std::string user = jstring_copy(env, juser); + const std::string password = jstring_copy(env, jpassword); + const std::string privkey_path = jstring_copy(env, jprivkey_path); + const std::string passphrase = jstring_copy(env, jpassphrase); + const std::string expected_fingerprint = jstring_copy(env, jexpected_fingerprint); + int port = static_cast(jport); + int timeout_ms = static_cast(jtimeout_ms); + int native_fd = static_cast(jnative_fd); + + if (native_fd < 0) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + "invalid native fd"); + return 0; + } + + ssh_session session = ssh_new(); + if (session == nullptr) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + "ssh_new failed"); + ::close(native_fd); + return 0; + } + + if (ssh_options_set(session, SSH_OPTIONS_HOST, host.c_str()) != SSH_OK || + ssh_options_set(session, SSH_OPTIONS_PORT, &port) != SSH_OK || + ssh_options_set(session, SSH_OPTIONS_USER, user.c_str()) != SSH_OK) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "set options")); + ssh_free(session); + ::close(native_fd); + return 0; + } + + if (timeout_ms > 0) { + long seconds = timeout_ms / 1000; + long usec = (timeout_ms % 1000) * 1000L; + ssh_options_set(session, SSH_OPTIONS_TIMEOUT, &seconds); + ssh_options_set(session, SSH_OPTIONS_TIMEOUT_USEC, &usec); + } + + if (ssh_connect(session) != SSH_OK) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "connect")); + ssh_free(session); + ::close(native_fd); + return 0; + } + + const std::string server_fingerprint = server_fingerprint_of(session); + if (server_fingerprint.empty()) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "obtain server host key")); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + if (!expected_fingerprint.empty() && server_fingerprint != expected_fingerprint) { + throw_hostkey_mismatch(env, server_fingerprint, expected_fingerprint); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + if (!privkey_path.empty()) { + ssh_key privkey = nullptr; + if (ssh_pki_import_privkey_file(privkey_path.c_str(), passphrase.c_str(), + nullptr, nullptr, &privkey) != SSH_OK || + privkey == nullptr) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshAuthException", + ssh_error_str(session, "load private key")); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + const int rc = ssh_userauth_publickey(session, user.c_str(), privkey); + ssh_key_free(privkey); + if (rc != SSH_AUTH_SUCCESS) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshAuthException", + ssh_error_str(session, "public key auth")); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + } else if (!password.empty()) { + if (ssh_userauth_password(session, user.c_str(), password.c_str()) != + SSH_AUTH_SUCCESS) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshAuthException", + ssh_error_str(session, "password auth")); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + } else { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshAuthException", + "no credentials provided"); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + ssh_channel channel = ssh_channel_new(session); + if (channel == nullptr) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "new channel")); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + if (ssh_channel_open_session(channel) != SSH_OK) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "open session channel")); + ssh_channel_free(channel); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + if (ssh_channel_request_pty_size(channel, "xterm-256color", cols, rows) != SSH_OK || + ssh_channel_request_shell(channel) != SSH_OK) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + ssh_error_str(session, "request pty/shell")); + ssh_channel_free(channel); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + // 后续 I/O 走非阻塞轮询(阻塞读在本实现中会直接返回 SSH_AGAIN) + ssh_set_blocking(session, 0); + + native_ssh* h = new (std::nothrow) native_ssh(); + if (h == nullptr) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + "out of memory"); + ssh_channel_free(channel); + ssh_disconnect(session); + ssh_free(session); + ::close(native_fd); + return 0; + } + + h->session = session; + h->channel = channel; + h->native_fd = native_fd; + h->server_fingerprint = server_fingerprint; + + if (pthread_create(&h->reader, nullptr, io_reader, h) != 0) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + "reader thread create failed"); + teardown(h, true); + delete h; + return 0; + } + h->reader_joined = false; + + if (pthread_create(&h->writer, nullptr, io_writer, h) != 0) { + throw_ssh_exception(env, "com/awkoo/terminal/core/SshConnectException", + "writer thread create failed"); + teardown(h, true); + delete h; + return 0; + } + h->writer_joined = false; + + return reinterpret_cast(h); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows, jint cols) { + native_ssh* h = reinterpret_cast(handle); + if (h == nullptr || h->channel == nullptr) { + return; + } + ssh_channel_change_pty_size(h->channel, cols, rows); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong handle) { + native_ssh* h = reinterpret_cast(handle); + if (h == nullptr || h->server_fingerprint.empty()) { + return nullptr; + } + return env->NewStringUTF(h->server_fingerprint.c_str()); +} + +extern "C" JNIEXPORT jint JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { + native_ssh* h = reinterpret_cast(handle); + if (h == nullptr) { + return -1; + } + // 只等输出侧线程:IO writer 读到 EOF 即代表进程退出且 exit_st 就绪。 + // io_reader 阻塞在本地 fd 读上,只能由 App 关闭 fd 解锁(close() 会先关 fdObj); + // 若在此 join 它,退出管线会被拖到"下一次输入"(表现为多按一次回车)。 + if (!h->writer_joined && h->writer != 0) { + pthread_join(h->writer, nullptr); + h->writer_joined = true; + } + return h->exit_st; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { + native_ssh* h = reinterpret_cast(handle); + if (h == nullptr) { + return; + } + // 只置标志。io_writer 每 10ms 检查一次 killed 即退出; + // 不动 session/channel(ssh_disconnect 在 0.12 会释放 channel,线程读取时构成 UAF)。 + h->killed = true; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_awkoo_terminal_core_SshProcess_sshClose(JNIEnv*, jclass, jlong handle) { + native_ssh* h = reinterpret_cast(handle); + dispose(h); +} \ No newline at end of file diff --git a/app/src/main/cpp/third_party/.gitignore b/app/src/main/cpp/third_party/.gitignore new file mode 100644 index 0000000..2e3bcab --- /dev/null +++ b/app/src/main/cpp/third_party/.gitignore @@ -0,0 +1,4 @@ +/* +!mbedtls_user_config.h +# submodule 目录交由 gitlink 管理(ignore 不作用于已跟踪路径),add 时用 -f +!mbedtls/ \ No newline at end of file diff --git a/app/src/main/cpp/third_party/libssh b/app/src/main/cpp/third_party/libssh new file mode 160000 index 0000000..5031388 --- /dev/null +++ b/app/src/main/cpp/third_party/libssh @@ -0,0 +1 @@ +Subproject commit 50313883f3a077458cde4ea95bf46bfeb0771b34 diff --git a/app/src/main/cpp/third_party/mbedtls b/app/src/main/cpp/third_party/mbedtls new file mode 160000 index 0000000..2ca6c28 --- /dev/null +++ b/app/src/main/cpp/third_party/mbedtls @@ -0,0 +1 @@ +Subproject commit 2ca6c285a0dd3f33982dd57299012dacab1ff206 diff --git a/app/src/main/cpp/third_party/mbedtls_user_config.h b/app/src/main/cpp/third_party/mbedtls_user_config.h new file mode 100644 index 0000000..6150322 --- /dev/null +++ b/app/src/main/cpp/third_party/mbedtls_user_config.h @@ -0,0 +1,2 @@ +#define MBEDTLS_THREADING_C +#define MBEDTLS_THREADING_PTHREAD diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/CredentialCipher.kt b/app/src/main/kotlin/com/awkoo/terminal/core/CredentialCipher.kt new file mode 100644 index 0000000..c48aa4e --- /dev/null +++ b/app/src/main/kotlin/com/awkoo/terminal/core/CredentialCipher.kt @@ -0,0 +1,86 @@ +package com.awkoo.terminal.core + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import javax.inject.Inject +import javax.inject.Singleton + +/** + * SSH 凭据(口令/私钥口令)的落盘加密器。 + * + * 使用 Android Keystore 中生成的不可导出 AES/GCM 密钥;密文以 + * Base64(iv || ciphertext) 存储,只有本应用可解密。KeyStore 密钥丢失 + * (设备重置/恢复)或数据损坏时 [decrypt] 返回 null,调用方须让用户重输。 + */ +@Singleton +class CredentialCipher @Inject constructor() { + + @Volatile + private var secretKey: SecretKey? = null + + fun encrypt(plain: String): String? { + if (plain.isEmpty()) return null + return try { + val cipher = Cipher.getInstance(TRANSFORM) + cipher.init(Cipher.ENCRYPT_MODE, loadKey()) + val iv = cipher.iv + val ct = cipher.doFinal(plain.encodeToByteArray()) + Base64.encodeToString(iv + ct, Base64.NO_WRAP) + } catch (e: Exception) { + null + } + } + + fun decrypt(payload: String): String? { + if (payload.isEmpty()) return null + return try { + val raw = Base64.decode(payload, Base64.NO_WRAP) + val iv = raw.copyOfRange(0, IV_LEN) + val ct = raw.copyOfRange(IV_LEN, raw.size) + val cipher = Cipher.getInstance(TRANSFORM) + cipher.init(Cipher.DECRYPT_MODE, loadKey(), GCMParameterSpec(TAG_LEN_BITS, iv)) + String(cipher.doFinal(ct)) + } catch (e: Exception) { + null + } + } + + private fun loadKey(): SecretKey { + secretKey?.let { return it } + synchronized(this) { + secretKey?.let { return it } + val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) } + (ks.getKey(KEY_ALIAS, null) as? SecretKey)?.let { + secretKey = it + return it + } + val generator = KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, KEYSTORE + ) + generator.init( + KeyGenParameterSpec.Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .build() + ) + return generator.generateKey().also { secretKey = it } + } + } + + private companion object { + const val KEYSTORE = "AndroidKeyStore" + const val KEY_ALIAS = "terminal_ssh_credentials" + const val TRANSFORM = "AES/GCM/NoPadding" + const val IV_LEN = 12 + const val TAG_LEN_BITS = 128 + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt index c1625b7..7811f6b 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt @@ -74,6 +74,39 @@ class SessionManager @Inject constructor() { _sessionList.update { it + targetSession } currentSessionId.update { targetSession.id } + observeRemoval(targetSession) + } + + /** + * 建立 SSH 会话:点击创建即入列并成为当前会话,连接异步进行, + * 失败时按"进程立即退出"结束,不抛出到调用线程。 + */ + fun addSshSession( + sshInfo: SshInfo, + cipher: CredentialCipher?, + maxTranscriptRows: Int = 5000 + ) { + val sessionId = idGenerator.incrementAndFetch() + val displayName = sshInfo.name ?: "${sshInfo.user}@${sshInfo.host}" + + val targetSession = TerminalSession( + id = sessionId, + sessionName = MutableStateFlow(displayName), + stdin = null, + maxTranscriptRows = maxTranscriptRows + ) { rows, cols, _, _ -> + SshProcess(sshInfo, cipher, rows, cols) + } + + targetSession.execute() + + _sessionList.update { it + targetSession } + currentSessionId.update { targetSession.id } + + observeRemoval(targetSession) + } + + private fun observeRemoval(targetSession: TerminalSession) { // 使用 combine 联合监听 Session 自身的 isRemove 状态与全局的 _sessionList // 一旦会话要求移除,或者它已经被外部手段从列表中剔除,first { it } 都会立刻放行 // 随后执行兜底的 removeSession 并自然结束协程,杜绝任何内存泄漏的可能。 @@ -81,7 +114,7 @@ class SessionManager @Inject constructor() { combine(targetSession.isRemove, _sessionList) { isRemove, list -> isRemove || list.none { it.id == targetSession.id } }.first { it } - + removeSession(targetSession.id) } } diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt new file mode 100644 index 0000000..ce430d9 --- /dev/null +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt @@ -0,0 +1,126 @@ +package com.awkoo.terminal.core + +import android.content.Context +import android.util.Base64 +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable +import kotlinx.serialization.decodeFromByteArray +import kotlinx.serialization.encodeToByteArray +import kotlinx.serialization.protobuf.ProtoBuf +import javax.inject.Inject +import javax.inject.Singleton + +private val Context.sshDataStore by preferencesDataStore("SshInfo") + +@Serializable +enum class SshAuthType { + PASSWORD, + PRIVATE_KEY +} + +/** + * 持久化的 SSH 连接配置(进程参数载体,与 [CommandInfo] 对应)。 + * + * 敏感字段(密码、私钥口令)只保存 [CredentialCipher] 加密后的密文; + * 已知会话指纹存于 [hostKeyFingerprint],为 null 表示尚未做首次信任(TOFU)。 + */ +@Serializable +data class SshInfo( + val id: Long = 0, + val name: String? = null, + val host: String, + val port: Int = 22, + val user: String, + val authType: SshAuthType = SshAuthType.PASSWORD, + val passwordCipher: String? = null, + val keyPath: String? = null, + val keyPassphraseCipher: String? = null, + val hostKeyFingerprint: String? = null, + val keepAliveMs: Int = 0, + val timeoutMs: Int = 10000 +) + +/** + * SSH 连接配置持久化存储。 + * + * 依赖既有的 Preferences DataStore + ProtoBuf 模式(同 [com.awkoo.terminal.extrakeys.ExtraKeysConfig]), + * 独立文件 [SshInfo],损坏条目(解码失败)自动跳过。 + */ +@OptIn(ExperimentalSerializationApi::class) +@Singleton +class SshInfoStore @Inject constructor( + @ApplicationContext context: Context +) { + private val datastore = context.sshDataStore + + /** 全部连接配置,按 id 升序。损坏条目被剔除。 */ + val sshInfoList: Flow> = datastore.data.map { prefs -> + prefs.asMap() + .filterKeys { it.name.startsWith(KEY_PREFIX) } + .mapNotNull { (key, value) -> + (value as? String)?.let { decode(it) } + } + .sortedBy { it.id } + } + + suspend fun get(id: Long): SshInfo? { + val list = sshInfoList.first() + return list.firstOrNull { it.id == id } + } + + /** 分配自增 id 后落盘,返回带 id 的副本。 */ + suspend fun insert(input: SshInfo): SshInfo { + var assigned = input.id + datastore.edit { prefs -> + if (input.id <= 0) { + assigned = (prefs[nextIdKey] ?: 1).toLong() + prefs[nextIdKey] = assigned.toInt() + 1 + } + prefs[infoKey(assigned)] = encode(input.copy(id = assigned)) + } + return input.copy(id = assigned) + } + + suspend fun upsert(info: SshInfo) { + if (info.id <= 0) { + insert(info) + return + } + datastore.edit { prefs -> + prefs[infoKey(info.id)] = encode(info) + } + } + + suspend fun delete(id: Long) { + datastore.edit { prefs -> + prefs.remove(infoKey(id)) + } + } + + private fun infoKey(id: Long) = stringPreferencesKey(KEY_PREFIX + id) + + private fun encode(info: SshInfo): String = + Base64.encodeToString(ProtoBuf.encodeToByteArray(info), Base64.NO_WRAP) + + private fun decode(encoded: String): SshInfo? = + try { + ProtoBuf.decodeFromByteArray( + Base64.decode(encoded, Base64.NO_WRAP) + ) + } catch (e: Exception) { + null + } + + companion object { + private const val KEY_PREFIX = "info_" + private val nextIdKey = intPreferencesKey("nextInfoId") + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt new file mode 100644 index 0000000..83139c8 --- /dev/null +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt @@ -0,0 +1,156 @@ +package com.awkoo.terminal.core + +import android.os.ParcelFileDescriptor +import com.awkoo.libterminal.process.ITerminalProcess +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.InputStream +import java.io.OutputStream + +/** SSH 连接失败的根异常;按类别派生,UI 依据类型分支提示与重试。 */ +open class SshException(message: String) : RuntimeException(message) + +/** 建连/会话建立类错误(不可达、超时、通道/PTY 失败等)。 */ +class SshConnectException(message: String) : SshException(message) + +/** 主机密钥与期望值不符(可能是重装系统或被劫持)。 */ +class SshHostKeyMismatchException( + message: String, + val expectedFingerprint: String, + val gotFingerprint: String +) : SshException(message) + +/** 凭据无效或认证方式可用性错误。 */ +class SshAuthException(message: String) : SshException(message) + +/** + * 基于 libssh(mbedTLS 后端)的 SSH 会话进程。 + * + * 构造立即返回:App 侧先拿到 socketpair 的流(读阻塞、写积压、键盘可立即弹出), + * 真正的连接在后台线程进行。连接成功后 native 的 I/O 线程开始搬运字节, + * 期间用户先行输入的字节保留在 socket 缓冲中不会丢失;连接失败时 native + * 关闭对应 fd,App 侧流读到 EOF,会话按"进程立即退出"结束,不会崩溃。 + */ +class SshProcess( + sshInfo: SshInfo, + cipher: CredentialCipher?, + rows: Int, + columns: Int +) : ITerminalProcess { + + companion object { + init { System.loadLibrary("sshterm") } + + @JvmStatic + private external fun sshConnect( + host: String, + port: Int, + user: String, + password: String?, + privateKeyPath: String?, + keyPassphrase: String?, + expectedHostKeyFingerprint: String?, + timeoutMs: Int, + nativeFd: Int, + rows: Int, + cols: Int + ): Long + + @JvmStatic + private external fun sshResize(handle: Long, rows: Int, cols: Int) + + /** OpenSSH 风格服务器指纹(如 "SHA256:..."),返回会话的实际主机密钥指纹。 */ + @JvmStatic + private external fun sshGetServerFingerprint(handle: Long): String? + + @JvmStatic + private external fun sshWait(handle: Long): Int + + @JvmStatic + private external fun sshKill(handle: Long) + + @JvmStatic + private external fun sshClose(handle: Long) + } + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + /** 连接结果句柄:0 = 失败;仅在连接协程完成后被置位。 */ + private val handleDeferred = CompletableDeferred() + + /** 连接完成后的有效句柄,供 resize/kill/close 即时读取。 */ + @Volatile + private var handle: Long = 0 + + private var fdObj: ParcelFileDescriptor? = null + + override var inputStream: InputStream + override var outputStream: OutputStream + + init { + val socketPair = ParcelFileDescriptor.createSocketPair() + fdObj = socketPair[0] + inputStream = FileInputStream(socketPair[0].fileDescriptor) + outputStream = FileOutputStream(socketPair[0].fileDescriptor) + + val connFd = socketPair[1].detachFd() + scope.launch { + val password = + sshInfo.passwordCipher?.let { cipher?.decrypt(it) } + val passphrase = + sshInfo.keyPassphraseCipher?.let { cipher?.decrypt(it) } + val h = try { + sshConnect( + sshInfo.host, sshInfo.port, sshInfo.user, + password, sshInfo.keyPath, passphrase, + sshInfo.hostKeyFingerprint, + sshInfo.timeoutMs, connFd, rows, columns + ) + } catch (e: Throwable) { + // native 负责关闭 connFd;对会话表现为"进程立即退出"。 + 0L + } + handle = h + handleDeferred.complete(h) + } + } + + override fun resize(columns: Int, rows: Int, cellWidthPixels: Int, cellHeightPixels: Int) { + if (handle != 0L) { + sshResize(handle, rows, columns) + } + } + + override fun waitFor(): Int = runBlocking { + val h = handleDeferred.await() + if (h == 0L) -1 else sshWait(h) + } + + override fun kill() { + // 连接中无句柄可杀;连接完成后由 close() 统一释放。 + if (handle != 0L) { + sshKill(handle) + } + } + + override fun close() { + try { fdObj?.close() } catch (e: Exception) {} + val h = handle + if (h != 0L) { + sshClose(h) + handle = 0 + } else if (!handleDeferred.isCompleted) { + // 连接尚未结束:等它收敛后释放,避免泄漏 native 会话。 + scope.launch { + val h2 = handleDeferred.await() + if (h2 != 0L) sshClose(h2) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt b/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt index f2ea19c..2dfc8df 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt @@ -8,8 +8,11 @@ import androidx.lifecycle.viewModelScope import com.awkoo.terminal.TerminalService import com.awkoo.terminal.AppPreferences import com.awkoo.terminal.Constants +import com.awkoo.terminal.core.CredentialCipher import com.awkoo.terminal.core.SessionManager import com.awkoo.terminal.core.ShellInfo +import com.awkoo.terminal.core.SshInfo +import com.awkoo.terminal.core.SshInfoStore import com.awkoo.terminal.extrakeys.ExtraKeysConfig import com.awkoo.terminal.ui.theme.ThemeMode import com.awkoo.libterminal.engine.TerminalCursorStyle @@ -30,10 +33,16 @@ import javax.inject.Inject class MainViewModel @Inject constructor( @param:ApplicationContext private val context: Context, val sessionManager: SessionManager, - val preferences: AppPreferences + val preferences: AppPreferences, + val sshInfoStore: SshInfoStore, + private val credentialCipher: CredentialCipher ): ViewModel() { // 数据流 val sessionListState = sessionManager.sessionList + + /** 持久化的 SSH 连接配置列表。 */ + val sshInfoList = sshInfoStore.sshInfoList + fun addSession(name: String?) { val shellInfo = ShellInfo( "sh", @@ -46,6 +55,17 @@ class MainViewModel @Inject constructor( sessionManager.addSession(shellInfo, maxTranscriptRows = transcriptRows.value) + ensureTerminalService() + } + + /** 立即建立 SSH 会话(连接异步、失败不抛到调用线程)。 */ + fun addSshSession(sshInfo: SshInfo) { + sessionManager.addSshSession(sshInfo, credentialCipher, maxTranscriptRows = transcriptRows.value) + + ensureTerminalService() + } + + private fun ensureTerminalService() { // 启动前台服务用于增加生命周期稳定性 if (!TerminalService.isRunning) { val serviceIntent = Intent(context, TerminalService::class.java) From a859efe1c0b76123d967d9890062fa018b8c73bb Mon Sep 17 00:00:00 2001 From: awkoo <133107732+awkox@users.noreply.github.com> Date: Sun, 13 Sep 2026 10:13:45 +0000 Subject: [PATCH 2/4] =?UTF-8?q?refactor:=20SSH=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=E6=8A=BD=E5=8F=96=E4=B8=BA=20libterminal-ssh=20=E7=8B=AC?= =?UTF-8?q?=E7=AB=8B=E6=A8=A1=E5=9D=97,=E5=AD=98=E5=82=A8=E7=94=B1?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E8=B4=9F=E8=B4=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新模块 :libterminal-ssh(com.awkoo.ssh):SshProcess/SshException/ SshInfo(纯配置)/SshCredentials;native(libssh+mbedTLS)与 C++ 一并迁入, JNI 符号同步改为 com_awkoo_ssh_SshProcess - SshProcess 凭据接口改为明文 SshCredentials(调用方解密后当场提供), 模块不再持有 CredentialCipher,不负责任何加密/落盘 - app 保留 CredentialCipher/SshInfoStore,持久化模型改名 PersistedSshInfo, addSshSession 内部解密并转换为模块类型;MainViewModel 接口不变 - app 摘除 ssh/third_party 原生阶段,仅剩本地 pty - CI:actions/checkout 增加 submodules: recursive,云编译可拉取三方源码 --- .github/workflows/ci.yml | 2 + .gitmodules | 4 +- app/build.gradle.kts | 1 + app/src/main/cpp/CMakeLists.txt | 42 +--------- app/src/main/cpp/ssh/CMakeLists.txt | 20 ----- .../com/awkoo/terminal/core/SessionManager.kt | 18 ++++- .../com/awkoo/terminal/core/SshInfoStore.kt | 35 +++++--- .../com/awkoo/terminal/ui/MainViewModel.kt | 4 +- gradle/libs.versions.toml | 2 + libterminal-ssh/build.gradle.kts | 41 ++++++++++ libterminal-ssh/src/main/AndroidManifest.xml | 2 + libterminal-ssh/src/main/cpp/CMakeLists.txt | 80 +++++++++++++++++++ .../src/main/cpp}/sshterm.cpp | 12 +-- .../src/main/cpp/third_party/.gitignore | 0 .../src/main/cpp/third_party/libssh | 0 .../src/main/cpp/third_party/mbedtls | 0 .../cpp/third_party/mbedtls_user_config.h | 0 .../src/main/kotlin/com/awkoo/ssh/SshInfo.kt | 38 +++++++++ .../main/kotlin/com/awkoo/ssh}/SshProcess.kt | 12 ++- settings.gradle.kts | 1 + 20 files changed, 224 insertions(+), 90 deletions(-) delete mode 100644 app/src/main/cpp/ssh/CMakeLists.txt create mode 100644 libterminal-ssh/build.gradle.kts create mode 100644 libterminal-ssh/src/main/AndroidManifest.xml create mode 100644 libterminal-ssh/src/main/cpp/CMakeLists.txt rename {app/src/main/cpp/ssh => libterminal-ssh/src/main/cpp}/sshterm.cpp (96%) rename {app => libterminal-ssh}/src/main/cpp/third_party/.gitignore (100%) rename {app => libterminal-ssh}/src/main/cpp/third_party/libssh (100%) rename {app => libterminal-ssh}/src/main/cpp/third_party/mbedtls (100%) rename {app => libterminal-ssh}/src/main/cpp/third_party/mbedtls_user_config.h (100%) create mode 100644 libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt rename {app/src/main/kotlin/com/awkoo/terminal/core => libterminal-ssh/src/main/kotlin/com/awkoo/ssh}/SshProcess.kt (93%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cda77d..f00553f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: steps: - name: 检出代码 uses: actions/checkout@v7 + with: + submodules: recursive - name: 解密KeyStore if: github.event_name != 'pull_request' diff --git a/.gitmodules b/.gitmodules index d3a5d7b..66bb391 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "app/src/main/cpp/third_party/mbedtls"] - path = app/src/main/cpp/third_party/mbedtls + path = libterminal-ssh/src/main/cpp/third_party/mbedtls url = https://github.com/Mbed-TLS/mbedtls.git [submodule "app/src/main/cpp/third_party/libssh"] - path = app/src/main/cpp/third_party/libssh + path = libterminal-ssh/src/main/cpp/third_party/libssh url = https://github.com/libssh/libssh-mirror.git diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0d7ed2b..6c8a909 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -110,4 +110,5 @@ dependencies { implementation(libs.serialization.protobuf) //implementation(libs.timber) implementation(project(":libterminal")) + implementation(project(":libterminal-ssh")) } diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index a8f9481..8bd1d27 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -27,44 +27,4 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/include ) -set(THIRD_PARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party) - -set(MBEDTLS_USER_CONFIG_FILE - "${THIRD_PARTY_DIR}/mbedtls_user_config.h" - CACHE FILEPATH "" FORCE) -set(USE_SHARED_MBEDTLS_LIBRARY OFF CACHE BOOL "" FORCE) -set(USE_STATIC_MBEDTLS_LIBRARY ON CACHE BOOL "" FORCE) -set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE) -set(ENABLE_TESTING OFF CACHE BOOL "" FORCE) -set(GEN_FILES OFF CACHE BOOL "" FORCE) -set(CMAKE_POSITION_INDEPENDENT_CODE ON CACHE BOOL "" FORCE) - -add_subdirectory(${THIRD_PARTY_DIR}/mbedtls mbedtls) - -set(MBEDTLS_INCLUDE_DIR - "${THIRD_PARTY_DIR}/mbedtls/include" - CACHE PATH "" FORCE) -set(MBEDTLS_SSL_LIBRARY - "${THIRD_PARTY_DIR}/mbedtls/library/libmbedtls.a" - CACHE FILEPATH "" FORCE) -set(MBEDTLS_CRYPTO_LIBRARY - "${THIRD_PARTY_DIR}/mbedtls/library/libmbedcrypto.a" - CACHE FILEPATH "" FORCE) -set(MBEDTLS_X509_LIBRARY - "${THIRD_PARTY_DIR}/mbedtls/library/libmbedx509.a" - CACHE FILEPATH "" FORCE) - -set(WITH_MBEDTLS ON CACHE BOOL "" FORCE) -set(WITH_SERVER OFF CACHE BOOL "" FORCE) -set(WITH_ZLIB OFF CACHE BOOL "" FORCE) -set(WITH_EXAMPLES OFF CACHE BOOL "" FORCE) -set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) -set(BUILD_STATIC_LIB OFF CACHE BOOL "" FORCE) - -add_subdirectory(${THIRD_PARTY_DIR}/libssh libssh) - -# libssh 的部分平台代码依赖 glibc/bionic 的 BSD 扩展宏 -target_compile_definitions(ssh PRIVATE _BSD_SOURCE=1) - -add_subdirectory(pty) -add_subdirectory(ssh) \ No newline at end of file +add_subdirectory(pty) \ No newline at end of file diff --git a/app/src/main/cpp/ssh/CMakeLists.txt b/app/src/main/cpp/ssh/CMakeLists.txt deleted file mode 100644 index 031cb5a..0000000 --- a/app/src/main/cpp/ssh/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -add_library(sshterm SHARED - sshterm.cpp -) - -target_compile_options(sshterm PRIVATE - ${TERMINAL_COMPILE_OPTIONS} -) - -target_include_directories(sshterm PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/../include -) - -target_link_libraries(sshterm PRIVATE - ssh::ssh -) - -target_link_options(sshterm PRIVATE - -Wl,--exclude-libs,ALL - ${TERMINAL_LINK_OPTIONS} -) \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt index 7811f6b..15def55 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt @@ -1,6 +1,9 @@ package com.awkoo.terminal.core import com.awkoo.libterminal.engine.TerminalSession +import com.awkoo.ssh.SshCredentials +import com.awkoo.ssh.SshInfo +import com.awkoo.ssh.SshProcess import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -80,9 +83,12 @@ class SessionManager @Inject constructor() { /** * 建立 SSH 会话:点击创建即入列并成为当前会话,连接异步进行, * 失败时按"进程立即退出"结束,不抛出到调用线程。 + * + * [sshInfo] 为含密文的持久化记录;解密后的明文凭据只在本调用中 + * 构造 [SshCredentials] 交给 libterminal-ssh,不做任何落盘。 */ fun addSshSession( - sshInfo: SshInfo, + sshInfo: PersistedSshInfo, cipher: CredentialCipher?, maxTranscriptRows: Int = 5000 ) { @@ -95,7 +101,15 @@ class SessionManager @Inject constructor() { stdin = null, maxTranscriptRows = maxTranscriptRows ) { rows, cols, _, _ -> - SshProcess(sshInfo, cipher, rows, cols) + SshProcess( + sshInfo.toSshInfo(), + SshCredentials( + password = sshInfo.passwordCipher?.let { cipher?.decrypt(it) }, + keyPassphrase = sshInfo.keyPassphraseCipher?.let { cipher?.decrypt(it) } + ), + rows, + cols + ) } targetSession.execute() diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt index ce430d9..7cef7a2 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt @@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore +import com.awkoo.ssh.SshInfo import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first @@ -33,7 +34,7 @@ enum class SshAuthType { * 已知会话指纹存于 [hostKeyFingerprint],为 null 表示尚未做首次信任(TOFU)。 */ @Serializable -data class SshInfo( +data class PersistedSshInfo( val id: Long = 0, val name: String? = null, val host: String, @@ -52,7 +53,7 @@ data class SshInfo( * SSH 连接配置持久化存储。 * * 依赖既有的 Preferences DataStore + ProtoBuf 模式(同 [com.awkoo.terminal.extrakeys.ExtraKeysConfig]), - * 独立文件 [SshInfo],损坏条目(解码失败)自动跳过。 + * 独立文件 [PersistedSshInfo],损坏条目(解码失败)自动跳过。 */ @OptIn(ExperimentalSerializationApi::class) @Singleton @@ -62,7 +63,7 @@ class SshInfoStore @Inject constructor( private val datastore = context.sshDataStore /** 全部连接配置,按 id 升序。损坏条目被剔除。 */ - val sshInfoList: Flow> = datastore.data.map { prefs -> + val sshInfoList: Flow> = datastore.data.map { prefs -> prefs.asMap() .filterKeys { it.name.startsWith(KEY_PREFIX) } .mapNotNull { (key, value) -> @@ -71,13 +72,13 @@ class SshInfoStore @Inject constructor( .sortedBy { it.id } } - suspend fun get(id: Long): SshInfo? { + suspend fun get(id: Long): PersistedSshInfo? { val list = sshInfoList.first() return list.firstOrNull { it.id == id } } /** 分配自增 id 后落盘,返回带 id 的副本。 */ - suspend fun insert(input: SshInfo): SshInfo { + suspend fun insert(input: PersistedSshInfo): PersistedSshInfo { var assigned = input.id datastore.edit { prefs -> if (input.id <= 0) { @@ -89,7 +90,7 @@ class SshInfoStore @Inject constructor( return input.copy(id = assigned) } - suspend fun upsert(info: SshInfo) { + suspend fun upsert(info: PersistedSshInfo) { if (info.id <= 0) { insert(info) return @@ -107,12 +108,12 @@ class SshInfoStore @Inject constructor( private fun infoKey(id: Long) = stringPreferencesKey(KEY_PREFIX + id) - private fun encode(info: SshInfo): String = + private fun encode(info: PersistedSshInfo): String = Base64.encodeToString(ProtoBuf.encodeToByteArray(info), Base64.NO_WRAP) - private fun decode(encoded: String): SshInfo? = + private fun decode(encoded: String): PersistedSshInfo? = try { - ProtoBuf.decodeFromByteArray( + ProtoBuf.decodeFromByteArray( Base64.decode(encoded, Base64.NO_WRAP) ) } catch (e: Exception) { @@ -123,4 +124,18 @@ class SshInfoStore @Inject constructor( private const val KEY_PREFIX = "info_" private val nextIdKey = intPreferencesKey("nextInfoId") } -} \ No newline at end of file +} + +/** 持久化记录(含密文/标识)→ libterminal-ssh 的纯连接配置。 */ +fun PersistedSshInfo.toSshInfo(): SshInfo = + SshInfo( + name = name, + host = host, + port = port, + user = user, + authType = com.awkoo.ssh.SshAuthType.valueOf(authType.name), + keyPath = keyPath, + hostKeyFingerprint = hostKeyFingerprint, + keepAliveMs = keepAliveMs, + timeoutMs = timeoutMs + ) \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt b/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt index 2dfc8df..840fe18 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/ui/MainViewModel.kt @@ -11,7 +11,7 @@ import com.awkoo.terminal.Constants import com.awkoo.terminal.core.CredentialCipher import com.awkoo.terminal.core.SessionManager import com.awkoo.terminal.core.ShellInfo -import com.awkoo.terminal.core.SshInfo +import com.awkoo.terminal.core.PersistedSshInfo import com.awkoo.terminal.core.SshInfoStore import com.awkoo.terminal.extrakeys.ExtraKeysConfig import com.awkoo.terminal.ui.theme.ThemeMode @@ -59,7 +59,7 @@ class MainViewModel @Inject constructor( } /** 立即建立 SSH 会话(连接异步、失败不抛到调用线程)。 */ - fun addSshSession(sshInfo: SshInfo) { + fun addSshSession(sshInfo: PersistedSshInfo) { sessionManager.addSshSession(sshInfo, credentialCipher, maxTranscriptRows = transcriptRows.value) ensureTerminalService() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a23fdf7..1d4d846 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -8,6 +8,7 @@ composeBom = "2026.08.00" kotlin = "2.4.20" materialIconsCore = "1.7.8" serialization = "1.11.0" +coroutines = "1.10.2" compose-settings = "3.2.0" uiToolingPreview = "1.12.0" uiTooling = "1.12.0" @@ -36,6 +37,7 @@ composeSettings-ui = { group = "com.github.alorma.compose-settings", name = "ui- composeSettings-ui-extended = { group = "com.github.alorma.compose-settings", name = "ui-tiles-extended", version.ref = "compose-settings" } serialization-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-core", version.ref = "serialization" } serialization-protobuf = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-protobuf", version.ref = "serialization" } +kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } timber = { group = "com.jakewharton.timber", name = "timber", version = "5.0.1" } androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview", version.ref = "uiToolingPreview" } androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "uiTooling" } diff --git a/libterminal-ssh/build.gradle.kts b/libterminal-ssh/build.gradle.kts new file mode 100644 index 0000000..5dcd714 --- /dev/null +++ b/libterminal-ssh/build.gradle.kts @@ -0,0 +1,41 @@ +plugins { + alias(libs.plugins.androidLibrary) +} + +android { + namespace = "com.awkoo.ssh" + ndkVersion = "29.0.14206865" + + compileSdk { + version = release(37) + } + + defaultConfig { + minSdk = 28 + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + externalNativeBuild { + cmake { + path(file("src/main/cpp/CMakeLists.txt")) + version = "4.1.2" + } + } + + compileOptions { + // Flag to enable support for the new language APIs + isCoreLibraryDesugaringEnabled = true + } +} + +kotlin { + jvmToolchain(21) +} + +dependencies { + coreLibraryDesugaring(libs.android.desugar) + api(project(":libterminal")) + implementation(libs.androidx.core) + implementation(libs.kotlinx.coroutines.android) +} \ No newline at end of file diff --git a/libterminal-ssh/src/main/AndroidManifest.xml b/libterminal-ssh/src/main/AndroidManifest.xml new file mode 100644 index 0000000..de749ac --- /dev/null +++ b/libterminal-ssh/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/libterminal-ssh/src/main/cpp/CMakeLists.txt b/libterminal-ssh/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..b703c01 --- /dev/null +++ b/libterminal-ssh/src/main/cpp/CMakeLists.txt @@ -0,0 +1,80 @@ +cmake_minimum_required(VERSION 4.1) + +# 跳过所有 install (含 EXPORT) 生成, +set(CMAKE_SKIP_INSTALL_RULES ON CACHE BOOL "" FORCE) + +project("sshterm") + +set(CMAKE_C_STANDARD 23) +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(TERMINAL_COMPILE_OPTIONS + -Wall -Wextra -Werror + -O3 + -fno-stack-protector + -flto +) + +set(TERMINAL_LINK_OPTIONS + -Wl,--gc-sections + -Wl,-s + -flto +) + +set(THIRD_PARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party) + +set(MBEDTLS_USER_CONFIG_FILE + "${THIRD_PARTY_DIR}/mbedtls_user_config.h" + CACHE FILEPATH "" FORCE) +set(USE_SHARED_MBEDTLS_LIBRARY OFF CACHE BOOL "" FORCE) +set(USE_STATIC_MBEDTLS_LIBRARY ON CACHE BOOL "" FORCE) +set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE) +set(ENABLE_TESTING OFF CACHE BOOL "" FORCE) +set(GEN_FILES OFF CACHE BOOL "" FORCE) +set(CMAKE_POSITION_INDEPENDENT_CODE ON CACHE BOOL "" FORCE) + +add_subdirectory(${THIRD_PARTY_DIR}/mbedtls mbedtls) + +set(MBEDTLS_INCLUDE_DIR + "${THIRD_PARTY_DIR}/mbedtls/include" + CACHE PATH "" FORCE) +set(MBEDTLS_SSL_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedtls.a" + CACHE FILEPATH "" FORCE) +set(MBEDTLS_CRYPTO_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedcrypto.a" + CACHE FILEPATH "" FORCE) +set(MBEDTLS_X509_LIBRARY + "${THIRD_PARTY_DIR}/mbedtls/library/libmbedx509.a" + CACHE FILEPATH "" FORCE) + +set(WITH_MBEDTLS ON CACHE BOOL "" FORCE) +set(WITH_SERVER OFF CACHE BOOL "" FORCE) +set(WITH_ZLIB OFF CACHE BOOL "" FORCE) +set(WITH_EXAMPLES OFF CACHE BOOL "" FORCE) +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(BUILD_STATIC_LIB OFF CACHE BOOL "" FORCE) + +add_subdirectory(${THIRD_PARTY_DIR}/libssh libssh) + +# libssh 的部分平台代码依赖 glibc/bionic 的 BSD 扩展宏 +target_compile_definitions(ssh PRIVATE _BSD_SOURCE=1) + +add_library(sshterm SHARED + sshterm.cpp +) + +target_compile_options(sshterm PRIVATE + ${TERMINAL_COMPILE_OPTIONS} +) + +target_link_libraries(sshterm PRIVATE + ssh::ssh +) + +target_link_options(sshterm PRIVATE + -Wl,--exclude-libs,ALL + ${TERMINAL_LINK_OPTIONS} +) \ No newline at end of file diff --git a/app/src/main/cpp/ssh/sshterm.cpp b/libterminal-ssh/src/main/cpp/sshterm.cpp similarity index 96% rename from app/src/main/cpp/ssh/sshterm.cpp rename to libterminal-ssh/src/main/cpp/sshterm.cpp index 6245fcc..0f6509d 100644 --- a/app/src/main/cpp/ssh/sshterm.cpp +++ b/libterminal-ssh/src/main/cpp/sshterm.cpp @@ -226,7 +226,7 @@ std::string server_fingerprint_of(ssh_session session) { } // namespace extern "C" JNIEXPORT jlong JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshConnect( +Java_com_awkoo_ssh_SshProcess_sshConnect( JNIEnv* env, jclass, jstring jhost, @@ -419,7 +419,7 @@ Java_com_awkoo_terminal_core_SshProcess_sshConnect( } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows, jint cols) { +Java_com_awkoo_ssh_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows, jint cols) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr || h->channel == nullptr) { return; @@ -428,7 +428,7 @@ Java_com_awkoo_terminal_core_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, } extern "C" JNIEXPORT jstring JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong handle) { +Java_com_awkoo_ssh_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr || h->server_fingerprint.empty()) { return nullptr; @@ -437,7 +437,7 @@ Java_com_awkoo_terminal_core_SshProcess_sshGetServerFingerprint(JNIEnv* env, jcl } extern "C" JNIEXPORT jint JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_ssh_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr) { return -1; @@ -453,7 +453,7 @@ Java_com_awkoo_terminal_core_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_ssh_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr) { return; @@ -464,7 +464,7 @@ Java_com_awkoo_terminal_core_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_terminal_core_SshProcess_sshClose(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_ssh_SshProcess_sshClose(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); dispose(h); } \ No newline at end of file diff --git a/app/src/main/cpp/third_party/.gitignore b/libterminal-ssh/src/main/cpp/third_party/.gitignore similarity index 100% rename from app/src/main/cpp/third_party/.gitignore rename to libterminal-ssh/src/main/cpp/third_party/.gitignore diff --git a/app/src/main/cpp/third_party/libssh b/libterminal-ssh/src/main/cpp/third_party/libssh similarity index 100% rename from app/src/main/cpp/third_party/libssh rename to libterminal-ssh/src/main/cpp/third_party/libssh diff --git a/app/src/main/cpp/third_party/mbedtls b/libterminal-ssh/src/main/cpp/third_party/mbedtls similarity index 100% rename from app/src/main/cpp/third_party/mbedtls rename to libterminal-ssh/src/main/cpp/third_party/mbedtls diff --git a/app/src/main/cpp/third_party/mbedtls_user_config.h b/libterminal-ssh/src/main/cpp/third_party/mbedtls_user_config.h similarity index 100% rename from app/src/main/cpp/third_party/mbedtls_user_config.h rename to libterminal-ssh/src/main/cpp/third_party/mbedtls_user_config.h diff --git a/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt b/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt new file mode 100644 index 0000000..f02e91a --- /dev/null +++ b/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt @@ -0,0 +1,38 @@ +package com.awkoo.ssh + +/** + * SSH 连接配置(协议参数)。 + * + * 仅描述"连到哪、如何认证",不含任何持久化/加密假设。敏感凭据 + * (口令、私钥口令)通过 [SshCredentials] 由调用方解密后在调用时 + * 当场提供,存储与加密策略交由使用方自行完成。 + */ +data class SshInfo( + val name: String? = null, + val host: String, + val port: Int = 22, + val user: String, + val authType: SshAuthType = SshAuthType.PASSWORD, + val keyPath: String? = null, + /** 期望的主机密钥指纹(OpenSSH 风格 "SHA256:...");null 表示尚未信任(TOFU)。 */ + val hostKeyFingerprint: String? = null, + val keepAliveMs: Int = 0, + val timeoutMs: Int = 10000 +) + +/** 认证方式。 */ +enum class SshAuthType { + PASSWORD, + PRIVATE_KEY +} + +/** + * 运行期明文凭据。 + * + * 由调用方从自己的存储/加密策略中解密后当场提供;本模块从不落盘, + * 也不持有任何密钥。 + */ +data class SshCredentials( + val password: String? = null, + val keyPassphrase: String? = null +) \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt b/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt similarity index 93% rename from app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt rename to libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt index 83139c8..5636967 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SshProcess.kt +++ b/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt @@ -1,4 +1,4 @@ -package com.awkoo.terminal.core +package com.awkoo.ssh import android.os.ParcelFileDescriptor import com.awkoo.libterminal.process.ITerminalProcess @@ -36,10 +36,12 @@ class SshAuthException(message: String) : SshException(message) * 真正的连接在后台线程进行。连接成功后 native 的 I/O 线程开始搬运字节, * 期间用户先行输入的字节保留在 socket 缓冲中不会丢失;连接失败时 native * 关闭对应 fd,App 侧流读到 EOF,会话按"进程立即退出"结束,不会崩溃。 + * + * 凭据([SshCredentials])为调用方解密后的明文,仅存在于本进程对象生命周期内。 */ class SshProcess( sshInfo: SshInfo, - cipher: CredentialCipher?, + credentials: SshCredentials, rows: Int, columns: Int ) : ITerminalProcess { @@ -101,14 +103,10 @@ class SshProcess( val connFd = socketPair[1].detachFd() scope.launch { - val password = - sshInfo.passwordCipher?.let { cipher?.decrypt(it) } - val passphrase = - sshInfo.keyPassphraseCipher?.let { cipher?.decrypt(it) } val h = try { sshConnect( sshInfo.host, sshInfo.port, sshInfo.user, - password, sshInfo.keyPath, passphrase, + credentials.password, sshInfo.keyPath, credentials.keyPassphrase, sshInfo.hostKeyFingerprint, sshInfo.timeoutMs, connFd, rows, columns ) diff --git a/settings.gradle.kts b/settings.gradle.kts index 2d2f4f5..7e99a9e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -26,3 +26,4 @@ dependencyResolutionManagement { rootProject.name = "AndroidTerminal" include(":app") include(":libterminal") +include(":libterminal-ssh") From 53eb05f826e7f19a32b34c8189c988b1f9b430a8 Mon Sep 17 00:00:00 2001 From: awkoo <133107732+awkox@users.noreply.github.com> Date: Sun, 13 Sep 2026 10:23:45 +0000 Subject: [PATCH 3/4] =?UTF-8?q?refactor:=20=E6=8A=BD=E5=8F=96=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=20PTY=20=E4=B8=BA=20libterminal-lpty,=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=91=BD=E5=90=8D=E7=A9=BA=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新模块 :libterminal-lpty(com.awkoo.libterminal.lpty):LibPtyProcess/ PtyParams + pty.cpp/macro.h native,代为宿主承载本地进程职责 - libterminal-ssh 命名空间统一为 com.awkoo.libterminal.ssh(包目录+ JNI 符号 Java_com_awkoo_libterminal_ssh_SshProcess_*) - LocalPtyProcess 解耦 CommandInfo:模块定义 PtyParams(可执行/工作 目录/argv/环境),app 在 SessionManager 转换 - app 彻底移除 native(externalNativeBuild/CMake/cpp 目录全删),仅作组装层 - SessionManager 注入不变,内部转向 LibPtyProcess + SshProcess --- app/build.gradle.kts | 9 +--- app/src/main/cpp/pty/CMakeLists.txt | 11 ----- .../com/awkoo/terminal/core/SessionManager.kt | 18 ++++++-- .../com/awkoo/terminal/core/SshInfoStore.kt | 4 +- libterminal-lpty/build.gradle.kts | 39 +++++++++++++++++ libterminal-lpty/src/main/AndroidManifest.xml | 2 + .../src/main/cpp/CMakeLists.txt | 18 ++++++-- .../src/main/cpp/include/macro.h | 0 .../src/main/cpp}/pty.cpp | 6 +-- .../com/awkoo/libterminal/lpty/LibPty.kt | 43 +++++++++++++++---- libterminal-ssh/build.gradle.kts | 2 +- libterminal-ssh/src/main/cpp/sshterm.cpp | 12 +++--- .../awkoo/{ => libterminal}/ssh/SshInfo.kt | 2 +- .../awkoo/{ => libterminal}/ssh/SshProcess.kt | 2 +- settings.gradle.kts | 1 + 15 files changed, 120 insertions(+), 49 deletions(-) delete mode 100644 app/src/main/cpp/pty/CMakeLists.txt create mode 100644 libterminal-lpty/build.gradle.kts create mode 100644 libterminal-lpty/src/main/AndroidManifest.xml rename {app => libterminal-lpty}/src/main/cpp/CMakeLists.txt (66%) rename {app => libterminal-lpty}/src/main/cpp/include/macro.h (100%) rename {app/src/main/cpp/pty => libterminal-lpty/src/main/cpp}/pty.cpp (97%) rename app/src/main/kotlin/com/awkoo/terminal/core/LocalPtyProcess.kt => libterminal-lpty/src/main/kotlin/com/awkoo/libterminal/lpty/LibPty.kt (65%) rename libterminal-ssh/src/main/kotlin/com/awkoo/{ => libterminal}/ssh/SshInfo.kt (96%) rename libterminal-ssh/src/main/kotlin/com/awkoo/{ => libterminal}/ssh/SshProcess.kt (99%) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6c8a909..ea605f3 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -8,7 +8,6 @@ plugins { android { namespace = "com.awkoo.terminal" - ndkVersion = "29.0.14206865" compileSdk { version = release(37) @@ -60,13 +59,6 @@ android { isCoreLibraryDesugaringEnabled = true } - externalNativeBuild { - cmake { - path(file("src/main/cpp/CMakeLists.txt")) - version = "4.1.2" - } - } - lint { disable.add("ProtectedPermissions") disable.add("ExpiredTargetSdkVersion") @@ -110,5 +102,6 @@ dependencies { implementation(libs.serialization.protobuf) //implementation(libs.timber) implementation(project(":libterminal")) + implementation(project(":libterminal-lpty")) implementation(project(":libterminal-ssh")) } diff --git a/app/src/main/cpp/pty/CMakeLists.txt b/app/src/main/cpp/pty/CMakeLists.txt deleted file mode 100644 index 1a987b7..0000000 --- a/app/src/main/cpp/pty/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -add_library(pty SHARED - pty.cpp -) - -target_compile_options(pty PRIVATE - ${TERMINAL_COMPILE_OPTIONS} -) - -target_link_options(pty PRIVATE - ${TERMINAL_LINK_OPTIONS} -) \ No newline at end of file diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt index 15def55..de2f339 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt @@ -1,9 +1,11 @@ package com.awkoo.terminal.core import com.awkoo.libterminal.engine.TerminalSession -import com.awkoo.ssh.SshCredentials -import com.awkoo.ssh.SshInfo -import com.awkoo.ssh.SshProcess +import com.awkoo.libterminal.lpty.LibPtyProcess +import com.awkoo.libterminal.lpty.PtyParams +import com.awkoo.libterminal.ssh.SshCredentials +import com.awkoo.libterminal.ssh.SshInfo +import com.awkoo.libterminal.ssh.SshProcess import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -69,7 +71,15 @@ class SessionManager @Inject constructor() { stdin = commandInfo.stdin?.toByteArray(), maxTranscriptRows = maxTranscriptRows ) { rows, cols, w, h -> - LocalPtyProcess(commandInfo, rows, cols, w, h) + LibPtyProcess( + PtyParams( + executable = commandInfo.executable, + cwd = commandInfo.workingDirectory, + arguments = commandInfo.arguments, + environment = commandInfo.environmentArray + ), + rows, cols, w, h + ) } targetSession.execute() diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt index 7cef7a2..7e3c25e 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt +++ b/app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt @@ -6,7 +6,7 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore -import com.awkoo.ssh.SshInfo +import com.awkoo.libterminal.ssh.SshInfo import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first @@ -133,7 +133,7 @@ fun PersistedSshInfo.toSshInfo(): SshInfo = host = host, port = port, user = user, - authType = com.awkoo.ssh.SshAuthType.valueOf(authType.name), + authType = com.awkoo.libterminal.ssh.SshAuthType.valueOf(authType.name), keyPath = keyPath, hostKeyFingerprint = hostKeyFingerprint, keepAliveMs = keepAliveMs, diff --git a/libterminal-lpty/build.gradle.kts b/libterminal-lpty/build.gradle.kts new file mode 100644 index 0000000..1ffe72b --- /dev/null +++ b/libterminal-lpty/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + alias(libs.plugins.androidLibrary) +} + +android { + namespace = "com.awkoo.libterminal.lpty" + ndkVersion = "29.0.14206865" + + compileSdk { + version = release(37) + } + + defaultConfig { + minSdk = 28 + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + externalNativeBuild { + cmake { + path(file("src/main/cpp/CMakeLists.txt")) + version = "4.1.2" + } + } + + compileOptions { + // Flag to enable support for the new language APIs + isCoreLibraryDesugaringEnabled = true + } +} + +kotlin { + jvmToolchain(21) +} + +dependencies { + coreLibraryDesugaring(libs.android.desugar) + api(project(":libterminal")) +} \ No newline at end of file diff --git a/libterminal-lpty/src/main/AndroidManifest.xml b/libterminal-lpty/src/main/AndroidManifest.xml new file mode 100644 index 0000000..de749ac --- /dev/null +++ b/libterminal-lpty/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/app/src/main/cpp/CMakeLists.txt b/libterminal-lpty/src/main/cpp/CMakeLists.txt similarity index 66% rename from app/src/main/cpp/CMakeLists.txt rename to libterminal-lpty/src/main/cpp/CMakeLists.txt index 8bd1d27..ab1343d 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/libterminal-lpty/src/main/cpp/CMakeLists.txt @@ -3,21 +3,21 @@ cmake_minimum_required(VERSION 4.1) # 跳过所有 install (含 EXPORT) 生成, set(CMAKE_SKIP_INSTALL_RULES ON CACHE BOOL "" FORCE) -project("terminal") +project("lpty") set(CMAKE_C_STANDARD 23) set(CMAKE_CXX_STANDARD 23) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(TERMINAL_COMPILE_OPTIONS +set(LPTY_COMPILE_OPTIONS -Wall -Wextra -Werror -O3 -fno-stack-protector -flto ) -set(TERMINAL_LINK_OPTIONS +set(LPTY_LINK_OPTIONS -Wl,--gc-sections -Wl,-s -flto @@ -27,4 +27,14 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/include ) -add_subdirectory(pty) \ No newline at end of file +add_library(pty SHARED + pty.cpp +) + +target_compile_options(pty PRIVATE + ${LPTY_COMPILE_OPTIONS} +) + +target_link_options(pty PRIVATE + ${LPTY_LINK_OPTIONS} +) \ No newline at end of file diff --git a/app/src/main/cpp/include/macro.h b/libterminal-lpty/src/main/cpp/include/macro.h similarity index 100% rename from app/src/main/cpp/include/macro.h rename to libterminal-lpty/src/main/cpp/include/macro.h diff --git a/app/src/main/cpp/pty/pty.cpp b/libterminal-lpty/src/main/cpp/pty.cpp similarity index 97% rename from app/src/main/cpp/pty/pty.cpp rename to libterminal-lpty/src/main/cpp/pty.cpp index 41f5887..39aa472 100644 --- a/app/src/main/cpp/pty/pty.cpp +++ b/libterminal-lpty/src/main/cpp/pty.cpp @@ -130,7 +130,7 @@ static int create_subprocess(JNIEnv* env, extern "C" { -JNIEXPORT jint JNICALL Java_com_awkoo_terminal_core_LocalPtyProcess_createSubprocess( +JNIEXPORT jint JNICALL Java_com_awkoo_libterminal_lpty_LibPtyProcess_createSubprocess( JNIEnv* env, jclass UNUSED(clazz), jstring cmd, @@ -279,7 +279,7 @@ JNIEXPORT jint JNICALL Java_com_awkoo_terminal_core_LocalPtyProcess_createSubpro return ptm; } -JNIEXPORT void JNICALL Java_com_awkoo_terminal_core_LocalPtyProcess_setPtyWindowSize( +JNIEXPORT void JNICALL Java_com_awkoo_libterminal_lpty_LibPtyProcess_setPtyWindowSize( JNIEnv* UNUSED(env), jclass UNUSED(clazz), jint fd, @@ -296,7 +296,7 @@ JNIEXPORT void JNICALL Java_com_awkoo_terminal_core_LocalPtyProcess_setPtyWindow ioctl(fd, TIOCSWINSZ, &sz); } -JNIEXPORT jint JNICALL Java_com_awkoo_terminal_core_LocalPtyProcess_waitFor( +JNIEXPORT jint JNICALL Java_com_awkoo_libterminal_lpty_LibPtyProcess_waitFor( JNIEnv* UNUSED(env), jclass UNUSED(clazz), jint pid) { diff --git a/app/src/main/kotlin/com/awkoo/terminal/core/LocalPtyProcess.kt b/libterminal-lpty/src/main/kotlin/com/awkoo/libterminal/lpty/LibPty.kt similarity index 65% rename from app/src/main/kotlin/com/awkoo/terminal/core/LocalPtyProcess.kt rename to libterminal-lpty/src/main/kotlin/com/awkoo/libterminal/lpty/LibPty.kt index 195687d..6098169 100644 --- a/app/src/main/kotlin/com/awkoo/terminal/core/LocalPtyProcess.kt +++ b/libterminal-lpty/src/main/kotlin/com/awkoo/libterminal/lpty/LibPty.kt @@ -1,4 +1,4 @@ -package com.awkoo.terminal.core +package com.awkoo.libterminal.lpty import android.os.ParcelFileDescriptor import android.system.ErrnoException @@ -10,8 +10,29 @@ import java.io.FileOutputStream import java.io.InputStream import java.io.OutputStream -class LocalPtyProcess( - commandInfo: CommandInfo, +/** + * 本地终端启动参数(模块原生层参数载体)。 + * + * 仅描述"拉起什么进程",环境排序与命令组装由调用方负责; + * [arguments] 应为完整 argv(含可执行名),风格与 AppCompat 的 + * 命令行组装保持一致。 + */ +data class PtyParams( + val executable: String, + val cwd: String, + val arguments: Array = emptyArray(), + val environment: Array> = emptyArray() +) + +/** + * 本地 PTY 进程(fork/exec + pseudoterminal)。 + * + * 与 [PtyParams] 的解耦:本模块只负责通过 POSIX ptmx 拉起 + * 本地子进程并暴露标准 Java 流;工作目录、环境变量、argv 等 + * 一律由调用方通过 [PtyParams] 传入。 + */ +class LibPtyProcess( + params: PtyParams, rows: Int, columns: Int, cellWidth: Int, @@ -20,7 +41,9 @@ class LocalPtyProcess( companion object { init { System.loadLibrary("pty") } - @JvmStatic private external fun createSubprocess( + + @JvmStatic + private external fun createSubprocess( cmd: String, cwd: String, args: Array?, @@ -31,8 +54,12 @@ class LocalPtyProcess( cellWidth: Int, cellHeight: Int ): Int - @JvmStatic private external fun setPtyWindowSize(fd: Int, rows: Int, cols: Int, cellWidth: Int, cellHeight: Int) - @JvmStatic private external fun waitFor(processId: Int): Int + + @JvmStatic + private external fun setPtyWindowSize(fd: Int, rows: Int, cols: Int, cellWidth: Int, cellHeight: Int) + + @JvmStatic + private external fun waitFor(processId: Int): Int } /** 本地 OS 进程号,仅本类内部用于 [kill]/[waitFor],不对外暴露。 */ @@ -45,8 +72,8 @@ class LocalPtyProcess( init { val processIdArray = IntArray(1) val fdInt = createSubprocess( - commandInfo.executable, commandInfo.workingDirectory, - commandInfo.arguments, commandInfo.environmentArray, + params.executable, params.cwd, + params.arguments, params.environment, processIdArray, rows, columns, cellWidth, cellHeight ) diff --git a/libterminal-ssh/build.gradle.kts b/libterminal-ssh/build.gradle.kts index 5dcd714..e2c6e9a 100644 --- a/libterminal-ssh/build.gradle.kts +++ b/libterminal-ssh/build.gradle.kts @@ -3,7 +3,7 @@ plugins { } android { - namespace = "com.awkoo.ssh" + namespace = "com.awkoo.libterminal.ssh" ndkVersion = "29.0.14206865" compileSdk { diff --git a/libterminal-ssh/src/main/cpp/sshterm.cpp b/libterminal-ssh/src/main/cpp/sshterm.cpp index 0f6509d..fc404f5 100644 --- a/libterminal-ssh/src/main/cpp/sshterm.cpp +++ b/libterminal-ssh/src/main/cpp/sshterm.cpp @@ -226,7 +226,7 @@ std::string server_fingerprint_of(ssh_session session) { } // namespace extern "C" JNIEXPORT jlong JNICALL -Java_com_awkoo_ssh_SshProcess_sshConnect( +Java_com_awkoo_libterminal_ssh_SshProcess_sshConnect( JNIEnv* env, jclass, jstring jhost, @@ -419,7 +419,7 @@ Java_com_awkoo_ssh_SshProcess_sshConnect( } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_ssh_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows, jint cols) { +Java_com_awkoo_libterminal_ssh_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows, jint cols) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr || h->channel == nullptr) { return; @@ -428,7 +428,7 @@ Java_com_awkoo_ssh_SshProcess_sshResize(JNIEnv*, jclass, jlong handle, jint rows } extern "C" JNIEXPORT jstring JNICALL -Java_com_awkoo_ssh_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong handle) { +Java_com_awkoo_libterminal_ssh_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr || h->server_fingerprint.empty()) { return nullptr; @@ -437,7 +437,7 @@ Java_com_awkoo_ssh_SshProcess_sshGetServerFingerprint(JNIEnv* env, jclass, jlong } extern "C" JNIEXPORT jint JNICALL -Java_com_awkoo_ssh_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_libterminal_ssh_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr) { return -1; @@ -453,7 +453,7 @@ Java_com_awkoo_ssh_SshProcess_sshWait(JNIEnv*, jclass, jlong handle) { } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_ssh_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_libterminal_ssh_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); if (h == nullptr) { return; @@ -464,7 +464,7 @@ Java_com_awkoo_ssh_SshProcess_sshKill(JNIEnv*, jclass, jlong handle) { } extern "C" JNIEXPORT void JNICALL -Java_com_awkoo_ssh_SshProcess_sshClose(JNIEnv*, jclass, jlong handle) { +Java_com_awkoo_libterminal_ssh_SshProcess_sshClose(JNIEnv*, jclass, jlong handle) { native_ssh* h = reinterpret_cast(handle); dispose(h); } \ No newline at end of file diff --git a/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt b/libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshInfo.kt similarity index 96% rename from libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt rename to libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshInfo.kt index f02e91a..53f2e1b 100644 --- a/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshInfo.kt +++ b/libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshInfo.kt @@ -1,4 +1,4 @@ -package com.awkoo.ssh +package com.awkoo.libterminal.ssh /** * SSH 连接配置(协议参数)。 diff --git a/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt b/libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshProcess.kt similarity index 99% rename from libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt rename to libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshProcess.kt index 5636967..54f814d 100644 --- a/libterminal-ssh/src/main/kotlin/com/awkoo/ssh/SshProcess.kt +++ b/libterminal-ssh/src/main/kotlin/com/awkoo/libterminal/ssh/SshProcess.kt @@ -1,4 +1,4 @@ -package com.awkoo.ssh +package com.awkoo.libterminal.ssh import android.os.ParcelFileDescriptor import com.awkoo.libterminal.process.ITerminalProcess diff --git a/settings.gradle.kts b/settings.gradle.kts index 7e99a9e..1bdf354 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -26,4 +26,5 @@ dependencyResolutionManagement { rootProject.name = "AndroidTerminal" include(":app") include(":libterminal") +include(":libterminal-lpty") include(":libterminal-ssh") From 8a3bb710a5074bd402b8db0c8ee3802e0ca68ab1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:17:18 +0000 Subject: [PATCH 4/4] Bump org.jetbrains.kotlinx:kotlinx-coroutines-android Bumps [org.jetbrains.kotlinx:kotlinx-coroutines-android](https://github.com/Kotlin/kotlinx.coroutines) from 1.10.2 to 1.11.0. - [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases) - [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md) - [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.10.2...1.11.0) --- updated-dependencies: - dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-android dependency-version: 1.11.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1d4d846..aa3dd0d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -8,7 +8,7 @@ composeBom = "2026.08.00" kotlin = "2.4.20" materialIconsCore = "1.7.8" serialization = "1.11.0" -coroutines = "1.10.2" +coroutines = "1.11.0" compose-settings = "3.2.0" uiToolingPreview = "1.12.0" uiTooling = "1.12.0"