Skip to content

Commit 00354bc

Browse files
committed
Improved file descriptor handling
1 parent 96b1973 commit 00354bc

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

src/ssh.zsh

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,23 +25,26 @@ ssh() {
2525
stty -echo -icanon time 0 min 0 <&$fd
2626

2727
# Ask: terminal replies DCS "1$r q<Ps> q" ST (success)
28-
printf '%s' "$DECRQSS" > /dev/tty
28+
printf '%s' "$DECRQSS" >&$fd
2929

3030
buf=''
31-
# Read until we see ST (ESC \) anywhere in the buffer (cap ~2s)
32-
for i in {1..100}; do
33-
IFS= read -r -u $fd -k 1 -t 0.01 chunk || chunk=''
34-
[[ -n "$chunk" ]] && buf+="$chunk"
35-
[[ $buf == *"$ST"* ]] && break
31+
# Read until we see ST (ESC \) anywhere in the buffer (cap ~2s = 200 × 10ms)
32+
for i in {1..200}; do
33+
if IFS= read -r -u $fd -k 1 -t 0.01 chunk; then
34+
buf+="$chunk"
35+
[[ $buf == *"$ST"* ]] && break
36+
fi
3637
done
3738

39+
# Require we saw a DCS...ST block
40+
[[ $buf == *"$DCS"*"$ST"* ]] || return 1
41+
3842
# Extract first DCS block and require DECRQSS success "1$r"
39-
[[ $buf == *"$DCS"*"$ST"* ]] || return 0
4043
dcs_reply=${buf#*"$DCS"}
4144
dcs_reply=${dcs_reply%%"$ST"*}
4245

4346
# Must be a success reply
44-
[[ $dcs_reply == 1'$r'* ]] || return 0
47+
[[ $dcs_reply == 1'$r'* ]] || return 1
4548

4649
ps=''
4750
if [[ $dcs_reply == '1$r q'[0-6]' q'* ]]; then
@@ -52,14 +55,26 @@ ssh() {
5255
# Validate 0..6 and print
5356
if [[ $ps = <-> && $ps -ge 0 && $ps -le 6 ]]; then
5457
print -r -- "$ps"
58+
return 0
59+
else
60+
return 1
5561
fi
56-
return 0
5762
} always {
5863
# --- always cleanup, even on early return ---
5964

60-
# Restore TTY and close FD
65+
# Preserve result of the try-block (including any return above)
66+
local ret=$?
67+
68+
# Restores the terminal mode on the same fd
6169
stty "$stty_orig" <&$fd 2>/dev/null
70+
71+
# We close the file descriptor with redirection `>&-`
72+
# Redirections in zsh must be attached to a command.
73+
# Since we don’t actually want to run a real command
74+
# the no-op builtin `:` is used as the command.
6275
: {fd}>&-
76+
77+
return $ret
6378
}
6479
}
6580

0 commit comments

Comments
 (0)