package render import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "sync" "time" ) // The CDP client: JSON messages over the browser's // --remote-debugging-pipe, each ended by a NUL byte. Everything the // browser sends is untrusted: a frame over maxFrame ends the connection, // a frame that is not a message ends it, replies are matched only to // calls this side made, and every wait has a deadline. // maxFrame is the largest message accepted from the browser. The // largest a render asks for is a full-page capture: at most 1440 by // 10,000 pixels, a PNG no larger than its raw 57.6 MB, base64 encoded. const maxFrame = 100 << 20 // callBound is a call's deadline when its context has none. const callBound = 30 * time.Second var ( errFrameTooLarge = errors.New("cdp: a message from the browser is over the size limit") errConnClosed = errors.New("cdp: the browser's pipe closed") ) // readFrame reads one NUL-ended message of at most max bytes (the NUL // not counted) and returns it without the NUL. func readFrame(r *bufio.Reader, max int) ([]byte, error) { var msg []byte for { chunk, err := r.ReadSlice(0) n := len(chunk) if err == nil { n-- // the NUL } if len(msg)+n > max { return nil, errFrameTooLarge } msg = append(msg, chunk[:n]...) switch { case err == nil: return msg, nil case errors.Is(err, bufio.ErrBufferFull): continue case errors.Is(err, io.EOF) && len(msg) > 0: return nil, io.ErrUnexpectedEOF default: return nil, err } } } // deadlineWriter is the pipe to the browser: a write that cannot finish // by its deadline fails. type deadlineWriter interface { io.Writer SetWriteDeadline(time.Time) error } // cdpError is the browser's error reply to a call. type cdpError struct { Method string Code int Message string } func (e *cdpError) Error() string { return fmt.Sprintf("cdp: %s: %d %s", e.Method, e.Code, e.Message) } type cdpReply struct { result json.RawMessage err error } // cdpConn is one connection to the browser. Events go to onEvent, called // from the reading goroutine one at a time; it must not block. type cdpConn struct { w deadlineWriter max int onEvent func(session, method string, params json.RawMessage) wmu sync.Mutex mu sync.Mutex next int64 calls map[int64]chan cdpReply err error done chan struct{} } func newConn(r io.Reader, w deadlineWriter, max int, onEvent func(session, method string, params json.RawMessage)) *cdpConn { c := &cdpConn{w: w, max: max, onEvent: onEvent, calls: map[int64]chan cdpReply{}, done: make(chan struct{})} go c.read(bufio.NewReaderSize(r, 64<<10)) return c } // frame is any message from the browser: a reply (ID set) or an event // (Method set, ID zero). type frame struct { ID int64 `json:"id"` Method string `json:"method"` SessionID string `json:"sessionId"` Params json.RawMessage `json:"params"` Result json.RawMessage `json:"result"` Error *struct { Code int `json:"code"` Message string `json:"message"` } `json:"error"` } func (c *cdpConn) read(r *bufio.Reader) { for { raw, err := readFrame(r, c.max) if err != nil { if errors.Is(err, io.EOF) { err = errConnClosed } c.fail(err) return } var f frame if err = json.Unmarshal(raw, &f); err != nil { c.fail(fmt.Errorf("cdp: a message from the browser is not JSON: %w", err)) return } if f.ID != 0 { c.mu.Lock() ch := c.calls[f.ID] delete(c.calls, f.ID) c.mu.Unlock() if ch == nil { // Not a call this side has waiting: a late reply to // one that gave up, or one the browser made up. continue } reply := cdpReply{result: f.Result} if f.Error != nil { reply.err = &cdpError{Code: f.Error.Code, Message: clean(f.Error.Message, maxMessage)} } ch <- reply continue } if f.Method != "" && c.onEvent != nil { c.onEvent(f.SessionID, f.Method, f.Params) } } } // fail ends the connection with err: every waiting call gets it. func (c *cdpConn) fail(err error) { c.mu.Lock() defer c.mu.Unlock() if c.err != nil { return } c.err = err for id, ch := range c.calls { ch <- cdpReply{err: err} delete(c.calls, id) } close(c.done) } // Err is why the connection ended, or nil while it is open. func (c *cdpConn) Err() error { c.mu.Lock() defer c.mu.Unlock() return c.err } // call sends method with params to session ("" is the browser) and // waits for the reply, decoding its result into result when that is not // nil. It gives up when ctx ends (callBound when ctx has no deadline) or // the connection does. func (c *cdpConn) call(ctx context.Context, session, method string, params, result any) error { if _, ok := ctx.Deadline(); !ok { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, callBound) defer cancel() } ch := make(chan cdpReply, 1) c.mu.Lock() if c.err != nil { c.mu.Unlock() return c.err } c.next++ id := c.next c.calls[id] = ch c.mu.Unlock() forget := func() { c.mu.Lock() delete(c.calls, id) c.mu.Unlock() } msg := struct { ID int64 `json:"id"` Method string `json:"method"` SessionID string `json:"sessionId,omitempty"` Params any `json:"params,omitempty"` }{id, method, session, params} raw, err := json.Marshal(msg) if err != nil { forget() return err } if err = c.write(ctx, append(raw, 0)); err != nil { forget() // A message half written leaves the pipe unusable. c.fail(err) return err } select { case reply := <-ch: if reply.err != nil { var ce *cdpError if errors.As(reply.err, &ce) { ce.Method = method } return reply.err } if result != nil { if err := json.Unmarshal(reply.result, result); err != nil { return fmt.Errorf("cdp: %s: reply: %w", method, err) } } return nil case <-ctx.Done(): forget() return context.Cause(ctx) } } func (c *cdpConn) write(ctx context.Context, msg []byte) error { c.wmu.Lock() defer c.wmu.Unlock() deadline, _ := ctx.Deadline() if err := c.w.SetWriteDeadline(deadline); err != nil { return err } _, err := c.w.Write(msg) return err }