package rex import ( "context" "encoding/base64" "encoding/binary" "errors" "fmt" "time" "github.com/coder/websocket" ) const ( dataPath = "/api/data" // TerminalSubprotocol is the subprotocol of a terminal's data // connection. TerminalSubprotocol = "rex.data.terminal.v1" // maxDataMessage is the largest stream message the server sends. maxDataMessage = 64 << 10 handshakeTimeout = 8 * time.Second ) // DataWelcome is the server's answer to a data connection's HELLO or RESUME. type DataWelcome struct { // Token resumes the stream on a later connection. Never log it. Token [16]byte // Retention is how long the server keeps the stream for a resume. Retention time.Duration // Nonce marks Rex's own messages in the stream. It is never zero. Nonce uint64 } // RejectError is a data handshake the server refused. type RejectError struct { Reason byte } func (e *RejectError) Error() string { var why string switch e.Reason { case 0x01: why = "unknown, expired, or used ticket" case 0x02: why = "this client already has a connection to that stream" case 0x03: why = "stream unavailable" case 0x04: why = "limit reached" case 0x05: why = "malformed handshake" case 0x06: why = "server failure" case 0x07: why = "ticket issued for a different subprotocol" default: why = "unknown reason" } return fmt.Sprintf("rex: data handshake rejected (0x%02x, %s)", e.Reason, why) } // ErrBlockClosed is returned by DataConn.Read when the block has closed. The // stream won't resume. var ErrBlockClosed = errors.New("rex: block closed") // ErrStreamEnded is returned by DataConn.Read when the stream ended normally. var ErrStreamEnded = errors.New("rex: stream ended") // DataConn is a data connection: one block's output, streamed from the // server. type DataConn struct { ws *websocket.Conn welcome DataWelcome } // DataConnect asks the server for a ticket to a block's data source, such as // a terminal's data_ref_id "terminal". The connection must be attached to the // session with Attach or Bootstrap. func (c *Conn) DataConnect(ctx context.Context, sessionID, blockID, dataRefID, subprotocol string) (DataTicket, error) { t := DataTicket{SessionID: sessionID, BlockID: blockID, DataRefID: dataRefID, Subprotocol: subprotocol} _, err := c.Call(ctx, "data.connect", map[string]string{ "session_id": sessionID, "block_id": blockID, "data_ref_id": dataRefID, "subprotocol": subprotocol, }, &t) return t, err } // OpenData opens a data connection with a ticket from DataConnect or // Bootstrap. A ticket works once, even if the handshake fails. func OpenData(ctx context.Context, ep Endpoint, t DataTicket) (*DataConn, error) { ticket, err := base64.RawURLEncoding.DecodeString(t.Ticket) if err != nil || len(ticket) != 16 { return nil, fmt.Errorf("rex: invalid data ticket") } hello := append([]byte{0x01}, ticket...) return openData(ctx, ep, t.Subprotocol, hello) } // ResumeData continues a stream on a new connection, after the last one // dropped. received is the number of stream bytes used so far, across every // connection of the stream; it must be exact. func ResumeData(ctx context.Context, ep Endpoint, subprotocol string, token [16]byte, received uint64) (*DataConn, error) { resume := make([]byte, 0, 25) resume = append(resume, 0x02) resume = append(resume, token[:]...) resume = binary.LittleEndian.AppendUint64(resume, received) return openData(ctx, ep, subprotocol, resume) } func openData(ctx context.Context, ep Endpoint, subprotocol string, handshake []byte) (*DataConn, error) { if subprotocol == "" { subprotocol = TerminalSubprotocol } ctx, cancel := context.WithTimeout(ctx, handshakeTimeout) defer cancel() ws, err := dial(ctx, ep, dataPath, subprotocol) if err != nil { return nil, err } ws.SetReadLimit(maxDataMessage) if err := ws.Write(ctx, websocket.MessageBinary, handshake); err != nil { ws.CloseNow() return nil, fmt.Errorf("rex: send data handshake: %w", err) } typ, msg, err := ws.Read(ctx) if err != nil { ws.CloseNow() return nil, fmt.Errorf("rex: read data welcome: %w", err) } if typ == websocket.MessageBinary && len(msg) >= 1 && msg[0] == 0x82 { ws.CloseNow() reason := byte(0) if len(msg) > 1 { reason = msg[1] } return nil, &RejectError{Reason: reason} } if typ != websocket.MessageBinary || len(msg) != 32 || msg[0] != 0x81 { ws.CloseNow() return nil, fmt.Errorf("rex: invalid data welcome") } var w DataWelcome copy(w.Token[:], msg[1:17]) w.Retention = time.Duration(binary.LittleEndian.Uint32(msg[20:24])) * time.Millisecond w.Nonce = binary.LittleEndian.Uint64(msg[24:32]) if w.Nonce == 0 { ws.CloseNow() return nil, fmt.Errorf("rex: invalid data welcome: zero nonce") } return &DataConn{ws: ws, welcome: w}, nil } // Welcome returns the server's welcome. func (d *DataConn) Welcome() DataWelcome { return d.welcome } // Read returns the next part of the stream. Where one part ends and the next // begins has no meaning. When the stream won't continue, Read returns // ErrBlockClosed or ErrStreamEnded; any other error leaves the stream waiting // for ResumeData. func (d *DataConn) Read(ctx context.Context) ([]byte, error) { for { typ, msg, err := d.ws.Read(ctx) if err != nil { switch websocket.CloseStatus(err) { case 4000: return nil, ErrBlockClosed case websocket.StatusNormalClosure: return nil, ErrStreamEnded } return nil, fmt.Errorf("rex: data connection: %w", err) } if typ == websocket.MessageBinary && len(msg) > 0 { return msg, nil } } } // Close ends the stream: the server stops keeping it for a resume. func (d *DataConn) Close() error { return d.ws.Close(websocket.StatusNormalClosure, "") } // Drop closes the connection without ending the stream, so that it can be // resumed. func (d *DataConn) Drop() error { return d.ws.CloseNow() }