@fefeding/aicmd 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/public/index.js +321 -144
- package/dist/public/views.css +32 -32
- package/dist/public/views.js +131 -105
- package/dist/public/vue.js +76 -36
- package/dist/server/service/ssh.service.d.ts +81 -16
- package/dist/server/service/ssh.service.d.ts.map +1 -1
- package/dist/server/service/ssh.service.js +550 -133
- package/dist/server/service/ssh.service.js.map +1 -1
- package/dist/server/service/ssh.service.ts +558 -130
- package/electron/main.js +8 -2
- package/electron/preload.js +2 -2
- package/package.json +9 -9
- package/server.js +9 -1
|
@@ -51,6 +51,119 @@ try {
|
|
|
51
51
|
catch (e) {
|
|
52
52
|
console.warn('[SSH] node-pty 不可用,本地 Shell 将使用降级模式(无 PTY)');
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* CWD 缓存有效期:超过该时长没能再次成功解析目录,缓存即视为不可信。
|
|
56
|
+
* 后台刷新在终端静默 700ms 后就会跑,正常情况下 cwd 时间戳远新于此值。
|
|
57
|
+
*/
|
|
58
|
+
const CWD_CACHE_TTL = 120000;
|
|
59
|
+
/**
|
|
60
|
+
* cd 跟踪值的保护期:这段时间内后台探测结果不会覆盖它(见 refreshCwd)。
|
|
61
|
+
*/
|
|
62
|
+
const CWD_TRACK_GRACE = 5000;
|
|
63
|
+
/**
|
|
64
|
+
* 后台 CWD 刷新的最小间隔:目录刚解析过就跳过,避免频繁 exec 占用 SSH channel。
|
|
65
|
+
*/
|
|
66
|
+
const CWD_REFRESH_MIN_INTERVAL = 15000;
|
|
67
|
+
/**
|
|
68
|
+
* 远端进程探测脚本(通过独立 exec 通道执行,不会向交互式终端写入任何内容)。
|
|
69
|
+
*
|
|
70
|
+
* 输出格式(每行一条,可能 0~2 行):
|
|
71
|
+
* SHELL:<pid>:<cwd> 本会话的交互式 shell
|
|
72
|
+
* XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
|
|
73
|
+
*
|
|
74
|
+
* 设计要点:
|
|
75
|
+
* 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
|
|
76
|
+
* 避免同一台机器开多个标签页时串台读到别的终端目录;
|
|
77
|
+
* 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
|
|
78
|
+
* 误判成终端 —— 这正是"文件被传到家目录"的根因;
|
|
79
|
+
* 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
|
|
80
|
+
*/
|
|
81
|
+
const SESSION_PROBE_SCRIPT = [
|
|
82
|
+
// 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
|
|
83
|
+
'if [ ! -d /proc ]; then',
|
|
84
|
+
' for pid in $(ps -eo pid=,comm= 2>/dev/null | awk \'$2 ~ /^(bash|zsh|sh|fish|dash|ksh|ksh93|mksh|tcsh|csh)$/ {print $1}\'); do',
|
|
85
|
+
' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
|
|
86
|
+
' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
|
|
87
|
+
' done',
|
|
88
|
+
' exit 0',
|
|
89
|
+
'fi',
|
|
90
|
+
'self=$$',
|
|
91
|
+
'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
92
|
+
'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
93
|
+
'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
|
|
94
|
+
// 收集 exec 通道自身的进程链(self + 祖先),这些必须排除
|
|
95
|
+
'self_chain=" $self "',
|
|
96
|
+
'p=$self',
|
|
97
|
+
'i=0',
|
|
98
|
+
'while [ $i -lt 12 ]; do',
|
|
99
|
+
' p=$(ppid_of "$p")',
|
|
100
|
+
' case "$p" in ""|0|1) break;; esac',
|
|
101
|
+
' self_chain="$self_chain$p "',
|
|
102
|
+
' i=$((i+1))',
|
|
103
|
+
'done',
|
|
104
|
+
// 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
|
|
105
|
+
'sshd_anc=""',
|
|
106
|
+
'for q in $self_chain; do',
|
|
107
|
+
' n=$(name_of "$q")',
|
|
108
|
+
' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
|
|
109
|
+
'done',
|
|
110
|
+
'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
|
|
111
|
+
// 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
|
|
112
|
+
'match_pri() {',
|
|
113
|
+
' pid=$1',
|
|
114
|
+
' if [ -n "$sshd_anc" ]; then',
|
|
115
|
+
' q=$pid; j=0',
|
|
116
|
+
' while [ $j -lt 12 ]; do',
|
|
117
|
+
' q=$(ppid_of "$q")',
|
|
118
|
+
' case "$q" in ""|0|1) break;; esac',
|
|
119
|
+
' [ "$q" = "$sshd_anc" ] && return 2',
|
|
120
|
+
' j=$((j+1))',
|
|
121
|
+
' done',
|
|
122
|
+
' fi',
|
|
123
|
+
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
124
|
+
' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) return 1;; esac',
|
|
125
|
+
' return 0',
|
|
126
|
+
'}',
|
|
127
|
+
// 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
|
|
128
|
+
// 用户的登录 shell 可能只是外层进程(tmux/byobu/su 后真正交互的是它的子孙),
|
|
129
|
+
// 最内层的 shell 才是用户实际在执行命令的地方。
|
|
130
|
+
'depth_of() {',
|
|
131
|
+
' d=0; q=$1',
|
|
132
|
+
' while [ $d -lt 20 ]; do',
|
|
133
|
+
' pp=$(ppid_of "$q")',
|
|
134
|
+
' case "$pp" in ""|0|1) break;; esac',
|
|
135
|
+
' q=$pp; d=$((d+1))',
|
|
136
|
+
' done',
|
|
137
|
+
' echo $d',
|
|
138
|
+
'}',
|
|
139
|
+
'best_shell=""; best_shell_key=0',
|
|
140
|
+
'best_xfer=""; best_xfer_key=0',
|
|
141
|
+
'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
|
|
142
|
+
' in_chain "$pid" && continue',
|
|
143
|
+
' n=$(name_of "$pid")',
|
|
144
|
+
' case "$n" in',
|
|
145
|
+
' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
|
|
146
|
+
' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
|
|
147
|
+
' *) continue;;',
|
|
148
|
+
' esac',
|
|
149
|
+
' c=$(cwd_of "$pid")',
|
|
150
|
+
' [ -n "$c" ] || continue',
|
|
151
|
+
' match_pri "$pid"',
|
|
152
|
+
' pri=$?',
|
|
153
|
+
' [ "$pri" = 0 ] && continue',
|
|
154
|
+
' dep=$(depth_of "$pid")',
|
|
155
|
+
' key=$((pri * 100 + dep))',
|
|
156
|
+
' echo "CAND:$kind:$pid:$c:$pri:$dep"',
|
|
157
|
+
' if [ "$kind" = shell ]; then',
|
|
158
|
+
' if [ "$key" -gt "$best_shell_key" ]; then best_shell="$pid:$c"; best_shell_key=$key; fi',
|
|
159
|
+
' else',
|
|
160
|
+
' if [ "$key" -gt "$best_xfer_key" ]; then best_xfer="$pid:$c"; best_xfer_key=$key; fi',
|
|
161
|
+
' fi',
|
|
162
|
+
'done',
|
|
163
|
+
'[ -n "$best_shell" ] && echo "SHELL:$best_shell"',
|
|
164
|
+
'[ -n "$best_xfer" ] && echo "XFER:$best_xfer"',
|
|
165
|
+
'exit 0',
|
|
166
|
+
].join('\n');
|
|
54
167
|
/**
|
|
55
168
|
* 终端会话管理服务
|
|
56
169
|
* 支持 SSH 远程连接和本地 Shell
|
|
@@ -68,6 +181,8 @@ class SSHService {
|
|
|
68
181
|
hasCreatedSession = false;
|
|
69
182
|
/** 定时清理僵尸 session 的定时器 */
|
|
70
183
|
cleanupTimer = null;
|
|
184
|
+
/** 正在建立中的 SFTP 连接(避免并发重复创建) */
|
|
185
|
+
sftpPromises = new Map();
|
|
71
186
|
constructor(connectionService) {
|
|
72
187
|
this.connectionService = connectionService;
|
|
73
188
|
this.sessionsFilePath = (0, data_dir_1.getDataPath)('sessions.json');
|
|
@@ -287,8 +402,15 @@ class SSHService {
|
|
|
287
402
|
if (this.sessions.has(sessionId))
|
|
288
403
|
this.seedCwd(sessionId);
|
|
289
404
|
}, 1500);
|
|
405
|
+
// 终端输出静默后,在后台通过 exec 通道刷新一次 CWD。
|
|
406
|
+
// 这样即便用户 cd 之后立刻执行 rz,session.cwd 也已是最新值,
|
|
407
|
+
// 无需在 rz 等待接收文件时向交互式 shell 注入命令(那会打断 rz)。
|
|
408
|
+
stream.on('data', () => this.scheduleCwdRefresh(sessionId));
|
|
290
409
|
stream.on('close', () => {
|
|
291
410
|
log(`Shell 流已关闭`);
|
|
411
|
+
const closing = this.sessions.get(sessionId);
|
|
412
|
+
if (closing?.cwdRefreshTimer)
|
|
413
|
+
clearTimeout(closing.cwdRefreshTimer);
|
|
292
414
|
this.sessions.delete(sessionId);
|
|
293
415
|
});
|
|
294
416
|
// Execute startup script if configured (e.g. jump host SSH hop)
|
|
@@ -891,13 +1013,30 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
891
1013
|
/**
|
|
892
1014
|
* 根据用户输入的命令实时更新跟踪的 CWD。
|
|
893
1015
|
* 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
|
|
894
|
-
*
|
|
1016
|
+
* 由后台刷新 / 上传时的探测兜底。
|
|
1017
|
+
*
|
|
1018
|
+
* 注意:xterm 默认「逐字符」发送按键,writeData 每次收到的往往只是单个字符,
|
|
1019
|
+
* 因此必须先把输入累积成完整命令行、等回车提交后再解析,否则 cd 跟踪形同虚设。
|
|
895
1020
|
*/
|
|
896
1021
|
updateCwdFromInput(session, data) {
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
const
|
|
900
|
-
|
|
1022
|
+
let buf = (session.inputBuffer || '') + data;
|
|
1023
|
+
// Ctrl+U 清空行、Ctrl+C 取消当前输入:丢弃控制符之前的内容
|
|
1024
|
+
const uIdx = buf.lastIndexOf('\x15');
|
|
1025
|
+
if (uIdx >= 0)
|
|
1026
|
+
buf = buf.slice(uIdx + 1);
|
|
1027
|
+
const cIdx = buf.lastIndexOf('\x03');
|
|
1028
|
+
if (cIdx >= 0)
|
|
1029
|
+
buf = buf.slice(cIdx + 1);
|
|
1030
|
+
// 取最后一个换行/回车之前的内容作为「已提交的命令行」
|
|
1031
|
+
const idx = Math.max(buf.lastIndexOf('\r'), buf.lastIndexOf('\n'));
|
|
1032
|
+
if (idx < 0) {
|
|
1033
|
+
// 尚未提交:保留缓冲(限制长度,防止长时间输入导致内存膨胀)
|
|
1034
|
+
session.inputBuffer = buf.length > 4096 ? buf.slice(-2048) : buf;
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
const submitted = buf.slice(0, idx);
|
|
1038
|
+
session.inputBuffer = buf.slice(idx + 1);
|
|
1039
|
+
for (const raw of submitted.split(/[\r\n]+/)) {
|
|
901
1040
|
const line = raw.trim();
|
|
902
1041
|
if (!line)
|
|
903
1042
|
continue;
|
|
@@ -905,50 +1044,238 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
905
1044
|
if (!m)
|
|
906
1045
|
continue;
|
|
907
1046
|
const rest = m[1].trim();
|
|
1047
|
+
// Tab 补全(cd /data/se<Tab>)时输入流里只有补全前的片段,
|
|
1048
|
+
// 上下箭头调出的历史命令同理:输入的都不是完整路径,无法解析 -> 交给探测兜底。
|
|
1049
|
+
if (raw.includes('\t') || raw.includes('\x1b')) {
|
|
1050
|
+
console.log(`[SSH] cwd tracked: '${line}' skipped (completion/history, using probe)`);
|
|
1051
|
+
session.cwd = undefined;
|
|
1052
|
+
session.cwdAt = undefined;
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
908
1055
|
// 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
|
|
909
1056
|
if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
|
|
910
1057
|
session.cwd = undefined;
|
|
1058
|
+
session.cwdAt = undefined;
|
|
911
1059
|
continue;
|
|
912
1060
|
}
|
|
913
1061
|
const target = rest.trim();
|
|
914
1062
|
if (!target || target === '-') {
|
|
915
1063
|
// cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
|
|
916
1064
|
session.cwd = undefined;
|
|
1065
|
+
session.cwdAt = undefined;
|
|
917
1066
|
continue;
|
|
918
1067
|
}
|
|
1068
|
+
let next;
|
|
919
1069
|
if (target.startsWith('/')) {
|
|
920
|
-
|
|
1070
|
+
next = target;
|
|
921
1071
|
}
|
|
922
1072
|
else if (session.cwd && session.cwd.startsWith('/')) {
|
|
923
|
-
|
|
1073
|
+
next = path.posix.resolve(session.cwd, target);
|
|
924
1074
|
}
|
|
925
1075
|
else {
|
|
926
1076
|
// 当前目录未知,无法拼接相对路径,重置为未知
|
|
927
|
-
|
|
1077
|
+
next = undefined;
|
|
928
1078
|
}
|
|
1079
|
+
session.cwd = next;
|
|
1080
|
+
session.cwdAt = next ? Date.now() : undefined;
|
|
1081
|
+
console.log(`[SSH] cwd tracked: '${line}' -> ${next || '(unknown)'}`);
|
|
929
1082
|
}
|
|
930
1083
|
}
|
|
931
|
-
/**
|
|
1084
|
+
/** 连接后后台探测一次会话身份(shell PID + CWD)并缓存(不阻塞,失败忽略) */
|
|
932
1085
|
async seedCwd(sessionId) {
|
|
933
1086
|
const session = this.sessions.get(sessionId);
|
|
934
|
-
if (!session
|
|
1087
|
+
if (!session)
|
|
1088
|
+
return;
|
|
1089
|
+
// 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
|
|
1090
|
+
if (session.type !== 'ssh' || !session.client)
|
|
1091
|
+
return;
|
|
1092
|
+
if (session.shellPid && session.cwd && session.cwd.startsWith('/'))
|
|
1093
|
+
return;
|
|
1094
|
+
try {
|
|
1095
|
+
await this.refreshCwd(sessionId);
|
|
1096
|
+
if (session.cwd)
|
|
1097
|
+
console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
// 忽略,上传时再探测
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* 调度一次后台 CWD 刷新(终端输出静默后执行)。
|
|
1105
|
+
*
|
|
1106
|
+
* 目的:让 rz/上传触发时 session.cwd 已经是最新值,从而完全避免在 rz 运行期间
|
|
1107
|
+
* 向交互式 shell 注入命令(那会打断 rz,且输入会被 rz 吞掉导致探测失败)。
|
|
1108
|
+
* 刷新走独立 exec 通道,对终端零影响。
|
|
1109
|
+
*/
|
|
1110
|
+
scheduleCwdRefresh(sessionId) {
|
|
1111
|
+
const session = this.sessions.get(sessionId);
|
|
1112
|
+
if (!session || session.type !== 'ssh' || !session.client)
|
|
1113
|
+
return;
|
|
1114
|
+
// 目录刚解析过就别再跑 exec 了:每次 exec 都要占用一个 channel,
|
|
1115
|
+
// 频繁调用会挤占 SFTP 的 channel 配额(MaxSessions)。
|
|
1116
|
+
if (session.cwdAt && (Date.now() - session.cwdAt) < CWD_REFRESH_MIN_INTERVAL)
|
|
935
1117
|
return;
|
|
1118
|
+
if (session.cwdRefreshTimer)
|
|
1119
|
+
clearTimeout(session.cwdRefreshTimer);
|
|
1120
|
+
session.cwdRefreshTimer = setTimeout(() => {
|
|
1121
|
+
session.cwdRefreshTimer = undefined;
|
|
1122
|
+
// 限流:距离上次刷新不足 1.5s 则跳过,避免高频 exec
|
|
1123
|
+
if (session.lastCwdRefreshAt && Date.now() - session.lastCwdRefreshAt < 1500)
|
|
1124
|
+
return;
|
|
1125
|
+
this.refreshCwd(sessionId).catch(() => { });
|
|
1126
|
+
}, 700);
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* 刷新并缓存会话的当前工作目录(走 exec 通道,不干扰交互式终端)。
|
|
1130
|
+
* 优先用已缓存的 shell PID 直接读 /proc/<pid>/cwd(一次 readlink,极轻量),
|
|
1131
|
+
* 否则回退到完整进程探测。失败时保留旧值不清除。
|
|
1132
|
+
*/
|
|
1133
|
+
async refreshCwd(sessionId) {
|
|
1134
|
+
const session = this.sessions.get(sessionId);
|
|
1135
|
+
if (!session || session.type !== 'ssh' || !session.client)
|
|
1136
|
+
return session?.cwd || '';
|
|
1137
|
+
if (session.cwdRefreshing)
|
|
1138
|
+
return session.cwd || '';
|
|
1139
|
+
session.cwdRefreshing = true;
|
|
936
1140
|
try {
|
|
937
1141
|
let cwd = '';
|
|
938
|
-
if (session.
|
|
939
|
-
cwd = await this.
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
1142
|
+
if (session.shellPid) {
|
|
1143
|
+
cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1144
|
+
if (!cwd)
|
|
1145
|
+
session.shellPid = undefined; // 进程已退出或 PID 失效
|
|
1146
|
+
}
|
|
1147
|
+
if (!cwd) {
|
|
1148
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1149
|
+
if (probe.shellPid)
|
|
1150
|
+
session.shellPid = probe.shellPid;
|
|
1151
|
+
cwd = probe.shellCwd;
|
|
947
1152
|
}
|
|
1153
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1154
|
+
// 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
|
|
1155
|
+
// cd 是用户的显式意图,比推断出的进程目录更可信,
|
|
1156
|
+
// 也能避免探测到错误进程时把正确目录改回成家目录。
|
|
1157
|
+
const trackedRecently = !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
|
|
1158
|
+
if (trackedRecently && session.cwd !== cwd) {
|
|
1159
|
+
console.log(`[SSH] refreshCwd: keep tracked cwd '${session.cwd}' (probe said '${cwd}')`);
|
|
1160
|
+
}
|
|
1161
|
+
else {
|
|
1162
|
+
session.cwd = cwd;
|
|
1163
|
+
session.cwdAt = Date.now();
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
948
1167
|
}
|
|
949
1168
|
catch {
|
|
950
|
-
|
|
1169
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
951
1170
|
}
|
|
1171
|
+
finally {
|
|
1172
|
+
session.cwdRefreshing = false;
|
|
1173
|
+
session.lastCwdRefreshAt = Date.now();
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* 通过 exec 通道读取指定 PID 的工作目录(远端 Linux /proc)。
|
|
1178
|
+
* 同时校验进程名,避免 PID 复用导致读到无关进程的目录。
|
|
1179
|
+
*/
|
|
1180
|
+
async readPidCwd(sessionId, pid) {
|
|
1181
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
1182
|
+
return '';
|
|
1183
|
+
const out = await this.execRemote(sessionId, `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`, 4000);
|
|
1184
|
+
const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
|
|
1185
|
+
if (lines.length < 2)
|
|
1186
|
+
return '';
|
|
1187
|
+
const comm = lines[0];
|
|
1188
|
+
const cwd = lines[lines.length - 1];
|
|
1189
|
+
if (!cwd.startsWith('/'))
|
|
1190
|
+
return '';
|
|
1191
|
+
if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm))
|
|
1192
|
+
return '';
|
|
1193
|
+
return cwd;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* 探测本会话的交互式 shell 与正在运行的 rz/sz 进程。
|
|
1197
|
+
* 走独立 exec 通道,不向交互式终端写入任何内容。
|
|
1198
|
+
*/
|
|
1199
|
+
async probeSessionProcess(sessionId) {
|
|
1200
|
+
const result = {
|
|
1201
|
+
shellPid: undefined,
|
|
1202
|
+
shellCwd: '',
|
|
1203
|
+
xferCwd: '',
|
|
1204
|
+
candidates: [],
|
|
1205
|
+
};
|
|
1206
|
+
const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
|
|
1207
|
+
for (const raw of out.split('\n')) {
|
|
1208
|
+
const line = raw.trim();
|
|
1209
|
+
if (!line)
|
|
1210
|
+
continue;
|
|
1211
|
+
if (line.startsWith('CAND:')) {
|
|
1212
|
+
// 诊断用:列出全部候选进程(kind:pid:cwd:pri:depth)
|
|
1213
|
+
result.candidates.push(line.substring(5));
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
|
|
1217
|
+
if (!m)
|
|
1218
|
+
continue;
|
|
1219
|
+
const pid = Number(m[2]);
|
|
1220
|
+
const cwd = m[3].trim();
|
|
1221
|
+
if (m[1] === 'SHELL') {
|
|
1222
|
+
result.shellPid = pid;
|
|
1223
|
+
result.shellCwd = cwd;
|
|
1224
|
+
}
|
|
1225
|
+
else {
|
|
1226
|
+
result.xferCwd = cwd;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
console.log(`[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
|
|
1230
|
+
`xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`);
|
|
1231
|
+
return result;
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* 在远端执行一条命令(独立 exec 通道),返回 stdout。
|
|
1235
|
+
* 不会向交互式终端写入任何内容,因此不会打断 rz/vim 等前台进程。
|
|
1236
|
+
*/
|
|
1237
|
+
execRemote(sessionId, command, timeoutMs = 5000) {
|
|
1238
|
+
return new Promise((resolve) => {
|
|
1239
|
+
const session = this.sessions.get(sessionId);
|
|
1240
|
+
if (!session?.client) {
|
|
1241
|
+
resolve('');
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
let stdout = '';
|
|
1245
|
+
let settled = false;
|
|
1246
|
+
let streamRef = null;
|
|
1247
|
+
const finish = () => {
|
|
1248
|
+
if (settled)
|
|
1249
|
+
return;
|
|
1250
|
+
settled = true;
|
|
1251
|
+
clearTimeout(timer);
|
|
1252
|
+
// 必须显式关闭 channel:OpenSSH 默认 MaxSessions=10,
|
|
1253
|
+
// 泄漏的 channel 累积后会导致后续 SFTP channel 打开失败(上传时好时坏)。
|
|
1254
|
+
try {
|
|
1255
|
+
streamRef?.end();
|
|
1256
|
+
}
|
|
1257
|
+
catch { /* ignore */ }
|
|
1258
|
+
resolve(stdout);
|
|
1259
|
+
};
|
|
1260
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1261
|
+
try {
|
|
1262
|
+
session.client.exec(command, (err, stream) => {
|
|
1263
|
+
if (err) {
|
|
1264
|
+
console.log('[SSH] execRemote error:', err.message);
|
|
1265
|
+
finish();
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
streamRef = stream;
|
|
1269
|
+
stream.on('data', (data) => { stdout += data.toString('utf-8'); });
|
|
1270
|
+
stream.stderr.on('data', () => { });
|
|
1271
|
+
stream.on('close', finish);
|
|
1272
|
+
stream.on('error', finish);
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
catch (e) {
|
|
1276
|
+
finish();
|
|
1277
|
+
}
|
|
1278
|
+
});
|
|
952
1279
|
}
|
|
953
1280
|
/**
|
|
954
1281
|
* 注册输出监听器(用于 Agent 捕获终端输出)
|
|
@@ -983,35 +1310,46 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
983
1310
|
* @param timeoutMs 等待时间(毫秒),默认 2000
|
|
984
1311
|
* @returns 捕获的输出文本(已去除 ANSI 转义序列)
|
|
985
1312
|
*/
|
|
986
|
-
captureOutput(sessionId, timeoutMs = 2000) {
|
|
1313
|
+
captureOutput(sessionId, timeoutMs = 2000, stopWhen) {
|
|
987
1314
|
return new Promise((resolve) => {
|
|
988
1315
|
let output = '';
|
|
1316
|
+
let settled = false;
|
|
989
1317
|
// 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
|
|
990
1318
|
const session = this.sessions.get(sessionId);
|
|
991
1319
|
let streamHandler = null;
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
else {
|
|
999
|
-
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1000
|
-
const listener = (data) => { output += data; };
|
|
1001
|
-
this.addOutputListener(sessionId, listener);
|
|
1002
|
-
}
|
|
1003
|
-
setTimeout(() => {
|
|
1320
|
+
let listener = null;
|
|
1321
|
+
const finish = () => {
|
|
1322
|
+
if (settled)
|
|
1323
|
+
return;
|
|
1324
|
+
settled = true;
|
|
1325
|
+
clearTimeout(timer);
|
|
1004
1326
|
if (streamHandler && session?.stream) {
|
|
1005
1327
|
session.stream.removeListener('data', streamHandler);
|
|
1006
1328
|
}
|
|
1007
|
-
else {
|
|
1329
|
+
else if (listener) {
|
|
1008
1330
|
this.removeOutputListener(sessionId);
|
|
1009
1331
|
}
|
|
1010
1332
|
resolve(output
|
|
1011
1333
|
.replace(/\x1B\][^\x07]*\x07/g, '')
|
|
1012
1334
|
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
1013
1335
|
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, ''));
|
|
1014
|
-
}
|
|
1336
|
+
};
|
|
1337
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1338
|
+
const onData = (text) => {
|
|
1339
|
+
output += text;
|
|
1340
|
+
// 拿到目标内容就立刻返回,不必每次都等满 timeout(探测 CWD 时可省下数秒)
|
|
1341
|
+
if (stopWhen && stopWhen(output))
|
|
1342
|
+
finish();
|
|
1343
|
+
};
|
|
1344
|
+
if (session?.stream) {
|
|
1345
|
+
streamHandler = (chunk) => onData(chunk.toString('utf-8'));
|
|
1346
|
+
session.stream.on('data', streamHandler);
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1350
|
+
listener = onData;
|
|
1351
|
+
this.addOutputListener(sessionId, listener);
|
|
1352
|
+
}
|
|
1015
1353
|
});
|
|
1016
1354
|
}
|
|
1017
1355
|
/**
|
|
@@ -1041,6 +1379,13 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1041
1379
|
closeSession(sessionId) {
|
|
1042
1380
|
const session = this.sessions.get(sessionId);
|
|
1043
1381
|
if (session) {
|
|
1382
|
+
if (session.cwdRefreshTimer) {
|
|
1383
|
+
clearTimeout(session.cwdRefreshTimer);
|
|
1384
|
+
session.cwdRefreshTimer = undefined;
|
|
1385
|
+
}
|
|
1386
|
+
// 关闭复用的 SFTP channel,避免连接关闭后仍占用资源
|
|
1387
|
+
this.invalidateSftp(sessionId);
|
|
1388
|
+
this.sftpPromises.delete(sessionId);
|
|
1044
1389
|
try {
|
|
1045
1390
|
if (session.pty) {
|
|
1046
1391
|
session.pty.kill();
|
|
@@ -1069,38 +1414,102 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1069
1414
|
}
|
|
1070
1415
|
/**
|
|
1071
1416
|
* 获取 SSH 会话的当前工作目录。
|
|
1072
|
-
*
|
|
1073
|
-
* 1)
|
|
1074
|
-
* 2)
|
|
1075
|
-
* 3)
|
|
1417
|
+
* 优先级(前 3 步都走独立 exec 通道,对交互式终端零影响):
|
|
1418
|
+
* 1) 缓存的 session.cwd —— 由 cd 跟踪 + 后台刷新共同维护,绝大多数情况直接命中
|
|
1419
|
+
* 2) 缓存的 shell PID → readlink /proc/<pid>/cwd(一次调用,最准)
|
|
1420
|
+
* 3) 完整进程探测(shell + rz/sz):rz 运行时的 cwd 就是文件将要写入的目录
|
|
1421
|
+
* 4) 向交互式 shell 注入 printf $PWD —— 会 Ctrl+C 打断前台进程,
|
|
1422
|
+
* 仅在 allowShellProbe 为真(即确认不在 rz/文件上传过程中)时使用
|
|
1423
|
+
*
|
|
1424
|
+
* @param opts.allowShellProbe 是否允许注入式探测。rz 正在等待接收文件时必须传 false,
|
|
1425
|
+
* 否则 Ctrl+C 会打断 rz,且注入的命令会被 rz 当作数据吞掉。
|
|
1426
|
+
* @param opts.preferTransferProcess 优先采用 rz/sz 进程的 cwd(rz 写文件的目录就是它自己的
|
|
1427
|
+
* cwd,比推断出来的 shell 目录更权威)。
|
|
1428
|
+
* @param opts.force 强制重新探测,忽略缓存(用户手动点"重新检测"、上传前兜底时使用)。
|
|
1429
|
+
*
|
|
1430
|
+
* 缓存有效期 CWD_CACHE_TTL:超过该时间没能再次成功解析目录,就认为缓存不可信
|
|
1431
|
+
* (例如后台 exec 探测一直失败),此时宁可返回空让前端提示手填,
|
|
1432
|
+
* 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
|
|
1076
1433
|
*/
|
|
1077
|
-
async getSessionCwd(sessionId) {
|
|
1434
|
+
async getSessionCwd(sessionId, opts = {}) {
|
|
1435
|
+
const allowShellProbe = opts.allowShellProbe !== false;
|
|
1078
1436
|
const session = this.sessions.get(sessionId);
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1437
|
+
if (!session)
|
|
1438
|
+
return '';
|
|
1439
|
+
const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1440
|
+
const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
|
|
1441
|
+
// 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
|
|
1442
|
+
// 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
|
|
1443
|
+
// 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
|
|
1444
|
+
if (opts.force && allowShellProbe) {
|
|
1445
|
+
let probed = await this.probeCwdViaShell(sessionId);
|
|
1446
|
+
if (!probed)
|
|
1447
|
+
probed = await this.probeCwdViaShell(sessionId);
|
|
1448
|
+
if (probed && probed.startsWith('/')) {
|
|
1449
|
+
session.cwd = probed;
|
|
1450
|
+
session.cwdAt = Date.now();
|
|
1451
|
+
console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
|
|
1452
|
+
return probed;
|
|
1453
|
+
}
|
|
1082
1454
|
}
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1455
|
+
// 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
|
|
1456
|
+
// 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
|
|
1457
|
+
// 不会受"登录 shell 与实际交互 shell 不是同一个进程"的影响。
|
|
1458
|
+
if (opts.preferTransferProcess && session.type === 'ssh' && session.client) {
|
|
1459
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1460
|
+
if (probe.shellPid)
|
|
1461
|
+
session.shellPid = probe.shellPid;
|
|
1462
|
+
const cwd = probe.xferCwd || probe.shellCwd;
|
|
1463
|
+
if (cwd) {
|
|
1464
|
+
session.cwd = cwd;
|
|
1465
|
+
session.cwdAt = Date.now();
|
|
1466
|
+
return cwd;
|
|
1087
1467
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
1468
|
+
}
|
|
1469
|
+
// 1) 缓存命中(且未过期、未强制刷新)
|
|
1470
|
+
if (cached && cacheFresh && !opts.force) {
|
|
1471
|
+
return cached;
|
|
1472
|
+
}
|
|
1473
|
+
// 2) 已知 shell PID:直接读 /proc
|
|
1474
|
+
if (session.type === 'ssh' && session.client) {
|
|
1475
|
+
if (session.shellPid) {
|
|
1476
|
+
const cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1477
|
+
if (cwd) {
|
|
1478
|
+
session.cwd = cwd;
|
|
1479
|
+
session.cwdAt = Date.now();
|
|
1480
|
+
return cwd;
|
|
1481
|
+
}
|
|
1482
|
+
session.shellPid = undefined;
|
|
1483
|
+
}
|
|
1484
|
+
// 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
|
|
1485
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1486
|
+
if (probe.shellPid)
|
|
1487
|
+
session.shellPid = probe.shellPid;
|
|
1488
|
+
const cwd = (opts.preferTransferProcess && probe.xferCwd)
|
|
1489
|
+
? probe.xferCwd
|
|
1490
|
+
: (probe.shellCwd || probe.xferCwd);
|
|
1491
|
+
if (cwd) {
|
|
1492
|
+
session.cwd = cwd;
|
|
1493
|
+
session.cwdAt = Date.now();
|
|
1494
|
+
return cwd;
|
|
1090
1495
|
}
|
|
1091
1496
|
}
|
|
1092
|
-
|
|
1093
|
-
|
|
1497
|
+
// 4) 注入式探测(会打断前台进程)
|
|
1498
|
+
if (allowShellProbe) {
|
|
1499
|
+
let cwd = await this.probeCwdViaShell(sessionId);
|
|
1094
1500
|
if (!cwd)
|
|
1095
1501
|
cwd = await this.probeCwdViaShell(sessionId);
|
|
1502
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1503
|
+
session.cwd = cwd;
|
|
1504
|
+
session.cwdAt = Date.now();
|
|
1505
|
+
return cwd;
|
|
1506
|
+
}
|
|
1096
1507
|
}
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
console.log(`[SSH] getSessionCwd: all probes failed for ${sessionId}`);
|
|
1103
|
-
return '';
|
|
1508
|
+
// 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
|
|
1509
|
+
const fallback = cacheFresh ? cached : '';
|
|
1510
|
+
console.log(`[SSH] getSessionCwd: probes failed for ${sessionId} ` +
|
|
1511
|
+
`(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`);
|
|
1512
|
+
return fallback;
|
|
1104
1513
|
}
|
|
1105
1514
|
/** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
|
|
1106
1515
|
async probeCwdViaShell(sessionId) {
|
|
@@ -1109,8 +1518,15 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1109
1518
|
// 否则 printf 命令会被前台进程吞掉,shell 不会执行
|
|
1110
1519
|
this.writeData(sessionId, '\x03');
|
|
1111
1520
|
await new Promise(r => setTimeout(r, 200));
|
|
1112
|
-
//
|
|
1113
|
-
const
|
|
1521
|
+
// 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
|
|
1522
|
+
const stopWhen = (text) => {
|
|
1523
|
+
const i = text.indexOf(marker);
|
|
1524
|
+
if (i < 0)
|
|
1525
|
+
return false;
|
|
1526
|
+
const after = text.slice(i + marker.length);
|
|
1527
|
+
return after.includes('\n') || after.length > 80;
|
|
1528
|
+
};
|
|
1529
|
+
const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
|
|
1114
1530
|
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
|
|
1115
1531
|
const output = await outputPromise;
|
|
1116
1532
|
console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
|
|
@@ -1151,67 +1567,6 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1151
1567
|
console.log(`[SSH] probeCwdViaShell: no marker found: ${JSON.stringify(cleaned.substring(0, 500))}`);
|
|
1152
1568
|
return '';
|
|
1153
1569
|
}
|
|
1154
|
-
/**
|
|
1155
|
-
* 通过 SSH exec 独立通道获取交互式 shell 的工作目录
|
|
1156
|
-
* 不依赖交互式 shell 状态,即使 shell 卡在 rz/vim/异常状态也能工作
|
|
1157
|
-
*/
|
|
1158
|
-
getSessionCwdViaExec(sessionId) {
|
|
1159
|
-
return new Promise((resolve) => {
|
|
1160
|
-
const session = this.sessions.get(sessionId);
|
|
1161
|
-
if (!session?.client) {
|
|
1162
|
-
resolve('');
|
|
1163
|
-
return;
|
|
1164
|
-
}
|
|
1165
|
-
// 通过 /proc 查找交互式 shell 进程的 CWD。
|
|
1166
|
-
// 关键:必须只匹配「stdin 是 tty(/dev/pts)」的 shell,排除本 exec 通道自己启动的
|
|
1167
|
-
// shell(它的 stdin 是管道、CWD 是 $HOME),否则会错误地返回家目录。
|
|
1168
|
-
const cmd = [
|
|
1169
|
-
'for pid in $(ls /proc 2>/dev/null | grep "^[0-9]*$"); do',
|
|
1170
|
-
' exe=$(readlink "/proc/$pid/exe" 2>/dev/null)',
|
|
1171
|
-
' case "$exe" in',
|
|
1172
|
-
' *bash*|*sh*|*zsh*|*dash*|*fish*|*tcsh*|*csh*)',
|
|
1173
|
-
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
1174
|
-
' case "$tty" in',
|
|
1175
|
-
' /dev/pts/*|/dev/tty*|/dev/console)',
|
|
1176
|
-
' cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)',
|
|
1177
|
-
' if [ -n "$cwd" ]; then echo "$cwd"; exit 0; fi',
|
|
1178
|
-
' ;;',
|
|
1179
|
-
' esac',
|
|
1180
|
-
' ;;',
|
|
1181
|
-
' esac',
|
|
1182
|
-
'done',
|
|
1183
|
-
'pwd'
|
|
1184
|
-
].join('\n');
|
|
1185
|
-
let stdout = '';
|
|
1186
|
-
let stderr = '';
|
|
1187
|
-
const timeout = setTimeout(() => {
|
|
1188
|
-
console.log('[SSH] getSessionCwdViaExec: timeout');
|
|
1189
|
-
resolve('');
|
|
1190
|
-
}, 5000);
|
|
1191
|
-
session.client.exec(cmd, (err, stream) => {
|
|
1192
|
-
if (err) {
|
|
1193
|
-
clearTimeout(timeout);
|
|
1194
|
-
console.log('[SSH] getSessionCwdViaExec error:', err.message);
|
|
1195
|
-
resolve('');
|
|
1196
|
-
return;
|
|
1197
|
-
}
|
|
1198
|
-
stream.on('data', (data) => { stdout += data.toString('utf-8'); });
|
|
1199
|
-
stream.stderr.on('data', (data) => { stderr += data.toString('utf-8'); });
|
|
1200
|
-
stream.on('close', () => {
|
|
1201
|
-
clearTimeout(timeout);
|
|
1202
|
-
const cwd = stdout.trim().split('\n')[0].trim();
|
|
1203
|
-
if (cwd && cwd.startsWith('/')) {
|
|
1204
|
-
console.log(`[SSH] getSessionCwdViaExec: '${cwd}'`);
|
|
1205
|
-
resolve(cwd);
|
|
1206
|
-
}
|
|
1207
|
-
else {
|
|
1208
|
-
console.log(`[SSH] getSessionCwdViaExec: no valid cwd, stdout: ${JSON.stringify(stdout.substring(0, 200))}, stderr: ${JSON.stringify(stderr.substring(0, 200))}`);
|
|
1209
|
-
resolve('');
|
|
1210
|
-
}
|
|
1211
|
-
});
|
|
1212
|
-
});
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
1570
|
/**
|
|
1216
1571
|
* 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
|
|
1217
1572
|
* @param sessionId 会话 ID
|
|
@@ -1272,21 +1627,25 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1272
1627
|
else
|
|
1273
1628
|
resolve(bytes);
|
|
1274
1629
|
};
|
|
1275
|
-
const doSftpWrite = (targetPath, callback) => {
|
|
1276
|
-
console.log(`[SSH] SFTP
|
|
1277
|
-
|
|
1630
|
+
const doSftpWrite = (targetPath, callback, isRetry = false) => {
|
|
1631
|
+
console.log(`[SSH] SFTP getting subsystem (reuse=${!!session.sftp})...`);
|
|
1632
|
+
this.getSftp(sessionId).then((sftp) => {
|
|
1278
1633
|
if (done)
|
|
1279
1634
|
return;
|
|
1280
|
-
if (sftpErr) {
|
|
1281
|
-
callback(new Error('SFTP init failed: ' + sftpErr.message));
|
|
1282
|
-
return;
|
|
1283
|
-
}
|
|
1284
1635
|
console.log(`[SSH] SFTP writing ${fileBuffer.length} bytes to ${targetPath}...`);
|
|
1285
1636
|
sftp.open(targetPath, 'w', (openErr, fd) => {
|
|
1286
1637
|
if (done)
|
|
1287
1638
|
return;
|
|
1288
1639
|
if (openErr) {
|
|
1289
1640
|
console.error(`[SSH] SFTP open error: ${openErr.message}`);
|
|
1641
|
+
// channel 类故障(达到 MaxSessions 上限 / channel 已失效):重建实例后重试一次
|
|
1642
|
+
if (!isRetry && /channel|not open|closed|failure/i.test(openErr.message)) {
|
|
1643
|
+
console.log('[SSH] SFTP channel broken, recreating subsystem and retrying once');
|
|
1644
|
+
this.invalidateSftp(sessionId);
|
|
1645
|
+
setTimeout(() => { if (!done)
|
|
1646
|
+
doSftpWrite(targetPath, callback, true); }, 300);
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1290
1649
|
callback(new Error('SFTP open failed: ' + openErr.message));
|
|
1291
1650
|
return;
|
|
1292
1651
|
}
|
|
@@ -1310,6 +1669,18 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1310
1669
|
});
|
|
1311
1670
|
});
|
|
1312
1671
|
});
|
|
1672
|
+
}).catch((initErr) => {
|
|
1673
|
+
if (done)
|
|
1674
|
+
return;
|
|
1675
|
+
// 建立 subsystem 就可能 "Channel open failure"(MaxSessions 上限):重建后重试一次
|
|
1676
|
+
if (!isRetry && /channel|failure|closed|not open/i.test(initErr?.message || '')) {
|
|
1677
|
+
console.log('[SSH] SFTP init failed, recreating subsystem and retrying once');
|
|
1678
|
+
this.invalidateSftp(sessionId);
|
|
1679
|
+
setTimeout(() => { if (!done)
|
|
1680
|
+
doSftpWrite(targetPath, callback, true); }, 300);
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
callback(new Error(initErr?.message || 'SFTP init failed'));
|
|
1313
1684
|
});
|
|
1314
1685
|
};
|
|
1315
1686
|
// 先尝试直接写入目标路径
|
|
@@ -1319,8 +1690,12 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1319
1690
|
if (!err) {
|
|
1320
1691
|
// 直接写入成功,验证文件
|
|
1321
1692
|
console.log(`[SSH] SFTP direct write succeeded, verifying...`);
|
|
1322
|
-
|
|
1693
|
+
this.getSftp(sessionId).then((sftp) => {
|
|
1694
|
+
if (done)
|
|
1695
|
+
return;
|
|
1323
1696
|
sftp.stat(fullPath, (statErr, stats) => {
|
|
1697
|
+
if (done)
|
|
1698
|
+
return;
|
|
1324
1699
|
if (statErr || stats.size !== fileBuffer.length) {
|
|
1325
1700
|
finish(new Error('SFTP verify failed'));
|
|
1326
1701
|
}
|
|
@@ -1329,6 +1704,10 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1329
1704
|
finish(null, fileBuffer.length);
|
|
1330
1705
|
}
|
|
1331
1706
|
});
|
|
1707
|
+
}).catch((statInitErr) => {
|
|
1708
|
+
if (done)
|
|
1709
|
+
return;
|
|
1710
|
+
finish(new Error(statInitErr?.message || 'SFTP verify init failed'));
|
|
1332
1711
|
});
|
|
1333
1712
|
return;
|
|
1334
1713
|
}
|
|
@@ -1453,20 +1832,58 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1453
1832
|
}
|
|
1454
1833
|
// ========== 文件管理(SFTP / 本地 fs) ==========
|
|
1455
1834
|
/**
|
|
1456
|
-
*
|
|
1835
|
+
* 获取(并复用)SFTP 客户端(ssh2 的 sftp 子系统)
|
|
1836
|
+
*
|
|
1837
|
+
* 必须复用:OpenSSH 默认 MaxSessions=10,而每次 client.sftp() 都会新开一个
|
|
1838
|
+
* subsystem channel。若每次调用都新建且不关闭,几次之后就会
|
|
1839
|
+
* "Channel open failure: open failed",表现为上传时好时坏、重连后又正常。
|
|
1457
1840
|
*/
|
|
1458
1841
|
getSftp(sessionId) {
|
|
1459
1842
|
const session = this.sessions.get(sessionId);
|
|
1460
1843
|
if (!session || !session.client) {
|
|
1461
1844
|
return Promise.reject(new Error('SFTP is only available for SSH sessions'));
|
|
1462
1845
|
}
|
|
1463
|
-
|
|
1846
|
+
if (session.sftp)
|
|
1847
|
+
return Promise.resolve(session.sftp);
|
|
1848
|
+
const pending = this.sftpPromises.get(sessionId);
|
|
1849
|
+
if (pending)
|
|
1850
|
+
return pending;
|
|
1851
|
+
const p = new Promise((resolve, reject) => {
|
|
1464
1852
|
session.client.sftp((err, sftp) => {
|
|
1465
|
-
|
|
1466
|
-
|
|
1853
|
+
this.sftpPromises.delete(sessionId);
|
|
1854
|
+
if (err || !sftp) {
|
|
1855
|
+
reject(new Error('SFTP init failed: ' + (err?.message || 'unknown')));
|
|
1856
|
+
return;
|
|
1857
|
+
}
|
|
1858
|
+
session.sftp = sftp;
|
|
1859
|
+
// 实例出错/关闭后丢弃,下次自动重建
|
|
1860
|
+
const drop = () => {
|
|
1861
|
+
if (session.sftp === sftp)
|
|
1862
|
+
session.sftp = undefined;
|
|
1863
|
+
};
|
|
1864
|
+
try {
|
|
1865
|
+
sftp.on('error', drop);
|
|
1866
|
+
sftp.on('close', drop);
|
|
1867
|
+
}
|
|
1868
|
+
catch { /* ignore */ }
|
|
1467
1869
|
resolve(sftp);
|
|
1468
1870
|
});
|
|
1469
1871
|
});
|
|
1872
|
+
this.sftpPromises.set(sessionId, p);
|
|
1873
|
+
return p;
|
|
1874
|
+
}
|
|
1875
|
+
/** 丢弃并关闭失效的 SFTP 实例(下次使用时重建) */
|
|
1876
|
+
invalidateSftp(sessionId) {
|
|
1877
|
+
const session = this.sessions.get(sessionId);
|
|
1878
|
+
const sftp = session?.sftp;
|
|
1879
|
+
if (!sftp)
|
|
1880
|
+
return;
|
|
1881
|
+
session.sftp = undefined;
|
|
1882
|
+
this.sftpPromises.delete(sessionId);
|
|
1883
|
+
try {
|
|
1884
|
+
sftp.end();
|
|
1885
|
+
}
|
|
1886
|
+
catch { /* ignore */ }
|
|
1470
1887
|
}
|
|
1471
1888
|
/**
|
|
1472
1889
|
* 列出远程(或本地)目录内容
|