|
| 1 | +//go:build !windows |
| 2 | + |
| 3 | +package exec |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + "sync" |
| 10 | + "syscall" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/bishopfox/sliver/client/console" |
| 14 | + "github.com/bishopfox/sliver/protobuf/sliverpb" |
| 15 | + "github.com/spf13/cobra" |
| 16 | + "golang.org/x/term" |
| 17 | + "google.golang.org/grpc/codes" |
| 18 | + "google.golang.org/grpc/status" |
| 19 | +) |
| 20 | + |
| 21 | +func startPtyResizeWatcher(con *console.SliverClient, cmd *cobra.Command, tunnelID uint64) func() { |
| 22 | + if con == nil || con.Rpc == nil { |
| 23 | + return func() {} |
| 24 | + } |
| 25 | + |
| 26 | + stdoutFd := int(os.Stdout.Fd()) |
| 27 | + stdinFd := int(os.Stdin.Fd()) |
| 28 | + if !term.IsTerminal(stdoutFd) && !term.IsTerminal(stdinFd) { |
| 29 | + return func() {} |
| 30 | + } |
| 31 | + |
| 32 | + sigCh := make(chan os.Signal, 1) |
| 33 | + signal.Notify(sigCh, syscall.SIGWINCH) |
| 34 | + |
| 35 | + stopCh := make(chan struct{}) |
| 36 | + doneCh := make(chan struct{}) |
| 37 | + |
| 38 | + go func() { |
| 39 | + defer close(doneCh) |
| 40 | + |
| 41 | + lastCols, lastRows := -1, -1 |
| 42 | + send := func() bool { |
| 43 | + cols, rows, err := term.GetSize(stdoutFd) |
| 44 | + if err != nil || cols <= 0 || rows <= 0 { |
| 45 | + cols, rows, err = term.GetSize(stdinFd) |
| 46 | + } |
| 47 | + if err != nil || cols <= 0 || rows <= 0 { |
| 48 | + return true |
| 49 | + } |
| 50 | + if cols == lastCols && rows == lastRows { |
| 51 | + return true |
| 52 | + } |
| 53 | + lastCols, lastRows = cols, rows |
| 54 | + |
| 55 | + req := con.ActiveTarget.Request(cmd) |
| 56 | + if req == nil { |
| 57 | + return false |
| 58 | + } |
| 59 | + req.Timeout = int64(2 * time.Second) |
| 60 | + |
| 61 | + _, err = con.Rpc.ShellResize(context.Background(), &sliverpb.ShellResizeReq{ |
| 62 | + Request: req, |
| 63 | + TunnelID: tunnelID, |
| 64 | + Rows: uint32(rows), |
| 65 | + Cols: uint32(cols), |
| 66 | + }) |
| 67 | + if status.Code(err) == codes.Unimplemented { |
| 68 | + return false |
| 69 | + } |
| 70 | + return true |
| 71 | + } |
| 72 | + |
| 73 | + if !send() { |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + for { |
| 78 | + select { |
| 79 | + case <-stopCh: |
| 80 | + return |
| 81 | + case <-sigCh: |
| 82 | + if !send() { |
| 83 | + return |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + }() |
| 88 | + |
| 89 | + var once sync.Once |
| 90 | + return func() { |
| 91 | + once.Do(func() { |
| 92 | + signal.Stop(sigCh) |
| 93 | + close(stopCh) |
| 94 | + <-doneCh |
| 95 | + }) |
| 96 | + } |
| 97 | +} |
0 commit comments