summaryrefslogtreecommitdiffstats
path: root/dom/file/Blob.cpp
blob: dc3a70c74c848f3bcf2f2c7fd3653cbbd9f0dade (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "Blob.h"
#include "EmptyBlobImpl.h"
#include "File.h"
#include "MemoryBlobImpl.h"
#include "mozilla/dom/BlobBinding.h"
#include "mozilla/dom/ReadableStream.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/HoldDropJSObjects.h"
#include "MultipartBlobImpl.h"
#include "nsCycleCollectionParticipant.h"
#include "nsIGlobalObject.h"
#include "nsIInputStream.h"
#include "nsPIDOMWindow.h"
#include "StreamBlobImpl.h"
#include "StringBlobImpl.h"
#include "js/GCAPI.h"

namespace mozilla::dom {

NS_IMPL_CYCLE_COLLECTION_CLASS(Blob)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Blob)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mGlobal)
  NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Blob)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGlobal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Blob)
  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_TRACE_END

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Blob)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
  NS_INTERFACE_MAP_ENTRY_CONCRETE(Blob)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(Blob)
NS_IMPL_CYCLE_COLLECTING_RELEASE(Blob)

void Blob::MakeValidBlobType(nsAString& aType) {
  char16_t* iter = aType.BeginWriting();
  char16_t* end = aType.EndWriting();

  for (; iter != end; ++iter) {
    char16_t c = *iter;
    if (c < 0x20 || c > 0x7E) {
      // Non-ASCII char, bail out.
      aType.Truncate();
      return;
    }

    if (c >= 'A' && c <= 'Z') {
      *iter = c + ('a' - 'A');
    }
  }
}

/* static */
Blob* Blob::Create(nsIGlobalObject* aGlobal, BlobImpl* aImpl) {
  MOZ_ASSERT(aImpl);

  MOZ_ASSERT(aGlobal);
  if (NS_WARN_IF(!aGlobal)) {
    return nullptr;
  }

  return aImpl->IsFile() ? new File(aGlobal, aImpl) : new Blob(aGlobal, aImpl);
}

/* static */
already_AddRefed<Blob> Blob::CreateStringBlob(nsIGlobalObject* aGlobal,
                                              const nsACString& aData,
                                              const nsAString& aContentType) {
  MOZ_ASSERT(aGlobal);
  if (NS_WARN_IF(!aGlobal)) {
    return nullptr;
  }

  RefPtr<BlobImpl> blobImpl = StringBlobImpl::Create(aData, aContentType);
  RefPtr<Blob> blob = Blob::Create(aGlobal, blobImpl);
  MOZ_ASSERT(!blob->mImpl->IsFile());
  return blob.forget();
}

/* static */
already_AddRefed<Blob> Blob::CreateMemoryBlob(nsIGlobalObject* aGlobal,
                                              void* aMemoryBuffer,
                                              uint64_t aLength,
                                              const nsAString& aContentType) {
  MOZ_ASSERT(aGlobal);
  if (NS_WARN_IF(!aGlobal)) {
    return nullptr;
  }

  RefPtr<Blob> blob = Blob::Create(
      aGlobal, new MemoryBlobImpl(aMemoryBuffer, aLength, aContentType));
  MOZ_ASSERT(!blob->mImpl->IsFile());
  return blob.forget();
}

Blob::Blob(nsIGlobalObject* aGlobal, BlobImpl* aImpl)
    : mImpl(aImpl), mGlobal(aGlobal) {
  MOZ_ASSERT(mImpl);
  MOZ_ASSERT(mGlobal);
}

Blob::~Blob() = default;

bool Blob::IsFile() const { return mImpl->IsFile(); }

const nsTArray<RefPtr<BlobImpl>>* Blob::GetSubBlobImpls() const {
  return mImpl->GetSubBlobImpls();
}

already_AddRefed<File> Blob::ToFile() {
  if (!mImpl->IsFile()) {
    return nullptr;
  }

  RefPtr<File> file;
  if (HasFileInterface()) {
    file = static_cast<File*>(this);
  } else {
    file = new File(mGlobal, mImpl);
  }

  return file.forget();
}

