diff --git a/.verify/01_connections.png b/.verify/01_connections.png new file mode 100644 index 0000000..b1c9e84 Binary files /dev/null and b/.verify/01_connections.png differ diff --git a/entry/src/main/ets/session/TerminalSession.ts b/entry/src/main/ets/session/TerminalSession.ts index d0bcf69..d6fe823 100644 --- a/entry/src/main/ets/session/TerminalSession.ts +++ b/entry/src/main/ets/session/TerminalSession.ts @@ -231,15 +231,19 @@ export class TerminalSession { if (this.ssh === ssh && this.emulator === emu && this.state === SessionState.READY) { this.channel = ch; this.notifyData(); + Log.info(TerminalSession.TAG, `session #${this.id} shell channel attached`); } else { + Log.warn(TerminalSession.TAG, + `session #${this.id} shell opened but session changed (ssh=${this.ssh === ssh}, ` + + `emu=${this.emulator === emu}, state=${this.state}), closing channel`); ch.close().catch((): void => { }); } }) .catch((e: Object): void => { this.shellPending = false; + Log.error(TerminalSession.TAG, `openShell failed: ${(e as Error).message}`); if (this.ssh === ssh && this.emulator === emu && this.state === SessionState.READY) { - Log.error(TerminalSession.TAG, `openShell failed: ${(e as Error).message}`); this.emulator = null; this.failStale(ssh, friendlyError((e as Error).message)); } @@ -272,6 +276,8 @@ export class TerminalSession { ch.write(data).catch((e: Object): void => { Log.warn(TerminalSession.TAG, `write failed: ${(e as Error).message}`); }); + } else { + Log.warn(TerminalSession.TAG, `input dropped: no channel (${data.length}B, state=${this.state})`); } } @@ -445,6 +451,16 @@ export class TerminalSession { this.closeReason = reason; this.setState(SessionState.CLOSED); Log.warn(TerminalSession.TAG, `session #${this.id} dropped: ${reason}`); + return; + } + // Transport death mid-attempt (connect/KEX/auth): the engine waiter may + // never fire, so surface the failure here instead of hanging the UI. + if (this.state === SessionState.CONNECTING || this.state === SessionState.HOSTKEY_WAIT || + this.state === SessionState.AUTHENTICATING) { + const ssh: SshSession | null = this.ssh; + if (ssh !== null) { + this.failStale(ssh, `连接中断:${reason}`); + } } } diff --git a/entry/src/main/ets/ssh/Channel.ts b/entry/src/main/ets/ssh/Channel.ts index 65f28b0..d606bf2 100644 --- a/entry/src/main/ets/ssh/Channel.ts +++ b/entry/src/main/ets/ssh/Channel.ts @@ -14,7 +14,7 @@ import { SshTransport } from './Transport'; import { SshMsg } from './SshTypes'; -import { SshReader, SshWriter } from './SshWire'; +import { SshReader, SshWriter, bytesToHex } from './SshWire'; import { Log } from '../common/Log'; /** Local receive window and max packet we advertise (2 MiB / 32 KiB). */ @@ -162,6 +162,8 @@ export class SshChannel { throw new Error('SshChannel: channel closed while writing'); } if (this.remoteWindow <= 0) { + Log.warn(SshChannel.TAG, + `write blocked at ${offset}/${data.length}: remote window 0, waiting for adjust`); await this.waitForWindow(); continue; } @@ -297,7 +299,8 @@ export class SshChannel { resolve(); } Log.debug(SshChannel.TAG, - `channel ${this.localId} open (remote ${this.remoteId}, window ${this.remoteWindow})`); + `channel ${this.localId} open (remote ${this.remoteId}, window ${this.remoteWindow}, ` + + `maxPkt ${this.remoteMaxPacket}) conf=${bytesToHex(payload)}`); } private onOpenFailure(payload: Uint8Array): void { @@ -324,6 +327,7 @@ export class SshChannel { r.readUint32(); const inc: number = r.readUint32(); this.remoteWindow = Math.min(this.remoteWindow + inc, 4294967295); + Log.debug(SshChannel.TAG, `channel ${this.localId} window +${inc} -> ${this.remoteWindow}`); this.flushWindowWaiters(); } @@ -386,6 +390,8 @@ export class SshChannel { } private onReply(ok: boolean): void { + Log.debug(SshChannel.TAG, `channel ${this.localId} reply ok=${ok} ` + + `(armed=${this.replyResolve !== undefined})`); if (this.replyTimerId >= 0) { clearTimeout(this.replyTimerId); this.replyTimerId = -1; @@ -399,6 +405,7 @@ export class SshChannel { } private waitReply(what: string, timeoutMs: number): Promise { + Log.debug(SshChannel.TAG, `channel ${this.localId} waiting reply for '${what}'`); return new Promise((resolve: (ok: boolean) => void, reject: (err: Error) => void): void => { if (this.replyTimerId >= 0) { diff --git a/entry/src/main/ets/ssh/OhosTcpSocket.ts b/entry/src/main/ets/ssh/OhosTcpSocket.ts index bb4361d..e73bc65 100644 --- a/entry/src/main/ets/ssh/OhosTcpSocket.ts +++ b/entry/src/main/ets/ssh/OhosTcpSocket.ts @@ -46,11 +46,47 @@ export class TcpRawSocket implements RawSocket { connect(host: string, port: number, timeoutMs: number): Promise { const addr: socket.NetAddress = { address: host, port: port }; const opts: socket.TCPConnectOptions = { address: addr, timeout: timeoutMs }; - return this.sock.connect(opts); + // TCPConnectOptions.timeout is not reliable on every network stack (e.g. + // emulator NAT with an unroutable address leaves SYN retries hanging far + // beyond the requested timeout), so race it with an application-level + // watchdog and tear the socket down when it fires. + return new Promise((resolve: () => void, reject: (e: Error) => void): void => { + let settled: boolean = false; + const watchdogId: number = setTimeout((): void => { + if (settled) { + return; + } + settled = true; + Log.warn(TcpRawSocket.TAG, `connect watchdog fired after ${timeoutMs + 2000} ms`); + this.close(); + reject(new Error(`connect timed out after ${timeoutMs} ms`)); + }, timeoutMs + 2000); + this.sock.connect(opts).then((): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(watchdogId); + Log.info(TcpRawSocket.TAG, `connect established to ${host}:${port}`); + resolve(); + }, (e: Object): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(watchdogId); + const err = e as BusinessError; + Log.error(TcpRawSocket.TAG, `connect failed (${err.code}): ${err.message}`); + reject(new Error(`connect failed: ${err.message}`)); + }); + }); } send(bytes: Uint8Array): Promise { - return this.sock.send(u8ToArrayBuffer(bytes)); + // TCPSocket.send takes TCPSendOptions, not a raw ArrayBuffer — passing + // the buffer directly fails with BusinessError 401 "Parameter error". + const opts: socket.TCPSendOptions = { data: u8ToArrayBuffer(bytes) }; + return this.sock.send(opts); } onData(cb: (chunk: Uint8Array) => void): void { diff --git a/entry/src/main/ets/ssh/PacketCodec.ts b/entry/src/main/ets/ssh/PacketCodec.ts index ac01527..387a38e 100644 --- a/entry/src/main/ets/ssh/PacketCodec.ts +++ b/entry/src/main/ets/ssh/PacketCodec.ts @@ -3,6 +3,9 @@ * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. */ +import { Log } from '../common/Log'; +import { bytesToHex } from './SshWire'; + /** * SSH binary packet protocol codec (RFC 4253 §6), with mounting points for * encrypted modes (RFC 5647 GCM, encrypt-then-MAC) that T4 fills in. @@ -77,6 +80,11 @@ export class PacketCodec { this.inCipher = cipher; } + /** True once the inbound cipher is installed (post-NEWKEYS traffic). */ + hasInCipher(): boolean { + return this.inCipher !== undefined; + } + /** Drop ciphers (used by tests / connection teardown). */ clearCiphers(): void { this.outCipher = undefined; @@ -122,6 +130,12 @@ export class PacketCodec { if (chunk.length === 0) { return; } + // Plaintext phase (pre-NEWKEYS) chunks are few and small; log them so + // stream-misalignment bugs can be diagnosed from raw bytes. + if (this.inCipher === undefined) { + const head: Uint8Array = chunk.subarray(0, Math.min(16, chunk.length)); + Log.debug('PacketCodec', `plain chunk ${chunk.length}B [${bytesToHex(head)}]`); + } this.ensureCapacity(this.bufferLen + chunk.length); this.buffer.set(chunk, this.bufferLen); this.bufferLen += chunk.length; @@ -164,13 +178,16 @@ export class PacketCodec { } const packetLen: number = ((this.buffer[0] * 256 + this.buffer[1]) * 256 + this.buffer[2]) * 256 + this.buffer[3]; if (packetLen < 12) { + this.dumpFailure(`packet_length ${packetLen} below minimum 12`); throw new Error(`PacketCodec: packet_length ${packetLen} below minimum 12`); } if (packetLen > PacketCodec.MAX_PACKET_LEN) { + this.dumpFailure(`packet_length ${packetLen} exceeds limit`); throw new Error(`PacketCodec: packet_length ${packetLen} exceeds limit`); } // Unencrypted packets are multiples of the 8-byte block (RFC 4253 §6). if ((4 + packetLen) % 8 !== 0) { + this.dumpFailure(`total length ${4 + packetLen} not a multiple of 8`); throw new Error(`PacketCodec: total length ${4 + packetLen} not a multiple of 8`); } if (this.bufferLen < 4 + packetLen) { @@ -189,8 +206,15 @@ export class PacketCodec { return payload; } - private ensureCapacity(need: number): void { - if (need <= this.buffer.length) { + /** Log the offending buffer bytes before a plaintext decode failure. */ + private dumpFailure(reason: string): void { + const n: number = Math.min(48, this.bufferLen); + const head: Uint8Array = this.buffer.subarray(0, n); + Log.error('PacketCodec', + `decode fail (${reason}) buffered=${this.bufferLen} head=[${bytesToHex(head)}]`); + } + + private ensureCapacity(need: number): void { if (need <= this.buffer.length) { return; } let cap: number = this.buffer.length * 2; diff --git a/entry/src/main/ets/ssh/SshSession.ts b/entry/src/main/ets/ssh/SshSession.ts index 361553c..92ccb2b 100644 --- a/entry/src/main/ets/ssh/SshSession.ts +++ b/entry/src/main/ets/ssh/SshSession.ts @@ -106,6 +106,12 @@ export class SshSession { await this.socket.connect(host, port, this.connectTimeoutMs); const serverBanner: string = await this.transport.start(SshVersion.CLIENT_BANNER, this.connectTimeoutMs); + // Transport death during KEX must surface immediately (the kex waiter + // may not be armed when a decode error hits, which used to leave the + // session hanging until an unrelated timeout). + this.transport.onClose((reason: string): void => { + this.handleTransportClosed(reason); + }); this.setState(SshSessionState.KEX); const engine: KexEngine = new KexEngine(this.transport, (algo: string, blob: Uint8Array, fp: string): Promise => { @@ -115,9 +121,6 @@ export class SshSession { const result: KexResult = await engine.run(SshVersion.CLIENT_BANNER, serverBanner, this.kexTimeoutMs); this.sessionId = result.sessionId; - this.transport.onClose((reason: string): void => { - this.handleTransportClosed(reason); - }); Log.info(SshSession.TAG, `connected to ${host}:${port} (kex ${result.negotiated.kex})`); } catch (e) { this.setState(SshSessionState.ERROR); diff --git a/entry/src/main/ets/ssh/Transport.ts b/entry/src/main/ets/ssh/Transport.ts index 7f63741..134f2c3 100644 --- a/entry/src/main/ets/ssh/Transport.ts +++ b/entry/src/main/ets/ssh/Transport.ts @@ -71,6 +71,16 @@ export class SshTransport { private dispatching: boolean = false; private sendChain: Promise = Promise.resolve(); private closeCallback: ((reason: string) => void) | undefined = undefined; + // Packets decoded while neither a waitPacket waiter nor the onPacket + // dispatcher was armed (async crypto between kex steps opens such windows). + // waitPacket() drains this queue before suspending, so early arrivals are + // never lost. + private queuedPackets: Uint8Array[] = []; + // Set when the plaintext NEWKEYS has been decoded in an unencrypted stream: + // everything after it is ciphertext for the not-yet-installed inbound + // cipher (servers commonly write KEXDH_REPLY+NEWKEYS+first encrypted packet + // back to back, RFC 4253 §7.3). drainLoop stops until setInCipher() runs. + private plainDecodeBlocked: boolean = false; constructor(socket: RawSocket) { this.socket = socket; @@ -126,6 +136,11 @@ export class SshTransport { * never reject the new waiter. */ async waitPacket(timeoutMs: number): Promise { + if (this.queuedPackets.length > 0) { + const queued: Uint8Array = this.queuedPackets[0]; + this.queuedPackets = this.queuedPackets.slice(1); + return Promise.resolve(queued); + } return new Promise((resolve: (p: Uint8Array) => void, reject: (e: Error) => void): void => { if (this.packetWaiterTimerId >= 0) { clearTimeout(this.packetWaiterTimerId); @@ -214,6 +229,11 @@ export class SshTransport { /** Install the inbound cipher after receiving NEWKEYS (T5 wires this). */ setInCipher(cipher: PacketCipher): void { this.codec.setInCipher(cipher); + if (this.plainDecodeBlocked) { + // Buffered ciphertext can now be decrypted; resume draining. + this.plainDecodeBlocked = false; + this.drainPackets(); + } } /** @@ -369,6 +389,11 @@ export class SshTransport { private async drainLoop(): Promise { while (!this.closed) { + if (this.plainDecodeBlocked) { + // NEWKEYS already decoded in the plaintext stream; everything left + // in the buffer is ciphertext for the pending inbound cipher. + return; + } const payload: Uint8Array | undefined = await this.codec.nextPacket(); if (payload === undefined) { return; @@ -387,6 +412,18 @@ export class SshTransport { const cb: ((payload: Uint8Array) => void) | undefined = this.packetCallback; if (cb !== undefined) { cb(payload); + } else if (waiter === undefined) { + // Nobody armed yet (kex crypto windows): keep the payload for the + // next waitPacket() instead of dropping it. + this.queuedPackets.push(payload); + } + // In an unencrypted stream NEWKEYS is the final plaintext packet; the + // server may pipeline the first encrypted packet right behind it in + // the same TCP segment, and plaintext decoding of those bytes would + // desync the stream. Block until the inbound cipher is installed. + if (!this.codec.hasInCipher() && payload.length > 0 && payload[0] === SshMsg.NEWKEYS) { + this.plainDecodeBlocked = true; + return; } } } diff --git a/entry/src/main/ets/ui/KeysPage.ets b/entry/src/main/ets/ui/KeysPage.ets index dd1dbf7..06e0f97 100644 --- a/entry/src/main/ets/ui/KeysPage.ets +++ b/entry/src/main/ets/ui/KeysPage.ets @@ -25,10 +25,15 @@ import { base64ToBytes, bytesToBase64, bytesToUtf8 } from '../ssh/SshWire'; import { authorizedKeysLine } from '../ssh/crypto/KeyImport'; import { copyText, showToast } from './SessionLaunch'; -/** RSA-4096 generation is synchronous and heavy — always run off the UI thread. */ +/** + * RSA-4096 generation is synchronous and heavy — always run off the UI + * thread. Must be an async concurrent function: a sync function returning + * a pending Promise fails taskpool result serialization with + * "Can't return Promise in pending state". + */ @Concurrent -function generateKeyTask(keyType: string, name: string): Promise { - return generateKey(keyType, name); +async function generateKeyTask(keyType: string, name: string): Promise { + return await generateKey(keyType, name); } @Component diff --git a/entry/src/main/ets/ui/TerminalPage.ets b/entry/src/main/ets/ui/TerminalPage.ets index cac6e85..b7eda0d 100644 --- a/entry/src/main/ets/ui/TerminalPage.ets +++ b/entry/src/main/ets/ui/TerminalPage.ets @@ -9,6 +9,7 @@ */ import { pasteboard } from '@kit.BasicServicesKit'; +import { Log } from '../common/Log'; import { HostColors } from '../common/HostColors'; import { SessionManager } from '../session/SessionManager'; import { SessionState, TerminalSession } from '../session/TerminalSession'; @@ -41,6 +42,10 @@ export struct TerminalPage { @State sessions: TerminalSession[] = []; @State activeId: number = -1; @State activeSnapshot: TerminalSession | null = null; + // Primitive mirror of activeSnapshot.getState(): reassigning the same class + // reference never triggers an ArkUI V1 re-render, so the body branch must + // be driven by this string state instead (refresh() keeps it in sync). + @State activeState: SessionState = SessionState.IDLE; @State passwordInput: string = ''; @State rememberPassword: boolean = true; @State fontSizeVp: number = 14; @@ -59,6 +64,13 @@ export struct TerminalPage { }); this.loadSettings(); this.refresh(); + // Catch-up refresh: a session that fails immediately after launch fires + // its ERROR notification before this page mounts (the tab switch happens + // after SessionManager.launch), so the subscription misses it and the + // panel would otherwise stay on "connecting" forever. + setTimeout((): void => { + this.refresh(); + }, 200); } aboutToDisappear(): void { @@ -81,6 +93,8 @@ export struct TerminalPage { const active: number | null = manager.getActiveId(); this.activeId = active === null ? -1 : active; this.activeSnapshot = manager.getActive(); + this.activeState = this.activeSnapshot === null ? + SessionState.IDLE : this.activeSnapshot.getState(); const current: TerminalSession | null = manager.getActive(); if (current === null || current.getState() !== SessionState.AUTH_REQUIRED) { this.passwordInput = ''; @@ -147,6 +161,7 @@ export struct TerminalPage { const v: string = this.textInputValue; this.textInputValue = ''; this.textInputVisible = false; + Log.info('TerminalPage', `sendTextLine: len=${v.length} withEnter=${withEnter} text="${v}"`); if (v.length > 0) { session.sendText(withEnter ? v + '\r' : v); } @@ -426,19 +441,19 @@ export struct TerminalPage { @Builder sessionBody(session: TerminalSession) { Column() { - if (session.getState() === SessionState.READY) { + if (this.activeState === SessionState.READY) { this.readyBody(session) - } else if (session.getState() === SessionState.CONNECTING) { + } else if (this.activeState === SessionState.CONNECTING) { this.progressPanel(`正在连接 ${session.getSubtitle()} …`) - } else if (session.getState() === SessionState.HOSTKEY_WAIT) { + } else if (this.activeState === SessionState.HOSTKEY_WAIT) { this.progressPanel('请在弹窗中确认主机密钥…') - } else if (session.getState() === SessionState.AUTHENTICATING) { + } else if (this.activeState === SessionState.AUTHENTICATING) { this.progressPanel('正在认证…') - } else if (session.getState() === SessionState.AUTH_REQUIRED) { + } else if (this.activeState === SessionState.AUTH_REQUIRED) { this.passwordPanel(session) - } else if (session.getState() === SessionState.ERROR) { + } else if (this.activeState === SessionState.ERROR) { this.endPanel('连接失败', session.getErrorText(), session) - } else if (session.getState() === SessionState.CLOSED) { + } else if (this.activeState === SessionState.CLOSED) { this.endPanel('连接已关闭', session.getCloseReason(), session) } }