Skip to main content

script/dom/file/
blob.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::ptr;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use encoding_rs::UTF_8;
10use js::context::{JSContext, NoGC};
11use js::jsapi::JSObject;
12use js::realm::CurrentRealm;
13use js::rust::HandleObject;
14use js::typedarray::{ArrayBufferU8, Uint8};
15use net_traits::filemanager_thread::RelativePos;
16use rustc_hash::FxHashMap;
17use script_bindings::reflector::{Reflector, reflect_weak_referenceable_dom_object_with_proto};
18use servo_base::id::{BlobId, BlobIndex};
19use servo_constellation_traits::{BlobData, BlobImpl};
20use uuid::Uuid;
21
22use crate::dom::bindings::buffer_source::{create_buffer_source, get_buffer_source_slice};
23use crate::dom::bindings::codegen::Bindings::BlobBinding;
24use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
25use crate::dom::bindings::codegen::UnionTypes::{
26    ArrayBufferOrArrayBufferViewOrBlobOrString, ArrayBufferViewOrArrayBuffer,
27};
28use crate::dom::bindings::error::{Error, Fallible};
29use crate::dom::bindings::reflector::DomGlobal;
30use crate::dom::bindings::root::DomRoot;
31use crate::dom::bindings::serializable::Serializable;
32use crate::dom::bindings::str::DOMString;
33use crate::dom::bindings::structuredclone::StructuredData;
34use crate::dom::encoding::textdecoderstream::TextDecoderStream;
35use crate::dom::globalscope::GlobalScope;
36use crate::dom::promise::Promise;
37use crate::dom::stream::readablestream::{ReadableStream, pipe_through};
38
39/// <https://w3c.github.io/FileAPI/#dfn-Blob>
40#[dom_struct]
41pub(crate) struct Blob {
42    reflector_: Reflector,
43    #[no_trace]
44    blob_id: BlobId,
45}
46
47impl Blob {
48    pub(crate) fn new(
49        cx: &mut JSContext,
50        global: &GlobalScope,
51        blob_impl: BlobImpl,
52    ) -> DomRoot<Blob> {
53        Self::new_with_proto(cx, global, None, blob_impl)
54    }
55
56    fn new_with_proto(
57        cx: &mut JSContext,
58        global: &GlobalScope,
59        proto: Option<HandleObject>,
60        blob_impl: BlobImpl,
61    ) -> DomRoot<Blob> {
62        let dom_blob = reflect_weak_referenceable_dom_object_with_proto(
63            cx,
64            Rc::new(Blob::new_inherited(&blob_impl)),
65            global,
66            proto,
67        );
68        global.track_blob(&dom_blob, blob_impl);
69        dom_blob
70    }
71
72    pub(crate) fn new_inherited(blob_impl: &BlobImpl) -> Blob {
73        Blob {
74            reflector_: Reflector::new(),
75            blob_id: blob_impl.blob_id(),
76        }
77    }
78
79    /// Get a slice to inner data, this might incur synchronous read and caching
80    pub(crate) fn get_bytes(&self) -> Result<Vec<u8>, ()> {
81        self.global().get_blob_bytes(&self.blob_id)
82    }
83
84    /// Get a copy of the type_string
85    pub(crate) fn type_string(&self) -> String {
86        self.global().get_blob_type_string(&self.blob_id)
87    }
88
89    /// Get a FileID representing the Blob content,
90    /// used by URL.createObjectURL
91    pub(crate) fn get_blob_url_id(&self) -> Uuid {
92        self.global().get_blob_url_id(&self.blob_id)
93    }
94
95    /// <https://w3c.github.io/FileAPI/#blob-get-stream>
96    pub(crate) fn get_stream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
97        self.global().get_blob_stream(cx, &self.blob_id)
98    }
99}
100
101impl Serializable for Blob {
102    type Index = BlobIndex;
103    type Data = BlobImpl;
104
105    /// <https://w3c.github.io/FileAPI/#ref-for-serialization-steps>
106    fn serialize(&self, _no_gc: &NoGC) -> Result<(BlobId, BlobImpl), ()> {
107        let blob_id = self.blob_id;
108
109        // 1. Get a clone of the blob impl.
110        let blob_impl = self.global().serialize_blob(&blob_id);
111
112        // We clone the data, but the clone gets its own Id.
113        let new_blob_id = blob_impl.blob_id();
114
115        Ok((new_blob_id, blob_impl))
116    }
117
118    /// <https://w3c.github.io/FileAPI/#ref-for-deserialization-steps>
119    fn deserialize(
120        cx: &mut JSContext,
121        owner: &GlobalScope,
122        serialized: BlobImpl,
123    ) -> Result<DomRoot<Self>, ()> {
124        Ok(Blob::new(cx, owner, serialized))
125    }
126
127    fn serialized_storage<'a>(
128        reader: StructuredData<'a, '_>,
129    ) -> &'a mut Option<FxHashMap<BlobId, Self::Data>> {
130        match reader {
131            StructuredData::Reader(r) => &mut r.blob_impls,
132            StructuredData::Writer(w) => &mut w.blobs,
133        }
134    }
135}
136
137/// <https://w3c.github.io/FileAPI/#convert-line-endings-to-native>
138fn convert_line_endings_to_native(s: &[u8]) -> Vec<u8> {
139    let native_line_ending: &[u8] = if cfg!(target_os = "windows") {
140        // Step 2. If the underlying platform’s conventions are to represent newlines
141        // as a carriage return and line feed sequence,
142        // set native line ending to the code point U+000D CR followed by the code point U+000A LF.
143        b"\r\n"
144    } else {
145        // Step 1. Let native line ending be the code point U+000A LF.
146        b"\n"
147    };
148
149    let len = s.len();
150    // Step 3. Set result to the empty string.
151    let mut result = Vec::with_capacity(len);
152
153    // Step 4. Let position be a position variable for s, initially pointing at the start of s.
154    let mut position = 0;
155
156    // <https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points>
157    let collect_a_sequence_of_code_points = |position: &mut usize| -> &[u8] {
158        let start = *position;
159        while *position < len && s[*position] != b'\r' && s[*position] != b'\n' {
160            *position += 1;
161        }
162        &s[start..*position]
163    };
164
165    // Step 5: Let token be the result of collecting a sequence of code points
166    // that are not equal to U+000A LF or U+000D CR from s given position.
167    // Step 6: Append token to result.
168    result.extend_from_slice(collect_a_sequence_of_code_points(&mut position));
169
170    // Step 7: While position is not past the end of s:
171    while position < len {
172        let byte = s[position];
173        // Step 7.1: If the code point at position within s equals U+000D CR:
174        if byte == b'\r' {
175            // Step 7.1.1: Append native line ending to result.
176            result.extend_from_slice(native_line_ending);
177            // Step 7.1.2: Advance position by 1.
178            position += 1;
179            // Step 7.1.3: If position is not past the end of s and the code point
180            // at position within s equals U+000A LF, advance position by 1.
181            if position < len && s[position] == b'\n' {
182                position += 1;
183            }
184        }
185        // Step 7.2: Otherwise, if the code point at position within s equals U+000A LF:
186        else if byte == b'\n' {
187            // Advance position by 1 and append native line ending to result.
188            position += 1;
189            result.extend_from_slice(native_line_ending);
190        }
191
192        // Step 7.3: Let token be the result of collecting a sequence of code points
193        // that are not equal to U+000A LF or U+000D CR from s given position.
194        // Step 7.4: Append token to result.
195        result.extend_from_slice(collect_a_sequence_of_code_points(&mut position));
196    }
197
198    // Step 8: Return result.
199    result
200}
201
202/// <https://w3c.github.io/FileAPI/#process-blob-parts>
203pub(crate) fn process_blob_parts(
204    no_gc: &NoGC,
205    blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>,
206    endings: BlobBinding::EndingType,
207) -> Result<Vec<u8>, ()> {
208    // Step 1. Let bytes be an empty sequence of bytes.
209    let mut bytes = vec![];
210    // Step 2. For each blobpart in blobparts:
211    for blobpart in blobparts {
212        match blobpart {
213            // Step 2.1. If blobpart is a USVString, run the following substeps:
214            ArrayBufferOrArrayBufferViewOrBlobOrString::String(s) => {
215                // Step 2.1.1. Let s be blobpart.
216                // Step 2.1.2. If the endings member of options is "native",
217                // set s to the result of converting line endings to native of blobpart.
218                if endings == BlobBinding::EndingType::Native {
219                    let converted = convert_line_endings_to_native(&s.as_bytes());
220                    // Step 2.1.3. Append the result of UTF-8 encoding s to bytes.
221                    bytes.extend(converted);
222                } else {
223                    // Step 2.1.3: Append the result of UTF-8 encoding s to bytes.
224                    bytes.extend_from_slice(&s.as_bytes());
225                }
226            },
227            // Step 2.2. If element is a BufferSource,
228            // get a copy of the bytes held by the buffer source,
229            // and append those bytes to bytes.
230            ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBuffer(a) => {
231                let array_buffer = ArrayBufferViewOrArrayBuffer::ArrayBuffer(a);
232                bytes.extend_from_slice(get_buffer_source_slice(&array_buffer, no_gc));
233            },
234            ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBufferView(a) => {
235                let array_view = ArrayBufferViewOrArrayBuffer::ArrayBufferView(a);
236                bytes.extend_from_slice(get_buffer_source_slice(&array_view, no_gc));
237            },
238            // Step 2.3. If element is a Blob, append the bytes it represents to bytes.
239            ArrayBufferOrArrayBufferViewOrBlobOrString::Blob(b) => {
240                let blob_bytes = b.get_bytes().unwrap_or(vec![]);
241                bytes.extend(blob_bytes);
242            },
243        }
244    }
245
246    // Step 3. Return bytes.
247    Ok(bytes)
248}
249
250impl BlobMethods<crate::DomTypeHolder> for Blob {
251    // https://w3c.github.io/FileAPI/#constructorBlob
252    #[expect(non_snake_case)]
253    fn Constructor(
254        cx: &mut JSContext,
255        global: &GlobalScope,
256        proto: Option<HandleObject>,
257        blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>,
258        blobPropertyBag: &BlobBinding::BlobPropertyBag,
259    ) -> Fallible<DomRoot<Blob>> {
260        let bytes: Vec<u8> = match blobParts {
261            None => Vec::new(),
262            Some(blobparts) => {
263                match process_blob_parts(cx.no_gc(), blobparts, blobPropertyBag.endings) {
264                    Ok(bytes) => bytes,
265                    Err(_) => return Err(Error::InvalidCharacter(None)),
266                }
267            },
268        };
269
270        let type_string = normalize_type_string(&blobPropertyBag.type_.str());
271        let blob_impl = BlobImpl::new_from_bytes(bytes, type_string);
272
273        Ok(Blob::new_with_proto(cx, global, proto, blob_impl))
274    }
275
276    /// <https://w3c.github.io/FileAPI/#dfn-size>
277    fn Size(&self) -> u64 {
278        self.global().get_blob_size(&self.blob_id)
279    }
280
281    /// <https://w3c.github.io/FileAPI/#dfn-type>
282    fn Type(&self) -> DOMString {
283        DOMString::from(self.type_string())
284    }
285
286    // <https://w3c.github.io/FileAPI/#blob-get-stream>
287    fn Stream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
288        self.get_stream(cx)
289    }
290
291    /// <https://w3c.github.io/FileAPI/#text-stream-method-algo>
292    fn TextStream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
293        // Step 1: Let stream be the result of calling get stream on this.
294        let stream = self.get_stream(cx)?;
295        // Step 2: Let decoder be a new TextDecoderStream in this's relevant realm.
296        // Step 3: Set up decoder with UTF-8.
297        let decoder = TextDecoderStream::new_with_proto(
298            cx,
299            &self.global(),
300            None,
301            UTF_8,
302            false, // fatal
303            false, // ignoreBOM
304        )?;
305        // Step 4: Return the result of calling stream, piped through decoder.
306        Ok(pipe_through(&stream, cx, &self.global(), &decoder))
307    }
308
309    /// <https://w3c.github.io/FileAPI/#slice-method-algo>
310    fn Slice(
311        &self,
312        cx: &mut JSContext,
313        start: Option<i64>,
314        end: Option<i64>,
315        content_type: Option<DOMString>,
316    ) -> DomRoot<Blob> {
317        let global = self.global();
318        let type_string = normalize_type_string(&content_type.unwrap_or_default().str());
319
320        // If our parent is already a sliced blob then we reference the data from the grandparent instead,
321        // to keep the blob ancestry chain short.
322        let (parent, range) = match *global.get_blob_data(&self.blob_id) {
323            BlobData::Sliced(grandparent, parent_range) => {
324                let range = RelativePos {
325                    start: parent_range.start + start.unwrap_or_default(),
326                    end: end.map(|end| end + parent_range.start).or(parent_range.end),
327                };
328                (grandparent, range)
329            },
330            _ => (self.blob_id, RelativePos::from_opts(start, end)),
331        };
332
333        let blob_impl = BlobImpl::new_sliced(range, parent, type_string);
334        Blob::new(cx, &global, blob_impl)
335    }
336
337    /// <https://w3c.github.io/FileAPI/#text-method-algo>
338    fn Text(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
339        let global = self.global();
340        let p = Promise::new_in_realm(cx);
341        let id = self.get_blob_url_id();
342        global.read_file_async(
343            id,
344            p.clone(),
345            Box::new(|cx, promise, bytes| match bytes {
346                Ok(b) => {
347                    let (text, _) = UTF_8.decode_with_bom_removal(&b);
348                    let text = DOMString::from(text);
349                    promise.resolve_native(cx, &text);
350                },
351                Err(e) => {
352                    promise.reject_error(cx, e);
353                },
354            }),
355        );
356        p
357    }
358
359    /// <https://w3c.github.io/FileAPI/#arraybuffer-method-algo>
360    fn ArrayBuffer(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
361        let promise = Promise::new_in_realm(cx);
362
363        // 1. Let stream be the result of calling get stream on this.
364        let stream = self.get_stream(cx);
365
366        // 2. Let reader be the result of getting a reader from stream.
367        //    If that threw an exception, return a new promise rejected with that exception.
368        let reader = match stream.and_then(|s| s.acquire_default_reader(cx)) {
369            Ok(reader) => reader,
370            Err(error) => {
371                promise.reject_error(cx, error);
372                return promise;
373            },
374        };
375
376        // 3. Let promise be the result of reading all bytes from stream with reader.
377        let success_promise = promise.clone();
378        let failure_promise = promise.clone();
379        reader.read_all_bytes(
380            cx,
381            Rc::new(move |cx, bytes| {
382                rooted!(&in(cx) let mut js_object = ptr::null_mut::<JSObject>());
383                // 4. Return the result of transforming promise by a fulfillment handler that returns a new
384                //    [ArrayBuffer]
385                let array_buffer =
386                    create_buffer_source::<ArrayBufferU8>(cx, bytes, js_object.handle_mut())
387                        .expect("Converting input to ArrayBufferU8 should never fail");
388                success_promise.resolve_native(cx, &array_buffer);
389            }),
390            Rc::new(move |cx, value| {
391                failure_promise.reject(cx, value);
392            }),
393        );
394
395        promise
396    }
397
398    /// <https://w3c.github.io/FileAPI/#dom-blob-bytes>
399    fn Bytes(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
400        let p = Promise::new_in_realm(cx);
401
402        // 1. Let stream be the result of calling get stream on this.
403        let stream = self.get_stream(cx);
404
405        // 2. Let reader be the result of getting a reader from stream.
406        //    If that threw an exception, return a new promise rejected with that exception.
407        let reader = match stream.and_then(|s| s.acquire_default_reader(cx)) {
408            Ok(r) => r,
409            Err(e) => {
410                p.reject_error(cx, e);
411                return p;
412            },
413        };
414
415        // 3. Let promise be the result of reading all bytes from stream with reader.
416        let p_success = p.clone();
417        let p_failure = p.clone();
418        reader.read_all_bytes(
419            cx,
420            Rc::new(move |cx, bytes| {
421                rooted!(&in(cx) let mut js_object = ptr::null_mut::<JSObject>());
422                let arr = create_buffer_source::<Uint8>(cx, bytes, js_object.handle_mut())
423                    .expect("Converting input to uint8 array should never fail");
424                p_success.resolve_native(cx, &arr);
425            }),
426            Rc::new(move |cx, v| {
427                p_failure.reject(cx, v);
428            }),
429        );
430        p
431    }
432}
433
434/// Get the normalized, MIME-parsable type string
435/// <https://w3c.github.io/FileAPI/#dfn-type>
436/// XXX: We will relax the restriction here,
437/// since the spec has some problem over this part.
438/// see <https://github.com/w3c/FileAPI/issues/43>
439pub(crate) fn normalize_type_string(s: &str) -> String {
440    if is_ascii_printable(s) {
441        s.to_ascii_lowercase()
442        // match s_lower.parse() as Result<Mime, ()> {
443        // Ok(_) => s_lower,
444        // Err(_) => "".to_string()
445    } else {
446        "".to_string()
447    }
448}
449
450fn is_ascii_printable(string: &str) -> bool {
451    // Step 5.1 in Sec 5.1 of File API spec
452    // <https://w3c.github.io/FileAPI/#constructorBlob>
453    string.chars().all(|c| ('\x20'..='\x7E').contains(&c))
454}