already_AddRefed<File> Blob::ToFile(const nsAString& aName,
                                    ErrorResult& aRv) const {
  AutoTArray<RefPtr<BlobImpl>, 1> blobImpls({mImpl});

  nsAutoString contentType;
  mImpl->GetType(contentType);

  RefPtr<MultipartBlobImpl> impl =
      MultipartBlobImpl::Create(std::move(blobImpls), aName, contentType,
                                mGlobal->GetRTPCallerType(), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  RefPtr<File> file = new File(mGlobal, impl);
  return file.forget();
}

already_AddRefed<Blob> Blob::CreateSlice(uint64_t aStart, uint64_t aLength,
                                         const nsAString& aContentType,
                                         ErrorResult& aRv) const {
  RefPtr<BlobImpl> impl =
      mImpl->CreateSlice(aStart, aLength, aContentType, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  RefPtr<Blob> blob = Blob::Create(mGlobal, impl);
  return blob.forget();
}

uint64_t Blob::GetSize(ErrorResult& aRv) { return mImpl->GetSize(aRv); }

void Blob::GetType(nsAString& aType) { mImpl->GetType(aType); }

void Blob::GetBlobImplType(nsAString& aBlobImplType) {
  mImpl->GetBlobImplType(aBlobImplType);
}

already_AddRefed<Blob> Blob::Slice(const Optional<int64_t>& aStart,
                                   const Optional<int64_t>& aEnd,
                                   const Optional<nsAString>& aContentType,
                                   ErrorResult& aRv) {
  nsAutoString contentType;
  if (aContentType.WasPassed()) {
    contentType = aContentType.Value();
  }

  RefPtr<BlobImpl> impl = mImpl->Slice(aStart, aEnd, contentType, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  RefPtr<Blob> blob = Blob::Create(mGlobal, impl);
  return blob.forget();
}

size_t Blob::GetAllocationSize() const { return mImpl->GetAllocationSize(); }

// contentTypeWithCharset can be set to the contentType or
// contentType+charset based on what the spec says.
// See: https://fetch.spec.whatwg.org/#concept-bodyinit-extract
nsresult Blob::GetSendInfo(nsIInputStream** aBody, uint64_t* aContentLength,
                           nsACString& aContentType,
                           nsACString& aCharset) const {
  return mImpl->GetSendInfo(aBody, aContentLength, aContentType, aCharset);
}

JSObject* Blob::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
  return Blob_Binding::Wrap(aCx, this, aGivenProto);
}

/* static */
already_AddRefed<Blob> Blob::Constructor(
    const GlobalObject& aGlobal, const Optional<Sequence<BlobPart>>& aData,
    const BlobPropertyBag& aBag, ErrorResult& aRv) {
  RefPtr<MultipartBlobImpl> impl = new MultipartBlobImpl();

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  MOZ_ASSERT(global);
  if (aData.WasPassed()) {
    nsAutoString type(aBag.mType);
    MakeValidBlobType(type);
    impl->InitializeBlob(aData.Value(), type,
                         aBag.mEndings == EndingType::Native,
                         global->GetRTPCallerType(), aRv);
  } else {
    impl->InitializeBlob(global->GetRTPCallerType(), aRv);
  }

  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  MOZ_ASSERT(!impl->IsFile());

  RefPtr<Blob> blob = Blob::Create(global, impl);
  return blob.forget();
}

int64_t Blob::GetFileId() const { return mImpl->GetFileId(); }

bool Blob::IsMemoryFile() const { return mImpl->IsMemoryFile(); }

void Blob::CreateInputStream(nsIInputStream** aStream, ErrorResult& aRv) const {
  mImpl->CreateInputStream(aStream, aRv);
}

size_t BindingJSObjectMallocBytes(Blob* aBlob) {
  MOZ_ASSERT(aBlob);

  // TODO: The hazard analysis currently can't see that none of the
  // implementations of the GetAllocationSize virtual method call can GC (see
  // bug 1531951).
  JS::AutoSuppressGCAnalysis nogc;

  return aBlob->GetAllocationSize();
}

already_AddRefed<Promise> Blob::Text(ErrorResult& aRv) const {
  return ConsumeBody(BodyConsumer::CONSUME_TEXT, aRv);
}

already_AddRefed<Promise> Blob::ArrayBuffer(ErrorResult& aRv) const {
  return ConsumeBody(BodyConsumer::CONSUME_ARRAYBUFFER, aRv);
}

already_AddRefed<Promise> Blob::ConsumeBody(
    BodyConsumer::ConsumeType aConsumeType, ErrorResult& aRv) const {
  if (NS_WARN_IF(!mGlobal)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsISerialEventTarget> mainThreadEventTarget;
  if (!NS_IsMainThread()) {
    WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(workerPrivate);
    mainThreadEventTarget = workerPrivate->MainThreadEventTarget();
  } else {
    mainThreadEventTarget = mGlobal->EventTargetFor(TaskCategory::Other);
  }

  MOZ_ASSERT(mainThreadEventTarget);

  nsCOMPtr<nsIInputStream> inputStream;
  CreateInputStream(getter_AddRefs(inputStream), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  return BodyConsumer::Create(mGlobal, mainThreadEventTarget, inputStream,
                              nullptr, aConsumeType, VoidCString(),
                              VoidString(), VoidCString(), VoidCString(),
                              MutableBlobStorage::eOnlyInMemory, aRv);
}

// https://w3c.github.io/FileAPI/#stream-method-algo
// "The stream() method, when invoked, must return the result of calling get
// stream on this."
// And that's https://w3c.github.io/FileAPI/#blob-get-stream.
already_AddRefed<ReadableStream> Blob::Stream(JSContext* aCx,
                                              ErrorResult& aRv) const {
  nsCOMPtr<nsIInputStream> stream;
  CreateInputStream(getter_AddRefs(stream), aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  if (NS_WARN_IF(!mGlobal)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  auto algorithms =
      MakeRefPtr<NonAsyncInputToReadableStreamAlgorithms>(*stream);

  // Step 1: Let stream be a new ReadableStream created in blob’s relevant
  // Realm.
  // Step 2: Set up stream with byte reading support.
  // Step 3: ...
  // (The spec here does not define pullAlgorithm and instead greedily enqueues
  // everything into the stream when .stream() is called, but here we only reads
  // the data when actual read request happens, via
  // InputToReadableStreamAlgorithms. See
  // https://github.com/w3c/FileAPI/issues/194.)
  RefPtr<ReadableStream> body = ReadableStream::CreateByteNative(
      aCx, mGlobal, *algorithms, Nothing(), aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  return body.forget();
}

}  // namespace mozilla::dom