Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/dom/fetch/Request.cpp
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
 * License, v. 2.0. If a copy of the MPL was not distributed with this
5
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "Request.h"
8
9
#include "nsIURI.h"
10
#include "nsPIDOMWindow.h"
11
12
#include "mozilla/ErrorResult.h"
13
#include "mozilla/dom/Headers.h"
14
#include "mozilla/dom/Fetch.h"
15
#include "mozilla/dom/FetchUtil.h"
16
#include "mozilla/dom/Promise.h"
17
#include "mozilla/dom/URL.h"
18
#include "mozilla/dom/WorkerPrivate.h"
19
#include "mozilla/Unused.h"
20
21
namespace mozilla {
22
namespace dom {
23
24
NS_IMPL_CYCLE_COLLECTING_ADDREF(Request)
25
NS_IMPL_CYCLE_COLLECTING_RELEASE(Request)
26
27
NS_IMPL_CYCLE_COLLECTION_CLASS(Request)
28
29
0
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Request)
30
0
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOwner)
31
0
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mHeaders)
32
0
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSignal)
33
0
  tmp->Unfollow();
34
0
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
35
0
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
36
37
0
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Request)
38
0
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwner)
39
0
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mHeaders)
40
0
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSignal)
41
0
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFollowingSignal)
42
0
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
43
44
0
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Request)
45
0
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mReadableStreamBody)
46
0
  MOZ_DIAGNOSTIC_ASSERT(!tmp->mReadableStreamReader);
47
0
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mReadableStreamReader)
48
0
  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
49
0
NS_IMPL_CYCLE_COLLECTION_TRACE_END
50
51
0
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Request)
52
0
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
53
0
  NS_INTERFACE_MAP_ENTRY(nsISupports)
54
0
NS_INTERFACE_MAP_END
55
56
Request::Request(nsIGlobalObject* aOwner, InternalRequest* aRequest,
57
                 AbortSignal* aSignal)
58
  : FetchBody<Request>(aOwner)
59
  , mRequest(aRequest)
