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 "MultipartBlobImpl.h"
8 #include "jsfriendapi.h"
9 #include "mozilla/dom/BlobSet.h"
10 #include "mozilla/dom/FileBinding.h"
11 #include "mozilla/dom/UnionTypes.h"
12 #include "nsComponentManagerUtils.h"
13 #include "nsIMultiplexInputStream.h"
14 #include "nsReadableUtils.h"
15 #include "nsRFPService.h"
16 #include "nsStringStream.h"
17 #include "nsTArray.h"
18 #include "nsJSUtils.h"
19 #include "nsContentUtils.h"
20 #include <algorithm>
21 
22 using namespace mozilla;
23 using namespace mozilla::dom;
24 
25 /* static */
Create(nsTArray<RefPtr<BlobImpl>> && aBlobImpls,const nsAString & aName,const nsAString & aContentType,bool aCrossOriginIsolated,ErrorResult & aRv)26 already_AddRefed<MultipartBlobImpl> MultipartBlobImpl::Create(
27     nsTArray<RefPtr<BlobImpl>>&& aBlobImpls, const nsAString& aName,
28     const nsAString& aContentType, bool aCrossOriginIsolated,
29     ErrorResult& aRv) {
30   RefPtr<MultipartBlobImpl> blobImpl =
31       new MultipartBlobImpl(std::move(aBlobImpls), aName, aContentType);
32   blobImpl->SetLengthAndModifiedDate(Some(aCrossOriginIsolated), aRv);
33   if (NS_WARN_IF(aRv.Failed())) {
34     return nullptr;
35   }
36 
37   return blobImpl.forget();
38 }
39 
40 /* static */
Create(nsTArray<RefPtr<BlobImpl>> && aBlobImpls,const nsAString & aContentType,ErrorResult & aRv)41 already_AddRefed<MultipartBlobImpl> MultipartBlobImpl::Create(
42     nsTArray<RefPtr<BlobImpl>>&& aBlobImpls, const nsAString& aContentType,
43     ErrorResult& aRv) {
44   RefPtr<MultipartBlobImpl> blobImpl =
45       new MultipartBlobImpl(std::move(aBlobImpls), aContentType);
46   blobImpl->SetLengthAndModifiedDate(/* aCrossOriginIsolated */ Nothing(), aRv);
47   if (NS_WARN_IF(aRv.Failed())) {
48     return nullptr;
49   }
50 
51   return blobImpl.forget();
52 }
53 
CreateInputStream(nsIInputStream ** aStream,ErrorResult & aRv)54 void MultipartBlobImpl::CreateInputStream(nsIInputStream** aStream,
55                                           ErrorResult& aRv) {
56   *aStream = nullptr;
57 
58   uint32_t length = mBlobImpls.Length();
59   if (length == 0 || mLength == 0) {
60     aRv = NS_NewCStringInputStream(aStream, ""_ns);
61     return;
62   }
63 
64   if (length == 1) {
65     BlobImpl* blobImpl = mBlobImpls.ElementAt(0);
66     blobImpl->CreateInputStream(aStream, aRv);
67     return;
68   }
69 
70   nsCOMPtr<nsIMultiplexInputStream> stream =
71       do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1");
72   if (NS_WARN_IF(!stream)) {
73     aRv.Throw(NS_ERROR_FAILURE);
74     return;
75   }
76 
77   uint32_t i;
78   for (i = 0; i < length; i++) {
79     nsCOMPtr<nsIInputStream> scratchStream;
80     BlobImpl* blobImpl = mBlobImpls.ElementAt(i).get();
81 
82     // nsIMultiplexInputStream doesn't work well with empty sub streams. Let's
83     // skip the empty blobs.
84     uint32_t size = blobImpl->GetSize(aRv);
85     if (NS_WARN_IF(aRv.Failed())) {
86       return;
87     }
88 
89     if (size == 0) {
90       continue;
91     }
92 
93     blobImpl->CreateInputStream(getter_AddRefs(scratchStream), aRv);
94     if (NS_WARN_IF(aRv.Failed())) {
95       return;
96     }
97 
98     aRv = stream->AppendStream(scratchStream);
99     if (NS_WARN_IF(aRv.Failed())) {
100       return;
101     }
102   }
103 
104   CallQueryInterface(stream, aStream);
105 }
106 
CreateSlice(uint64_t aStart,uint64_t aLength,const nsAString & aContentType,ErrorResult & aRv)107 already_AddRefed<BlobImpl> MultipartBlobImpl::CreateSlice(
108     uint64_t aStart, uint64_t aLength, const nsAString& aContentType,
109     ErrorResult& aRv) {
110   // If we clamped to nothing we create an empty blob
111   nsTArray<RefPtr<BlobImpl>> blobImpls;
112 
113   uint64_t length = aLength;
114   uint64_t skipStart = aStart;
115 
116   // Prune the list of blobs if we can
117   uint32_t i;
118   for (i = 0; length && skipStart && i < mBlobImpls.Length(); i++) {
119     BlobImpl* blobImpl = mBlobImpls[i].get();
120 
121     uint64_t l = blobImpl->GetSize(aRv);
122     if (NS_WARN_IF(aRv.Failed())) {
123       return nullptr;
124     }
125 
126     if (skipStart < l) {
127       uint64_t upperBound = std::min<uint64_t>(l - skipStart, length);
128 
129       RefPtr<BlobImpl> firstBlobImpl =
130           blobImpl->CreateSlice(skipStart, upperBound, aContentType, aRv);
131       if (NS_WARN_IF(aRv.Failed())) {
132         return nullptr;
133       }
134 
135       // Avoid wrapping a single blob inside an MultipartBlobImpl
136       if (length == upperBound) {
137         return firstBlobImpl.forget();
138       }
139 
140       blobImpls.AppendElement(firstBlobImpl);
141       length -= upperBound;
142       i++;
143       break;
144     }
145     skipStart -= l;
146   }
147 
148   // Now append enough blobs until we're done
149   for (; length && i < mBlobImpls.Length(); i++) {
150     BlobImpl* blobImpl = mBlobImpls[i].get();
151 
152     uint64_t l = blobImpl->GetSize(aRv);
153     if (NS_WARN_IF(aRv.Failed())) {
154       return nullptr;
155     }
156 
157     if (length < l) {
158       RefPtr<BlobImpl> lastBlobImpl =
159           blobImpl->CreateSlice(0, length, aContentType, aRv);
160       if (NS_WARN_IF(aRv.Failed())) {
161         return nullptr;
162       }
163 
164       blobImpls.AppendElement(lastBlobImpl);
165     } else {
166       blobImpls.AppendElement(blobImpl);
167     }
168     length -= std::min<uint64_t>(l, length);
169   }
170 
171   // we can create our blob now
172   RefPtr<BlobImpl> impl = Create(std::move(blobImpls), aContentType, aRv);
173   if (NS_WARN_IF(aRv.Failed())) {
174     return nullptr;
175   }
176 
177   return impl.forget();
178 }
179 
InitializeBlob(bool aCrossOriginIsolated,ErrorResult & aRv)180 void MultipartBlobImpl::InitializeBlob(bool aCrossOriginIsolated,
181                                        ErrorResult& aRv) {
182   SetLengthAndModifiedDate(Some(aCrossOriginIsolated), aRv);
183   NS_WARNING_ASSERTION(!aRv.Failed(), "SetLengthAndModifiedDate failed");
184 }
185 
InitializeBlob(const Sequence<Blob::BlobPart> & aData,const nsAString & aContentType,bool aNativeEOL,bool aCrossOriginIsolated,ErrorResult & aRv)186 void MultipartBlobImpl::InitializeBlob(const Sequence<Blob::BlobPart>& aData,
187                                        const nsAString& aContentType,
188                                        bool aNativeEOL,
189                                        bool aCrossOriginIsolated,
190                                        ErrorResult& aRv) {
191   mContentType = aContentType;
192   BlobSet blobSet;
193 
194   for (uint32_t i = 0, len = aData.Length(); i < len; ++i) {
195     const Blob::BlobPart& data = aData[i];
196 
197     if (data.IsBlob()) {
198       RefPtr<Blob> blob = data.GetAsBlob().get();
199       aRv = blobSet.AppendBlobImpl(blob->Impl());
200       if (aRv.Failed()) {
201         return;
202       }
203     }
204 
205     else if (data.IsUSVString()) {
206       aRv = blobSet.AppendString(data.GetAsUSVString(), aNativeEOL);
207       if (aRv.Failed()) {
208         return;
209       }
210     }
211 
212     else if (data.IsArrayBuffer()) {
213       const ArrayBuffer& buffer = data.GetAsArrayBuffer();
214       buffer.ComputeState();
215       aRv = blobSet.AppendVoidPtr(buffer.Data(), buffer.Length());
216       if (aRv.Failed()) {
217         return;
218       }
219     }
220 
221     else if (data.IsArrayBufferView()) {
222       const ArrayBufferView& buffer = data.GetAsArrayBufferView();
223       buffer.ComputeState();
224       aRv = blobSet.AppendVoidPtr(buffer.Data(), buffer.Length());
225       if (aRv.Failed()) {
226         return;
227       }
228     }
229 
230     else {
231       MOZ_CRASH("Impossible blob data type.");
232     }
233   }
234 
235   mBlobImpls = blobSet.GetBlobImpls();
236   SetLengthAndModifiedDate(Some(aCrossOriginIsolated), aRv);
237   NS_WARNING_ASSERTION(!aRv.Failed(), "SetLengthAndModifiedDate failed");
238 }
239 
SetLengthAndModifiedDate(const Maybe<bool> & aCrossOriginIsolated,ErrorResult & aRv)240 void MultipartBlobImpl::SetLengthAndModifiedDate(
241     const Maybe<bool>& aCrossOriginIsolated, ErrorResult& aRv) {
242   MOZ_ASSERT(mLength == MULTIPARTBLOBIMPL_UNKNOWN_LENGTH);
243   MOZ_ASSERT_IF(mIsFile, IsLastModificationDateUnset());
244 
245   uint64_t totalLength = 0;
246   int64_t lastModified = 0;
247   bool lastModifiedSet = false;
248 
249   for (uint32_t index = 0, count = mBlobImpls.Length(); index < count;
250        index++) {
251     RefPtr<BlobImpl>& blob = mBlobImpls[index];
252 
253     uint64_t subBlobLength = blob->GetSize(aRv);
254     if (NS_WARN_IF(aRv.Failed())) {
255       return;
256     }
257 
258     MOZ_ASSERT(UINT64_MAX - subBlobLength >= totalLength);
259     totalLength += subBlobLength;
260 
261     if (blob->IsFile()) {
262       int64_t partLastModified = blob->GetLastModified(aRv);
263       if (NS_WARN_IF(aRv.Failed())) {
264         return;
265       }
266 
267       if (lastModified < partLastModified) {
268         lastModified = partLastModified * PR_USEC_PER_MSEC;
269         lastModifiedSet = true;
270       }
271     }
272   }
273 
274   mLength = totalLength;
275 
276   if (mIsFile) {
277     if (lastModifiedSet) {
278       SetLastModificationDatePrecisely(lastModified);
279     } else {
280       MOZ_ASSERT(aCrossOriginIsolated.isSome());
281 
282       // We cannot use PR_Now() because bug 493756 and, for this reason:
283       //   var x = new Date(); var f = new File(...);
284       //   x.getTime() < f.dateModified.getTime()
285       // could fail.
286       SetLastModificationDate(aCrossOriginIsolated.value(), JS_Now());
287     }
288   }
289 }
290 
GetAllocationSize() const291 size_t MultipartBlobImpl::GetAllocationSize() const {
292   FallibleTArray<BlobImpl*> visitedBlobs;
293 
294   // We want to report the unique blob allocation, avoiding duplicated blobs in
295   // the multipart blob tree.
296   size_t total = 0;
297   for (uint32_t i = 0; i < mBlobImpls.Length(); ++i) {
298     total += mBlobImpls[i]->GetAllocationSize(visitedBlobs);
299   }
300 
301   return total;
302 }
303 
GetAllocationSize(FallibleTArray<BlobImpl * > & aVisitedBlobs) const304 size_t MultipartBlobImpl::GetAllocationSize(
305     FallibleTArray<BlobImpl*>& aVisitedBlobs) const {
306   FallibleTArray<BlobImpl*> visitedBlobs;
307 
308   size_t total = 0;
309   for (BlobImpl* blobImpl : mBlobImpls) {
310     if (!aVisitedBlobs.Contains(blobImpl)) {
311       if (NS_WARN_IF(!aVisitedBlobs.AppendElement(blobImpl, fallible))) {
312         return 0;
313       }
314       total += blobImpl->GetAllocationSize(aVisitedBlobs);
315     }
316   }
317 
318   return total;
319 }
320 
GetBlobImplType(nsAString & aBlobImplType) const321 void MultipartBlobImpl::GetBlobImplType(nsAString& aBlobImplType) const {
322   aBlobImplType.AssignLiteral("MultipartBlobImpl[");
323 
324   StringJoinAppend(aBlobImplType, u", "_ns, mBlobImpls,
325                    [](nsAString& dest, BlobImpl* subBlobImpl) {
326                      nsAutoString blobImplType;
327                      subBlobImpl->GetBlobImplType(blobImplType);
328 
329                      dest.Append(blobImplType);
330                    });
331 
332   aBlobImplType.AppendLiteral("]");
333 }
334 
SetLastModified(int64_t aLastModified)335 void MultipartBlobImpl::SetLastModified(int64_t aLastModified) {
336   SetLastModificationDatePrecisely(aLastModified * PR_USEC_PER_MSEC);
337 }
338