Skip to content

Commit 39e4401

Browse files
fix(telnet): stop Mudlet masking all input for the whole session (#633)
* fix(telnet): stop Mudlet masking all input for the whole session Mudlet (and other local-echo clients) treat telnet WILL ECHO as a "mask this field" hint rather than a server-echo request. GoMud asserted WILL ECHO unconditionally at connect and never withdrew it, so Mudlet masked every keystroke for the entire session. Detect the client type at connect via an MNES NEW-ENVIRON probe and branch the echo behavior: - Mudlet: baseline WONT ECHO (Mudlet echoes locally); the server no longer echoes/masks per character or emits its own newline. Password prompts are masked by transiently asserting WILL ECHO and withdrawing it (WONT ECHO) once the step validates. - Raw telnet: unchanged - WILL ECHO baseline with server-side echo and mask-character passwords. - Web client: unchanged - TEXTMASK toggling, no server-side per-char echo. Detection is synchronous and bounded (200ms per read, 2s overall); a client that ignores NEW-ENVIRON falls back to non-Mudlet and still logs in. AI connections skip the probe and keep the historical baseline. Changes: - connections.ClientSettings: add IsMudlet / DetectionComplete. - ConnectionDetails.SetReadDeadline for the bounded probe reads. - term: NEW-ENVIRON sub-negotiation codes, request/response matchers, and a TelnetRequestMNESVars helper. - TelnetIACHandler: negotiate NEW-ENVIRON and record IsMudlet from CLIENT_NAME, plus a unit test for the response parser. - main.go: detectClientType probe and echo-baseline branch. - login_prompt_handler: skip server echo/mask and newline for local-echo clients; toggle ECHO masking around Mudlet password steps. * term: alias NEW-ENVIRON codes to existing telnet constants Address review feedback on PR #633: the NEW-ENVIRON sub-negotiation codes share byte values with telnet option constants already defined in this block, so alias them instead of re-declaring literals. Values are unchanged (IS/VAR=0, SEND/VALUE=1, INFO/ESC=2, USERVAR=3), so behavior is identical. * telnet: offer EOR and broaden NEW-ENVIRON detection for Mudlet masking Real-Mudlet testing showed password masking half-working: Mudlet honored WILL ECHO (command echo suppressed) but did not put asterisks on the input line. Aligns the connect/detection sequence with a known-working downstream fork: - Offer WILL EOR at connect. Mudlet prefers EOR over GA to delimit prompts; with SUPPRESS-GO-AHEAD set and no EOR, Mudlet has no prompt anchor for its input-line masking. - Request ALL NEW-ENVIRON variables (empty SEND) instead of naming specific ones - broadly compatible; Mudlet returns CLIENT_NAME among them. - Match the NEW-ENVIRON IS response on the 'IAC SB NEW-ENVIRON IS' prefix alone (tolerant of TCP segmentation / trailing bytes), and make the parser treat IAC as a name/value terminator so a trailing IAC SE never bleeds into the final variable's value.
1 parent 99305b2 commit 39e4401

8 files changed

Lines changed: 399 additions & 30 deletions

File tree

internal/connections/clientsettings.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ type ClientSettings struct {
1212
// Is MSP enabled?
1313
MSPEnabled bool // Do they accept sound in their client?
1414
SendTelnetGoAhead bool // Defaults false, should we send a IAC GA after prompts?
15+
// IsMudlet is true when the client identified itself as Mudlet (via the MNES
16+
// NEW-ENVIRON CLIENT_NAME variable). Mudlet echoes input locally and treats
17+
// the telnet ECHO option purely as a password-masking hint, so it must not
18+
// receive server-side echo.
19+
IsMudlet bool
20+
// DetectionComplete is set once the connect-time client-type probe has
21+
// resolved (either a NEW-ENVIRON reply arrived or the probe timed out).
22+
DetectionComplete bool
1523
}
1624

1725
func (c ClientSettings) IsMsp() bool {

internal/connections/connectiondetails.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,17 @@ func (cd *ConnectionDetails) Read(p []byte) (n int, err error) {
324324
return cd.conn.Read(p)
325325
}
326326

327+
// SetReadDeadline bounds how long the next Read may block. It only applies to
328+
// the raw telnet path (net.Conn); SSH and WebSocket connections do not use the
329+
// connect-time detection probe, so this is a no-op for them. Pass the zero time
330+
// to clear a previously-set deadline.
331+
func (cd *ConnectionDetails) SetReadDeadline(t time.Time) error {
332+
if cd.conn != nil {
333+
return cd.conn.SetReadDeadline(t)
334+
}
335+
return nil
336+
}
337+
327338
func (cd *ConnectionDetails) Close() {
328339
if cd.heartbeat != nil {
329340
cd.heartbeat.stop()

internal/inputhandlers/login_prompt_handler.go

Lines changed: 53 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -204,31 +204,41 @@ func CreatePromptHandler(steps []*PromptStep, onComplete CompletionFunc) connect
204204
// Handle printable characters
205205
//clientInput.Buffer = append(clientInput.Buffer, clientInput.DataIn...)
206206

207-
// Echo or Mask
208-
if currentStep.MaskInput {
209-
210-
// Cache the mask template string if needed
211-
if state.maskTemplate == "" && currentStep.MaskTemplate != "" {
212-
213-
if maskStr, err := templates.Process(currentStep.MaskTemplate, nil); err != nil {
214-
mudlog.Error("Mask template error", "template", currentStep.MaskTemplate, "error", err)
215-
state.maskTemplate = "*" // Fallback mask
216-
} else {
217-
state.maskTemplate = templates.AnsiParse(maskStr)
207+
// Local-echo clients (Mudlet, web client) echo input themselves,
208+
// so the server must not echo or emit mask characters per byte -
209+
// doing so would double every character. Their masking is handled
210+
// out-of-band (telnet ECHO toggling for Mudlet, TEXTMASK for the
211+
// web client). Only raw telnet relies on this server-side echo.
212+
cs := connections.GetClientSettings(clientInput.ConnectionId)
213+
isLocalEcho := cs.IsMudlet || connections.IsWebsocket(clientInput.ConnectionId)
214+
215+
if !isLocalEcho {
216+
// Echo or Mask
217+
if currentStep.MaskInput {
218+
219+
// Cache the mask template string if needed
220+
if state.maskTemplate == "" && currentStep.MaskTemplate != "" {
221+
222+
if maskStr, err := templates.Process(currentStep.MaskTemplate, nil); err != nil {
223+
mudlog.Error("Mask template error", "template", currentStep.MaskTemplate, "error", err)
224+
state.maskTemplate = "*" // Fallback mask
225+
} else {
226+
state.maskTemplate = templates.AnsiParse(maskStr)
227+
}
228+
229+
} else if state.maskTemplate == "" {
230+
state.maskTemplate = "*" // Default fallback if no template specified
218231
}
219232

220-
} else if state.maskTemplate == "" {
221-
state.maskTemplate = "*" // Default fallback if no template specified
222-
}
233+
// Send mask character(s)
234+
for i := 0; i < len(clientInput.DataIn); i++ {
235+
connections.SendTo([]byte(state.maskTemplate), clientInput.ConnectionId)
236+
}
223237

224-
// Send mask character(s)
225-
for i := 0; i < len(clientInput.DataIn); i++ {
226-
connections.SendTo([]byte(state.maskTemplate), clientInput.ConnectionId)
238+
} else {
239+
// Echo input directly
240+
connections.SendTo(clientInput.DataIn, clientInput.ConnectionId)
227241
}
228-
229-
} else {
230-
// Echo input directly
231-
connections.SendTo(clientInput.DataIn, clientInput.ConnectionId)
232242
}
233243

234244
}
@@ -258,7 +268,12 @@ func CreatePromptHandler(steps []*PromptStep, onComplete CompletionFunc) connect
258268
}
259269

260270
// Enter Pressed: Process Input
261-
connections.SendTo(term.CRLF, clientInput.ConnectionId) // Echo newline
271+
// Mudlet echoes the submitted line (and its newline) locally, so a
272+
// server-sent CRLF here would produce a blank line. Raw telnet
273+
// (server-side echo) and the web client still need it.
274+
if !connections.GetClientSettings(clientInput.ConnectionId).IsMudlet {
275+
connections.SendTo(term.CRLF, clientInput.ConnectionId) // Echo newline
276+
}
262277
submittedInput := strings.TrimSpace(string(clientInput.Buffer))
263278
clientInput.Buffer = clientInput.Buffer[:0] // Clear buffer for next input
264279
state.maskTemplate = "" // Clear cached mask template
@@ -309,6 +324,14 @@ func CreatePromptHandler(steps []*PromptStep, onComplete CompletionFunc) connect
309324
mudlog.Debug("Prompt Step Success", "step", currentStep.ID, "value", validatedValue, "connectionId", clientInput.ConnectionId)
310325
}
311326

327+
// A masked Mudlet step just passed: withdraw the telnet ECHO mask so
328+
// input is visible again. If the next step is also masked, sendPrompt
329+
// re-asserts WILL ECHO; if this was the last step, this restores normal
330+
// echo before gameplay begins.
331+
if currentStep.MaskInput && connections.GetClientSettings(clientInput.ConnectionId).IsMudlet {
332+
connections.SendTo(term.TelnetWONT(term.TELNET_OPT_ECHO), clientInput.ConnectionId)
333+
}
334+
312335
// Advance to Next Step or Complete
313336
if advanceAndSendPrompt(state, clientInput) {
314337

@@ -367,6 +390,14 @@ func sendPrompt(step *PromptStep, clientInput *connections.ClientInput, results
367390
connections.SendTo([]byte(maskCmd), clientInput.ConnectionId)
368391
}
369392

393+
// Mudlet reads telnet WILL ECHO as "mask this field". Assert it for masked
394+
// steps (passwords) so Mudlet hides the input; it is withdrawn (WONT ECHO)
395+
// once the step validates. Sent before the prompt text so masking is active
396+
// the moment the prompt appears.
397+
if step.MaskInput && connections.GetClientSettings(clientInput.ConnectionId).IsMudlet {
398+
connections.SendTo(term.TelnetWILL(term.TELNET_OPT_ECHO), clientInput.ConnectionId)
399+
}
400+
370401
connections.SendTo([]byte(parsedPrompt), clientInput.ConnectionId)
371402
}
372403

internal/inputhandlers/term_iac.go

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package inputhandlers
22

33
import (
4+
"strings"
5+
46
"github.com/GoMudEngine/GoMud/internal/configs"
57
"github.com/GoMudEngine/GoMud/internal/connections"
68
"github.com/GoMudEngine/GoMud/internal/mudlog"
@@ -148,6 +150,44 @@ func TelnetIACHandler(clientInput *connections.ClientInput, sharedState map[stri
148150
continue
149151
}
150152

153+
//
154+
// NEW-ENVIRON / MNES client detection (see handleTelnetConnection in main.go).
155+
//
156+
157+
// Client agreed to NEW-ENVIRON: ask it to send all of its variables.
158+
// (Requesting all is more broadly compatible than naming specific vars;
159+
// Mudlet replies with CLIENT_NAME among them.)
160+
if ok, _ := term.Matches(iacCmd, term.TelnetWillNewEnviron); ok {
161+
mudlog.Debug("Received", "type", "IAC (WILL NEW-ENVIRON)")
162+
connections.SendTo(term.TelnetNewEnvironSendRequest.BytesWithPayload(nil), clientInput.ConnectionId)
163+
continue
164+
}
165+
166+
// Client refused NEW-ENVIRON: it won't identify itself this way, so
167+
// treat detection as complete (and not Mudlet).
168+
if ok, _ := term.Matches(iacCmd, term.TelnetWontNewEnviron); ok {
169+
mudlog.Debug("Received", "type", "IAC (WONT NEW-ENVIRON)")
170+
171+
cs := connections.GetClientSettings(clientInput.ConnectionId)
172+
cs.DetectionComplete = true
173+
connections.OverwriteClientSettings(clientInput.ConnectionId, cs)
174+
175+
continue
176+
}
177+
178+
// Client sent its NEW-ENVIRON variables. Scan for CLIENT_NAME=MUDLET.
179+
if ok, payload := term.Matches(iacCmd, term.TelnetNewEnvironResponse); ok {
180+
isMudlet := newEnvironIsMudlet(payload)
181+
mudlog.Debug("Received", "type", "IAC (NEW-ENVIRON IS)", "isMudlet", isMudlet, "data", term.BytesString(payload))
182+
183+
cs := connections.GetClientSettings(clientInput.ConnectionId)
184+
cs.IsMudlet = isMudlet
185+
cs.DetectionComplete = true
186+
connections.OverwriteClientSettings(clientInput.ConnectionId, cs)
187+
188+
continue
189+
}
190+
151191
// Unhanlded IAC command, log it
152192
mudlog.Debug("Received", "type", "IAC (Unhandled)", "size", len(clientInput.DataIn), "data", term.TelnetCommandToString(iacCmd))
153193

@@ -156,3 +196,52 @@ func TelnetIACHandler(clientInput *connections.ClientInput, sharedState map[stri
156196
// We handled it, so don't pass it on
157197
return false
158198
}
199+
200+
// newEnvironIsMudlet walks a NEW-ENVIRON IS payload looking for the MNES
201+
// CLIENT_NAME variable. It returns true when CLIENT_NAME equals "MUDLET"
202+
// (case-insensitive). The payload is a sequence of VAR/USERVAR name segments,
203+
// each optionally followed by a VALUE segment; segments are delimited by the
204+
// VAR(0)/VALUE(1)/USERVAR(3) control bytes. IAC (255) is also treated as a
205+
// terminator so a trailing `IAC SE` left in the payload by the lenient matcher
206+
// never bleeds into the final variable's value.
207+
func newEnvironIsMudlet(payload []byte) bool {
208+
isControl := func(b byte) bool {
209+
return b == term.TELNET_NEWENV_VAR || b == term.TELNET_NEWENV_VALUE ||
210+
b == term.TELNET_NEWENV_USERVAR || b == term.TELNET_IAC
211+
}
212+
213+
i := 0
214+
for i < len(payload) {
215+
code := payload[i]
216+
i++
217+
218+
// Only VAR / USERVAR start a named variable.
219+
if code != term.TELNET_NEWENV_VAR && code != term.TELNET_NEWENV_USERVAR {
220+
continue
221+
}
222+
223+
// Read the variable name up to the next control byte.
224+
nameStart := i
225+
for i < len(payload) && !isControl(payload[i]) {
226+
i++
227+
}
228+
name := string(payload[nameStart:i])
229+
230+
// An optional VALUE segment follows.
231+
value := ""
232+
if i < len(payload) && payload[i] == term.TELNET_NEWENV_VALUE {
233+
i++
234+
valueStart := i
235+
for i < len(payload) && !isControl(payload[i]) {
236+
i++
237+
}
238+
value = string(payload[valueStart:i])
239+
}
240+
241+
if name == "CLIENT_NAME" && strings.EqualFold(value, "MUDLET") {
242+
return true
243+
}
244+
}
245+
246+
return false
247+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package inputhandlers
2+
3+
import (
4+
"testing"
5+
6+
"github.com/GoMudEngine/GoMud/internal/term"
7+
)
8+
9+
// newEnvironPayload builds the bytes that appear between `IAC SB NEW-ENVIRON IS`
10+
// and the trailing `IAC SE` for a sequence of VAR/VALUE pairs.
11+
func newEnvironPayload(pairs ...[2]string) []byte {
12+
out := []byte{}
13+
for _, p := range pairs {
14+
out = append(out, term.TELNET_NEWENV_VAR)
15+
out = append(out, []byte(p[0])...)
16+
out = append(out, term.TELNET_NEWENV_VALUE)
17+
out = append(out, []byte(p[1])...)
18+
}
19+
return out
20+
}
21+
22+
func TestNewEnvironIsMudlet(t *testing.T) {
23+
tests := []struct {
24+
name string
25+
payload []byte
26+
want bool
27+
}{
28+
{
29+
name: "mudlet with version",
30+
payload: newEnvironPayload([2]string{"CLIENT_NAME", "Mudlet"}, [2]string{"CLIENT_VERSION", "4.17.2"}),
31+
want: true,
32+
},
33+
{
34+
name: "mudlet uppercase value",
35+
payload: newEnvironPayload([2]string{"CLIENT_NAME", "MUDLET"}),
36+
want: true,
37+
},
38+
{
39+
name: "client name not first",
40+
payload: newEnvironPayload([2]string{"CLIENT_VERSION", "4.17.2"}, [2]string{"CLIENT_NAME", "Mudlet"}),
41+
want: true,
42+
},
43+
{
44+
name: "different client",
45+
payload: newEnvironPayload([2]string{"CLIENT_NAME", "TinTin++"}),
46+
want: false,
47+
},
48+
{
49+
name: "client name without value",
50+
payload: append([]byte{term.TELNET_NEWENV_VAR}, []byte("CLIENT_NAME")...),
51+
want: false,
52+
},
53+
{
54+
name: "empty payload",
55+
payload: []byte{},
56+
want: false,
57+
},
58+
{
59+
name: "uservar segment ignored, var matched",
60+
payload: append(append([]byte{term.TELNET_NEWENV_USERVAR}, []byte("FOO")...), newEnvironPayload([2]string{"CLIENT_NAME", "Mudlet"})...),
61+
want: true,
62+
},
63+
}
64+
65+
for _, tc := range tests {
66+
t.Run(tc.name, func(t *testing.T) {
67+
if got := newEnvironIsMudlet(tc.payload); got != tc.want {
68+
t.Errorf("newEnvironIsMudlet() = %v, want %v", got, tc.want)
69+
}
70+
})
71+
}
72+
}
73+
74+
// TestNewEnvironResponseMatcher verifies the term matcher extracts the payload
75+
// that newEnvironIsMudlet expects from a full client response frame, including
76+
// the trailing IAC SE terminator that the lenient matcher leaves in the payload.
77+
func TestNewEnvironResponseMatcher(t *testing.T) {
78+
// IAC SB NEW-ENVIRON IS <vars> IAC SE
79+
frame := append(
80+
term.TelnetNewEnvironResponse.BytesWithPayload(newEnvironPayload([2]string{"CLIENT_NAME", "Mudlet"})),
81+
term.TELNET_IAC, term.TELNET_SE,
82+
)
83+
84+
ok, payload := term.Matches(frame, term.TelnetNewEnvironResponse)
85+
if !ok {
86+
t.Fatalf("expected frame to match TelnetNewEnvironResponse")
87+
}
88+
// The trailing IAC SE remains in payload; the parser must still detect Mudlet.
89+
if !newEnvironIsMudlet(payload) {
90+
t.Errorf("expected extracted payload to be detected as Mudlet, payload=%v", payload)
91+
}
92+
}

internal/term/telnet.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,19 @@ const (
132132
TELNET_OPT_PRAGMA_HEARTBEAT IACByte = 140 // TELOPT PRAGMA HEARTBEAT RFC:
133133
TELNET_OPT_254 IACByte = 254
134134
TELNET_OPT_EXTENDED_OPT IACByte = 255 // Extended-Options-List RFC: https://www.ietf.org/rfc/rfc861.txt
135+
136+
// NEW-ENVIRON (option 39) sub-negotiation codes. RFC: https://www.ietf.org/rfc/rfc1572.txt
137+
// Used by the MNES (Mud New-Environ Standard) handshake that we use to detect
138+
// Mudlet (and other clients that advertise CLIENT_NAME). Their byte values
139+
// coincide with telnet option codes already defined above, so they are aliased
140+
// to those constants instead of being re-declared as literals.
141+
TELNET_NEWENV_IS = TELNET_OPT_TXBIN // 0: Client -> Server: here are my variables
142+
TELNET_NEWENV_SEND = TELNET_OPT_ECHO // 1: Server -> Client: please send these variables
143+
TELNET_NEWENV_INFO = TELNET_OPT_RECONN // 2: Client -> Server: a variable changed
144+
TELNET_NEWENV_VAR = TELNET_OPT_TXBIN // 0: A well-known variable name follows
145+
TELNET_NEWENV_VALUE = TELNET_NEWENV_SEND // 1: A variable value follows
146+
TELNET_NEWENV_ESC = TELNET_NEWENV_INFO // 2: Escape the next byte (it is data, not a code)
147+
TELNET_NEWENV_USERVAR = TELNET_OPT_SUP_GO_AHD // 3: A user-defined variable name follows
135148
)
136149

137150
// https://users.cs.cf.ac.uk/Dave.Marshall/Internet/node142.html

internal/term/term.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,26 @@ var (
8080
// Go Ahead
8181
TelnetGoAhead = TerminalCommand{[]byte{TELNET_IAC, TELNET_GA}, []byte{}}
8282

83+
//
84+
// NEW-ENVIRON / MNES (used to detect the client at connect time)
85+
//
86+
// Ask the client to enable NEW-ENVIRON. A compliant client replies with
87+
// TelnetWillNewEnviron (or TelnetWontNewEnviron to refuse).
88+
TelnetRequestNewEnviron = TerminalCommand{[]byte{TELNET_IAC, TELNET_DO, TELNET_OPT_NEW_ENV}, []byte{}}
89+
// Client agrees / refuses to use NEW-ENVIRON.
90+
TelnetWillNewEnviron = TerminalCommand{[]byte{TELNET_IAC, TELNET_WILL, TELNET_OPT_NEW_ENV}, []byte{}}
91+
TelnetWontNewEnviron = TerminalCommand{[]byte{TELNET_IAC, TELNET_WONT, TELNET_OPT_NEW_ENV}, []byte{}}
92+
// Server -> Client request for variables. Sent with an empty payload to
93+
// request ALL of the client's environment variables (broadly compatible;
94+
// Mudlet replies with CLIENT_NAME among them).
95+
TelnetNewEnvironSendRequest = TerminalCommand{[]byte{TELNET_IAC, TELNET_SB, TELNET_OPT_NEW_ENV, TELNET_NEWENV_SEND}, []byte{TELNET_IAC, TELNET_SE}}
96+
// Client -> Server response carrying the variable values. EndChars are left
97+
// empty so the match succeeds on the `IAC SB NEW-ENVIRON IS` prefix alone -
98+
// the trailing IAC SE is tolerated inside the payload and ignored by the
99+
// parser. This is more robust to TCP segmentation and trailing bytes than
100+
// requiring an exact terminator.
101+
TelnetNewEnvironResponse = TerminalCommand{[]byte{TELNET_IAC, TELNET_SB, TELNET_OPT_NEW_ENV, TELNET_NEWENV_IS}, []byte{}}
102+
83103
///////////////////////////
84104
// ANSI COMMANDS
85105
///////////////////////////

0 commit comments

Comments
 (0)