60
0
{
61
0
  MOZ_ASSERT(aRequest->Headers()->Guard() == HeadersGuardEnum::Immutable ||
62
0
             aRequest->Headers()->Guard() == HeadersGuardEnum::Request ||
63
0
             aRequest->Headers()->Guard() == HeadersGuardEnum::Request_no_cors);
64
0
  SetMimeType();
65
0
66
0
  if (aSignal) {
67
0
    // If we don't have a signal as argument, we will create it when required by
68
0
    // content, otherwise the Request's signal must follow what has been passed.
69
0
    mSignal = new AbortSignal(aOwner, aSignal->Aborted());
70
0
    if (!mSignal->Aborted()) {
71
0
      mSignal->Follow(aSignal);
72
0
    }
73
0
  }
74
0
}
75
76
Request::~Request()
77
0
{
78
0
}
79
80
already_AddRefed<InternalRequest>
81
Request::GetInternalRequest()
82
0
{
83
0
  RefPtr<InternalRequest> r = mRequest;
84
0
  return r.forget();
85
0
}
86
87
namespace {
88
already_AddRefed<nsIURI>
89
ParseURLFromDocument(nsIDocument* aDocument, const nsAString& aInput,
90
                     ErrorResult& aRv)
91
0
{
92
0
  MOZ_ASSERT(aDocument);
93
0
  MOZ_ASSERT(NS_IsMainThread());
94
0
95
0
  nsCOMPtr<nsIURI> baseURI = aDocument->GetBaseURI();
96
0
  nsCOMPtr<nsIURI> resolvedURI;
97
0
  aRv = NS_NewURI(getter_AddRefs(resolvedURI), aInput, nullptr, baseURI);
98
0
  if (NS_WARN_IF(aRv.Failed())) {
99
0
    aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
100
0
  }
101
0
  return resolvedURI.forget();
102
0
}
103
void
104
GetRequestURLFromDocument(nsIDocument* aDocument, const nsAString& aInput,
105
                          nsAString& aRequestURL, nsACString& aURLfragment,
106
                          ErrorResult& aRv)
107
0
{
108
0
  nsCOMPtr<nsIURI> resolvedURI = ParseURLFromDocument(aDocument, aInput, aRv);
109
0
  if (aRv.Failed()) {
110
0
    return;
111
0
  }
112
0
  // This fails with URIs with weird protocols, even when they are valid,
113
0
  // so we ignore the failure
114
0
  nsAutoCString credentials;
115
0
  Unused << resolvedURI->GetUserPass(credentials);
116
0
  if (!credentials.IsEmpty()) {
117
0
    aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
118
0
    return;
119
0
  }
120
0
121
0
  nsCOMPtr<nsIURI> resolvedURIClone;
122
0
  aRv = NS_GetURIWithoutRef(resolvedURI, getter_AddRefs(resolvedURIClone));
123
0
  if (NS_WARN_IF(aRv.Failed())) {
124
0
    return;
125
0
  }
126
0
  nsAutoCString spec;
127
0
  aRv = resolvedURIClone->GetSpec(spec);
128
0
  if (NS_WARN_IF(aRv.Failed())) {
129
0
    return;
130
0
  }
131
0
  CopyUTF8toUTF16(spec, aRequestURL);
132
0
133
0
  // Get the fragment from nsIURI.
134
0
  aRv = resolvedURI->GetRef(aURLfragment);
135
0
  if (NS_WARN_IF(aRv.Failed())) {
136
0
    return;
137
0
  }
138
0
}
139
already_AddRefed<nsIURI>
140
ParseURLFromChrome(const nsAString& aInput, ErrorResult& aRv)
141
0
{
142
0
  MOZ_ASSERT(NS_IsMainThread());
143
0
  nsCOMPtr<nsIURI> uri;
144
0
  aRv = NS_NewURI(getter_AddRefs(uri), aInput, nullptr, nullptr);
145
0
  if (aRv.Failed()) {
146
0
    aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
147
0
  }
148
0
  return uri.forget();
149
0
}
150
void
151
GetRequestURLFromChrome(const nsAString& aInput, nsAString& aRequestURL,
152
                        nsACString& aURLfragment, ErrorResult& aRv)
153
0
{
154
0
  nsCOMPtr<nsIURI> uri = ParseURLFromChrome(aInput, aRv);
155
0
  if (aRv.Failed()) {
156
0
    return;
157
0
  }
158
0
  // This fails with URIs with weird protocols, even when they are valid,
159
0
  // so we ignore the failure
160
0
  nsAutoCString credentials;
161
0
  Unused << uri->GetUserPass(credentials);
162
0
  if (!credentials.IsEmpty()) {
163
0
    aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
164
0
    return;
165
0
  }
166
0
167
0
  nsCOMPtr<nsIURI> uriClone;
168
0
  aRv = NS_GetURIWithoutRef(uri, getter_AddRefs(uriClone));
169
0
  if (NS_WARN_IF(aRv.Failed())) {
170
0
    return;
171
0
  }
172
0
  nsAutoCString spec;
173
0
  aRv = uriClone->GetSpec(spec);
174
0
  if (NS_WARN_IF(aRv.Failed())) {
175
0
    return;
176
0
  }
177
0
  CopyUTF8toUTF16(spec, aRequestURL);
178
0
179
0
  // Get the fragment from nsIURI.
180
0
  aRv = uri->GetRef(aURLfragment);
181
0
  if (NS_WARN_IF(aRv.Failed())) {
182
0
    return;
183
0
  }
184
0
}
185
already_AddRefed<URL>
186
ParseURLFromWorker(const GlobalObject& aGlobal, const nsAString& aInput,
187
                   ErrorResult& aRv)
188
0
{
189
0
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
190
0
  MOZ_ASSERT(worker);
191
0
  worker->AssertIsOnWorkerThread();
192
0
193
0
  NS_ConvertUTF8toUTF16 baseURL(worker->GetLocationInfo().mHref);
194
0
  RefPtr<URL> url = URL::WorkerConstructor(aGlobal, aInput, baseURL, aRv);
195
0
  if (NS_WARN_IF(aRv.Failed())) {
196
0
    aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
197
0
  }
198
0
  return url.forget();
199
0
}
200
void
201
GetRequestURLFromWorker(const GlobalObject& aGlobal, const nsAString& aInput,
202
                        nsAString& aRequestURL, nsACString& aURLfragment,
203
                        ErrorResult& aRv)
204
0
{
205
0
  RefPtr<URL> url = ParseURLFromWorker(aGlobal, aInput, aRv);
206
0
  if (aRv.Failed()) {
207
0
    return;
208
0
  }
209
0
  nsString username;
210
0
  url->GetUsername(username);
211
0
212
0
  nsString password;
213
0
  url->GetPassword(password);
214
0
215
0
  if (!username.IsEmpty() || !password.IsEmpty()) {
216
0
    aRv.ThrowTypeError<MSG_URL_HAS_CREDENTIALS>(aInput);
217
0
    return;
218
0
  }
219
0
220
0
  // Get the fragment from URL.
221
0
  nsAutoString fragment;
222
0
  url->GetHash(fragment);
223
0
224
0
  // Note: URL::GetHash() includes the "#" and we want the fragment with out
225
0
  // the hash symbol.
226
0
  if (!fragment.IsEmpty()) {
227
0
    CopyUTF16toUTF8(Substring(fragment, 1), aURLfragment);
228
0
  }
229
0
230
0
  url->SetHash(EmptyString());
231
0
  url->Stringify(aRequestURL);
232
0
}
233
234
class ReferrerSameOriginChecker final : public WorkerMainThreadRunnable
235
{
236
public:
237
  ReferrerSameOriginChecker(WorkerPrivate* aWorkerPrivate,
238
                            const nsAString& aReferrerURL,
239
                            nsresult& aResult)
240
    : WorkerMainThreadRunnable(aWorkerPrivate,
241
                               NS_LITERAL_CSTRING("Fetch :: Referrer same origin check")),
242
      mReferrerURL(aReferrerURL),
243
      mResult(aResult)
244
0
  {
245
0
    mWorkerPrivate->AssertIsOnWorkerThread();
246
0
  }
247
248
  bool
249
  MainThreadRun() override
250
0
  {
251
0
    nsCOMPtr<nsIURI> uri;
252
0
    if (NS_SUCCEEDED(NS_NewURI(getter_AddRefs(uri), mReferrerURL))) {
253
0
      nsCOMPtr<nsIPrincipal> principal = mWorkerPrivate->GetPrincipal();
254
0
      if (principal) {
255
0
        mResult = principal->CheckMayLoad(uri, /* report */ false,
256
0
                                          /* allowIfInheritsPrincipal */ false);
257
0
      }
258
0
    }
259
0
    return true;
260
0
  }
261
262
private:
263
  const nsString mReferrerURL;
264
  nsresult& mResult;
265
};
266
267
} // namespace
268
269
/*static*/ already_AddRefed<Request>
270
Request::Constructor(const GlobalObject& aGlobal,
271
                     const RequestOrUSVString& aInput,
272
                     const RequestInit& aInit, ErrorResult& aRv)
