@@ -5,7 +5,11 @@ import (
55 "encoding/base64"
66 "encoding/json"
77 "github.com/pkg/errors"
8+ "log"
9+ "os"
10+ "strconv"
811 "sync"
12+ "time"
913)
1014
1115// WebTTY bridges a PTY slave and its PTY master.
@@ -24,8 +28,9 @@ type WebTTY struct {
2428 reconnect int // in seconds
2529 masterPrefs []byte
2630
27- bufferSize int
28- writeMutex sync.Mutex
31+ bufferSize int
32+ writeMutex sync.Mutex
33+ lastPingTime time.Time
2934}
3035
3136const (
@@ -45,7 +50,8 @@ func New(masterConn Master, slave Slave, options ...Option) (*WebTTY, error) {
4550 columns : 0 ,
4651 rows : 0 ,
4752
48- bufferSize : MaxBufferSize ,
53+ bufferSize : MaxBufferSize ,
54+ lastPingTime : time .Now (),
4955 }
5056
5157 for _ , option := range options {
@@ -102,6 +108,26 @@ func (wt *WebTTY) Run(ctx context.Context) error {
102108 }()
103109 }()
104110
111+ go func () {
112+ errs <- func () error {
113+ lostPingTimeout := time .Duration (180 ) * time .Second
114+ seconds , _err := strconv .Atoi (os .Getenv ("LOST_PING_TIMEOUT_SECONDS" ))
115+ if _err != nil && seconds > 30 {
116+ lostPingTimeout = time .Duration (seconds ) * time .Second
117+ }
118+ for {
119+ time .Sleep (time .Duration (30 ) * time .Second )
120+ if err != nil {
121+ return nil
122+ }
123+ if time .Now ().After (wt .lastPingTime .Add (lostPingTimeout )) {
124+ log .Println ("Connection lost ping." )
125+ return errors .Wrapf (err , "Connection lost ping." )
126+ }
127+ }
128+ }()
129+ }()
130+
105131 select {
106132 case <- ctx .Done ():
107133 err = ctx .Err ()
@@ -178,6 +204,7 @@ func (wt *WebTTY) handleMasterReadEvent(data []byte) error {
178204
179205 case Ping :
180206 err := wt .masterWrite ([]byte {Pong })
207+ wt .lastPingTime = time .Now ();
181208 if err != nil {
182209 return errors .Wrapf (err , "failed to return Pong message to master" )
183210 }
@@ -206,7 +233,7 @@ func (wt *WebTTY) handleMasterReadEvent(data []byte) error {
206233 columns = int (args .Columns )
207234 }
208235
209- wt .slave .ResizeTerminal (columns , rows )
236+ return wt .slave .ResizeTerminal (columns , rows )
210237 default :
211238 return errors .Errorf ("unknown message type `%c`" , data [0 ])
212239 }
0 commit comments