generated from ali/HarmonyTemplate
484 lines
16 KiB
TypeScript
484 lines
16 KiB
TypeScript
/*
|
|
* Copyright (c) 2026 Haven for HarmonyOS contributors.
|
|
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
|
|
*/
|
|
|
|
/**
|
|
* SSH "session" channel (RFC 4254 §5): open/confirmation, flow-controlled
|
|
* DATA both ways, channel requests (pty-req / shell / exec /
|
|
* window-change, §5.4/§6) and the EOF/CLOSE lifecycle. Inbound packets are
|
|
* routed here by SshSession's dispatcher; replies are awaited through
|
|
* per-channel promise slots, never through SshTransport.waitPacket (the
|
|
* dispatcher is already installed while channels are live).
|
|
*/
|
|
|
|
import { SshTransport } from './Transport';
|
|
import { SshMsg } from './SshTypes';
|
|
import { SshReader, SshWriter } from './SshWire';
|
|
import { Log } from '../common/Log';
|
|
|
|
/** Local receive window and max packet we advertise (2 MiB / 32 KiB). */
|
|
const LOCAL_WINDOW: number = 2097152;
|
|
const LOCAL_MAX_PACKET: number = 32768;
|
|
/** Send WINDOW_ADJUST once half the local window has been consumed. */
|
|
const ADJUST_THRESHOLD: number = LOCAL_WINDOW / 2;
|
|
|
|
/** Inbound callbacks for one channel. */
|
|
export interface ChannelCallbacks {
|
|
onData: (data: Uint8Array) => void;
|
|
onExtendedData: (data: Uint8Array) => void;
|
|
onClose: () => void;
|
|
}
|
|
|
|
export class SshChannel {
|
|
private static readonly TAG: string = 'SshChannel';
|
|
|
|
readonly localId: number;
|
|
private readonly transport: SshTransport;
|
|
private readonly callbacks: ChannelCallbacks;
|
|
|
|
private remoteId: number = -1;
|
|
private remoteWindow: number = 0;
|
|
private remoteMaxPacket: number = 0;
|
|
private localWindowConsumed: number = 0;
|
|
private exitStatus: number = -1;
|
|
|
|
private closed: boolean = false;
|
|
private sentClose: boolean = false;
|
|
private eof: boolean = false;
|
|
|
|
private openResolve: (() => void) | undefined = undefined;
|
|
private openReject: ((err: Error) => void) | undefined = undefined;
|
|
private openTimerId: number = -1;
|
|
|
|
private replyResolve: ((ok: boolean) => void) | undefined = undefined;
|
|
private replyReject: ((err: Error) => void) | undefined = undefined;
|
|
private replyTimerId: number = -1;
|
|
|
|
private readonly windowWaiters: Array<() => void> = [];
|
|
private readonly closedWaiters: Array<(v: boolean) => void> = [];
|
|
|
|
constructor(transport: SshTransport, localId: number, callbacks: ChannelCallbacks) {
|
|
this.transport = transport;
|
|
this.localId = localId;
|
|
this.callbacks = callbacks;
|
|
}
|
|
|
|
/** Open the channel and wait for the server's confirmation. */
|
|
async open(timeoutMs: number): Promise<void> {
|
|
const w: SshWriter = new SshWriter(48);
|
|
w.writeByte(SshMsg.CHANNEL_OPEN);
|
|
w.writeString('session');
|
|
w.writeUint32(this.localId);
|
|
w.writeUint32(LOCAL_WINDOW);
|
|
w.writeUint32(LOCAL_MAX_PACKET);
|
|
const opened: Promise<void> = new Promise<void>((resolve: () => void,
|
|
reject: (err: Error) => void): void => {
|
|
this.openResolve = resolve;
|
|
this.openReject = reject;
|
|
this.openTimerId = setTimeout((): void => {
|
|
if (this.openReject !== undefined) {
|
|
this.openReject(new Error('SshChannel: open confirmation timeout'));
|
|
this.openResolve = undefined;
|
|
this.openReject = undefined;
|
|
}
|
|
}, timeoutMs);
|
|
});
|
|
// If sendPacket below throws first, the timer above would later reject
|
|
// a promise nobody awaits; mark it handled (await below still throws).
|
|
opened.catch((e: Object): void => {
|
|
const err = e as Error;
|
|
Log.debug(SshChannel.TAG, `open wait aborted: ${err.message}`);
|
|
});
|
|
await this.transport.sendPacket(w.toBytes());
|
|
await opened;
|
|
}
|
|
|
|
/** pty-req (RFC 4254 §6.2), want_reply = true. */
|
|
async requestPty(cols: number, rows: number, timeoutMs: number): Promise<boolean> {
|
|
const w: SshWriter = new SshWriter(80);
|
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
|
w.writeUint32(this.remoteId);
|
|
w.writeString('pty-req');
|
|
w.writeBoolean(true);
|
|
w.writeString('xterm-256color');
|
|
w.writeUint32(cols);
|
|
w.writeUint32(rows);
|
|
w.writeUint32(0); // pixel width
|
|
w.writeUint32(0); // pixel height
|
|
w.writeString(''); // no terminal modes
|
|
await this.transport.sendPacket(w.toBytes());
|
|
return this.waitReply('pty-req', timeoutMs);
|
|
}
|
|
|
|
/** shell request (RFC 4254 §6.1), want_reply = true. */
|
|
async requestShell(timeoutMs: number): Promise<boolean> {
|
|
const w: SshWriter = new SshWriter(32);
|
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
|
w.writeUint32(this.remoteId);
|
|
w.writeString('shell');
|
|
w.writeBoolean(true);
|
|
await this.transport.sendPacket(w.toBytes());
|
|
return this.waitReply('shell', timeoutMs);
|
|
}
|
|
|
|
/** exec request (RFC 4254 §6.5), want_reply = true. */
|
|
async exec(command: string, timeoutMs: number): Promise<boolean> {
|
|
const w: SshWriter = new SshWriter(command.length + 32);
|
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
|
w.writeUint32(this.remoteId);
|
|
w.writeString('exec');
|
|
w.writeBoolean(true);
|
|
w.writeString(command);
|
|
await this.transport.sendPacket(w.toBytes());
|
|
return this.waitReply('exec', timeoutMs);
|
|
}
|
|
|
|
/** window-change (RFC 4254 §6.7), fire and forget. */
|
|
async resize(cols: number, rows: number): Promise<void> {
|
|
if (this.closed || this.remoteId < 0) {
|
|
return;
|
|
}
|
|
const w: SshWriter = new SshWriter(40);
|
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
|
w.writeUint32(this.remoteId);
|
|
w.writeString('window-change');
|
|
w.writeBoolean(false);
|
|
w.writeUint32(cols);
|
|
w.writeUint32(rows);
|
|
w.writeUint32(0);
|
|
w.writeUint32(0);
|
|
await this.transport.sendPacket(w.toBytes());
|
|
}
|
|
|
|
/**
|
|
* Flow-controlled write: chunks to min(remoteMaxPacket, LOCAL_MAX_PACKET,
|
|
* remoteWindow) and awaits while the remote window is exhausted.
|
|
*/
|
|
async write(data: Uint8Array): Promise<void> {
|
|
let offset: number = 0;
|
|
while (offset < data.length) {
|
|
if (this.closed) {
|
|
throw new Error('SshChannel: channel closed while writing');
|
|
}
|
|
if (this.remoteWindow <= 0) {
|
|
await this.waitForWindow();
|
|
continue;
|
|
}
|
|
const room: number = Math.min(this.remoteMaxPacket, LOCAL_MAX_PACKET,
|
|
this.remoteWindow, data.length - offset);
|
|
const chunk: Uint8Array = data.slice(offset, offset + room);
|
|
const w: SshWriter = new SshWriter(chunk.length + 16);
|
|
w.writeByte(SshMsg.CHANNEL_DATA);
|
|
w.writeUint32(this.remoteId);
|
|
w.writeStringBytes(chunk);
|
|
await this.transport.sendPacket(w.toBytes());
|
|
this.remoteWindow -= room;
|
|
offset += room;
|
|
}
|
|
}
|
|
|
|
/** Resolve once the peer sends CLOSE (immediately when already closed). */
|
|
async waitClosed(timeoutMs: number): Promise<void> {
|
|
if (this.closed) {
|
|
return;
|
|
}
|
|
const closedPromise: Promise<boolean> = new Promise<boolean>((resolve: (v: boolean) => void): void => {
|
|
this.closedWaiters.push(resolve);
|
|
});
|
|
const timerPromise: Promise<boolean> = new Promise<boolean>((resolve: (v: boolean) => void): void => {
|
|
setTimeout((): void => {
|
|
resolve(false);
|
|
}, timeoutMs);
|
|
});
|
|
const first: boolean = await Promise.race([closedPromise, timerPromise]);
|
|
if (!first) {
|
|
throw new Error('SshChannel: timed out waiting for channel close');
|
|
}
|
|
}
|
|
|
|
/** Send CHANNEL_CLOSE and mark the channel dead (idempotent). */
|
|
async close(): Promise<void> {
|
|
if (this.sentClose) {
|
|
return;
|
|
}
|
|
this.sentClose = true;
|
|
if (this.remoteId >= 0 && !this.transport.isClosed()) {
|
|
const w: SshWriter = new SshWriter(16);
|
|
w.writeByte(SshMsg.CHANNEL_CLOSE);
|
|
w.writeUint32(this.remoteId);
|
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
|
sent.catch((e: Object): void => {
|
|
const err = e as Error;
|
|
Log.debug(SshChannel.TAG, `CHANNEL_CLOSE send failed: ${err.message}`);
|
|
});
|
|
}
|
|
this.markClosed();
|
|
}
|
|
|
|
isClosed(): boolean {
|
|
return this.closed;
|
|
}
|
|
|
|
hasEof(): boolean {
|
|
return this.eof;
|
|
}
|
|
|
|
/** exit-status from the server, or -1 when none arrived. */
|
|
getExitStatus(): number {
|
|
return this.exitStatus;
|
|
}
|
|
|
|
/**
|
|
* Route one inbound packet (msg 91..100 with recipient == localId);
|
|
* called by SshSession's dispatcher only.
|
|
*/
|
|
handlePacket(payload: Uint8Array): void {
|
|
const msg: number = payload[0];
|
|
switch (msg) {
|
|
case SshMsg.CHANNEL_OPEN_CONFIRMATION:
|
|
this.onOpenConfirmation(payload);
|
|
return;
|
|
case SshMsg.CHANNEL_OPEN_FAILURE:
|
|
this.onOpenFailure(payload);
|
|
return;
|
|
case SshMsg.CHANNEL_WINDOW_ADJUST:
|
|
this.onWindowAdjust(payload);
|
|
return;
|
|
case SshMsg.CHANNEL_DATA:
|
|
this.onData(payload, false);
|
|
return;
|
|
case SshMsg.CHANNEL_EXTENDED_DATA:
|
|
this.onData(payload, true);
|
|
return;
|
|
case SshMsg.CHANNEL_EOF:
|
|
this.eof = true;
|
|
return;
|
|
case SshMsg.CHANNEL_CLOSE:
|
|
this.onPeerClose();
|
|
return;
|
|
case SshMsg.CHANNEL_REQUEST:
|
|
this.onChannelRequest(payload);
|
|
return;
|
|
case SshMsg.CHANNEL_SUCCESS:
|
|
this.onReply(true);
|
|
return;
|
|
case SshMsg.CHANNEL_FAILURE:
|
|
this.onReply(false);
|
|
return;
|
|
default:
|
|
Log.warn(SshChannel.TAG, `channel ${this.localId}: unexpected msg ${msg}`);
|
|
return;
|
|
}
|
|
}
|
|
|
|
/** The transport died: mark dead without sending anything. */
|
|
handleSessionClosing(): void {
|
|
this.markClosed();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- private
|
|
|
|
private onOpenConfirmation(payload: Uint8Array): void {
|
|
const r: SshReader = new SshReader(payload);
|
|
r.readByte();
|
|
r.readUint32(); // recipient = localId
|
|
this.remoteId = r.readUint32();
|
|
this.remoteWindow = r.readUint32();
|
|
this.remoteMaxPacket = r.readUint32();
|
|
if (this.openTimerId >= 0) {
|
|
clearTimeout(this.openTimerId);
|
|
this.openTimerId = -1;
|
|
}
|
|
const resolve: (() => void) | undefined = this.openResolve;
|
|
this.openResolve = undefined;
|
|
this.openReject = undefined;
|
|
if (resolve !== undefined) {
|
|
resolve();
|
|
}
|
|
Log.debug(SshChannel.TAG,
|
|
`channel ${this.localId} open (remote ${this.remoteId}, window ${this.remoteWindow})`);
|
|
}
|
|
|
|
private onOpenFailure(payload: Uint8Array): void {
|
|
const r: SshReader = new SshReader(payload);
|
|
r.readByte();
|
|
r.readUint32();
|
|
const code: number = r.readUint32();
|
|
const desc: string = r.readString();
|
|
if (this.openTimerId >= 0) {
|
|
clearTimeout(this.openTimerId);
|
|
this.openTimerId = -1;
|
|
}
|
|
const reject: ((err: Error) => void) | undefined = this.openReject;
|
|
this.openResolve = undefined;
|
|
this.openReject = undefined;
|
|
if (reject !== undefined) {
|
|
reject(new Error(`SshChannel: open failed (code ${code}: ${desc})`));
|
|
}
|
|
}
|
|
|
|
private onWindowAdjust(payload: Uint8Array): void {
|
|
const r: SshReader = new SshReader(payload);
|
|
r.readByte();
|
|
r.readUint32();
|
|
const inc: number = r.readUint32();
|
|
this.remoteWindow = Math.min(this.remoteWindow + inc, 4294967295);
|
|
this.flushWindowWaiters();
|
|
}
|
|
|
|
private onData(payload: Uint8Array, extended: boolean): void {
|
|
if (this.closed) {
|
|
return;
|
|
}
|
|
const r: SshReader = new SshReader(payload);
|
|
r.readByte();
|
|
r.readUint32(); // recipient
|
|
if (extended) {
|
|
r.readUint32(); // data type code (1 = stderr)
|
|
}
|
|
const data: Uint8Array = r.readStringBytes();
|
|
this.localWindowConsumed += data.length;
|
|
if (this.localWindowConsumed >= ADJUST_THRESHOLD) {
|
|
this.sendWindowAdjust(this.localWindowConsumed);
|
|
this.localWindowConsumed = 0;
|
|
}
|
|
if (extended) {
|
|
this.callbacks.onExtendedData(data);
|
|
} else {
|
|
this.callbacks.onData(data);
|
|
}
|
|
}
|
|
|
|
private onPeerClose(): void {
|
|
if (!this.sentClose && !this.transport.isClosed()) {
|
|
this.sentClose = true;
|
|
const w: SshWriter = new SshWriter(16);
|
|
w.writeByte(SshMsg.CHANNEL_CLOSE);
|
|
w.writeUint32(this.remoteId);
|
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
|
sent.catch((e: Object): void => {
|
|
const err = e as Error;
|
|
Log.debug(SshChannel.TAG, `CHANNEL_CLOSE reply failed: ${err.message}`);
|
|
});
|
|
}
|
|
this.markClosed();
|
|
}
|
|
|
|
private onChannelRequest(payload: Uint8Array): void {
|
|
const r: SshReader = new SshReader(payload);
|
|
r.readByte();
|
|
r.readUint32(); // recipient
|
|
const type: string = r.readString();
|
|
const wantReply: boolean = r.readBoolean();
|
|
if (type === 'exit-status') {
|
|
this.exitStatus = r.readUint32();
|
|
Log.debug(SshChannel.TAG, `channel ${this.localId} exit-status ${this.exitStatus}`);
|
|
if (wantReply) {
|
|
this.sendChannelResult(true);
|
|
}
|
|
return;
|
|
}
|
|
Log.debug(SshChannel.TAG, `channel ${this.localId}: request '${type}' ignored`);
|
|
if (wantReply) {
|
|
this.sendChannelResult(false);
|
|
}
|
|
}
|
|
|
|
private onReply(ok: boolean): void {
|
|
if (this.replyTimerId >= 0) {
|
|
clearTimeout(this.replyTimerId);
|
|
this.replyTimerId = -1;
|
|
}
|
|
const resolve: ((ok: boolean) => void) | undefined = this.replyResolve;
|
|
this.replyResolve = undefined;
|
|
this.replyReject = undefined;
|
|
if (resolve !== undefined) {
|
|
resolve(ok);
|
|
}
|
|
}
|
|
|
|
private waitReply(what: string, timeoutMs: number): Promise<boolean> {
|
|
return new Promise<boolean>((resolve: (ok: boolean) => void,
|
|
reject: (err: Error) => void): void => {
|
|
if (this.replyTimerId >= 0) {
|
|
clearTimeout(this.replyTimerId);
|
|
this.replyTimerId = -1;
|
|
}
|
|
this.replyResolve = resolve;
|
|
this.replyReject = reject;
|
|
this.replyTimerId = setTimeout((): void => {
|
|
if (this.replyReject !== undefined) {
|
|
this.replyReject(new Error(`SshChannel: '${what}' reply timeout`));
|
|
this.replyResolve = undefined;
|
|
this.replyReject = undefined;
|
|
}
|
|
}, timeoutMs);
|
|
});
|
|
}
|
|
|
|
private markClosed(): void {
|
|
if (this.closed) {
|
|
return;
|
|
}
|
|
this.closed = true;
|
|
if (this.openTimerId >= 0) {
|
|
clearTimeout(this.openTimerId);
|
|
this.openTimerId = -1;
|
|
}
|
|
const openReject: ((err: Error) => void) | undefined = this.openReject;
|
|
this.openResolve = undefined;
|
|
this.openReject = undefined;
|
|
if (openReject !== undefined) {
|
|
openReject(new Error('SshChannel: channel closed before confirmation'));
|
|
}
|
|
// Pending channel requests die with the channel (reply slot cleared
|
|
// by onReply; a stale timer can no longer reject anything).
|
|
this.onReply(false);
|
|
this.flushWindowWaiters();
|
|
const waiters: Array<(v: boolean) => void> = this.closedWaiters.slice();
|
|
this.closedWaiters.splice(0, this.closedWaiters.length);
|
|
for (let i: number = 0; i < waiters.length; i++) {
|
|
waiters[i](true);
|
|
}
|
|
this.callbacks.onClose();
|
|
}
|
|
|
|
private waitForWindow(): Promise<void> {
|
|
return new Promise<void>((resolve: () => void): void => {
|
|
this.windowWaiters.push(resolve);
|
|
});
|
|
}
|
|
|
|
private flushWindowWaiters(): void {
|
|
const waiters: Array<() => void> = this.windowWaiters.slice();
|
|
this.windowWaiters.splice(0, this.windowWaiters.length);
|
|
for (let i: number = 0; i < waiters.length; i++) {
|
|
waiters[i]();
|
|
}
|
|
}
|
|
|
|
private sendWindowAdjust(delta: number): void {
|
|
const w: SshWriter = new SshWriter(16);
|
|
w.writeByte(SshMsg.CHANNEL_WINDOW_ADJUST);
|
|
w.writeUint32(this.localId);
|
|
w.writeUint32(delta);
|
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
|
sent.catch((e: Object): void => {
|
|
const err = e as Error;
|
|
Log.debug(SshChannel.TAG, `WINDOW_ADJUST send failed: ${err.message}`);
|
|
});
|
|
}
|
|
|
|
private sendChannelResult(ok: boolean): void {
|
|
const w: SshWriter = new SshWriter(16);
|
|
w.writeByte(ok ? SshMsg.CHANNEL_SUCCESS : SshMsg.CHANNEL_FAILURE);
|
|
w.writeUint32(this.remoteId);
|
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
|
sent.catch((e: Object): void => {
|
|
const err = e as Error;
|
|
Log.debug(SshChannel.TAG, `channel result send failed: ${err.message}`);
|
|
});
|
|
}
|
|
}
|