273
0
{
274
0
  bool hasCopiedBody = false;
275
0
  RefPtr<InternalRequest> request;
276
0
277
0
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
278
0
279
0
  RefPtr<AbortSignal> signal;
280
0
281
0
  if (aInput.IsRequest()) {
282
0
    RefPtr<Request> inputReq = &aInput.GetAsRequest();
283
0
    nsCOMPtr<nsIInputStream> body;
284
0
    inputReq->GetBody(getter_AddRefs(body));
285
0
    if (inputReq->BodyUsed()) {
286
0
      aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
287
0
      return nullptr;
288
0
    }
289
0
290
0
    // The body will be copied when GetRequestConstructorCopy() is executed.
291
0
    if (body) {
292
0
      hasCopiedBody = true;
293
0
    }
294
0
295
0
    request = inputReq->GetInternalRequest();
296
0
    signal = inputReq->GetOrCreateSignal();
297
0
  } else {
298
0
    // aInput is USVString.
299
0
    // We need to get url before we create a InternalRequest.
300
0
    nsAutoString input;
301
0
    input.Assign(aInput.GetAsUSVString());
302
0
    nsAutoString requestURL;
303
0
    nsCString fragment;
304
0
    if (NS_IsMainThread()) {
305
0
      nsCOMPtr<nsPIDOMWindowInner> inner(do_QueryInterface(global));
306
0
      nsIDocument* doc = inner ? inner->GetExtantDoc() : nullptr;
307
0
      if (doc) {
308
0
        GetRequestURLFromDocument(doc, input, requestURL, fragment, aRv);
309
0
      } else {
310
0
        // If we don't have a document, we must assume that this is a full URL.
311
0
        GetRequestURLFromChrome(input, requestURL, fragment, aRv);
312
0
      }
313
0
    } else {
314
0
      GetRequestURLFromWorker(aGlobal, input, requestURL, fragment, aRv);
315
0
    }
316
0
    if (aRv.Failed()) {
317
0
      return nullptr;
318
0
    }
319
0
    request = new InternalRequest(NS_ConvertUTF16toUTF8(requestURL), fragment);
320
0
  }
321
0
  request = request->GetRequestConstructorCopy(global, aRv);
322
0
  if (NS_WARN_IF(aRv.Failed())) {
323
0
    return nullptr;
324
0
  }
325
0
  RequestMode fallbackMode = RequestMode::EndGuard_;
326
0
  RequestCredentials fallbackCredentials = RequestCredentials::EndGuard_;
327
0
  RequestCache fallbackCache = RequestCache::EndGuard_;
328
0
  if (aInput.IsUSVString()) {
329
0
    fallbackMode = RequestMode::Cors;
330
0
    fallbackCredentials = RequestCredentials::Same_origin;
331
0
    fallbackCache = RequestCache::Default;
332
0
  }
333
0
334
0
  RequestMode mode = aInit.mMode.WasPassed() ? aInit.mMode.Value() : fallbackMode;
335
0
  RequestCredentials credentials =
336
0
    aInit.mCredentials.WasPassed() ? aInit.mCredentials.Value()
337
0
                                   : fallbackCredentials;
338
0
339
0
  if (mode == RequestMode::Navigate ||
340
0
      (aInit.IsAnyMemberPresent() && request->Mode() == RequestMode::Navigate)) {
341
0
    mode = RequestMode::Same_origin;
342
0
  }
343
0
344
0
  if (aInit.IsAnyMemberPresent()) {
345
0
    request->SetReferrer(NS_LITERAL_STRING(kFETCH_CLIENT_REFERRER_STR));
346
0
    request->SetReferrerPolicy(ReferrerPolicy::_empty);
347
0
  }
348
0
  if (aInit.mReferrer.WasPassed()) {
349
0
    const nsString& referrer = aInit.mReferrer.Value();
350
0
    if (referrer.IsEmpty()) {
351
0
      request->SetReferrer(NS_LITERAL_STRING(""));
352
0
    } else {
353
0
      nsAutoString referrerURL;
354
0
      if (NS_IsMainThread()) {
355
0
        nsCOMPtr<nsPIDOMWindowInner> inner(do_QueryInterface(global));
356
0
        nsIDocument* doc = inner ? inner->GetExtantDoc() : nullptr;
357
0
        nsCOMPtr<nsIURI> uri;
358
0
        if (doc) {
359
0
          uri = ParseURLFromDocument(doc, referrer, aRv);
360
0
        } else {
361
0
          // If we don't have a document, we must assume that this is a full URL.
362
0
          uri = ParseURLFromChrome(referrer, aRv);
363
0
        }
364
0
        if (NS_WARN_IF(aRv.Failed())) {
365
0
          aRv.ThrowTypeError<MSG_INVALID_REFERRER_URL>(referrer);
366
0
          return nullptr;
367
0
        }
368
0
        nsAutoCString spec;
369
0
        uri->GetSpec(spec);
370
0
        CopyUTF8toUTF16(spec, referrerURL);
371
0
        if (!referrerURL.EqualsLiteral(kFETCH_CLIENT_REFERRER_STR)) {
372
0
          nsCOMPtr<nsIPrincipal> principal = global->PrincipalOrNull();
373
0
          if (principal) {
374
0
            nsresult rv = principal->CheckMayLoad(uri, /* report */ false,
375
0
                                                  /* allowIfInheritsPrincipal */ false);
376
0
            if (NS_FAILED(rv)) {
377
0
              referrerURL.AssignLiteral(kFETCH_CLIENT_REFERRER_STR);
378
0
            }
379
0
          }
380
0
        }
381
0
      } else {
382
0
        RefPtr<URL> url = ParseURLFromWorker(aGlobal, referrer, aRv);
383
0
        if (NS_WARN_IF(aRv.Failed())) {
384
0
          aRv.ThrowTypeError<MSG_INVALID_REFERRER_URL>(referrer);
385
0
          return nullptr;
386
0
        }
387
0
        url->Stringify(referrerURL);
388
0
        if (!referrerURL.EqualsLiteral(kFETCH_CLIENT_REFERRER_STR)) {
389
0
          WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
390
0
          nsresult rv = NS_OK;
391
0
          // ReferrerSameOriginChecker uses a sync loop to get the main thread
392
0
          // to perform the same-origin check.  Overall, on Workers this method
393
0
          // can create 3 sync loops (two for constructing URLs and one here) so
394
0
          // in the future we may want to optimize it all by off-loading all of
395
0
          // this work in a single sync loop.
396
0
          RefPtr<ReferrerSameOriginChecker> checker =
397
0
            new ReferrerSameOriginChecker(worker, referrerURL, rv);
398
0
          IgnoredErrorResult error;
399
0
          checker->Dispatch(Canceling, error);
400
0
          if (error.Failed() || NS_FAILED(rv)) {
401
0
            referrerURL.AssignLiteral(kFETCH_CLIENT_REFERRER_STR);
402
0
          }
403
0
        }
404
0
      }
405
0
      request->SetReferrer(referrerURL);
406
0
    }
407
0
  }
408
0
409
0
  if (aInit.mReferrerPolicy.WasPassed()) {
410
0
    request->SetReferrerPolicy(aInit.mReferrerPolicy.Value());
411
0
  }
412
0
413
0
  if (aInit.mSignal.WasPassed()) {
414
0
    signal = aInit.mSignal.Value();
415
0
  }
416
0
417
0
  if (NS_IsMainThread()) {
418
0
    nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);
419
0
    if (window) {
420
0
      nsCOMPtr<nsIDocument> doc;
421
0
      doc = window->GetExtantDoc();
422
0
      if (doc) {
423
0
        request->SetEnvironmentReferrerPolicy(doc->GetReferrerPolicy());
424
0
      }
425
0
    }
426
0
  } else {
427
0
    WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
428
0
    if (worker) {
429
0
      worker->AssertIsOnWorkerThread();
430
0
      request->SetEnvironmentReferrerPolicy(worker->GetReferrerPolicy());
431
0
    }
432
0
  }
