Skip to main content

script/dom/document/
websocket.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::cell::Cell;
6use std::ptr::{self, NonNull};
7use std::rc::Rc;
8
9use dom_struct::dom_struct;
10use js::context::JSContext;
11use js::conversions::ToJSValConvertible;
12use js::jsapi::JSObject;
13use js::jsval::UndefinedValue;
14use js::realm::AutoRealm;
15use js::rust::{CustomAutoRooterGuard, HandleObject};
16use js::typedarray::{ArrayBuffer, ArrayBufferU8, ArrayBufferView};
17use net_traits::blob_url_store::UrlWithBlobClaim;
18use net_traits::request::{
19    CacheMode, CredentialsMode, RedirectMode, Referrer, RequestBuilder, RequestMode,
20    ServiceWorkersMode,
21};
22use net_traits::{
23    CoreResourceMsg, FetchChannels, MessageData, WebSocketDomAction, WebSocketNetworkEvent,
24};
25use profile_traits::generic_callback::GenericCallback as ProfileGenericCallback;
26use script_bindings::cell::DomRefCell;
27use script_bindings::reflector::{DomObject, reflect_weak_referenceable_dom_object_with_proto};
28use servo_base::generic_channel::{LazyCallback, lazy_callback};
29use servo_constellation_traits::BlobImpl;
30use servo_url::{ImmutableOrigin, ServoUrl};
31
32use crate::dom::bindings::buffer_source::create_buffer_source;
33use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
34use crate::dom::bindings::codegen::Bindings::WebSocketBinding::{BinaryType, WebSocketMethods};
35use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
36use crate::dom::bindings::codegen::UnionTypes::StringOrStringSequence;
37use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
38use crate::dom::bindings::inheritance::Castable;
39use crate::dom::bindings::refcounted::Trusted;
40use crate::dom::bindings::reflector::DomGlobal;
41use crate::dom::bindings::root::DomRoot;
42use crate::dom::bindings::str::{DOMString, USVString, is_token};
43use crate::dom::blob::Blob;
44use crate::dom::closeevent::CloseEvent;
45use crate::dom::csp::{GlobalCspReporting, Violation};
46use crate::dom::event::{Event, EventBubbles, EventCancelable};
47use crate::dom::eventtarget::EventTarget;
48use crate::dom::globalscope::GlobalScope;
49use crate::dom::messageevent::MessageEvent;
50use crate::dom::window::Window;
51use crate::fetch::fetch::RequestWithGlobalScope;
52use crate::tasks::task::TaskOnce;
53use crate::tasks::task_source::SendableTaskSource;
54
55#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
56enum WebSocketRequestState {
57    Connecting = 0,
58    Open = 1,
59    Closing = 2,
60    Closed = 3,
61}
62
63// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
64// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
65#[expect(dead_code)]
66mod close_code {
67    pub(crate) const NORMAL: u16 = 1000;
68    pub(crate) const GOING_AWAY: u16 = 1001;
69    pub(crate) const PROTOCOL_ERROR: u16 = 1002;
70    pub(crate) const UNSUPPORTED_DATATYPE: u16 = 1003;
71    pub(crate) const NO_STATUS: u16 = 1005;
72    pub(crate) const ABNORMAL: u16 = 1006;
73    pub(crate) const INVALID_PAYLOAD: u16 = 1007;
74    pub(crate) const POLICY_VIOLATION: u16 = 1008;
75    pub(crate) const TOO_LARGE: u16 = 1009;
76    pub(crate) const EXTENSION_MISSING: u16 = 1010;
77    pub(crate) const INTERNAL_ERROR: u16 = 1011;
78    pub(crate) const TLS_FAILED: u16 = 1015;
79}
80
81fn close_the_websocket_connection(
82    address: Trusted<WebSocket>,
83    task_source: &SendableTaskSource,
84    code: Option<u16>,
85    reason: String,
86) {
87    task_source.queue(CloseTask {
88        address,
89        failed: false,
90        code,
91        reason: Some(reason),
92    });
93}
94
95fn fail_the_websocket_connection(address: Trusted<WebSocket>, task_source: &SendableTaskSource) {
96    task_source.queue(CloseTask {
97        address,
98        failed: true,
99        code: Some(close_code::ABNORMAL),
100        reason: None,
101    });
102}
103
104#[dom_struct]
105pub(crate) struct WebSocket {
106    eventtarget: EventTarget,
107    #[no_trace]
108    url: ServoUrl,
109    ready_state: Cell<WebSocketRequestState>,
110    buffered_amount: Cell<u64>,
111    clearing_buffer: Cell<bool>, // Flag to tell if there is a running thread to clear buffered_amount
112    #[no_trace]
113    callback: LazyCallback<WebSocketDomAction>,
114    binary_type: Cell<BinaryType>,
115    protocol: DomRefCell<String>, // Subprotocol selected by server
116}
117
118impl WebSocket {
119    fn new_inherited(url: ServoUrl, callback: LazyCallback<WebSocketDomAction>) -> WebSocket {
120        WebSocket {
121            eventtarget: EventTarget::new_inherited(),
122            url,
123            ready_state: Cell::new(WebSocketRequestState::Connecting),
124            buffered_amount: Cell::new(0),
125            clearing_buffer: Cell::new(false),
126            callback,
127            binary_type: Cell::new(BinaryType::Blob),
128            protocol: Default::default(),
129        }
130    }
131
132    fn new(
133        cx: &mut JSContext,
134        global: &GlobalScope,
135        proto: Option<HandleObject>,
136        url: ServoUrl,
137        sender: LazyCallback<WebSocketDomAction>,
138    ) -> DomRoot<WebSocket> {
139        let websocket = reflect_weak_referenceable_dom_object_with_proto(
140            cx,
141            Rc::new(WebSocket::new_inherited(url, sender)),
142            global,
143            proto,
144        );
145        if let Some(window) = global.downcast::<Window>() {
146            window.Document().track_websocket(&websocket);
147        }
148        websocket
149    }
150
151    /// <https://websockets.spec.whatwg.org/#dom-websocket-send>
152    fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
153        let return_after_buffer = match self.ready_state.get() {
154            WebSocketRequestState::Connecting => {
155                return Err(Error::InvalidState(Some(
156                    "Cannot send while socket is connecting".into(),
157                )));
158            },
159            WebSocketRequestState::Open => false,
160            WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
161        };
162
163        let address = Trusted::new(self);
164
165        match data_byte_len.checked_add(self.buffered_amount.get()) {
166            None => panic!(),
167            Some(new_amount) => self.buffered_amount.set(new_amount),
168        };
169
170        if return_after_buffer {
171            return Ok(false);
172        }
173
174        if !self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
175            self.clearing_buffer.set(true);
176
177            // TODO(mrobinson): Should this task be cancellable?
178            self.global()
179                .task_manager()
180                .websocket_task_source()
181                .queue_unconditionally(BufferedAmountTask { address });
182        }
183
184        Ok(true)
185    }
186
187    pub(crate) fn origin(&self) -> ImmutableOrigin {
188        self.url.origin()
189    }
190
191    /// <https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7>
192    fn fail_the_websocket_connection(&self) {
193        let _ = self.callback.send(WebSocketDomAction::Abort);
194
195        // Once studown starts, another cleanup call can not restart it, this make the WS teardown
196        // idempotent prevents duplicate shutdown actions and tasks.
197        self.ready_state.set(WebSocketRequestState::Closing);
198
199        fail_the_websocket_connection(
200            Trusted::new(self),
201            &self
202                .global()
203                .task_manager()
204                .websocket_task_source()
205                .to_sendable(),
206        );
207    }
208
209    /// <https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.2>
210    fn start_the_websocket_closing_handshake(&self, code: Option<u16>, reason: Option<String>) {
211        let _ = self.callback.send(WebSocketDomAction::Close(code, reason));
212        // Once studown starts, another cleanup call can not restart it, this make the WS teardown
213        // idempotent prevents duplicate shutdown actions and tasks.
214        self.ready_state.set(WebSocketRequestState::Closing);
215    }
216
217    /// <https://websockets.spec.whatwg.org/#make-disappear>
218    /// Returns true if any action was taken.
219    pub(crate) fn make_disappear(&self) -> bool {
220        match self.ready_state.get() {
221            WebSocketRequestState::Connecting => {
222                // If the WebSocket connection is not yet established: Fail the WebSocket connection.
223                self.fail_the_websocket_connection();
224                // Prevent an already queued open task from reopening the failed connection.
225                true
226            },
227            WebSocketRequestState::Open => {
228                // If the WebSocket closing handshake has not yet been started: Start the
229                // WebSocket closing handshake, with the status code to use in the WebSocket
230                // Close message being 1001.
231                self.start_the_websocket_closing_handshake(Some(close_code::GOING_AWAY), None);
232                true
233            },
234            WebSocketRequestState::Closing | WebSocketRequestState::Closed => {
235                // Otherwise: Do nothing.
236                false
237            },
238        }
239    }
240}
241
242impl WebSocketMethods<crate::DomTypeHolder> for WebSocket {
243    /// <https://websockets.spec.whatwg.org/#dom-websocket-websocket>
244    fn Constructor(
245        cx: &mut JSContext,
246        global: &GlobalScope,
247        proto: Option<HandleObject>,
248        url: DOMString,
249        protocols: Option<StringOrStringSequence>,
250    ) -> Fallible<DomRoot<WebSocket>> {
251        // Step 1. Let baseURL be this's relevant settings object's API base URL.
252        let base_url = global.api_base_url();
253        // Step 2. Let urlRecord be the result of applying the URL parser to url with baseURL.
254        // Step 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
255        let mut url_record = ServoUrl::parse_with_base(Some(&base_url), &url.str())
256            .or(Err(Error::Syntax(Some("Failed to parse url".into()))))?;
257
258        // Step 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
259        // Step 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
260        // Step 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
261        match url_record.scheme() {
262            "http" => {
263                url_record
264                    .as_mut_url()
265                    .set_scheme("ws")
266                    .expect("Can't set scheme from http to ws");
267            },
268            "https" => {
269                url_record
270                    .as_mut_url()
271                    .set_scheme("wss")
272                    .expect("Can't set scheme from https to wss");
273            },
274            "ws" | "wss" => {},
275            _ => {
276                return Err(Error::Syntax(Some("Forbidden URL scheme".into())));
277            },
278        }
279
280        // Step 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" DOMException.
281        if url_record.fragment().is_some() {
282            return Err(Error::Syntax(Some("Forbidden URL fragment".into())));
283        }
284
285        // Step 8. If protocols is a string, set protocols to a sequence consisting of just that string.
286        let protocols = protocols.map_or(vec![], |p| match p {
287            StringOrStringSequence::String(string) => vec![string.into()],
288            StringOrStringSequence::StringSequence(seq) => {
289                seq.into_iter().map(String::from).collect()
290            },
291        });
292
293        // Step 9. If any of the values in protocols occur more than once or otherwise fail to match the requirements
294        // for elements that comprise the value of `Sec-WebSocket-Protocol` fields as defined by The WebSocket protocol,
295        // then throw a "SyntaxError" DOMException.
296        for (i, protocol) in protocols.iter().enumerate() {
297            // https://tools.ietf.org/html/rfc6455#section-4.1
298            // Handshake requirements, step 10
299
300            if protocols[i + 1..]
301                .iter()
302                .any(|p| p.eq_ignore_ascii_case(protocol))
303            {
304                return Err(Error::Syntax(Some("Duplicate protocol header".into())));
305            }
306
307            // https://tools.ietf.org/html/rfc6455#section-4.1
308            if !is_token(protocol.as_bytes()) {
309                return Err(Error::Syntax(Some(
310                    "Protocol header field is not a valid token".into(),
311                )));
312            }
313        }
314
315        // Create the interface for communication with the resource thread
316        let (dom_action_sender, resource_action_receiver) = lazy_callback();
317
318        // Step 12. Establish a WebSocket connection given urlRecord, protocols, and client.
319        let ws = WebSocket::new(cx, global, proto, url_record.clone(), dom_action_sender);
320        let address = Trusted::new(&*ws);
321
322        // https://websockets.spec.whatwg.org/#concept-websocket-establish
323        //
324        // Let request be a new request, whose URL is requestURL, client is client, service-workers
325        // mode is "none", referrer is "no-referrer", mode is "websocket", credentials mode is
326        // "include", cache mode is "no-store" , and redirect mode is "error"
327        let request = RequestBuilder::new(
328            global.webview_id(),
329            UrlWithBlobClaim::from_url_without_having_claimed_blob(url_record.clone()),
330            Referrer::NoReferrer,
331        )
332        .with_global_scope(global)
333        .mode(RequestMode::WebSocket {
334            protocols,
335            original_url: url_record,
336        })
337        .service_workers_mode(ServiceWorkersMode::None)
338        .credentials_mode(CredentialsMode::Include)
339        .cache_mode(CacheMode::NoCache)
340        .redirect_mode(RedirectMode::Error);
341
342        let task_source = global.task_manager().websocket_task_source().to_sendable();
343        let resource_event_sender =
344            ProfileGenericCallback::new(move |message| match message.unwrap() {
345                WebSocketNetworkEvent::ReportCSPViolations(violations) => {
346                    let task = ReportCSPViolationTask {
347                        websocket: address.clone(),
348                        violations,
349                    };
350                    task_source.queue(task);
351                },
352                WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
353                    let open_thread = ConnectionEstablishedTask {
354                        address: address.clone(),
355                        protocol_in_use,
356                    };
357                    task_source.queue(open_thread);
358                },
359                WebSocketNetworkEvent::MessageReceived(message) => {
360                    let message_thread = MessageReceivedTask {
361                        address: address.clone(),
362                        message,
363                    };
364                    task_source.queue(message_thread);
365                },
366                WebSocketNetworkEvent::Fail => {
367                    fail_the_websocket_connection(address.clone(), &task_source);
368                },
369                WebSocketNetworkEvent::Close(code, reason) => {
370                    close_the_websocket_connection(address.clone(), &task_source, code, reason);
371                },
372            })
373            .expect("Couldn't create web socket callback.");
374
375        let channels = FetchChannels::WebSocket {
376            event_sender: resource_event_sender,
377            action_receiver: resource_action_receiver,
378        };
379        let _ = global
380            .core_resource_thread()
381            .send(CoreResourceMsg::Fetch(request, channels));
382
383        Ok(ws)
384    }
385
386    // https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
387    event_handler!(open, GetOnopen, SetOnopen);
388
389    // https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
390    event_handler!(close, GetOnclose, SetOnclose);
391
392    // https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
393    event_handler!(error, GetOnerror, SetOnerror);
394
395    // https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
396    event_handler!(message, GetOnmessage, SetOnmessage);
397
398    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-url>
399    fn Url(&self) -> DOMString {
400        DOMString::from(self.url.as_str())
401    }
402
403    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-readystate>
404    fn ReadyState(&self) -> u16 {
405        self.ready_state.get() as u16
406    }
407
408    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount>
409    fn BufferedAmount(&self) -> u64 {
410        self.buffered_amount.get()
411    }
412
413    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype>
414    fn BinaryType(&self) -> BinaryType {
415        self.binary_type.get()
416    }
417
418    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype>
419    fn SetBinaryType(&self, btype: BinaryType) {
420        self.binary_type.set(btype)
421    }
422
423    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-protocol>
424    fn Protocol(&self) -> DOMString {
425        DOMString::from(self.protocol.borrow().clone())
426    }
427
428    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-send>
429    fn Send(&self, data: USVString) -> ErrorResult {
430        let data_byte_len = data.0.len() as u64;
431        let send_data = self.send_impl(data_byte_len)?;
432
433        if send_data {
434            let _ = self
435                .callback
436                .send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
437        }
438
439        Ok(())
440    }
441
442    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-send>
443    fn Send_(&self, blob: &Blob) -> ErrorResult {
444        /* As per https://html.spec.whatwg.org/multipage/#websocket
445           the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
446           If the buffer limit is reached in the first place, there are likely other major problems
447        */
448        let data_byte_len = blob.Size();
449        let send_data = self.send_impl(data_byte_len)?;
450
451        if send_data {
452            let bytes = blob.get_bytes().unwrap_or_default();
453            let _ = self
454                .callback
455                .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
456        }
457
458        Ok(())
459    }
460
461    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-send>
462    fn Send__(&self, array: CustomAutoRooterGuard<ArrayBuffer>) -> ErrorResult {
463        let bytes = array.to_vec().unwrap_or_default();
464        let data_byte_len = bytes.len();
465        let send_data = self.send_impl(data_byte_len as u64)?;
466
467        if send_data {
468            let _ = self
469                .callback
470                .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
471        }
472        Ok(())
473    }
474
475    /// <https://html.spec.whatwg.org/multipage/#dom-websocket-send>
476    fn Send___(&self, array: CustomAutoRooterGuard<ArrayBufferView>) -> ErrorResult {
477        let bytes = array.to_vec().unwrap_or_default();
478        let data_byte_len = bytes.len();
479        let send_data = self.send_impl(data_byte_len as u64)?;
480
481        if send_data {
482            let _ = self
483                .callback
484                .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
485        }
486        Ok(())
487    }
488
489    /// <https://websockets.spec.whatwg.org/#dom-websocket-close>
490    fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
491        // Step 1. If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.
492        if let Some(code) = code &&
493            code != close_code::NORMAL &&
494            !(3000..=4999).contains(&code)
495        {
496            return Err(Error::InvalidAccess(Some(
497                "Invalid WebSocket connection close code".into(),
498            )));
499        }
500
501        // Step 2.2. If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.
502        if let Some(ref reason) = reason &&
503            reason.0.len() > 123
504        {
505            return Err(Error::Syntax(Some("Reason too long".to_string())));
506        }
507
508        // Step 3. Run the first matching steps from the following list:
509        match self.ready_state.get() {
510            // If this's ready state is CLOSING (2) or CLOSED (3): Do nothing.
511            WebSocketRequestState::Closing | WebSocketRequestState::Closed => {},
512            WebSocketRequestState::Connecting => {
513                // If the WebSocket connection is not yet established: Fail the WebSocket
514                // connection and set this's ready state to CLOSING (2).
515                self.fail_the_websocket_connection();
516            },
517            WebSocketRequestState::Open => {
518                // If the WebSocket closing handshake has not yet been started: Start the
519                // WebSocket closing handshake and set this's ready state to CLOSING (2).
520                self.start_the_websocket_closing_handshake(code, reason.map(|reason| reason.0));
521            },
522        }
523        Ok(())
524    }
525}
526
527struct ReportCSPViolationTask {
528    websocket: Trusted<WebSocket>,
529    violations: Vec<Violation>,
530}
531
532impl TaskOnce for ReportCSPViolationTask {
533    fn run_once(self, cx: &mut JSContext) {
534        let global = self.websocket.root().global();
535        global.report_csp_violations(cx, self.violations, None, None);
536    }
537}
538
539/// Task queued when *the WebSocket connection is established*.
540/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
541struct ConnectionEstablishedTask {
542    address: Trusted<WebSocket>,
543    protocol_in_use: Option<String>,
544}
545
546impl TaskOnce for ConnectionEstablishedTask {
547    /// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
548    fn run_once(self, cx: &mut JSContext) {
549        let ws = self.address.root();
550
551        if ws.ready_state.get() != WebSocketRequestState::Connecting {
552            return;
553        }
554
555        // Step 1.
556        ws.ready_state.set(WebSocketRequestState::Open);
557
558        // Step 2: Extensions.
559        // TODO: Set extensions to extensions in use.
560
561        // Step 3.
562        if let Some(protocol_name) = self.protocol_in_use {
563            *ws.protocol.safe_borrow_mut(cx.no_gc()) = protocol_name;
564        };
565
566        // Step 4.
567        ws.upcast().fire_event(cx, atom!("open"));
568    }
569}
570
571struct BufferedAmountTask {
572    address: Trusted<WebSocket>,
573}
574
575impl TaskOnce for BufferedAmountTask {
576    // See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
577    //
578    // To be compliant with standards, we need to reset bufferedAmount only when the event loop
579    // reaches step 1.  In our implementation, the bytes will already have been sent on a background
580    // thread.
581    fn run_once(self, _cx: &mut JSContext) {
582        let ws = self.address.root();
583
584        ws.buffered_amount.set(0);
585        ws.clearing_buffer.set(false);
586    }
587}
588
589struct CloseTask {
590    address: Trusted<WebSocket>,
591    failed: bool,
592    code: Option<u16>,
593    reason: Option<String>,
594}
595
596impl TaskOnce for CloseTask {
597    fn run_once(self, cx: &mut JSContext) {
598        let ws = self.address.root();
599
600        if ws.ready_state.get() == WebSocketRequestState::Closed {
601            // Do nothing if already closed.
602            return;
603        }
604
605        // Perform _the WebSocket connection is closed_ steps.
606        // https://html.spec.whatwg.org/multipage/#closeWebSocket
607
608        // Step 1.
609        ws.ready_state.set(WebSocketRequestState::Closed);
610
611        // Step 2.
612        if self.failed {
613            ws.upcast().fire_event(cx, atom!("error"));
614        }
615
616        // Step 3.
617        let clean_close = !self.failed;
618        let code = self.code.unwrap_or(close_code::NO_STATUS);
619        let reason = DOMString::from(self.reason.unwrap_or_default());
620        let close_event = CloseEvent::new(
621            cx,
622            &ws.global(),
623            atom!("close"),
624            EventBubbles::DoesNotBubble,
625            EventCancelable::NotCancelable,
626            clean_close,
627            code,
628            reason,
629        );
630        close_event.upcast::<Event>().fire(cx, ws.upcast());
631    }
632}
633
634struct MessageReceivedTask {
635    address: Trusted<WebSocket>,
636    message: MessageData,
637}
638
639impl TaskOnce for MessageReceivedTask {
640    fn run_once(self, cx: &mut JSContext) {
641        let ws = self.address.root();
642        debug!(
643            "MessageReceivedTask::handler({:p}): readyState={:?}",
644            &*ws,
645            ws.ready_state.get()
646        );
647
648        // Step 1.
649        if ws.ready_state.get() != WebSocketRequestState::Open {
650            return;
651        }
652
653        // Step 2-5.
654        let global = ws.global();
655        let mut realm = AutoRealm::new(
656            cx,
657            NonNull::new(ws.reflector().get_jsobject().get()).unwrap(),
658        );
659        let cx = &mut *realm;
660        rooted!(&in(cx) let mut message = UndefinedValue());
661        match self.message {
662            MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
663            MessageData::Binary(data) => match ws.binary_type.get() {
664                BinaryType::Blob => {
665                    let blob =
666                        Blob::new(cx, &global, BlobImpl::new_from_bytes(data, String::new()));
667                    blob.to_jsval(cx, message.handle_mut());
668                },
669                BinaryType::Arraybuffer => {
670                    rooted!(&in(cx) let mut array_buffer = ptr::null_mut::<JSObject>());
671                    assert!(
672                        create_buffer_source::<ArrayBufferU8>(cx, &data, array_buffer.handle_mut())
673                            .is_ok()
674                    );
675
676                    (*array_buffer).to_jsval(cx, message.handle_mut());
677                },
678            },
679        }
680        MessageEvent::dispatch_jsval(
681            cx,
682            ws.upcast(),
683            &global,
684            message.handle(),
685            Some(ws.origin().ascii_serialization().as_ref()),
686            None,
687            vec![],
688        );
689    }
690}