vendor/github.com/go-rod/rod/hijack.go

430 lines · 10344 bytes

  1package rod
  2
  3import (
  4	"bytes"
  5	"context"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11
 12	"github.com/go-rod/rod/lib/proto"
 13	"github.com/go-rod/rod/lib/utils"
 14	"github.com/ysmood/gson"
 15)
 16
 17// HijackRequests same as Page.HijackRequests, but can intercept requests of the entire browser.
 18func (b *Browser) HijackRequests() *HijackRouter {
 19	return newHijackRouter(b, b).initEvents()
 20}
 21
 22// HijackRequests creates a new router instance for requests hijacking.
 23// When use Fetch domain outside the router should be stopped. Enabling hijacking disables page caching,
 24// but such as 304 Not Modified will still work as expected.
 25// The entire process of hijacking one request:
 26//
 27//	browser --req-> rod ---> server ---> rod --res-> browser
 28//
 29// The --req-> and --res-> are the parts that can be modified.
 30func (p *Page) HijackRequests() *HijackRouter {
 31	return newHijackRouter(p.browser, p).initEvents()
 32}
 33
 34// HijackRouter context.
 35type HijackRouter struct {
 36	run      func()
 37	stop     func()
 38	handlers []*hijackHandler
 39	enable   *proto.FetchEnable
 40	client   proto.Client
 41	browser  *Browser
 42}
 43
 44func newHijackRouter(browser *Browser, client proto.Client) *HijackRouter {
 45	return &HijackRouter{
 46		enable:   &proto.FetchEnable{},
 47		browser:  browser,
 48		client:   client,
 49		handlers: []*hijackHandler{},
 50	}
 51}
 52
 53func (r *HijackRouter) initEvents() *HijackRouter { //nolint: gocognit
 54	ctx := r.browser.ctx
 55	if cta, ok := r.client.(proto.Contextable); ok {
 56		ctx = cta.GetContext()
 57	}
 58
 59	var sessionID proto.TargetSessionID
 60	if tsa, ok := r.client.(proto.Sessionable); ok {
 61		sessionID = tsa.GetSessionID()
 62	}
 63
 64	eventCtx, cancel := context.WithCancel(ctx)
 65	r.stop = cancel
 66
 67	_ = r.enable.Call(r.client)
 68
 69	r.run = r.browser.Context(eventCtx).eachEvent(sessionID, func(e *proto.FetchRequestPaused) bool {
 70		go func() {
 71			ctx := r.new(eventCtx, e)
 72			for _, h := range r.handlers {
 73				if !h.regexp.MatchString(e.Request.URL) {
 74					continue
 75				}
 76
 77				h.handler(ctx)
 78
 79				if ctx.continueRequest != nil {
 80					ctx.continueRequest.RequestID = e.RequestID
 81					err := ctx.continueRequest.Call(r.client)
 82					if err != nil {
 83						ctx.OnError(err)
 84					}
 85					return
 86				}
 87
 88				if ctx.Skip {
 89					continue
 90				}
 91
 92				if ctx.Response.fail.ErrorReason != "" {
 93					err := ctx.Response.fail.Call(r.client)
 94					if err != nil {
 95						ctx.OnError(err)
 96					}
 97					return
 98				}
 99
100				err := ctx.Response.payload.Call(r.client)
101				if err != nil {
102					ctx.OnError(err)
103					return
104				}
105			}
106		}()
107
108		return false
109	})
110	return r
111}
112
113// Add a hijack handler to router, the doc of the pattern is the same as "proto.FetchRequestPattern.URLPattern".
114func (r *HijackRouter) Add(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error {
115	r.enable.Patterns = append(r.enable.Patterns, &proto.FetchRequestPattern{
116		URLPattern:   pattern,
117		ResourceType: resourceType,
118	})
119
120	reg := regexp.MustCompile(proto.PatternToReg(pattern))
121
122	r.handlers = append(r.handlers, &hijackHandler{
123		pattern: pattern,
124		regexp:  reg,
125		handler: handler,
126	})
127
128	return r.enable.Call(r.client)
129}
130
131// Remove handler via the pattern.
132func (r *HijackRouter) Remove(pattern string) error {
133	patterns := []*proto.FetchRequestPattern{}
134	handlers := []*hijackHandler{}
135	for _, h := range r.handlers {
136		if h.pattern != pattern {
137			patterns = append(patterns, &proto.FetchRequestPattern{URLPattern: h.pattern})
138			handlers = append(handlers, h)
139		}
140	}
141	r.enable.Patterns = patterns
142	r.handlers = handlers
143
144	return r.enable.Call(r.client)
145}
146
147// new context.
148func (r *HijackRouter) new(ctx context.Context, e *proto.FetchRequestPaused) *Hijack {
149	headers := http.Header{}
150	for k, v := range e.Request.Headers {
151		headers[k] = []string{v.String()}
152	}
153
154	u, _ := url.Parse(e.Request.URL)
155
156	req := &http.Request{
157		Method: e.Request.Method,
158		URL:    u,
159		Body:   io.NopCloser(strings.NewReader(e.Request.PostData)),
160		Header: headers,
161	}
162
163	return &Hijack{
164		Request: &HijackRequest{
165			event: e,
166			req:   req.WithContext(ctx),
167		},
168		Response: &HijackResponse{
169			payload: &proto.FetchFulfillRequest{
170				ResponseCode: 200,
171				RequestID:    e.RequestID,
172			},
173			fail: &proto.FetchFailRequest{
174				RequestID: e.RequestID,
175			},
176		},
177		OnError: func(_ error) {},
178
179		browser: r.browser,
180	}
181}
182
183// Run the router, after you call it, you shouldn't add new handler to it.
184func (r *HijackRouter) Run() {
185	r.run()
186}
187
188// Stop the router.
189func (r *HijackRouter) Stop() error {
190	r.stop()
191	return proto.FetchDisable{}.Call(r.client)
192}
193
194// hijackHandler to handle each request that match the regexp.
195type hijackHandler struct {
196	pattern string
197	regexp  *regexp.Regexp
198	handler func(*Hijack)
199}
200
201// Hijack context.
202type Hijack struct {
203	Request  *HijackRequest
204	Response *HijackResponse
205	OnError  func(error)
206
207	// Skip to next handler
208	Skip bool
209
210	continueRequest *proto.FetchContinueRequest
211
212	// CustomState is used to store things for this context
213	CustomState interface{}
214
215	browser *Browser
216}
217
218// ContinueRequest without hijacking. The RequestID will be set by the router, you don't have to set it.
219func (h *Hijack) ContinueRequest(cq *proto.FetchContinueRequest) {
220	h.continueRequest = cq
221}
222
223// LoadResponse will send request to the real destination and load the response as default response to override.
224func (h *Hijack) LoadResponse(client *http.Client, loadBody bool) error {
225	res, err := client.Do(h.Request.req)
226	if err != nil {
227		return err
228	}
229
230	defer func() { _ = res.Body.Close() }()
231
232	h.Response.payload.ResponseCode = res.StatusCode
233	h.Response.RawResponse = res
234
235	for k, vs := range res.Header {
236		for _, v := range vs {
237			h.Response.SetHeader(k, v)
238		}
239	}
240
241	if loadBody {
242		b, err := io.ReadAll(res.Body)
243		if err != nil {
244			return err
245		}
246		h.Response.payload.Body = b
247	}
248
249	return nil
250}
251
252// HijackRequest context.
253type HijackRequest struct {
254	event *proto.FetchRequestPaused
255	req   *http.Request
256}
257
258// Type of the resource.
259func (ctx *HijackRequest) Type() proto.NetworkResourceType {
260	return ctx.event.ResourceType
261}
262
263// Method of the request.
264func (ctx *HijackRequest) Method() string {
265	return ctx.event.Request.Method
266}
267
268// URL of the request.
269func (ctx *HijackRequest) URL() *url.URL {
270	u, _ := url.Parse(ctx.event.Request.URL)
271	return u
272}
273
274// Header via a key.
275func (ctx *HijackRequest) Header(key string) string {
276	return ctx.event.Request.Headers[key].String()
277}
278
279// Headers of request.
280func (ctx *HijackRequest) Headers() proto.NetworkHeaders {
281	return ctx.event.Request.Headers
282}
283
284// Body of the request, devtools API doesn't support binary data yet, only string can be captured.
285func (ctx *HijackRequest) Body() string {
286	return ctx.event.Request.PostData
287}
288
289// JSONBody of the request.
290func (ctx *HijackRequest) JSONBody() gson.JSON {
291	return gson.NewFrom(ctx.Body())
292}
293
294// Req returns the underlying http.Request instance that will be used to send the request.
295func (ctx *HijackRequest) Req() *http.Request {
296	return ctx.req
297}
298
299// SetContext of the underlying http.Request instance.
300func (ctx *HijackRequest) SetContext(c context.Context) *HijackRequest {
301	ctx.req = ctx.req.WithContext(c)
302	return ctx
303}
304
305// SetBody of the request, if obj is []byte or string, raw body will be used, else it will be encoded as json.
306func (ctx *HijackRequest) SetBody(obj interface{}) *HijackRequest {
307	var b []byte
308
309	switch body := obj.(type) {
310	case []byte:
311		b = body
312	case string:
313		b = []byte(body)
314	default:
315		b = utils.MustToJSONBytes(body)
316	}
317
318	ctx.req.Body = io.NopCloser(bytes.NewBuffer(b))
319
320	return ctx
321}
322
323// IsNavigation determines whether the request is a navigation request.
324func (ctx *HijackRequest) IsNavigation() bool {
325	return ctx.Type() == proto.NetworkResourceTypeDocument
326}
327
328// HijackResponse context.
329type HijackResponse struct {
330	payload     *proto.FetchFulfillRequest
331	RawResponse *http.Response
332	fail        *proto.FetchFailRequest
333}
334
335// Payload to respond the request from the browser.
336func (ctx *HijackResponse) Payload() *proto.FetchFulfillRequest {
337	return ctx.payload
338}
339
340// Body of the payload.
341func (ctx *HijackResponse) Body() string {
342	return string(ctx.payload.Body)
343}
344
345// Headers returns the clone of response headers.
346// If you want to modify the response headers use HijackResponse.SetHeader .
347func (ctx *HijackResponse) Headers() http.Header {
348	header := http.Header{}
349
350	for _, h := range ctx.payload.ResponseHeaders {
351		header.Add(h.Name, h.Value)
352	}
353
354	return header
355}
356
357// SetHeader of the payload via key-value pairs.
358func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse {
359	for i := 0; i < len(pairs); i += 2 {
360		ctx.payload.ResponseHeaders = append(ctx.payload.ResponseHeaders, &proto.FetchHeaderEntry{
361			Name:  pairs[i],
362			Value: pairs[i+1],
363		})
364	}
365	return ctx
366}
367
368// SetBody of the payload, if obj is []byte or string, raw body will be used, else it will be encoded as json.
369func (ctx *HijackResponse) SetBody(obj interface{}) *HijackResponse {
370	switch body := obj.(type) {
371	case []byte:
372		ctx.payload.Body = body
373	case string:
374		ctx.payload.Body = []byte(body)
375	default:
376		ctx.payload.Body = utils.MustToJSONBytes(body)
377	}
378	return ctx
379}
380
381// Fail request.
382func (ctx *HijackResponse) Fail(reason proto.NetworkErrorReason) *HijackResponse {
383	ctx.fail.ErrorReason = reason
384	return ctx
385}
386
387// HandleAuth for the next basic HTTP authentication.
388// It will prevent the popup that requires user to input user name and password.
389// Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
390func (b *Browser) HandleAuth(username, password string) func() error {
391	enable := b.DisableDomain("", &proto.FetchEnable{})
392	disable := b.EnableDomain("", &proto.FetchEnable{
393		HandleAuthRequests: true,
394	})
395
396	paused := &proto.FetchRequestPaused{}
397	auth := &proto.FetchAuthRequired{}
398
399	ctx, cancel := context.WithCancel(b.ctx)
400	waitPaused := b.Context(ctx).WaitEvent(paused)
401	waitAuth := b.Context(ctx).WaitEvent(auth)
402
403	return func() (err error) {
404		defer enable()
405		defer disable()
406		defer cancel()
407
408		waitPaused()
409
410		err = proto.FetchContinueRequest{
411			RequestID: paused.RequestID,
412		}.Call(b)
413		if err != nil {
414			return
415		}
416
417		waitAuth()
418
419		err = proto.FetchContinueWithAuth{
420			RequestID: auth.RequestID,
421			AuthChallengeResponse: &proto.FetchAuthChallengeResponse{
422				Response: proto.FetchAuthChallengeResponseResponseProvideCredentials,
423				Username: username,
424				Password: password,
425			},
426		}.Call(b)
427
428		return
429	}
430}