433
0
434
0
  if (mode != RequestMode::EndGuard_) {
435
0
    request->ClearCreatedByFetchEvent();
436
0
    request->SetMode(mode);
437
0
  }
438
0
439
0
  if (credentials != RequestCredentials::EndGuard_) {
440
0
    request->ClearCreatedByFetchEvent();
441
0
    request->SetCredentialsMode(credentials);
442
0
  }
443
0
444
0
  RequestCache cache = aInit.mCache.WasPassed() ?
445
0
                       aInit.mCache.Value() : fallbackCache;
446
0
  if (cache != RequestCache::EndGuard_) {
447
0
    if (cache == RequestCache::Only_if_cached &&
448
0
        request->Mode() != RequestMode::Same_origin) {
449
0
      uint32_t t = static_cast<uint32_t>(request->Mode());
450
0
      NS_ConvertASCIItoUTF16 modeString(RequestModeValues::strings[t].value,
451
0
                                        RequestModeValues::strings[t].length);
452
0
      aRv.ThrowTypeError<MSG_ONLY_IF_CACHED_WITHOUT_SAME_ORIGIN>(modeString);
453
0
      return nullptr;
454
0
    }
455
0
    request->ClearCreatedByFetchEvent();
456
0
    request->SetCacheMode(cache);
457
0
  }
