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
package sshtransport
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"log/slog"
"maps"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
sshcontract "github.com/johnandersen777/socialweb-computer-kcp/internal/contract/ssh"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
"golang.org/x/crypto/ssh"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/supervise"
)
const (
NoKeyCouldMatchExtension = "sshtransport.socialweb.computer/no-key-could-match"
PermissionDID = "sshtransport.socialweb.computer/did"
PermissionHandle = "sshtransport.socialweb.computer/handle"
PermissionPDS = "sshtransport.socialweb.computer/pds"
DefaultMaxConnections = 10000
DefaultMaxSessions = 1000
DefaultSessionsPerAccount = 1000
DefaultMaxAuthAttempts = 6
DefaultAuthTimeout = 120 * time.Second
DefaultAuthorizationLookupTimeout = 30 * time.Second
DefaultKeepAliveInterval = 15 * time.Second
DefaultKeepAliveMisses = 3
DefaultShutdownGrace = 5 * time.Second
)
var (
allowedKeyAlgorithms = []string{
"ssh-ed25519",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
"sk-ssh-ed25519@openssh.com",
"sk-ecdsa-sha2-nistp256@openssh.com",
"rsa-sha2-256",
"rsa-sha2-512",
"ssh-rsa",
}
allowedSignatureFormats = map[string]bool{
"ssh-ed25519": true,
"ecdsa-sha2-nistp256": true,
"ecdsa-sha2-nistp384": true,
"ecdsa-sha2-nistp521": true,
"sk-ssh-ed25519@openssh.com": true,
"sk-ecdsa-sha2-nistp256@openssh.com": true,
"rsa-sha2-256": true,
"rsa-sha2-512": true,
}
newlinePattern = regexp.MustCompile(`\r?\n`)
)
type PTYSize = sshcontract.PTYSize
type CommandIO = sshcontract.CommandIO
type ComputeCommandRunner interface {
Run(ctx context.Context, account AuthorizedAccount, command string, env map[string]string, io CommandIO) error
}
type SessionRunnerShutdowner interface {
Shutdown(ctx context.Context) error
}
type Config struct {
Port int
Hostname string
HostKeyPath string
Banner string
NoKeyCouldMatchMessage string
MaxConnections int
MaxSessions int
SessionsPerAccount int
MaxAuthAttempts int
AuthTimeout time.Duration
SessionMax time.Duration
}
type ServerOptions struct {
Config Config
Authorizer KeyAuthorizer
Runner ComputeCommandRunner
DefaultCommand string
Log *slog.Logger
}
type Server struct {
opts Options
sshConfig *ssh.ServerConfig
log *slog.Logger
mu sync.Mutex
conns map[net.Conn]struct{}
connWG sync.WaitGroup
running int
perAccount map[string]int
}
type Options = ServerOptions
var _ sshcontract.Server = (*Server)(nil)
func NewServer(opts ServerOptions) (*Server, error) {
if opts.Authorizer == nil {
return nil, errors.New("sshtransport: SSH server has no key authorizer")
}
if opts.Runner == nil {
return nil, errors.New("sshtransport: SSH server has no command runner")
}
if opts.Config.HostKeyPath == "" {
return nil, errors.New("sshtransport: SSH server has no host key path")
}
if opts.Log == nil {
opts.Log = slog.Default()
}
opts.Config = configWithDefaults(opts.Config)
signer, err := loadOrCreateHostKey(opts.Config.HostKeyPath, opts.Log)
if err != nil {
return nil, err
}
s := &Server{
opts: opts,
log: opts.Log,
conns: map[net.Conn]struct{}{},
perAccount: map[string]int{},
}
cfg := &ssh.ServerConfig{
MaxAuthTries: opts.Config.MaxAuthAttempts,
PublicKeyAuthAlgorithms: allowedKeyAlgorithms,
PublicKeyCallback: func(ssh.ConnMetadata, ssh.PublicKey) (*ssh.Permissions, error) {
return &ssh.Permissions{}, nil
},
}
if opts.Config.Banner != "" {
banner := opts.Config.Banner
cfg.BannerCallback = func(ssh.ConnMetadata) string { return banner }
}
cfg.AddHostKey(signer)
s.sshConfig = cfg
return s, nil
}
func configWithDefaults(c Config) Config {
c.MaxConnections = opt.Positive(c.MaxConnections, DefaultMaxConnections)
c.MaxSessions = opt.Positive(c.MaxSessions, DefaultMaxSessions)
c.SessionsPerAccount = opt.Positive(c.SessionsPerAccount, DefaultSessionsPerAccount)
c.MaxAuthAttempts = opt.Positive(c.MaxAuthAttempts, DefaultMaxAuthAttempts)
c.AuthTimeout = opt.Positive(c.AuthTimeout, DefaultAuthTimeout)
return c
}
func loadOrCreateHostKey(path string, log *slog.Logger) (ssh.Signer, error) {
raw, err := os.ReadFile(path)
if err == nil {
signer, err := ssh.ParsePrivateKey(raw)
if err != nil {
return nil, fmt.Errorf("%s exists but is not a usable private key; refusing to start with a different identity: %w", path, err)
}
if st, err := os.Stat(path); err == nil && st.Mode().Perm()&0o077 != 0 {
if err := os.Chmod(path, 0o600); err != nil {
log.Warn("host_key_permissions_unrepaired", "path", path, "err", err)
} else {
log.Info("host_key_permissions_repaired", "path", path)
}
}
return signer, nil
}
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
block, err := ssh.MarshalPrivateKey(priv, "")
if err != nil {
return nil, err
}
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return nil, err
}
if _, err := file.Write(pem.EncodeToMemory(block)); err != nil {
file.Close()
return nil, err
}
if err := file.Close(); err != nil {
return nil, err
}
log.Info("host_key_generated", "path", path)
return ssh.NewSignerFromKey(priv)
}
func (s *Server) verifiedPublicKey(ctx context.Context, conn ssh.ConnMetadata, key ssh.PublicKey, permissions *ssh.Permissions, signatureAlgorithm string) (*ssh.Permissions, error) {
if !allowedSignatureFormats[signatureAlgorithm] {
s.log.Warn("auth_rejected_algo", "username", conn.User(), "algo", signatureAlgorithm)
return nil, fmt.Errorf("sshtransport: signature algorithm %q is not accepted", signatureAlgorithm)
}
presented := PresentedKey{Algo: key.Type(), Key: base64.StdEncoding.EncodeToString(key.Marshal())}
ctx, cancel := context.WithTimeout(ctx, DefaultAuthorizationLookupTimeout)
defer cancel()
account, err := s.opts.Authorizer.Authorize(ctx, conn.User(), presented)
if err != nil {
var noKey *NoKeyCouldMatchError
if errors.As(err, &noKey) {
s.log.Info("auth_accepted_no_key_could_match", "username", conn.User(), "reason", noKey.Reason)
return &ssh.Permissions{Extensions: map[string]string{NoKeyCouldMatchExtension: noKey.Reason}}, nil
}
s.log.Warn("auth_error", "username", conn.User(), "err", err)
return nil, err
}
if account == nil {
s.log.Info("auth_rejected", "username", conn.User())
return nil, errors.New("sshtransport: the offered key is not associated with the account")
}
s.log.Info("auth_accepted", "username", conn.User(), "did", account.DID)
return &ssh.Permissions{Extensions: map[string]string{
PermissionDID: account.DID,
PermissionHandle: account.Handle,
PermissionPDS: account.PDS,
}}, nil
}
func (s *Server) ServeConn(ctx context.Context, conn net.Conn) error {
if conn == nil {
return errors.New("sshtransport: no connection")
}
s.mu.Lock()
if len(s.conns) >= s.opts.Config.MaxConnections {
s.mu.Unlock()
conn.Close()
return errors.New("sshtransport: at the concurrent connection limit")
}
s.conns[conn] = struct{}{}
s.connWG.Add(1)
s.mu.Unlock()
done := make(chan struct{})
s.connWG.Go(func() {
select {
case <-ctx.Done():
conn.Close()
case <-done:
}
})
s.handleConnection(ctx, conn)
close(done)
s.mu.Lock()
delete(s.conns, conn)
s.mu.Unlock()
s.connWG.Done()
return nil
}
func (s *Server) handleConnection(ctx context.Context, raw net.Conn) {
if s.opts.Config.AuthTimeout > 0 {
raw.SetDeadline(time.Now().Add(s.opts.Config.AuthTimeout))
}
cfg := *s.sshConfig
cfg.VerifiedPublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey, permissions *ssh.Permissions, algo string) (*ssh.Permissions, error) {
return s.verifiedPublicKey(ctx, c, key, permissions, algo)
}
conn, channels, requests, err := ssh.NewServerConn(raw, &cfg)
if err != nil {
raw.Close()
s.log.Warn("connection_error", "err", err)
return
}
raw.SetDeadline(time.Time{})
defer conn.Close()
s.connWG.Go(func() { s.keepAlive(conn) })
account := accountFromPermissions(conn.Permissions)
noKeyUsername := ""
if conn.Permissions != nil {
if _, ok := conn.Permissions.Extensions[NoKeyCouldMatchExtension]; ok {
noKeyUsername = conn.User()
}
}
s.connWG.Go(func() { ssh.DiscardRequests(requests) })
for newChannel := range channels {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "only session channels are served")
continue
}
channel, channelRequests, err := newChannel.Accept()
if err != nil {
s.log.Warn("channel_accept_failed", "err", err)
continue
}
s.connWG.Go(func() { s.serveSession(ctx, channel, channelRequests, account, conn.User(), noKeyUsername) })
}
}
func (s *Server) keepAlive(conn *ssh.ServerConn) {
gone := make(chan struct{})
go func() {
_ = conn.Wait()
close(gone)
}()
ticker := time.NewTicker(DefaultKeepAliveInterval)
defer ticker.Stop()
misses := 0
for {
select {
case <-gone:
return
case <-ticker.C:
}
replied := make(chan error, 1)
go func() {
_, _, err := conn.SendRequest("keepalive@openssh.com", true, nil)
replied <- err
}()
select {
case <-gone:
return
case err := <-replied:
if err == nil {
misses = 0
continue
}
case <-time.After(DefaultKeepAliveInterval):
}
if misses++; misses >= DefaultKeepAliveMisses {
s.log.Info("connection_keepalive_lost", "user", conn.User(), "misses", misses)
_ = conn.Close()
return
}
}
}
func accountFromPermissions(permissions *ssh.Permissions) *AuthorizedAccount {
if permissions == nil || permissions.Extensions == nil {
return nil
}
did := permissions.Extensions[PermissionDID]
if did == "" {
return nil
}
return &AuthorizedAccount{
DID: did,
Handle: permissions.Extensions[PermissionHandle],
PDS: permissions.Extensions[PermissionPDS],
}
}
type ptyRequest struct {
Term string
Cols, Rows uint32
Width, Height uint32
Modes string
}
type windowChangeRequest struct {
Cols, Rows uint32
Width, Height uint32
}
type envRequest struct {
Name string
Value string
}
type execRequest struct {
Command string
}
func (s *Server) serveSession(ctx context.Context, channel ssh.Channel, requests <-chan *ssh.Request, account *AuthorizedAccount, username, noKeyUsername string) {
defer channel.Close()
ctx, closed := context.WithCancel(ctx)
defer closed()
io := newChannelIO(channel, &s.connWG)
env := map[string]string{}
envBytes := 0
started := false
for req := range requests {
switch req.Type {
case "pty-req":
var request ptyRequest
if err := ssh.Unmarshal(req.Payload, &request); err != nil {
req.Reply(false, nil)
continue
}
io.setPTY(&PTYSize{Cols: int(request.Cols), Rows: int(request.Rows)})
req.Reply(true, nil)
case "window-change":
var request windowChangeRequest
if err := ssh.Unmarshal(req.Payload, &request); err == nil && io.PTY() != nil {
io.setSize(int(request.Cols), int(request.Rows))
}
req.Reply(false, nil)
case "env":
var request envRequest
if err := ssh.Unmarshal(req.Payload, &request); err != nil {
req.Reply(false, nil)
continue
}
if len(env) < 64 && envBytes+len(request.Name)+len(request.Value) <= 8192 {
env[request.Name] = request.Value
envBytes += len(request.Name) + len(request.Value)
}
req.Reply(true, nil)
case "exec":
if started {
req.Reply(false, nil)
continue
}
var request execRequest
if err := ssh.Unmarshal(req.Payload, &request); err != nil {
req.Reply(false, nil)
continue
}
started = true
req.Reply(true, nil)
sessionEnv := copyEnv(env)
s.connWG.Go(func() { s.startSession(ctx, io, sessionEnv, account, username, noKeyUsername, request.Command) })
case "shell":
if started {
req.Reply(false, nil)
continue
}
started = true
req.Reply(true, nil)
sessionEnv := copyEnv(env)
s.connWG.Go(func() { s.startSession(ctx, io, sessionEnv, account, username, noKeyUsername, s.opts.DefaultCommand) })
default:
req.Reply(false, nil)
}
}
io.markClosed()
if started && !io.exited() {
s.log.Info("session_channel_closed", "username", username, "reason", "the client closed the channel or the connection dropped; the command ends")
}
closed()
}
func copyEnv(env map[string]string) map[string]string {
out := make(map[string]string, len(env))
maps.Copy(out, env)
return out
}
func (s *Server) startSession(ctx context.Context, io *channelIO, env map[string]string, account *AuthorizedAccount, username, noKeyUsername, command string) {
if account == nil {
explanation := "authentication required\n"
if noKeyUsername != "" {
explanation = s.opts.Config.NoKeyCouldMatchMessage
if explanation == "" {
explanation = defaultNoKeyMessage(noKeyUsername)
}
}
s.log.Info("session_refused_no_key_could_match", "username", username)
_ = io.WriteErr([]byte(explanation))
io.Exit(1)
return
}
if refusal := s.acquire(account.DID); refusal != "" {
s.log.Info("session_refused", "did", account.DID, "reason", refusal)
_ = io.WriteErr([]byte(refusal + "\n"))
io.Exit(1)
return
}
defer s.release(account.DID)
sessionID := randomHex(16)
remaining := s.opts.Config.SessionMax
s.log.Info("session_started", "sessionId", sessionID, "did", account.DID,
"remainingSec", int(remaining/time.Second), "commandChars", len(command))
sctx, cancel := context.WithCancel(ctx)
defer cancel()
var timer *time.Timer
if remaining > 0 {
timer = time.AfterFunc(remaining, func() {
s.log.Info("session_capped", "sessionId", sessionID, "did", account.DID,
"remainingSec", int(remaining/time.Second))
cancel()
io.Exit(1)
})
defer timer.Stop()
}
err := s.opts.Runner.Run(sctx, *account, command, env, io)
if err != nil {
if io.exited() {
s.log.Warn("post_exit_error", "did", account.DID, "err", err)
return
}
s.log.Warn("provisioning_failed", "did", account.DID, "err", err)
_ = io.WriteErr([]byte("provisioning failed: " + err.Error() + "\n"))
io.Exit(1)
}
}
func (s *Server) acquire(did string) string {
s.mu.Lock()
defer s.mu.Unlock()
if s.running >= s.opts.Config.MaxSessions {
return fmt.Sprintf("server is at its %d concurrent session limit", s.opts.Config.MaxSessions)
}
held := s.perAccount[did]
if held >= s.opts.Config.SessionsPerAccount {
return fmt.Sprintf("account already has %d sessions running", held)
}
s.running++
s.perAccount[did] = held + 1
return ""
}
func (s *Server) release(did string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.running > 0 {
s.running--
}
held := s.perAccount[did] - 1
if held <= 0 {
delete(s.perAccount, did)
} else {
s.perAccount[did] = held
}
}
func (s *Server) closeConnections() {
s.mu.Lock()
conns := make([]net.Conn, 0, len(s.conns))
for conn := range s.conns {
conns = append(conns, conn)
}
s.mu.Unlock()
for _, conn := range conns {
conn.Close()
}
}
func (s *Server) Shutdown(ctx context.Context) error {
if runner, ok := s.opts.Runner.(SessionRunnerShutdowner); ok {
grace, stop := context.WithTimeout(ctx, DefaultShutdownGrace)
_ = runner.Shutdown(grace)
stop()
}
s.closeConnections()
return supervise.Join(ctx, s.connWG.Wait)
}
func defaultNoKeyMessage(username string) string {
return "\n" +
"socialweb-computer-ssh\n" +
"\n" +
" No SSH key registered for \"" + username + "\" can sign in here.\n" +
"\n" +
" If that is your handle, register an SSH key against the account first.\n" +
" If it is not, use your handle as the username -- the account, not just the\n" +
" key, is what this door authenticates against.\n" +
"\n"
}
func randomHex(n int) string {
raw := make([]byte, n)
if _, err := rand.Read(raw); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 16)
}
return hex.EncodeToString(raw)
}
type channelIO struct {
channel ssh.Channel
reader *sync.WaitGroup
mu sync.Mutex
deliverMu sync.Mutex
pty *PTYSize
dataHandler func([]byte)
closeHandlers []func()
pending [][]byte
pendingBytes int
readerStarted bool
closed bool
exitOnce sync.Once
exitedFlag bool
}
func newChannelIO(channel ssh.Channel, reader *sync.WaitGroup) *channelIO {
return &channelIO{channel: channel, reader: reader}
}
func (c *channelIO) Write(chunk []byte) error {
_, err := c.channel.Write(forClientTerminal(c.PTY(), chunk))
return err
}
func (c *channelIO) WriteErr(chunk []byte) error {
_, err := c.channel.Stderr().Write(forClientTerminal(c.PTY(), chunk))
return err
}
func (c *channelIO) OnData(handler func(chunk []byte)) {
c.deliverMu.Lock()
c.mu.Lock()
c.dataHandler = handler
pending := c.pending
c.pending = nil
c.pendingBytes = 0
if !c.readerStarted {
c.readerStarted = true
c.reader.Go(c.readLoop)
}
c.mu.Unlock()
for _, chunk := range pending {
handler(chunk)
}
c.deliverMu.Unlock()
}
func (c *channelIO) readLoop() {
buf := make([]byte, 32*1024)
for {
n, err := c.channel.Read(buf)
if n > 0 {
chunk := append([]byte(nil), buf[:n]...)
c.mu.Lock()
handler := c.dataHandler
if handler == nil {
if c.pendingBytes+len(chunk) <= 1<<20 {
c.pending = append(c.pending, chunk)
c.pendingBytes += len(chunk)
}
}
c.mu.Unlock()
if handler != nil {
c.deliverMu.Lock()
handler(chunk)
c.deliverMu.Unlock()
}
}
if err != nil {
c.markClosed()
return
}
}
}
func (c *channelIO) OnClose(handler func()) {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
handler()
return
}
c.closeHandlers = append(c.closeHandlers, handler)
c.mu.Unlock()
}
func (c *channelIO) markClosed() {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return
}
c.closed = true
handlers := c.closeHandlers
c.closeHandlers = nil
c.mu.Unlock()
for _, handler := range handlers {
handler()
}
}
func (c *channelIO) Exit(code int) {
c.exitOnce.Do(func() {
c.mu.Lock()
c.exitedFlag = true
c.mu.Unlock()
_, _ = c.channel.SendRequest("exit-status", false, ssh.Marshal(struct {
Status uint32
}{uint32(code)}))
_ = c.channel.Close()
})
}
func (c *channelIO) exited() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.exitedFlag
}
func (c *channelIO) setPTY(size *PTYSize) {
c.mu.Lock()
c.pty = size
c.mu.Unlock()
}
func (c *channelIO) setSize(cols, rows int) {
c.mu.Lock()
if c.pty == nil {
c.pty = &PTYSize{}
}
c.pty.Cols = cols
c.pty.Rows = rows
c.mu.Unlock()
}
func (c *channelIO) PTY() *PTYSize {
c.mu.Lock()
defer c.mu.Unlock()
if c.pty == nil {
return nil
}
copied := *c.pty
return &copied
}
func forClientTerminal(pty *PTYSize, chunk []byte) []byte {
if pty == nil || !bytes.Contains(chunk, []byte("\n")) {
return chunk
}
return newlinePattern.ReplaceAll(chunk, []byte("\r\n"))
}