-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
390 lines (340 loc) · 9.87 KB
/
Copy pathmain.go
File metadata and controls
390 lines (340 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"sync"
"time"
"golang.org/x/term"
)
// ---------------------------------------------------------------------------
// Terminal management — raw mode input with interruption-safe output
// ---------------------------------------------------------------------------
// termMu serializes all terminal writes between the input reader goroutine
// and event/status callbacks that fire from other goroutines.
var termMu sync.Mutex
// inputBuf holds the current line being typed, shared between the input
// reader and printLine so events can redraw the prompt after printing.
var inputBuf []rune
// printLine clears the current input line, prints a message, then redraws
// the prompt and partial input. Thread-safe — safe to call from any goroutine.
func printLine(format string, args ...interface{}) {
termMu.Lock()
defer termMu.Unlock()
fmt.Print("\r\033[K")
fmt.Printf(format, args...)
fmt.Print("\r\n")
fmt.Printf("> %s", string(inputBuf))
}
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
// config holds the connection parameters parsed from flags or config.txt.
type config struct {
Host string
Port string
Password string
}
// loadConfig reads a simple key=value config file named "config.txt".
// Lines starting with '#' or empty lines are ignored.
func loadConfig(path string) (config, error) {
f, err := os.Open(path)
if err != nil {
return config{}, err
}
defer f.Close()
var cfg config
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
switch {
case strings.HasPrefix(line, "host="):
cfg.Host = strings.TrimPrefix(line, "host=")
case strings.HasPrefix(line, "port="):
cfg.Port = strings.TrimPrefix(line, "port=")
case strings.HasPrefix(line, "password="):
cfg.Password = strings.TrimPrefix(line, "password=")
}
}
if err := sc.Err(); err != nil {
return config{}, err
}
return cfg, nil
}
// parseFlagsOrConfig tries flags first, falls back to config.txt for any
// missing values, and errors out if anything required is still blank.
func parseFlagsOrConfig() (config, string, bool) {
host := flag.String("host", "", "server IP or hostname")
port := flag.String("port", "", "RCON port")
password := flag.String("password", "", "RCON password")
cmd := flag.String("cmd", "", "optional one-shot command (then exit)")
quiet := flag.Bool("quiet", false, "suppress server events, only show command responses")
flag.Parse()
cfg := config{Host: *host, Port: *port, Password: *password}
// Fall back to config.txt for anything not provided via flags
if cfg.Host == "" || cfg.Port == "" || cfg.Password == "" {
fileCfg, err := loadConfig("config.txt")
if err != nil && !os.IsNotExist(err) {
log.Fatalf("error reading config file: %v", err)
}
if cfg.Host == "" {
cfg.Host = fileCfg.Host
}
if cfg.Port == "" {
cfg.Port = fileCfg.Port
}
if cfg.Password == "" {
cfg.Password = fileCfg.Password
}
}
// Final validation
if cfg.Host == "" || cfg.Port == "" || cfg.Password == "" {
fmt.Fprintf(os.Stderr,
"usage: %s -host IP -port PORT -password PASS [-cmd \"status\"]\n"+
" or place host=, port=, password= in config.txt\n",
os.Args[0])
os.Exit(1)
}
return cfg, *cmd, *quiet
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
func main() {
cfg, oneShotCmd, quiet := parseFlagsOrConfig()
fmt.Printf("Connecting to %s:%s ...\n", cfg.Host, cfg.Port)
client, err := Connect(cfg.Host, cfg.Port, cfg.Password)
if err != nil {
log.Fatalf("connect failed: %v", err)
}
defer client.Close()
// Status messages always show — you need to know about reconnects
client.OnStatus = func(msg string) {
printLine("[status] %s", msg)
}
// Events only show when not in quiet mode
if !quiet {
client.OnEvent = func(resp Response) {
if resp.Message != "" {
printLine("[event] %s", resp.Message)
}
}
}
fmt.Println("Connected. Type commands (or 'quit' to exit).")
// --- One-shot mode ---
if oneShotCmd != "" {
runOneShot(client, oneShotCmd)
return
}
// --- Interactive mode ---
runInteractive(client)
}
// ---------------------------------------------------------------------------
// One-shot mode
// ---------------------------------------------------------------------------
// runOneShot sends a single command, prints the response, and exits.
func runOneShot(client *Client, command string) {
resp, err := client.SendAndWait(command, 5*time.Second)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
if resp.Message != "" {
fmt.Println(resp.Message)
}
}
// ---------------------------------------------------------------------------
// Interactive mode
// ---------------------------------------------------------------------------
// runInteractive runs the REPL loop. Attempts raw terminal mode for
// interruption-safe input. Falls back to line-buffered mode if raw mode
// is unavailable (e.g., piped input or unsupported terminal).
func runInteractive(client *Client) {
// Try raw terminal mode for interruption-safe input
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
// Fall back to line-buffered mode
readStdinLoopFallback(client)
return
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
// Channel signals when the stdin loop finishes (quit, EOF, or error)
stdinDone := make(chan struct{})
go func() {
defer close(stdinDone)
readStdinLoop(client)
}()
// Block until something tells us to exit
select {
case <-stdinDone:
// User typed quit/exit/Ctrl+C — clean exit
case <-client.Done():
termMu.Lock()
fmt.Print("\r\033[K[status] Client closed.\r\n")
termMu.Unlock()
case <-interrupt:
termMu.Lock()
fmt.Print("\r\nInterrupted.\r\n")
termMu.Unlock()
}
}
// readStdinLoop reads input in raw terminal mode. Each keystroke updates
// the input buffer and redraws the prompt. When events or status messages
// arrive from other goroutines, printLine clears the line, prints the
// message, then redraws the prompt + partial input — the user's typing
// is never destroyed.
func readStdinLoop(client *Client) {
inputBuf = inputBuf[:0]
// Initial prompt
termMu.Lock()
fmt.Print("> ")
termMu.Unlock()
var b [1]byte
for {
n, err := os.Stdin.Read(b[:])
if err != nil {
if err != io.EOF {
termMu.Lock()
fmt.Printf("stdin error: %v\r\n", err)
termMu.Unlock()
}
return
}
if n == 0 {
continue
}
ch := b[0]
switch {
case ch == 3: // Ctrl+C
fmt.Print("\r\n")
return
case ch == 4: // Ctrl+D (EOF)
fmt.Print("\r\n")
return
case ch == '\r' || ch == '\n': // Enter
line := strings.TrimSpace(string(inputBuf))
termMu.Lock()
inputBuf = inputBuf[:0]
fmt.Print("\r\n")
termMu.Unlock()
if line == "" {
termMu.Lock()
fmt.Print("> ")
termMu.Unlock()
continue
}
if line == "quit" || line == "exit" {
return
}
if client.IsConnected() {
// Connected — send and block for response
resp, err := client.SendAndWait(line, 10*time.Second)
termMu.Lock()
fmt.Print("\r\033[K") // clear any stale prompt from events
if err != nil {
fmt.Printf("error: %v\r\n", err)
} else if resp.Message != "" {
fmt.Printf("%s\r\n", resp.Message)
}
fmt.Print("> ")
termMu.Unlock()
} else {
// Disconnected — queue and keep reading
id, err := client.Send(line)
termMu.Lock()
if err != nil {
fmt.Printf("error: %v\r\n", err)
} else {
fmt.Printf("[queued #%d] %s\r\n", id, line)
}
fmt.Print("> ")
termMu.Unlock()
if err == nil {
// Wait for the response in a goroutine so the
// user can keep typing
go func(id int) {
resp, err := client.WaitFor(id, 0)
if err != nil {
printLine("[queued #%d] error: %v", id, err)
} else if resp.Message != "" {
printLine("[queued #%d] %s", id, resp.Message)
}
}(id)
}
}
case ch == 127 || ch == 8: // Backspace
termMu.Lock()
if len(inputBuf) > 0 {
inputBuf = inputBuf[:len(inputBuf)-1]
fmt.Print("\r\033[K")
fmt.Printf("> %s", string(inputBuf))
}
termMu.Unlock()
case ch >= 32 && ch < 127: // Printable ASCII
termMu.Lock()
inputBuf = append(inputBuf, rune(ch))
fmt.Print("\r\033[K")
fmt.Printf("> %s", string(inputBuf))
termMu.Unlock()
default:
// Ignore escape sequences and other control characters
}
}
}
// readStdinLoopFallback is used when raw terminal mode is unavailable.
// Uses traditional line-buffered input. Events still use printLine, which
// may not redraw perfectly in this mode but won't crash.
func readStdinLoopFallback(client *Client) {
sc := bufio.NewScanner(os.Stdin)
for {
fmt.Print("> ")
if !sc.Scan() {
if err := sc.Err(); err != nil {
fmt.Fprintf(os.Stderr, "stdin error: %v\n", err)
}
return
}
line := strings.TrimSpace(sc.Text())
if line == "" {
continue
}
if line == "quit" || line == "exit" {
return
}
if client.IsConnected() {
resp, err := client.SendAndWait(line, 10*time.Second)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
continue
}
if resp.Message != "" {
fmt.Println(resp.Message)
}
} else {
id, err := client.Send(line)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
continue
}
fmt.Printf("[queued #%d] %s\n", id, line)
go func(id int) {
resp, err := client.WaitFor(id, 0)
if err != nil {
printLine("[queued #%d] error: %v", id, err)
} else if resp.Message != "" {
printLine("[queued #%d] %s", id, resp.Message)
}
}(id)
}
}
}