458
0
459
0
  if (aInit.mRedirect.WasPassed()) {
460
0
    request->SetRedirectMode(aInit.mRedirect.Value());
461
0
  }
462
0
463
0
  if (aInit.mIntegrity.WasPassed()) {
464
0
    request->SetIntegrity(aInit.mIntegrity.Value());
465
0
  }
466
0
467
0
  if (aInit.mMozErrors.WasPassed() && aInit.mMozErrors.Value()) {
468
0
    request->SetMozErrors();
469
0
  }
470
0
471
0
  // Request constructor step 14.
472
0
  if (aInit.mMethod.WasPassed()) {
473
0
    nsAutoCString method(aInit.mMethod.Value());
474
0
475
0
    // Step 14.1. Disallow forbidden methods, and anything that is not a HTTP
476
0
    // token, since HTTP states that Method may be any of the defined values or
477
0
    // a token (extension method).
478
0
    nsAutoCString outMethod;
479
0
    nsresult rv = FetchUtil::GetValidRequestMethod(method, outMethod);
480
0
    if (NS_FAILED(rv)) {
481
0
      NS_ConvertUTF8toUTF16 label(method);
482
0
      aRv.ThrowTypeError<MSG_INVALID_REQUEST_METHOD>(label);
483
0
      return nullptr;
484
0
    }
485
0
486
0
    // Step 14.2
487
0
    request->ClearCreatedByFetchEvent();
488
0
    request->SetMethod(outMethod);
489
0
  }
