package rex import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "runtime" "strconv" "sync" "github.com/coder/websocket" ) const ( controlPath = "/api/control" controlSubprotocol = "rex.control.v1" // APIRevision is the revision of the control API whose message shapes // this package is written for. The server translates every message to // and from it. APIRevision = 18 // maxHelloBytes is the largest hello the server accepts, exclusive. maxHelloBytes = 512 ) // ClientInfo is what a client tells the server about itself, for showing to // people. type ClientInfo struct { // Kind is app, cli, agent, or other. Kind string `json:"kind,omitempty"` Platform string `json:"platform,omitempty"` Name string `json:"name,omitempty"` Version string `json:"version,omitempty"` Label string `json:"label,omitempty"` } // Welcome is the server's first message on a control connection. type Welcome struct { Protocol string `json:"protocol"` Limits struct { MaxMessageBytes int64 `json:"max_message_bytes"` } `json:"limits"` Client *struct { ID string `json:"id"` ReconnectToken string `json:"reconnect_token"` Resumed bool `json:"resumed"` } `json:"client"` Features []string `json:"features"` APIRevision int `json:"api_revision"` APIServerRevision int `json:"api_server_revision"` APIMinRevision int `json:"api_min_revision"` } // ClientID returns the ID of the client this connection serves, or "" if the // server didn't say. func (w *Welcome) ClientID() string { if w.Client == nil { return "" } return w.Client.ID } // Event is a message the server sent without being asked. type Event struct { // Seq is the event's place among the events on this connection, // starting at 1 with no gaps. Seq uint64 // SessionID is the session the event happened in, or "" for a server // event. SessionID string // Name is the event's type, such as session_created or block_closed. Name string // Payload holds the event's fields. Payload json.RawMessage } // Decode unmarshals the event's fields into v. func (e Event) Decode(v any) error { return json.Unmarshal(e.Payload, v) } // Error is a failed method call, as the server reported it. type Error struct { // Code says what kind of failure it was, such as not_found. Branch on // it, or on Status for a code you don't know. Code string `json:"code"` // Message is written for people; its wording can change. Message string `json:"message"` // Status has the meaning of an HTTP status code, such as 404. Status int `json:"status"` } func (e *Error) Error() string { return fmt.Sprintf("rex: %s (%d): %s", e.Code, e.Status, e.Message) } // IsCode reports whether err is an *Error with the given code. func IsCode(err error, code string) bool { var apiErr *Error return errors.As(err, &apiErr) && apiErr.Code == code } // Conn is a control connection. Its methods are safe for concurrent use. type Conn struct { ws *websocket.Conn welcome Welcome mu sync.Mutex nextID uint64 pending map[string]chan response err error // why the connection ended; set once, before done closes closing bool // Close was called events chan Event done chan struct{} onClose []func() // run when the connection ends ended bool // the connection has ended, and onClose has been taken } type response struct { seq uint64 payload json.RawMessage err error } // Dial opens a control connection to the server at ep and exchanges the hello // and welcome. func Dial(ctx context.Context, ep Endpoint, info ClientInfo) (*Conn, error) { if info.Platform == "" { info.Platform = runtime.GOOS } hello, err := json.Marshal(struct { Type string `json:"type"` APIRevision int `json:"api_revision"` APIMinRevision int `json:"api_min_revision"` Client ClientInfo `json:"client"` }{"hello", APIRevision, APIRevision, info}) if err != nil { return nil, err } if len(hello) >= maxHelloBytes { return nil, fmt.Errorf("rex: hello is %d bytes, and the server accepts less than %d", len(hello), maxHelloBytes) } ws, err := dial(ctx, ep, controlPath, controlSubprotocol) if err != nil { return nil, err } if err := ws.Write(ctx, websocket.MessageText, hello); err != nil { ws.CloseNow() return nil, fmt.Errorf("rex: send hello: %w", err) } _, data, err := ws.Read(ctx) if err != nil { ws.CloseNow() return nil, fmt.Errorf("rex: read welcome: %w", err) } var welcome struct { Type string `json:"type"` Welcome } if err := json.Unmarshal(data, &welcome); err != nil || welcome.Type != "welcome" { ws.CloseNow() return nil, fmt.Errorf("rex: the server's first message wasn't a welcome: %.200s", data) } if welcome.Protocol != controlSubprotocol { ws.CloseNow() return nil, fmt.Errorf("rex: unexpected protocol %q", welcome.Protocol) } if limit := welcome.Limits.MaxMessageBytes; limit > 0 { ws.SetReadLimit(limit) } c := &Conn{ ws: ws, welcome: welcome.Welcome, pending: make(map[string]chan response), events: make(chan Event), done: make(chan struct{}), } queue := make(chan Event) go c.readLoop(queue) go pumpEvents(queue, c.events) return c, nil } // dial opens a WebSocket to path on ep with the given subprotocol. func dial(ctx context.Context, ep Endpoint, path, subprotocol string) (*websocket.Conn, error) { ws, resp, err := websocket.Dial(ctx, ep.url(path), &websocket.DialOptions{ HTTPClient: ep.httpClient(), Subprotocols: []string{subprotocol}, // Data connections are never compressed, and the control // connection's hello must not be, so compression stays off. CompressionMode: websocket.CompressionDisabled, }) if err != nil { if resp != nil && resp.StatusCode == http.StatusForbidden { // A Rex server that doesn't let the caller in, such as a // Tailscale user its access rules don't allow, says why, as // {"error": "..."}. Another program's 403 is just not Rex. var body struct { Error string `json:"error"` } data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) if json.Unmarshal(data, &body) == nil && body.Error != "" { return nil, &ForbiddenError{Endpoint: ep, Reason: body.Error} } } return nil, fmt.Errorf("rex: connect to %s: %w", ep, err) } if ws.Subprotocol() != subprotocol { ws.CloseNow() return nil, fmt.Errorf("rex: server at %s didn't accept subprotocol %s", ep, subprotocol) } return ws, nil } // ForbiddenError is a Rex server that answered but didn't let this client // in, such as a Tailscale user its access rules don't allow. type ForbiddenError struct { Endpoint Endpoint Reason string // the server's } func (e *ForbiddenError) Error() string { return fmt.Sprintf("rex: %s didn't let this client in: %s", e.Endpoint, e.Reason) } // Welcome returns the server's welcome. func (c *Conn) Welcome() *Welcome { return &c.welcome } // Events returns the events the server sends, in order. Events are queued // without limit, so a slow reader never holds up responses; the server closes // a connection that falls more than 8 MiB of events behind. The channel is // closed when the connection ends, and events not yet received are dropped. func (c *Conn) Events() <-chan Event { return c.events } // Done is closed when the connection ends. Err then says why. func (c *Conn) Done() <-chan struct{} { return c.done } // Err returns why the connection ended, or nil while it is open. func (c *Conn) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } // Close closes the connection normally. func (c *Conn) Close() error { c.mu.Lock() c.closing = true c.mu.Unlock() err := c.ws.Close(websocket.StatusNormalClosure, "") <-c.done return err } // Drop ends the connection without closing it, as a network failure does: // the server keeps the client for a while, for it to reconnect. func (c *Conn) Drop() { c.ws.CloseNow() <-c.done } // Call calls method with args, which may be nil, and decodes its result into // result, which may also be nil. It returns the response's seq: events with a // higher seq happened after the server started the request. // // If ctx ends first, Call returns its error, though the server may still run // the request. func (c *Conn) Call(ctx context.Context, method string, args, result any) (seq uint64, err error) { c.mu.Lock() if c.err != nil { err := c.err c.mu.Unlock() return 0, err } c.nextID++ id := strconv.FormatUint(c.nextID, 10) reply := make(chan response, 1) c.pending[id] = reply c.mu.Unlock() defer func() { c.mu.Lock() delete(c.pending, id) c.mu.Unlock() }() req := struct { Type string `json:"type"` ID string `json:"id"` Method string `json:"method"` Payload any `json:"payload,omitempty"` }{"request", id, method, args} text, err := json.Marshal(req) if err != nil { return 0, fmt.Errorf("rex: encode %s: %w", method, err) } if limit := c.welcome.Limits.MaxMessageBytes; limit > 0 && int64(len(text)) > limit { // The server would close the connection. return 0, fmt.Errorf("rex: %s request is %d bytes, over the server's limit of %d", method, len(text), limit) } if err := c.ws.Write(ctx, websocket.MessageText, text); err != nil { return 0, fmt.Errorf("rex: send %s: %w", method, err) } select { case r := <-reply: if r.err != nil { return r.seq, r.err } if result != nil && len(r.payload) > 0 { if err := json.Unmarshal(r.payload, result); err != nil { return r.seq, fmt.Errorf("rex: decode %s result: %w", method, err) } } return r.seq, nil case <-c.done: return 0, c.Err() case <-ctx.Done(): return 0, ctx.Err() } } // incoming is any message from the server after the welcome. type incoming struct { Type string `json:"type"` ID string `json:"id"` Seq uint64 `json:"seq"` Payload json.RawMessage `json:"payload"` Error *Error `json:"error"` } // wireEvent is the event inside an event message, and inside a // session_event. type wireEvent struct { Type string `json:"type"` Payload json.RawMessage `json:"payload"` SessionID string `json:"session_id"` Event *wireEvent `json:"event"` } func (c *Conn) readLoop(queue chan<- Event) { defer close(queue) err := c.read(queue) c.mu.Lock() if c.closing { // However the read failed, it was because of Close. err = ErrClosed } c.err = err fs := c.onClose c.onClose, c.ended = nil, true c.mu.Unlock() // Before done closes, so that Close returns after them. for _, f := range fs { f() } close(c.done) } // OnClose calls f once the connection has ended, however it ended, or at // once if it already has: to end what carries it, such as an ssh tunnel. func (c *Conn) OnClose(f func()) { c.mu.Lock() if c.ended { c.mu.Unlock() f() return } c.onClose = append(c.onClose, f) c.mu.Unlock() } func (c *Conn) read(queue chan<- Event) error { for { _, data, err := c.ws.Read(context.Background()) if err != nil { if websocket.CloseStatus(err) == websocket.StatusNormalClosure { return ErrClosed } return fmt.Errorf("rex: control connection: %w", err) } var msg incoming if err := json.Unmarshal(data, &msg); err != nil { c.ws.Close(websocket.StatusProtocolError, "invalid JSON") return fmt.Errorf("rex: invalid message from server: %w", err) } switch msg.Type { case "response": c.mu.Lock() reply, ok := c.pending[msg.ID] c.mu.Unlock() if !ok { continue // its caller gave up waiting } r := response{seq: msg.Seq, payload: msg.Payload} if msg.Error != nil { r.err = msg.Error } reply <- r case "event": ev, err := decodeEvent(msg.Seq, msg.Payload) if err != nil { c.ws.Close(websocket.StatusProtocolError, "invalid event") return err } queue <- ev } // Newer servers may add message types; skip them. } } // ErrClosed is returned by calls on a connection that was closed normally. var ErrClosed = errors.New("rex: control connection closed") func decodeEvent(seq uint64, payload json.RawMessage) (Event, error) { var ev wireEvent if err := json.Unmarshal(payload, &ev); err != nil { return Event{}, fmt.Errorf("rex: invalid event %d: %w", seq, err) } if ev.Type == "session_event" { var inner wireEvent if err := json.Unmarshal(ev.Payload, &inner); err != nil || inner.Event == nil { return Event{}, fmt.Errorf("rex: invalid session event %d", seq) } return Event{Seq: seq, SessionID: inner.SessionID, Name: inner.Event.Type, Payload: inner.Event.Payload}, nil } return Event{Seq: seq, Name: ev.Type, Payload: ev.Payload}, nil } // pumpEvents moves events from in to out, queueing as many as it must so that // sends on in never block for long. func pumpEvents(in <-chan Event, out chan<- Event) { defer close(out) var queue []Event for { var send chan<- Event var next Event if len(queue) > 0 { send, next = out, queue[0] } select { case ev, ok := <-in: if !ok { // The connection has ended. Undelivered events are // dropped: after a disconnect the client must read the // state again anyway, and a reader that has stopped // reading would otherwise hold this goroutine forever. return } queue = append(queue, ev) case send <- next: queue[0] = Event{} queue = queue[1:] } } }