-
Notifications
You must be signed in to change notification settings - Fork 1
/
terminal.go
598 lines (552 loc) · 13.7 KB
/
terminal.go
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package main
import (
"bytes"
"fmt"
"log"
"math"
"math/rand"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"time"
"github.com/bwmarrin/discordgo"
"github.com/creack/pty"
"github.com/hinshun/vt10x"
"golang.org/x/exp/slices"
)
var (
BOT_KEYS = [...]Key{
{
Name: "LF [\\n]",
InSeq: "\\n",
OutSeq: "\n",
},
{
Name: "CR (Enter) [\\r]",
InSeq: "\\r",
OutSeq: "\r",
},
{
Name: "Backspace [\\b]",
InSeq: "\\b",
OutSeq: "\b",
},
{
Name: "Tab [\\t]",
InSeq: "\\t",
OutSeq: "\t",
},
{
Name: "Escape [ESC]",
InSeq: "[ESC]",
OutSeq: "\x1b",
},
{
Name: "F1",
InSeq: "[F1]",
OutSeq: "\x1bOP",
},
{
Name: "F2",
InSeq: "[F2]",
OutSeq: "\x1bOQ",
},
{
Name: "F3",
InSeq: "[F3]",
OutSeq: "\x1bOR",
},
{
Name: "F4",
InSeq: "[F4]",
OutSeq: "\x1bOS",
},
{
Name: "F5",
InSeq: "[F5]",
OutSeq: "\x1b[15~",
},
{
Name: "F6",
InSeq: "[F6]",
OutSeq: "\x1b[17~",
},
{
Name: "F7",
InSeq: "[F7]",
OutSeq: "\x1b[18~",
},
{
Name: "F8",
InSeq: "[F8]",
OutSeq: "\x1b[19~",
},
{
Name: "F9",
InSeq: "[F9]",
OutSeq: "\x1b[20~",
},
{
Name: "F10",
InSeq: "[F10]",
OutSeq: "\x1b[21~",
},
{
Name: "F11",
InSeq: "[F11]",
OutSeq: "\x1b[23~",
},
{
Name: "F12",
InSeq: "[F12]",
OutSeq: "\x1b[24~",
},
{
Name: "UP",
InSeq: "[UP]",
OutSeq: "\x1b[A",
},
{
Name: "DOWN",
InSeq: "[DOWN]",
OutSeq: "\x1b[B",
},
{
Name: "RIGHT",
InSeq: "[RIGHT]",
OutSeq: "\x1b[C",
},
{
Name: "LEFT",
InSeq: "[LEFT]",
OutSeq: "\x1b[D",
},
{
Name: "INS",
InSeq: "[INS]",
OutSeq: "\x1b[2~",
},
{
Name: "DEL",
InSeq: "[DEL]",
OutSeq: "\x1b[3~",
},
{
Name: "PGUP",
InSeq: "[PGUP]",
OutSeq: "\x1b[5~",
},
{
Name: "PGDN",
InSeq: "[PGDN]",
OutSeq: "\x1b[6~",
},
}
buttons = []discordgo.MessageComponent{
&discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
&discordgo.Button{
Label: "Set as active",
Style: discordgo.PrimaryButton,
CustomID: "active",
},
&discordgo.Button{
Label: "Move down",
Style: discordgo.SecondaryButton,
CustomID: "here",
},
&discordgo.Button{
Label: "Close",
Style: discordgo.DangerButton,
CustomID: "close",
}},
},
}
)
const UPDATE_INTERVAL = 2 * time.Second
type SafeTerm struct {
Mutex sync.Mutex
Term vt10x.Terminal
}
type DiscordTerminal struct {
ID int
Running bool
Bot *Bot
Owner *discordgo.User
SharedUsers []string
Color bool
Ticker *time.Ticker
CloseSignal chan bool
UpdateSignal chan bool // true if manual, false if ticker
Msg *discordgo.Message
Pty *os.File
SafeTerm SafeTerm
CurrentScreen string
LastScreen string
}
func (term *DiscordTerminal) AllowedToControl(user *discordgo.User) bool {
if user.ID == term.Owner.ID {
return true
}
if slices.Index(term.SharedUsers, user.ID) != -1 {
return true
}
return false
}
type Key struct {
Name string
InSeq string
OutSeq string
}
func ParseSequences(ins string) string {
// ^D, ^C, ^Z, etc...
match := regexp.MustCompile(`\^([A-Z])`).FindAllStringSubmatch(ins, -1)
for _, m := range match {
ac := []byte(m[1])[0]
ins = strings.ReplaceAll(ins, m[0], string(ac-64))
}
// Keys
for _, k := range BOT_KEYS {
ins = strings.ReplaceAll(ins, k.InSeq, k.OutSeq)
}
return ins
}
func StringANSI(t vt10x.Terminal) string {
t.Lock()
defer t.Unlock()
var view []rune
cols, rows := t.Size()
var prevcell vt10x.Glyph
for y := 0; y < rows; y++ {
for x := 0; x < cols; x++ {
cell := t.Cell(x, y)
if cell.FG != prevcell.FG {
if cell.FG == vt10x.DefaultFG {
view = append(view, []rune("\x1b[39m")...)
} else if cell.FG == vt10x.DefaultBG {
view = append(view, []rune("\x1b[30m")...)
} else {
view = append(view, []rune(fmt.Sprintf("\x1b[%dm", 30+cell.FG%8))...)
}
}
if cell.BG != prevcell.BG {
if cell.BG == vt10x.DefaultBG {
view = append(view, []rune("\x1b[49m")...)
} else if cell.BG == vt10x.DefaultFG {
view = append(view, []rune("\x1b[47m")...)
} else {
view = append(view, []rune(fmt.Sprintf("\x1b[%dm", 40+cell.BG%8))...)
}
}
view = append(view, cell.Char)
prevcell = cell
}
view = append(view, '\n')
}
// Truncate spaces at the end
view = []rune(regexp.MustCompile("(?m) +$").ReplaceAllString(string(view), ""))
// Replace 4 spaces with tabs
view = []rune(strings.ReplaceAll(string(view), " ", "\t"))
return string(view)
}
func (bot *Bot) Exec(i *discordgo.Interaction, cmd string, args string) {
var c *exec.Cmd
if args != "" {
aargs := strings.Split(args, " ")
c = exec.Command(cmd, aargs...)
} else {
c = exec.Command(cmd)
}
c.Env = os.Environ()
var outb bytes.Buffer
c.Stdout = &outb
c.Stderr = &outb
err := c.Start()
if err != nil {
bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Execution failed: " + err.Error(),
},
})
return
}
bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
var exitCode int
if err := c.Wait(); err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
exitCode = exiterr.ExitCode()
} else {
bot.Session.InteractionResponseEdit(i, &discordgo.WebhookEdit{
Content: "Error: " + err.Error(),
})
}
}
out := outb.Bytes()
var content string
if len(out) == 0 {
content = "Process provided no output"
} else {
content = "```ansi\n" + string(out) + "```"
}
if exitCode != 0 {
content += fmt.Sprintf("\nExit code: %d", exitCode)
}
/* bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: content,
},
}) */
_, err = bot.Session.InteractionResponseEdit(i, &discordgo.WebhookEdit{
Content: content,
})
if err != nil {
if err.(*discordgo.RESTError).Message.Code == 50035 {
bot.Session.InteractionResponseEdit(i, &discordgo.WebhookEdit{
Content: "Process' output is too long!",
})
return
}
bot.Session.InteractionResponseEdit(i, &discordgo.WebhookEdit{
Content: "Discord gave us an error: " + err.Error(),
})
return
}
}
func (bot *Bot) Macro(i *discordgo.Interaction, name string) {
if bot.Config.UserPrefs[i.Member.User.ID].ActiveSession == nil {
bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You don't have an active session!",
Flags: uint64(discordgo.MessageFlagsEphemeral),
},
})
return
}
for _, m := range bot.Config.Macros {
if m.Name == name {
if !m.Whitelist || (m.Whitelist && slices.Contains(m.AllowedIDs, i.Member.User.ID)) {
bot.Config.UserPrefs[i.Member.User.ID].ActiveSession.Pty.WriteString(m.In)
bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Executed macro " + m.Name,
Flags: uint64(discordgo.MessageFlagsEphemeral),
},
})
} else {
bot.Session.InteractionRespond(i, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You cannot use this macro!",
Flags: uint64(discordgo.MessageFlagsEphemeral),
},
})
}
return
}
}
bot.RespondString(i, "No such macro")
}
func (term *DiscordTerminal) PTYUpdater() {
for term.Running {
data := make([]byte, 8192)
_, err := term.Pty.Read(data)
if err != nil {
// term.Bot.Session.ChannelMessageDelete(term.Msg.ChannelID, term.Msg.ID)
term.Running = false
return
}
term.SafeTerm.Mutex.Lock()
term.SafeTerm.Term.Write(data)
if term.Color {
term.CurrentScreen = StringANSI(term.SafeTerm.Term)
} else {
term.CurrentScreen = term.SafeTerm.Term.String()
}
term.SafeTerm.Mutex.Unlock()
/* if bytes.Contains(data, []byte("\a")) { // Check for \a aka \x07 (BEL)
term.Bot.Session.ChannelMessageSend(term.Msg.ChannelID, fmt.Sprintf("<@%s> BEL", term.Owner.ID))
} */
}
}
func (term *DiscordTerminal) Update() {
term.Ticker.Reset(UPDATE_INTERVAL)
term.UpdateSignal <- true
}
func (term *DiscordTerminal) TickerTracker() {
for term.Running {
<-term.Ticker.C
term.UpdateSignal <- false
}
}
func (term *DiscordTerminal) ScreenUpdater() {
for term.Running {
if term.CurrentScreen != term.LastScreen {
// term.Msg, err = term.Bot.Session.ChannelMessageEdit(term.Msg.ChannelID, term.Msg.ID, "```\n"+term.CurrentScreen+"```")
msgcontent := "```ansi\n" + term.CurrentScreen + "```"
err2k := "Oops! You've hit Discord's 2000 character limit.\nYour terminal is still running though.\n\nTry turning off colors to fix it."
var newmsg *discordgo.Message
eButtons := term.Buttons()
newmsg, err := term.Bot.Session.ChannelMessageEditComplex(&discordgo.MessageEdit{
Content: &msgcontent,
Components: eButtons,
Embed: term.Embed(),
ID: term.Msg.ID,
Channel: term.Msg.ChannelID,
})
if err != nil {
log.Printf("Session %d: screen updater error: %s", term.ID, err)
newmsg, err = term.Bot.Session.ChannelMessageEditComplex(&discordgo.MessageEdit{
Content: &err2k,
Components: eButtons,
Embed: term.Embed(),
ID: term.Msg.ID,
Channel: term.Msg.ChannelID,
})
if err != nil {
log.Printf("Cannot send an error message: %s", err)
}
}
if newmsg != nil {
term.Msg = newmsg
}
term.LastScreen = term.CurrentScreen
}
// time.Sleep(2 * time.Second)
<-term.UpdateSignal
}
}
func (term *DiscordTerminal) Close() {
err := term.Pty.Close()
if err != nil {
term.Bot.Session.ChannelMessageSend(term.Msg.ChannelID, "Error closing pty: "+err.Error())
}
term.Running = false
<-term.CloseSignal
}
func (term *DiscordTerminal) FormatControlledBy() string {
out := ""
for uid, p := range term.Bot.Config.UserPrefs {
if p.ActiveSession == term {
if out == "" {
out += "<@" + uid + ">"
} else {
out += ", <@" + uid + ">"
}
}
}
if out == "" {
return "None"
}
return out
}
func (term *DiscordTerminal) Embed() *discordgo.MessageEmbed {
term.SafeTerm.Mutex.Lock()
title := term.SafeTerm.Term.Title()
term.SafeTerm.Mutex.Unlock()
return &discordgo.MessageEmbed{
Type: discordgo.EmbedTypeRich,
Title: "Session ID " + fmt.Sprint(term.ID),
Description: title,
Color: 0x00FFFF,
Fields: []*discordgo.MessageEmbedField{
{
Name: "Owner",
Value: term.Owner.Mention(),
Inline: false,
},
{
Name: "Controlled by",
Value: term.FormatControlledBy(),
Inline: false,
},
},
}
}
func (term *DiscordTerminal) Buttons() []discordgo.MessageComponent {
// Copy base non-stateful buttons
buttonsClone := slices.Clone(buttons[0].(*discordgo.ActionsRow).Components)
// Make a stateful color button
var colorStatus string
if term.Color {
colorStatus = "on"
} else {
colorStatus = "off"
}
colorButton := discordgo.Button{
Label: "Color: " + colorStatus,
Style: discordgo.SecondaryButton,
Disabled: false,
CustomID: "color",
}
// Copy close button (it must be last)
closeButton := *(buttonsClone[2].(*discordgo.Button))
// Replace last button with color
buttonsClone[2] = &colorButton
// Add close button back
buttonsClone = append(buttonsClone, &closeButton)
return []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: buttonsClone,
},
}
}
func NewDiscordTerminal(bot *Bot, cid string, owner *discordgo.User) {
var err error
this := &DiscordTerminal{
Bot: bot,
Owner: owner,
CloseSignal: make(chan bool),
SharedUsers: bot.Config.UserPrefs[owner.ID].DefaultSharedUsers,
ID: int(math.Floor(100000 + rand.Float64()*900000)),
Ticker: time.NewTicker(UPDATE_INTERVAL),
UpdateSignal: make(chan bool),
}
// this.Term = vt10x.New(vt10x.WithSize(W, H))
this.SafeTerm = SafeTerm{
Term: vt10x.New(vt10x.WithSize(W, H)),
}
this.SafeTerm.Mutex.Lock()
c := exec.Command(os.Getenv("SHELL"))
c.Env = os.Environ()
c.Env = append(c.Env, "TERM=vt100")
this.Pty, err = pty.StartWithSize(c, &pty.Winsize{Rows: H, Cols: W, X: 0, Y: 0})
if err != nil {
this.Bot.Session.ChannelMessageSend(cid, "Cannot start terminal: "+err.Error())
return
}
this.SafeTerm.Mutex.Unlock()
this.Msg, err = this.Bot.Session.ChannelMessageSendComplex(cid, &discordgo.MessageSend{
Content: "Waiting for pty...",
Components: this.Buttons(),
Embed: this.Embed(),
})
if err != nil {
log.Println("Unable to create message for terminal: " + err.Error())
this.Pty.Close()
return
}
bot.Terminals = append(bot.Terminals, this)
this.Running = true
bot.Config.UserPrefs[owner.ID].ActiveSession = this
go this.PTYUpdater()
go this.TickerTracker()
this.ScreenUpdater()
idx := slices.IndexFunc(bot.Terminals, func(t *DiscordTerminal) bool { return t == this })
if idx == -1 {
panic("cannot remove terminal belonging to " + this.Owner.ID)
}
bot.Terminals[idx] = bot.Terminals[len(bot.Terminals)-1]
bot.Terminals = bot.Terminals[:len(bot.Terminals)-1]
// closedstr := "Terminal closed"
// bot.Session.ChannelMessageEditComplex(&discordgo.MessageEdit{Content: &closedstr, Components: []discordgo.MessageComponent{}, Channel: this.Msg.ChannelID, ID: this.Msg.ID})
bot.Session.ChannelMessageDelete(this.Msg.ChannelID, this.Msg.ID)
this.CloseSignal <- true
}