490
0
491
0
  RefPtr<InternalHeaders> requestHeaders = request->Headers();
492
0
493
0
  RefPtr<InternalHeaders> headers;
494
0
  if (aInit.mHeaders.WasPassed()) {
495
0
    RefPtr<Headers> h = Headers::Constructor(aGlobal, aInit.mHeaders.Value(), aRv);
496
0
    if (aRv.Failed()) {
497
0
      return nullptr;
498
0
    }
499
0
    request->ClearCreatedByFetchEvent();
500
0
    headers = h->GetInternalHeaders();
501
0
  } else {
502
0
    headers = new InternalHeaders(*requestHeaders);
503
0
  }
504
0
505
0
  requestHeaders->Clear();
506
0
  // From "Let r be a new Request object associated with request and a new
507
0
  // Headers object whose guard is "request"."
508
0
  requestHeaders->SetGuard(HeadersGuardEnum::Request, aRv);
509
0
  MOZ_ASSERT(!aRv.Failed());
510
0
511
0
  if (request->Mode() == RequestMode::No_cors) {
512
0
    if (!request->HasSimpleMethod()) {
513
0
      nsAutoCString method;
514
0
      request->GetMethod(method);
515
0
      NS_ConvertUTF8toUTF16 label(method);
516
0
      aRv.ThrowTypeError<MSG_INVALID_REQUEST_METHOD>(label);
517
0
      return nullptr;
518
0
    }
519
0
520
0
    requestHeaders->SetGuard(HeadersGuardEnum::Request_no_cors, aRv);
521
0
    if (aRv.Failed()) {
522
0
      return nullptr;
523
0
    }
524
0
  }
525
0
526
0
  requestHeaders->Fill(*headers, aRv);
527
0
  if (aRv.Failed()) {
528
0
    return nullptr;
529
0
  }
530
0
531
0
  if ((aInit.mBody.WasPassed() && !aInit.mBody.Value().IsNull()) ||
532
0
      hasCopiedBody) {
533
0
    // HEAD and GET are not allowed to have a body.
534
0
    nsAutoCString method;
535
0
    request->GetMethod(method);
536
0
    // method is guaranteed to be uppercase due to step 14.2 above.
537
0
    if (method.EqualsLiteral("HEAD") || method.EqualsLiteral("GET")) {
538
0
      aRv.ThrowTypeError<MSG_NO_BODY_ALLOWED_FOR_GET_AND_HEAD>();
539
0
      return nullptr;
540
0
    }
541
0
  }
