Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
1045 lines (992 loc) · 28.1 KB
/
Copy pathserver.go
File metadata and controls
1045 lines (992 loc) · 28.1 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
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/creack/pty"
"golang.org/x/sys/unix"
)
// server is a session: it owns the command's PTY, keeps a terminal
// emulator in step with it (so the screen can be rendered for agents),
// and serves both over HTTP. It runs inside the shoulder process and ends
// with it. Its Unix socket carries the control API, your terminal's
// connection, and the agent API; shares add more listeners for the agent
// API only.
type server struct {
cfg *config
rwToken string
roToken string
ctlSock string
started chan struct{}
quitting chan struct{}
mu sync.Mutex
ptmx *os.File
cmd *exec.Cmd
vt *vterm
attached atomic.Int32 // len(clients), readable without mu
out []byte // raw output, the most recent maxOutput bytes
base int64 // absolute offset of out[0]
lastOutput time.Time
lastSend time.Time
exited bool
exitCode int
fg string // foreground process name
fgIsShell bool // the command itself is in the foreground
fgChanged time.Time
sawBusy time.Time // last time something other than the command was in the foreground
changed chan struct{}
clients map[*client]bool
owner *client
shares map[string]*share
// A browser session's browser (browser.go), once a tab is shared; the
// connection before that, while the person picks; what agents did.
browser browser
pending sharer
pendingKind string
connecting sync.Mutex
activity []activity
browserDone bool
browserTabs int // how many tabs are shared, as of the last look
}
const maxOutput = 8 << 20
type config struct {
Name string `json:"name"`
Dir string `json:"dir"`
Command []string `json:"command"`
Cwd string `json:"cwd"`
Started time.Time `json:"started"`
Port int `json:"port"`
Host string `json:"host"` // this machine's name, for agents' context
// A browser session shares a browser ("chrome", "safari") instead of
// running Command.
Browser string `json:"browser,omitempty"`
Profile string `json:"profile,omitempty"` // Chrome's profile, by name: "Work"
AllTabs bool `json:"all_tabs,omitempty"`
}
func (c *config) path(name string) string { return filepath.Join(c.Dir, name) }
func (c *config) save() error {
b, _ := json.MarshalIndent(c, "", " ")
return os.WriteFile(c.path("config.json"), b, 0o600)
}
// listen starts serving a session on its Unix socket; run does the rest.
func listen(cfg *config) (*server, error) {
s := &server{
cfg: cfg,
rwToken: newCode(),
roToken: newCode(),
ctlSock: cfg.path("sock"),
started: make(chan struct{}),
quitting: make(chan struct{}),
changed: make(chan struct{}),
clients: map[*client]bool{},
shares: map[string]*share{},
}
for s.roToken == s.rwToken {
s.roToken = newCode()
}
os.Remove(s.ctlSock)
ln, err := net.Listen("unix", s.ctlSock)
if err != nil {
return nil, err
}
os.Chmod(s.ctlSock, 0o600)
unixShare, _ := openShare(context.Background(), s, "unix")
s.shares["unix"] = unixShare
srv := &http.Server{Handler: s.handler(unixShare)}
go srv.Serve(ln)
return s, nil
}
// run serves the session until the command exits, the browser goes away,
// or quit, and then closes its shares.
func (s *server) run() error {
defer os.Remove(s.ctlSock)
defer s.closePending()
select {
case <-s.started:
case <-s.quitting:
return nil
}
if s.browser != nil {
return s.serveBrowser()
}
go s.watchForeground()
err := s.cmd.Wait()
code := 0
var ee *exec.ExitError
if errors.As(err, &ee) {
code = ee.ExitCode()
}
s.mu.Lock()
s.exited, s.exitCode = true, code
s.notifyLocked()
for c := range s.clients {
c.send(frameExit, binary.LittleEndian.AppendUint32(nil, uint32(code)))
}
s.mu.Unlock()
log.Printf("command exited with status %d", code)
// Give your terminal a moment to read the exit and hang up.
deadline := time.After(2 * time.Second)
wait:
for {
s.mu.Lock()
n, ch := len(s.clients), s.changed
s.mu.Unlock()
if n == 0 {
break
}
select {
case <-ch:
case <-deadline:
break wait
case <-s.quitting:
break wait
}
}
s.mu.Lock()
for _, sh := range s.shares {
sh.close()
}
s.mu.Unlock()
return nil
}
// quit ends the session: it hangs up on the command, as closing its
// terminal would, and stops serving.
func (s *server) quit() {
s.mu.Lock()
defer s.mu.Unlock()
select {
case <-s.quitting:
return
default:
close(s.quitting)
}
if s.cmd != nil && !s.exited {
// The command leads its own session (pty.Start setsid), so this
// reaches its whole process group.
syscall.Kill(-s.cmd.Process.Pid, syscall.SIGHUP)
}
}
// notifyLocked wakes everything waiting for output or a state change.
func (s *server) notifyLocked() {
close(s.changed)
s.changed = make(chan struct{})
}
// start runs the command at the given size. Its environment has
// $SHOULDER, the session name, which keeps shoulder from starting a
// session inside itself. (The codes stay out of the environment: they're
// secrets, and children inherit it.)
func (s *server) start(cols, rows int) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.cmd != nil {
return errors.New("already started")
}
cmd := exec.Command(s.cfg.Command[0], s.cfg.Command[1:]...)
cmd.Dir = s.cfg.Cwd
cmd.Env = append(os.Environ(), "SHOULDER="+s.cfg.Name)
ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
if err != nil {
return err
}
s.cmd, s.ptmx = cmd, ptmx
// With a terminal attached, it answers the program's queries itself;
// with none, the emulator's answers stand in, so programs that ask
// (where's the cursor? what are you?) don't hang.
s.vt = newTerm(cols, rows, func(reply []byte) {
if s.attached.Load() == 0 {
ptmx.Write(reply)
}
})
go s.readLoop()
close(s.started)
return nil
}
func (s *server) readLoop() {
buf := make([]byte, 32<<10)
for {
n, err := s.ptmx.Read(buf)
if n > 0 {
data := append([]byte(nil), buf[:n]...)
s.mu.Lock()
s.vt.write(data)
s.out = append(s.out, data...)
if len(s.out) > maxOutput {
drop := len(s.out) - maxOutput/2
s.out = append([]byte(nil), s.out[drop:]...)
s.base += int64(drop)
}
s.lastOutput = time.Now()
for c := range s.clients {
c.send(frameData, data)
}
s.notifyLocked()
s.mu.Unlock()
}
if err != nil {
return
}
}
}
// watchForeground tracks which process is in the terminal's foreground, so
// agents can wait for a shell command to finish.
func (s *server) watchForeground() {
t := time.NewTicker(100 * time.Millisecond)
defer t.Stop()
for range t.C {
s.mu.Lock()
if s.exited {
s.mu.Unlock()
return
}
fd := int(s.ptmx.Fd())
pid := s.cmd.Process.Pid
s.mu.Unlock()
pgrp, err := unix.IoctlGetInt(fd, unix.TIOCGPGRP)
if err != nil {
continue
}
name := processName(pgrp)
s.mu.Lock()
isShell := pgrp == pid
if name != s.fg || isShell != s.fgIsShell {
s.fg, s.fgIsShell, s.fgChanged = name, isShell, time.Now()
s.notifyLocked()
}
if !isShell {
s.sawBusy = time.Now()
}
s.mu.Unlock()
}
}
func processName(pid int) string {
out, err := exec.Command("ps", "-o", "comm=", "-p", strconv.Itoa(pid)).Output()
if err != nil {
return ""
}
return strings.TrimPrefix(filepath.Base(strings.TrimSpace(string(out))), "-")
}
// typeInput writes to the command's terminal.
func (s *server) typeInput(b []byte) error {
s.mu.Lock()
ptmx, exited := s.ptmx, s.exited
s.lastSend = time.Now()
s.mu.Unlock()
if ptmx == nil || exited {
return errors.New("the command is not running")
}
_, err := ptmx.Write(b)
return err
}
// resizeLocked applies a terminal size to the PTY and the emulator.
func (s *server) resizeLocked(cols, rows int) {
if s.ptmx == nil || cols <= 0 || rows <= 0 {
return
}
if c, r := s.vt.size(); c == cols && r == rows {
return
}
pty.Setsize(s.ptmx, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
s.vt.resize(cols, rows)
}
// ---------------------------------------------------------------------------
// Your terminal. shoulder's own terminal upgrades GET /ctl/attach and speaks
// frames: [type u8][len u32 LE][payload].
const (
frameData = 1 // both directions: terminal bytes
frameWinch = 2 // client→server: cols u16, rows u16
frameExit = 4 // server→client: exit status u32
)
type client struct {
conn net.Conn
q chan []byte
cols int
rows int
}
// send queues a frame without blocking; a client too slow to keep up is
// dropped rather than stalling the command.
func (c *client) send(typ byte, payload []byte) {
f := make([]byte, 5+len(payload))
f[0] = typ
binary.LittleEndian.PutUint32(f[1:], uint32(len(payload)))
copy(f[5:], payload)
select {
case c.q <- f:
default:
c.conn.Close()
}
}
func readFrame(r io.Reader) (byte, []byte, error) {
var hdr [5]byte
if _, err := io.ReadFull(r, hdr[:]); err != nil {
return 0, nil, err
}
n := binary.LittleEndian.Uint32(hdr[1:])
if n > 1<<20 {
return 0, nil, fmt.Errorf("frame too large: %d", n)
}
p := make([]byte, n)
_, err := io.ReadFull(r, p)
return hdr[0], p, err
}
func writeFrame(w io.Writer, typ byte, payload []byte) error {
f := make([]byte, 5+len(payload))
f[0] = typ
binary.LittleEndian.PutUint32(f[1:], uint32(len(payload)))
copy(f[5:], payload)
_, err := w.Write(f)
return err
}
func (s *server) handleAttach(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "cannot attach", http.StatusInternalServerError)
return
}
conn, rw, err := hj.Hijack()
if err != nil {
return
}
defer conn.Close()
rw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: shoulder\r\nConnection: Upgrade\r\n\r\n")
rw.Flush()
c := &client{conn: conn, q: make(chan []byte, 1024)}
cols, _ := strconv.Atoi(r.URL.Query().Get("cols"))
rows, _ := strconv.Atoi(r.URL.Query().Get("rows"))
c.cols, c.rows = cols, rows
s.mu.Lock()
if s.vt != nil {
// The newest terminal owns the size.
s.owner = c
s.resizeLocked(cols, rows)
}
if s.exited {
c.send(frameExit, binary.LittleEndian.AppendUint32(nil, uint32(s.exitCode)))
}
s.clients[c] = true
s.attached.Store(int32(len(s.clients)))
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.clients, c)
s.attached.Store(int32(len(s.clients)))
if s.owner == c {
s.owner = nil
}
s.notifyLocked()
s.mu.Unlock()
}()
go func() {
for f := range c.q {
if _, err := conn.Write(f); err != nil {
conn.Close()
return
}
}
}()
defer close(c.q)
br := bufio.NewReader(rw)
for {
typ, p, err := readFrame(br)
if err != nil {
return
}
switch typ {
case frameData:
s.mu.Lock()
if s.owner != c && c.cols > 0 {
// Typing claims the size, so the terminal in use fits.
s.owner = c
s.resizeLocked(c.cols, c.rows)
}
s.mu.Unlock()
s.typeInput(p)
case frameWinch:
if len(p) >= 4 {
s.mu.Lock()
c.cols, c.rows = int(binary.LittleEndian.Uint16(p[0:])), int(binary.LittleEndian.Uint16(p[2:]))
if s.owner == c || s.owner == nil {
s.owner = c
s.resizeLocked(c.cols, c.rows)
}
s.mu.Unlock()
}
}
}
}
// ---------------------------------------------------------------------------
// HTTP.
// handler serves the agent API under /<token>/ for a share, and, on the
// session's own socket only, the control API under /ctl/.
func (s *server) handler(sh *share) http.Handler {
mux := http.NewServeMux()
if sh.transport == "unix" {
mux.HandleFunc("POST /ctl/start", s.ctlStart)
mux.HandleFunc("POST /ctl/share", s.ctlShare)
mux.HandleFunc("GET /ctl/info", s.ctlInfo)
mux.HandleFunc("POST /ctl/quit", func(w http.ResponseWriter, r *http.Request) { s.quit() })
mux.HandleFunc("GET /ctl/attach", s.handleAttach)
mux.HandleFunc("POST /ctl/kind", s.ctlKind)
mux.HandleFunc("POST /ctl/browser", s.ctlBrowser)
mux.HandleFunc("GET /ctl/activity", s.ctlActivity)
}
mux.HandleFunc("/{token}/{rest...}", func(w http.ResponseWriter, r *http.Request) { s.agent(w, r, sh) })
return mux
}
func (s *server) ctlStart(w http.ResponseWriter, r *http.Request) {
cols, _ := strconv.Atoi(r.URL.Query().Get("cols"))
rows, _ := strconv.Atoi(r.URL.Query().Get("rows"))
if cols <= 0 || rows <= 0 {
cols, rows = 80, 24
}
if err := s.start(cols, rows); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
}
}
// shareInfo is what the launcher shows: the text to paste to an agent.
type shareInfo struct {
Transport string `json:"transport"`
ReadOnly bool `json:"read_only"`
Paste string `json:"paste"`
Warning string `json:"warning,omitempty"`
Hint string `json:"hint,omitempty"`
}
func (s *server) ctlShare(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
transport := q.Get("transport")
readOnly := q.Get("read_only") == "1"
exclusive := q.Get("exclusive") == "1"
sh, err := s.share(r.Context(), transport, exclusive)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
token := s.rwToken
if readOnly {
token = s.roToken
}
info := shareInfo{Transport: transport, ReadOnly: readOnly, Paste: paste(s.cfg, sh, token, readOnly), Warning: sh.warning}
if transport == "unix" {
info.Hint = unixHint(s.cfg, s.ctlSock)
}
writeJSON(w, info)
}
// share returns the listener for transport, setting it up if need be.
// With exclusive, other network shares are closed: the launcher's menu
// switches between them.
func (s *server) share(ctx context.Context, transport string, exclusive bool) (*share, error) {
s.mu.Lock()
if exclusive {
for name, sh := range s.shares {
if name != transport && name != "unix" {
sh.close()
delete(s.shares, name)
}
}
}
if sh := s.shares[transport]; sh != nil {
s.mu.Unlock()
return sh, nil
}
s.mu.Unlock()
sh, err := openShare(ctx, s, transport)
if err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if old := s.shares[transport]; old != nil {
sh.close()
return old, nil
}
s.shares[transport] = sh
return sh, nil
}
func (s *server) ctlInfo(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
var shares []string
for name := range s.shares {
shares = append(shares, name)
}
s.mu.Unlock()
st := s.status()
writeJSON(w, map[string]any{"status": st, "shares": shares})
}
type status struct {
Name string `json:"name"`
Command []string `json:"command"`
Host string `json:"host"`
Cwd string `json:"cwd"`
Started bool `json:"started"`
Running bool `json:"running"`
ExitCode *int `json:"exit_code,omitempty"`
Foreground string `json:"foreground,omitempty"`
AtPrompt bool `json:"at_prompt"` // the command itself is in the foreground (for a shell: at its prompt)
Cols int `json:"cols"`
Rows int `json:"rows"`
Terminals int `json:"attached_terminals"`
IdleFor string `json:"no_output_for,omitempty"`
Offset int64 `json:"output_offset"`
ReadOnly bool `json:"read_only"`
Browser string `json:"browser,omitempty"` // a browser session's browser
SharedTabs int `json:"shared_tabs,omitempty"`
}
func (s *server) status() status {
s.mu.Lock()
defer s.mu.Unlock()
st := status{
Name: s.cfg.Name, Command: s.cfg.Command, Host: s.cfg.Host, Cwd: s.cfg.Cwd,
Started: s.cmd != nil, Running: s.cmd != nil && !s.exited,
Foreground: s.fg, AtPrompt: s.fgIsShell, Terminals: len(s.clients),
Offset: s.base + int64(len(s.out)),
}
if s.cfg.Browser != "" {
st.Browser = browserLabels[s.cfg.Browser]
if s.browser != nil {
st.Browser = s.browser.label()
st.Started, st.Running = true, !s.browserDone
st.SharedTabs = s.browserTabs
}
}
if s.exited {
code := s.exitCode
st.ExitCode = &code
}
if s.vt != nil {
st.Cols, st.Rows = s.vt.size()
}
if !s.lastOutput.IsZero() {
st.IdleFor = time.Since(s.lastOutput).Round(100 * time.Millisecond).String()
}
return st
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(v)
}
// agent serves the agent API: /<code>/<endpoint>.
func (s *server) agent(w http.ResponseWriter, r *http.Request, sh *share) {
if until := sh.lockedUntil(); !until.IsZero() {
http.Error(w, "too many wrong codes; this share is locked until "+until.Format("15:04:05"), http.StatusTooManyRequests)
return
}
var readOnly bool
switch r.PathValue("token") {
case s.rwToken:
case s.roToken:
readOnly = true
default:
sh.failed()
http.Error(w, "unknown code", http.StatusForbidden)
return
}
token := r.PathValue("token")
s.mu.Lock()
isBrowser := s.cfg.Browser != ""
s.mu.Unlock()
if isBrowser {
s.browserAgent(w, r, sh, token, readOnly)
return
}
switch rest := r.PathValue("rest"); {
case rest == "" && r.Method == "GET":
w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
io.WriteString(w, guide(s.cfg, sh, token, readOnly))
case rest == "status" && r.Method == "GET":
st := s.status()
st.ReadOnly = readOnly
writeJSON(w, st)
case rest == "capture-pane" && r.Method == "GET":
s.getScreen(w, r)
case rest == "output" && r.Method == "GET":
s.getOutput(w, r)
case rest == "wait" && r.Method == "GET":
s.getWait(w, r)
case (rest == "send-keys" || rest == "run") && r.Method == "POST":
if readOnly {
http.Error(w, "this code is read-only: you can watch the terminal but not type into it", http.StatusForbidden)
return
}
if rest == "send-keys" {
s.postSendKeys(w, r)
} else {
s.postRun(w, r)
}
default:
http.Error(w, "no such endpoint; GET "+sh.url(token)+"/ describes the API", http.StatusNotFound)
}
}
func (s *server) getScreen(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
if s.vt == nil {
s.mu.Unlock()
http.Error(w, "the command has not started yet", http.StatusServiceUnavailable)
return
}
var body []byte
switch r.URL.Query().Get("format") {
case "ansi":
body = s.vt.ansi()
default:
body = []byte(s.vt.text())
}
cx, cy := s.vt.cursor()
cols, rows := s.vt.size()
s.mu.Unlock()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Cursor", fmt.Sprintf("%d,%d", cx, cy))
w.Header().Set("X-Size", fmt.Sprintf("%dx%d", cols, rows))
w.Write(body)
}
// outputSince returns cleaned output from absolute offset off, and the
// offset to pass next time.
func (s *server) outputSince(off int64) (string, int64, bool) {
s.mu.Lock()
defer s.mu.Unlock()
end := s.base + int64(len(s.out))
truncated := off < s.base
off = min(max(off, s.base), end)
return string(s.out[off-s.base:]), end, truncated
}
func (s *server) getOutput(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
maxLines := intParam(q.Get("lines"), 200)
var off int64 = -1
if v := q.Get("since"); v != "" {
off, _ = strconv.ParseInt(v, 10, 64)
}
if wait := durationParam(q.Get("wait"), 0, 5*time.Minute); wait > 0 && off >= 0 {
// Long-poll: hold the request until there is something new.
deadline := time.After(wait)
for {
s.mu.Lock()
end, ch, exited := s.base+int64(len(s.out)), s.changed, s.exited
s.mu.Unlock()
if end > off || exited {
break
}
select {
case <-ch:
continue
case <-deadline:
case <-r.Context().Done():
return
}
break
}
}
var text string
var next int64
var truncated bool
if off < 0 {
text, next, _ = s.outputSince(0)
} else {
text, next, truncated = s.outputSince(off)
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Offset", strconv.FormatInt(next, 10))
if q.Get("raw") == "1" {
w.Write([]byte(text))
return
}
if truncated {
io.WriteString(w, "[some output was discarded; the session keeps the last 8 MiB]\n")
}
if out := tailLines(cleanLines(text), maxLines); out != "" {
io.WriteString(w, out+"\n")
}
fmt.Fprintf(w, "[offset %d]\n", next)
}
// getWait blocks until a condition holds, then reports which, plus the
// output since the wait's starting point.
func (s *server) getWait(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
timeout := durationParam(q.Get("timeout"), 60*time.Second, 30*time.Minute)
quiet := durationParam(q.Get("quiet"), 0, 30*time.Minute)
idle := q.Get("idle") == "1"
var re *regexp.Regexp
if p := q.Get("pattern"); p != "" {
var err error
if re, err = regexp.Compile(p); err != nil {
http.Error(w, "bad pattern: "+err.Error(), http.StatusBadRequest)
return
}
}
s.mu.Lock()
from := s.base + int64(len(s.out))
since := time.Now()
if !s.lastSend.IsZero() && time.Since(s.lastSend) < 5*time.Second {
// Waiting right after typing: count from the keystrokes, so a
// command that already finished still counts.
since = s.lastSend
}
s.mu.Unlock()
if v := q.Get("since"); v != "" {
from, _ = strconv.ParseInt(v, 10, 64)
}
reason := s.waitFor(r.Context(), from, since, re, quiet, idle, timeout)
if reason == "" {
return // client went away
}
text, next, _ := s.outputSince(from)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "[%s]\n", reason)
if out := tailLines(cleanLines(text), intParam(q.Get("lines"), 200)); out != "" {
io.WriteString(w, out+"\n")
}
fmt.Fprintf(w, "[offset %d]\n", next)
}
// waitFor blocks until output after from matches re, there has been no
// output for quiet, the command is back in the foreground (idle), the
// command exits, or timeout. It returns why it stopped.
func (s *server) waitFor(ctx context.Context, from int64, since time.Time, re *regexp.Regexp, quiet time.Duration, idle bool, timeout time.Duration) string {
deadline := time.Now().Add(timeout)
scanned := from
for {
s.mu.Lock()
ch := s.changed
exited, code := s.exited, s.exitCode
lastOut := s.lastOutput
atPrompt, sawBusy := s.fgIsShell, s.sawBusy
end := s.base + int64(len(s.out))
s.mu.Unlock()
if re != nil && end > scanned {
text, _, _ := s.outputSince(scanned)
for _, line := range cleanLines(text) {
if re.MatchString(line) {
return "matched: " + strings.TrimSpace(line)
}
}
// Resume from the start of the last, possibly partial, line.
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
scanned += int64(i + 1)
}
}
if exited {
return fmt.Sprintf("exited with status %d", code)
}
if lastOut.Before(since) {
lastOut = since
}
quietFor := time.Since(lastOut)
if quiet > 0 && quietFor >= quiet {
return "quiet for " + quiet.String()
}
// Back at the prompt: either something else held the foreground
// since the wait began, or a command quick enough to slip between
// polls has printed and gone quiet.
if idle && atPrompt && (sawBusy.After(since) || (end > from && quietFor >= 300*time.Millisecond)) {
return "idle: back at the prompt"
}
remaining := time.Until(deadline)
if remaining <= 0 {
return "timed out after " + timeout.String()
}
tick := min(remaining, 100*time.Millisecond)
select {
case <-ctx.Done():
return ""
case <-ch:
case <-time.After(tick):
}
}
}
// postSendKeys types into the terminal. The body is tmux send-keys
// arguments: words naming keys (Enter, C-c, Up, ...) are pressed, other
// words are typed; quote text with spaces. A leading -l types everything
// literally.
func (s *server) postSendKeys(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
b, err := sendKeysBytes(string(body))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.typeInput(b); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
_, next, _ := s.outputSince(0)
fmt.Fprintf(w, "[sent %d bytes] [offset %d]\n", len(b), next)
}
// postRun types the body and Enter, then waits for the shell's prompt to
// come back (or timeout), and returns the output.
func (s *server) postRun(w http.ResponseWriter, r *http.Request) {
cmdText, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, from, _ := s.outputSince(0)
since := time.Now()
if err := s.typeInput(append([]byte(strings.TrimRight(string(cmdText), "\n")), '\r')); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
timeout := durationParam(r.URL.Query().Get("timeout"), 60*time.Second, 30*time.Minute)
reason := s.waitFor(r.Context(), from, since, nil, 0, true, timeout)
if reason == "" {
return
}
text, next, _ := s.outputSince(from)
fmt.Fprintf(w, "[%s]\n", reason)
if out := tailLines(cleanLines(text), intParam(r.URL.Query().Get("lines"), 200)); out != "" {
io.WriteString(w, out+"\n")
}
fmt.Fprintf(w, "[offset %d]\n", next)
}
// sendKeysBytes turns tmux send-keys arguments into terminal input.
func sendKeysBytes(args string) ([]byte, error) {
words, err := splitWords(args)
if err != nil {
return nil, err
}
literal := false
if len(words) > 0 && words[0] == "-l" {
literal, words = true, words[1:]
}
if len(words) == 0 {
return nil, errors.New("nothing to send; the body is like tmux send-keys arguments: 'git status' Enter")
}
var b []byte
for _, w := range words {
if !literal && len([]rune(w)) > 1 {
if seq, err := keyBytes(w); err == nil {
b = append(b, seq...)
continue
}
}
b = append(b, w...)
}
return b, nil
}
// splitWords splits like a shell: whitespace separates words, '...' is
// literal, "..." and unquoted text take backslash escapes.
func splitWords(s string) ([]string, error) {
var words []string
var cur strings.Builder
inWord := false
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '\'':
j := strings.IndexByte(s[i+1:], '\'')
if j < 0 {
return nil, errors.New("unterminated ' quote")
}
cur.WriteString(s[i+1 : i+1+j])
i += j + 1
inWord = true
case c == '"':
i++
for ; i < len(s) && s[i] != '"'; i++ {
if s[i] == '\\' && i+1 < len(s) {
i++
}
cur.WriteByte(s[i])
}
if i >= len(s) {
return nil, errors.New(`unterminated " quote`)
}
inWord = true
case c == '\\' && i+1 < len(s):
i++
cur.WriteByte(s[i])
inWord = true
case c == ' ' || c == '\t' || c == '\n' || c == '\r':
if inWord {
words = append(words, cur.String())
cur.Reset()
inWord = false
}
default:
cur.WriteByte(c)
inWord = true
}
}
if inWord {
words = append(words, cur.String())
}
return words, nil
}
var namedKeys = map[string]string{
"Enter": "\r", "Tab": "\t", "BTab": "\x1b[Z", "Escape": "\x1b", "Esc": "\x1b", "BSpace": "\x7f", "Backspace": "\x7f", "Space": " ",
"Up": "\x1b[A", "Down": "\x1b[B", "Right": "\x1b[C", "Left": "\x1b[D",
"Home": "\x1b[H", "End": "\x1b[F", "PageUp": "\x1b[5~", "PageDown": "\x1b[6~", "PPage": "\x1b[5~", "NPage": "\x1b[6~",
"Delete": "\x1b[3~", "DC": "\x1b[3~", "Insert": "\x1b[2~", "IC": "\x1b[2~",
"F1": "\x1bOP", "F2": "\x1bOQ", "F3": "\x1bOR", "F4": "\x1bOS",
"F5": "\x1b[15~", "F6": "\x1b[17~", "F7": "\x1b[18~", "F8": "\x1b[19~",
"F9": "\x1b[20~", "F10": "\x1b[21~", "F11": "\x1b[23~", "F12": "\x1b[24~",
}
// keyBytes encodes a key name as the bytes a terminal sends: names from
// namedKeys (tmux's names work too), C-x for control characters, M-x for
// meta (ESC prefix).
func keyBytes(k string) ([]byte, error) {
if rest, ok := strings.CutPrefix(k, "M-"); ok {
b, err := keyBytes(rest)
return append([]byte{0x1b}, b...), err