]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/roundtrip_js.go
net/http: guarantee that the Transport dial functions are respected in js/wasm
[gostls13.git] / src / net / http / roundtrip_js.go
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build js && wasm
6 // +build js,wasm
7
8 package http
9
10 import (
11         "errors"
12         "fmt"
13         "io"
14         "strconv"
15         "syscall/js"
16 )
17
18 var uint8Array = js.Global().Get("Uint8Array")
19
20 // jsFetchMode is a Request.Header map key that, if present,
21 // signals that the map entry is actually an option to the Fetch API mode setting.
22 // Valid values are: "cors", "no-cors", "same-origin", "navigate"
23 // The default is "same-origin".
24 //
25 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
26 const jsFetchMode = "js.fetch:mode"
27
28 // jsFetchCreds is a Request.Header map key that, if present,
29 // signals that the map entry is actually an option to the Fetch API credentials setting.
30 // Valid values are: "omit", "same-origin", "include"
31 // The default is "same-origin".
32 //
33 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
34 const jsFetchCreds = "js.fetch:credentials"
35
36 // jsFetchRedirect is a Request.Header map key that, if present,
37 // signals that the map entry is actually an option to the Fetch API redirect setting.
38 // Valid values are: "follow", "error", "manual"
39 // The default is "follow".
40 //
41 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
42 const jsFetchRedirect = "js.fetch:redirect"
43
44 // jsFetchMissing will be true if the Fetch API is not present in
45 // the browser globals.
46 var jsFetchMissing = js.Global().Get("fetch").IsUndefined()
47
48 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
49 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
50         // The Transport has a documented contract that states that if the DialContext or
51         // DialTLSContext functions are set, they will be used to set up the connections.
52         // If they aren't set then the documented contract is to use Dial or DialTLS, even
53         // though they are deprecated. Therefore, if any of these are set, we should obey
54         // the contract and dial using the regular round-trip instead. Otherwise, we'll try
55         // to fall back on the Fetch API, unless it's not available.
56         if t.Dial != nil || t.DialContext != nil || t.DialTLS != nil || t.DialTLSContext != nil || jsFetchMissing {
57                 return t.roundTrip(req)
58         }
59
60         ac := js.Global().Get("AbortController")
61         if !ac.IsUndefined() {
62                 // Some browsers that support WASM don't necessarily support
63                 // the AbortController. See
64                 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
65                 ac = ac.New()
66         }
67
68         opt := js.Global().Get("Object").New()
69         // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
70         // for options available.
71         opt.Set("method", req.Method)
72         opt.Set("credentials", "same-origin")
73         if h := req.Header.Get(jsFetchCreds); h != "" {
74                 opt.Set("credentials", h)
75                 req.Header.Del(jsFetchCreds)
76         }
77         if h := req.Header.Get(jsFetchMode); h != "" {
78                 opt.Set("mode", h)
79                 req.Header.Del(jsFetchMode)
80         }
81         if h := req.Header.Get(jsFetchRedirect); h != "" {
82                 opt.Set("redirect", h)
83                 req.Header.Del(jsFetchRedirect)
84         }
85         if !ac.IsUndefined() {
86                 opt.Set("signal", ac.Get("signal"))
87         }
88         headers := js.Global().Get("Headers").New()
89         for key, values := range req.Header {
90                 for _, value := range values {
91                         headers.Call("append", key, value)
92                 }
93         }
94         opt.Set("headers", headers)
95
96         if req.Body != nil {
97                 // TODO(johanbrandhorst): Stream request body when possible.
98                 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
99                 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
100                 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
101                 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
102                 // and browser support.
103                 body, err := io.ReadAll(req.Body)
104                 if err != nil {
105                         req.Body.Close() // RoundTrip must always close the body, including on errors.
106                         return nil, err
107                 }
108                 req.Body.Close()
109                 if len(body) != 0 {
110                         buf := uint8Array.New(len(body))
111                         js.CopyBytesToJS(buf, body)
112                         opt.Set("body", buf)
113                 }
114         }
115
116         fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
117         var (
118                 respCh           = make(chan *Response, 1)
119                 errCh            = make(chan error, 1)
120                 success, failure js.Func
121         )
122         success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
123                 success.Release()
124                 failure.Release()
125
126                 result := args[0]
127                 header := Header{}
128                 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
129                 headersIt := result.Get("headers").Call("entries")
130                 for {
131                         n := headersIt.Call("next")
132                         if n.Get("done").Bool() {
133                                 break
134                         }
135                         pair := n.Get("value")
136                         key, value := pair.Index(0).String(), pair.Index(1).String()
137                         ck := CanonicalHeaderKey(key)
138                         header[ck] = append(header[ck], value)
139                 }
140
141                 contentLength := int64(0)
142                 clHeader := header.Get("Content-Length")
143                 switch {
144                 case clHeader != "":
145                         cl, err := strconv.ParseInt(clHeader, 10, 64)
146                         if err != nil {
147                                 errCh <- fmt.Errorf("net/http: ill-formed Content-Length header: %v", err)
148                                 return nil
149                         }
150                         if cl < 0 {
151                                 // Content-Length values less than 0 are invalid.
152                                 // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
153                                 errCh <- fmt.Errorf("net/http: invalid Content-Length header: %q", clHeader)
154                                 return nil
155                         }
156                         contentLength = cl
157                 default:
158                         // If the response length is not declared, set it to -1.
159                         contentLength = -1
160                 }
161
162                 b := result.Get("body")
163                 var body io.ReadCloser
164                 // The body is undefined when the browser does not support streaming response bodies (Firefox),
165                 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
166                 if !b.IsUndefined() && !b.IsNull() {
167                         body = &streamReader{stream: b.Call("getReader")}
168                 } else {
169                         // Fall back to using ArrayBuffer
170                         // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
171                         body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
172                 }
173
174                 code := result.Get("status").Int()
175                 respCh <- &Response{
176                         Status:        fmt.Sprintf("%d %s", code, StatusText(code)),
177                         StatusCode:    code,
178                         Header:        header,
179                         ContentLength: contentLength,
180                         Body:          body,
181                         Request:       req,
182                 }
183
184                 return nil
185         })
186         failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
187                 success.Release()
188                 failure.Release()
189                 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
190                 return nil
191         })
192
193         fetchPromise.Call("then", success, failure)
194         select {
195         case <-req.Context().Done():
196                 if !ac.IsUndefined() {
197                         // Abort the Fetch request.
198                         ac.Call("abort")
199                 }
200                 return nil, req.Context().Err()
201         case resp := <-respCh:
202                 return resp, nil
203         case err := <-errCh:
204                 return nil, err
205         }
206 }
207
208 var errClosed = errors.New("net/http: reader is closed")
209
210 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
211 // See https://fetch.spec.whatwg.org/#readablestream for more information.
212 type streamReader struct {
213         pending []byte
214         stream  js.Value
215         err     error // sticky read error
216 }
217
218 func (r *streamReader) Read(p []byte) (n int, err error) {
219         if r.err != nil {
220                 return 0, r.err
221         }
222         if len(r.pending) == 0 {
223                 var (
224                         bCh   = make(chan []byte, 1)
225                         errCh = make(chan error, 1)
226                 )
227                 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
228                         result := args[0]
229                         if result.Get("done").Bool() {
230                                 errCh <- io.EOF
231                                 return nil
232                         }
233                         value := make([]byte, result.Get("value").Get("byteLength").Int())
234                         js.CopyBytesToGo(value, result.Get("value"))
235                         bCh <- value
236                         return nil
237                 })
238                 defer success.Release()
239                 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
240                         // Assumes it's a TypeError. See
241                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
242                         // for more information on this type. See
243                         // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
244                         // the read method.
245                         errCh <- errors.New(args[0].Get("message").String())
246                         return nil
247                 })
248                 defer failure.Release()
249                 r.stream.Call("read").Call("then", success, failure)
250                 select {
251                 case b := <-bCh:
252                         r.pending = b
253                 case err := <-errCh:
254                         r.err = err
255                         return 0, err
256                 }
257         }
258         n = copy(p, r.pending)
259         r.pending = r.pending[n:]
260         return n, nil
261 }
262
263 func (r *streamReader) Close() error {
264         // This ignores any error returned from cancel method. So far, I did not encounter any concrete
265         // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
266         // If there's a need to report error here, it can be implemented and tested when that need comes up.
267         r.stream.Call("cancel")
268         if r.err == nil {
269                 r.err = errClosed
270         }
271         return nil
272 }
273
274 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
275 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
276 type arrayReader struct {
277         arrayPromise js.Value
278         pending      []byte
279         read         bool
280         err          error // sticky read error
281 }
282
283 func (r *arrayReader) Read(p []byte) (n int, err error) {
284         if r.err != nil {
285                 return 0, r.err
286         }
287         if !r.read {
288                 r.read = true
289                 var (
290                         bCh   = make(chan []byte, 1)
291                         errCh = make(chan error, 1)
292                 )
293                 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
294                         // Wrap the input ArrayBuffer with a Uint8Array
295                         uint8arrayWrapper := uint8Array.New(args[0])
296                         value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
297                         js.CopyBytesToGo(value, uint8arrayWrapper)
298                         bCh <- value
299                         return nil
300                 })
301                 defer success.Release()
302                 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
303                         // Assumes it's a TypeError. See
304                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
305                         // for more information on this type.
306                         // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
307                         errCh <- errors.New(args[0].Get("message").String())
308                         return nil
309                 })
310                 defer failure.Release()
311                 r.arrayPromise.Call("then", success, failure)
312                 select {
313                 case b := <-bCh:
314                         r.pending = b
315                 case err := <-errCh:
316                         return 0, err
317                 }
318         }
319         if len(r.pending) == 0 {
320                 return 0, io.EOF
321         }
322         n = copy(p, r.pending)
323         r.pending = r.pending[n:]
324         return n, nil
325 }
326
327 func (r *arrayReader) Close() error {
328         if r.err == nil {
329                 r.err = errClosed
330         }
331         return nil
332 }