| 1 | package render |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "sync" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // The CDP client: JSON messages over the browser's |
| 15 | // --remote-debugging-pipe, each ended by a NUL byte. Everything the |
| 16 | // browser sends is untrusted: a frame over maxFrame ends the connection, |
| 17 | // a frame that is not a message ends it, replies are matched only to |
| 18 | // calls this side made, and every wait has a deadline. |
| 19 | |
| 20 | // maxFrame is the largest message accepted from the browser. The |
| 21 | // largest a render asks for is a full-page capture: at most 1440 by |
| 22 | // 10,000 pixels, a PNG no larger than its raw 57.6 MB, base64 encoded. |
| 23 | const maxFrame = 100 << 20 |
| 24 | |
| 25 | // callBound is a call's deadline when its context has none. |
| 26 | const callBound = 30 * time.Second |
| 27 | |
| 28 | var ( |
| 29 | errFrameTooLarge = errors.New("cdp: a message from the browser is over the size limit") |
| 30 | errConnClosed = errors.New("cdp: the browser's pipe closed") |
| 31 | ) |
| 32 | |
| 33 | // readFrame reads one NUL-ended message of at most max bytes (the NUL |
| 34 | // not counted) and returns it without the NUL. |
| 35 | func readFrame(r *bufio.Reader, max int) ([]byte, error) { |
| 36 | var msg []byte |
| 37 | for { |
| 38 | chunk, err := r.ReadSlice(0) |
| 39 | n := len(chunk) |
| 40 | if err == nil { |
| 41 | n-- // the NUL |
| 42 | } |
| 43 | if len(msg)+n > max { |
| 44 | return nil, errFrameTooLarge |
| 45 | } |
| 46 | msg = append(msg, chunk[:n]...) |
| 47 | switch { |
| 48 | case err == nil: |
| 49 | return msg, nil |
| 50 | case errors.Is(err, bufio.ErrBufferFull): |
| 51 | continue |
| 52 | case errors.Is(err, io.EOF) && len(msg) > 0: |
| 53 | return nil, io.ErrUnexpectedEOF |
| 54 | default: |
| 55 | return nil, err |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // deadlineWriter is the pipe to the browser: a write that cannot finish |
| 61 | // by its deadline fails. |
| 62 | type deadlineWriter interface { |
| 63 | io.Writer |
| 64 | SetWriteDeadline(time.Time) error |
| 65 | } |
| 66 | |
| 67 | // cdpError is the browser's error reply to a call. |
| 68 | type cdpError struct { |
| 69 | Method string |
| 70 | Code int |
| 71 | Message string |
| 72 | } |
| 73 | |
| 74 | func (e *cdpError) Error() string { |
| 75 | return fmt.Sprintf("cdp: %s: %d %s", e.Method, e.Code, e.Message) |
| 76 | } |
| 77 | |
| 78 | type cdpReply struct { |
| 79 | result json.RawMessage |
| 80 | err error |
| 81 | } |
| 82 | |
| 83 | // cdpConn is one connection to the browser. Events go to onEvent, called |
| 84 | // from the reading goroutine one at a time; it must not block. |
| 85 | type cdpConn struct { |
| 86 | w deadlineWriter |
| 87 | max int |
| 88 | onEvent func(session, method string, params json.RawMessage) |
| 89 | |
| 90 | wmu sync.Mutex |
| 91 | |
| 92 | mu sync.Mutex |
| 93 | next int64 |
| 94 | calls map[int64]chan cdpReply |
| 95 | err error |
| 96 | done chan struct{} |
| 97 | } |
| 98 | |
| 99 | func newConn(r io.Reader, w deadlineWriter, max int, onEvent func(session, method string, params json.RawMessage)) *cdpConn { |
| 100 | c := &cdpConn{w: w, max: max, onEvent: onEvent, calls: map[int64]chan cdpReply{}, done: make(chan struct{})} |
| 101 | go c.read(bufio.NewReaderSize(r, 64<<10)) |
| 102 | return c |
| 103 | } |
| 104 | |
| 105 | // frame is any message from the browser: a reply (ID set) or an event |
| 106 | // (Method set, ID zero). |
| 107 | type frame struct { |
| 108 | ID int64 `json:"id"` |
| 109 | Method string `json:"method"` |
| 110 | SessionID string `json:"sessionId"` |
| 111 | Params json.RawMessage `json:"params"` |
| 112 | Result json.RawMessage `json:"result"` |
| 113 | Error *struct { |
| 114 | Code int `json:"code"` |
| 115 | Message string `json:"message"` |
| 116 | } `json:"error"` |
| 117 | } |
| 118 | |
| 119 | func (c *cdpConn) read(r *bufio.Reader) { |
| 120 | for { |
| 121 | raw, err := readFrame(r, c.max) |
| 122 | if err != nil { |
| 123 | if errors.Is(err, io.EOF) { |
| 124 | err = errConnClosed |
| 125 | } |
| 126 | c.fail(err) |
| 127 | return |
| 128 | } |
| 129 | var f frame |
| 130 | if err = json.Unmarshal(raw, &f); err != nil { |
| 131 | c.fail(fmt.Errorf("cdp: a message from the browser is not JSON: %w", err)) |
| 132 | return |
| 133 | } |
| 134 | if f.ID != 0 { |
| 135 | c.mu.Lock() |
| 136 | ch := c.calls[f.ID] |
| 137 | delete(c.calls, f.ID) |
| 138 | c.mu.Unlock() |
| 139 | if ch == nil { |
| 140 | // Not a call this side has waiting: a late reply to |
| 141 | // one that gave up, or one the browser made up. |
| 142 | continue |
| 143 | } |
| 144 | reply := cdpReply{result: f.Result} |
| 145 | if f.Error != nil { |
| 146 | reply.err = &cdpError{Code: f.Error.Code, Message: clean(f.Error.Message, maxMessage)} |
| 147 | } |
| 148 | ch <- reply |
| 149 | continue |
| 150 | } |
| 151 | if f.Method != "" && c.onEvent != nil { |
| 152 | c.onEvent(f.SessionID, f.Method, f.Params) |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // fail ends the connection with err: every waiting call gets it. |
| 158 | func (c *cdpConn) fail(err error) { |
| 159 | c.mu.Lock() |
| 160 | defer c.mu.Unlock() |
| 161 | if c.err != nil { |
| 162 | return |
| 163 | } |
| 164 | c.err = err |
| 165 | for id, ch := range c.calls { |
| 166 | ch <- cdpReply{err: err} |
| 167 | delete(c.calls, id) |
| 168 | } |
| 169 | close(c.done) |
| 170 | } |
| 171 | |
| 172 | // Err is why the connection ended, or nil while it is open. |
| 173 | func (c *cdpConn) Err() error { |
| 174 | c.mu.Lock() |
| 175 | defer c.mu.Unlock() |
| 176 | return c.err |
| 177 | } |
| 178 | |
| 179 | // call sends method with params to session ("" is the browser) and |
| 180 | // waits for the reply, decoding its result into result when that is not |
| 181 | // nil. It gives up when ctx ends (callBound when ctx has no deadline) or |
| 182 | // the connection does. |
| 183 | func (c *cdpConn) call(ctx context.Context, session, method string, params, result any) error { |
| 184 | if _, ok := ctx.Deadline(); !ok { |
| 185 | var cancel context.CancelFunc |
| 186 | ctx, cancel = context.WithTimeout(ctx, callBound) |
| 187 | defer cancel() |
| 188 | } |
| 189 | ch := make(chan cdpReply, 1) |
| 190 | c.mu.Lock() |
| 191 | if c.err != nil { |
| 192 | c.mu.Unlock() |
| 193 | return c.err |
| 194 | } |
| 195 | c.next++ |
| 196 | id := c.next |
| 197 | c.calls[id] = ch |
| 198 | c.mu.Unlock() |
| 199 | forget := func() { |
| 200 | c.mu.Lock() |
| 201 | delete(c.calls, id) |
| 202 | c.mu.Unlock() |
| 203 | } |
| 204 | msg := struct { |
| 205 | ID int64 `json:"id"` |
| 206 | Method string `json:"method"` |
| 207 | SessionID string `json:"sessionId,omitempty"` |
| 208 | Params any `json:"params,omitempty"` |
| 209 | }{id, method, session, params} |
| 210 | raw, err := json.Marshal(msg) |
| 211 | if err != nil { |
| 212 | forget() |
| 213 | return err |
| 214 | } |
| 215 | if err = c.write(ctx, append(raw, 0)); err != nil { |
| 216 | forget() |
| 217 | // A message half written leaves the pipe unusable. |
| 218 | c.fail(err) |
| 219 | return err |
| 220 | } |
| 221 | select { |
| 222 | case reply := <-ch: |
| 223 | if reply.err != nil { |
| 224 | var ce *cdpError |
| 225 | if errors.As(reply.err, &ce) { |
| 226 | ce.Method = method |
| 227 | } |
| 228 | return reply.err |
| 229 | } |
| 230 | if result != nil { |
| 231 | if err := json.Unmarshal(reply.result, result); err != nil { |
| 232 | return fmt.Errorf("cdp: %s: reply: %w", method, err) |
| 233 | } |
| 234 | } |
| 235 | return nil |
| 236 | case <-ctx.Done(): |
| 237 | forget() |
| 238 | return context.Cause(ctx) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func (c *cdpConn) write(ctx context.Context, msg []byte) error { |
| 243 | c.wmu.Lock() |
| 244 | defer c.wmu.Unlock() |
| 245 | deadline, _ := ctx.Deadline() |
| 246 | if err := c.w.SetWriteDeadline(deadline); err != nil { |
| 247 | return err |
| 248 | } |
| 249 | _, err := c.w.Write(msg) |
| 250 | return err |
| 251 | } |
| 252 | |