542
0
543
0
  if (aInit.mBody.WasPassed()) {
544
0
    const Nullable<fetch::OwningBodyInit>& bodyInitNullable = aInit.mBody.Value();
545
0
    if (!bodyInitNullable.IsNull()) {
546
0
      const fetch::OwningBodyInit& bodyInit = bodyInitNullable.Value();
547
0
      nsCOMPtr<nsIInputStream> stream;
548
0
      nsAutoCString contentTypeWithCharset;
549
0
      uint64_t contentLength = 0;
550
0
      aRv = ExtractByteStreamFromBody(bodyInit,
551
0
                                      getter_AddRefs(stream),
552
0
                                      contentTypeWithCharset,
553
0
                                      contentLength);
554
0
      if (NS_WARN_IF(aRv.Failed())) {
555
0
        return nullptr;
556
0
      }
557
0
558
0
      nsCOMPtr<nsIInputStream> temporaryBody = stream;
559
0
560
0
      if (!contentTypeWithCharset.IsVoid() &&
561
0
          !requestHeaders->Has(NS_LITERAL_CSTRING("Content-Type"), aRv)) {
562
0
        requestHeaders->Append(NS_LITERAL_CSTRING("Content-Type"),
563
0
                               contentTypeWithCharset, aRv);
564
0
      }
565
0
566
0
      if (NS_WARN_IF(aRv.Failed())) {
567
0
        return nullptr;
568
0
      }
569
0
570
0
      request->ClearCreatedByFetchEvent();
571
0
572
0
      if (hasCopiedBody) {
573
0
        request->SetBody(nullptr, 0);
574
0
      }
575
0
576
0
      request->SetBody(temporaryBody, contentLength);
577
0
    }
578
0
  }
579
0
580
0
  RefPtr<Request> domRequest = new Request(global, request, signal);
581
0
  domRequest->SetMimeType();
582
0
583
0
  if (aInput.IsRequest()) {
584
0
    RefPtr<Request> inputReq = &aInput.GetAsRequest();
585
0
    nsCOMPtr<nsIInputStream> body;
586
0
    inputReq->GetBody(getter_AddRefs(body));
587
0
    if (body) {
588
0
      inputReq->SetBody(nullptr, 0);
589
0
      inputReq->SetBodyUsed(aGlobal.Context(), aRv);
590
0
      if (NS_WARN_IF(aRv.Failed())) {
591
0
        return nullptr;
592
0
      }
593
0
    }
594
0
  }
595
0
  return domRequest.forget();
596
0
}
597
598
already_AddRefed<Request>
599
Request::Clone(ErrorResult& aRv)
600
0
{
601
0
  if (BodyUsed()) {
602
0
    aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
603
0
    return nullptr;
604
0
  }
605
0
606
0
  RefPtr<InternalRequest> ir = mRequest->Clone();
607
0
  if (!ir) {
608
0
    aRv.Throw(NS_ERROR_FAILURE);
609
0
    return nullptr;
610
0
  }
611
0
612
0
  RefPtr<Request> request = new Request(mOwner, ir, GetOrCreateSignal());
613
0
614
0
  return request.forget();
615
0
}
616
617
Headers*
618
Request::Headers_()
619
0
{
620
0
  if (!mHeaders) {
621
0
    mHeaders = new Headers(mOwner, mRequest->Headers());
622
0
  }
623
0
624
0
  return mHeaders;
625
0
}
626
627
AbortSignal*
628
Request::GetOrCreateSignal()
629
0
{
630
0
  if (!mSignal) {
631
0
    mSignal = new AbortSignal(mOwner, false);
632
0
  }
633
0
634
0
  return mSignal;
635
0
}
636
637
AbortSignalImpl*
638
Request::GetSignalImpl() const
639
0
{
640
0
  return mSignal;
641
0
}
642
643
} // namespace dom
644
} // namespace mozilla