View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host;
16  
17  import java.io.IOException;
18  import java.net.MalformedURLException;
19  import java.net.URI;
20  import java.net.URISyntaxException;
21  import java.net.URL;
22  import java.nio.ByteBuffer;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.HashSet;
26  import java.util.List;
27  import java.util.concurrent.RejectedExecutionException;
28  import java.util.concurrent.atomic.AtomicInteger;
29  import java.util.concurrent.atomic.AtomicLong;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.htmlunit.WebClient;
34  import org.htmlunit.corejs.javascript.Context;
35  import org.htmlunit.corejs.javascript.Function;
36  import org.htmlunit.corejs.javascript.Scriptable;
37  import org.htmlunit.corejs.javascript.ScriptableObject;
38  import org.htmlunit.corejs.javascript.VarScope;
39  import org.htmlunit.corejs.javascript.typedarrays.NativeArrayBuffer;
40  import org.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView;
41  import org.htmlunit.html.HtmlPage;
42  import org.htmlunit.html.csp.ContentSecurityPolicy;
43  import org.htmlunit.javascript.AbstractJavaScriptEngine;
44  import org.htmlunit.javascript.JavaScriptEngine;
45  import org.htmlunit.javascript.PostponedAction;
46  import org.htmlunit.javascript.background.BasicJavaScriptJob;
47  import org.htmlunit.javascript.background.JavaScriptJob;
48  import org.htmlunit.javascript.configuration.JsxClass;
49  import org.htmlunit.javascript.configuration.JsxConstant;
50  import org.htmlunit.javascript.configuration.JsxConstructor;
51  import org.htmlunit.javascript.configuration.JsxFunction;
52  import org.htmlunit.javascript.configuration.JsxGetter;
53  import org.htmlunit.javascript.configuration.JsxSetter;
54  import org.htmlunit.javascript.host.dom.DOMException;
55  import org.htmlunit.javascript.host.event.CloseEvent;
56  import org.htmlunit.javascript.host.event.Event;
57  import org.htmlunit.javascript.host.event.EventTarget;
58  import org.htmlunit.javascript.host.event.MessageEvent;
59  import org.htmlunit.javascript.host.file.Blob;
60  import org.htmlunit.util.UrlUtils;
61  import org.htmlunit.websocket.WebSocketAdapter;
62  import org.htmlunit.websocket.WebSocketListener;
63  
64  /**
65   * JavaScript host object for {@code WebSocket}.
66   *
67   * <p>Ready state handling: readyState_ is read and written by the JS thread (close(), send(),
68   * getReadyState()), by the threads of the websocket adapter and by queued tasks. Every change goes through
69   * one of the three methods switchToOpen(), switchToClosing() and switchToClosed(). Each is a single atomic
70   * operation and tells the caller which state was left, so only the caller that really performed a
71   * transition fires the matching event. That gives at most one open event and exactly one close event
72   * whatever the interleaving.</p>
73   *
74   * <pre>{@code
75   *   CONNECTING      -> OPEN      switchToOpen()      handshake finished
76   *   OPEN            -> CLOSING   switchToClosing()   close() called
77   *   CONNECTING      -> ABORTED   switchToClosing()   close() called, reported as CLOSING
78   *   any but CLOSED  -> CLOSED    switchToClosed()    connection ended, see connectionEnded()
79   * }</pre>
80   *
81   * <p>The state never moves backwards and CLOSED is final.</p>
82   *
83   * @author Ahmed Ashour
84   * @author Ronald Brill
85   * @author Madis Pärn
86   *
87   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">MDN Documentation</a>
88   */
89  @JsxClass
90  public class WebSocket extends EventTarget implements AutoCloseable {
91  
92      private static final Log LOG = LogFactory.getLog(WebSocket.class);
93  
94      /** The connection has not yet been established. */
95      @JsxConstant
96      public static final int CONNECTING = 0;
97      /** The WebSocket connection is established and communication is possible. */
98      @JsxConstant
99      public static final int OPEN = 1;
100     /** The connection is going through the closing handshake. */
101     @JsxConstant
102     public static final int CLOSING = 2;
103     /** The connection has been closed or could not be opened. */
104     @JsxConstant
105     public static final int CLOSED = 3;
106 
107     /**
108      * Internal state, never visible to scripts (reported as {@link #CLOSING}): close() was called while
109      * the connection was still CONNECTING. Such a connection fails: error event, then close event 1006.
110      */
111     private static final int ABORTED = 4;
112 
113     /** The close frame has 125 bytes of payload, two of them are the status code. */
114     private static final int MAX_CLOSE_REASON_BYTES = 123;
115 
116     /** The status code for "no status code": the close frame is sent without any. */
117     private static final int NO_STATUS_CODE = 1005;
118 
119     /** The status code of a normal closure. */
120     private static final int CLOSE_NORMAL = 1000;
121 
122     /** The status code sent when the server violated the protocol, e.g. selected a sub-protocol nobody offered. */
123     private static final int CLOSE_PROTOCOL_ERROR = 1002;
124 
125     /** The status code reported locally for a connection that was lost or failed; it is never sent. */
126     private static final int CLOSE_ABNORMAL = 1006;
127 
128     /** The status code reported locally for a failed TLS handshake; it is never sent. */
129     private static final int CLOSE_TLS_FAILURE = 1015;
130 
131     /** Returned by switchToClosing() if the connection already is CLOSING or CLOSED. */
132     private static final int NOT_CLOSABLE = -1;
133 
134     /** Tells closeSessions() to close with the default status code of the adapter. */
135     private static final int DEFAULT_STATUS_CODE = -1;
136 
137     private final URI url_;
138     private final String origin_;
139 
140     private final AtomicInteger readyState_ = new AtomicInteger(CONNECTING);
141     // bytes handed to send() after the connection was closed; see getBufferedAmount()
142     private final AtomicLong bufferedAmount_ = new AtomicLong();
143     private volatile String binaryType_ = "blob";
144 
145     private HtmlPage containingPage_;
146     private WebSocketAdapter webSocketImpl_;
147 
148     // the sub-protocols offered in the handshake, and the one the server selected
149     private final List<String> requestedProtocols_;
150     private volatile String protocol_ = "";
151 
152     /**
153      * Creates a new instance.
154      */
155     public WebSocket() {
156         super();
157         requestedProtocols_ = null;
158         url_ = null;
159         origin_ = null;
160     }
161 
162     /**
163      * Creates a new instance connected to the given URL.
164      *
165      * @param url the URL to connect to
166      * @param protocols the sub-protocols to offer in the handshake
167      * @param scope the scope
168      * @param window the top-level window
169      * @param page the page this WebSocket belongs to
170      */
171     private WebSocket(final URI url, final List<String> protocols, final VarScope scope,
172             final Window window, final HtmlPage page) {
173         super();
174         url_ = url;
175         origin_ = originOf(url);
176 
177         requestedProtocols_ = protocols;
178         containingPage_ = page;
179 
180         setParentScope(scope);
181         setDomNode(page.getDocumentElement(), false);
182 
183         if (!isConnectionAllowed(page, url)) {
184             // like a failed connection (error event, close event 1006), but after the running script
185             // and after the securitypolicyviolation event
186             final AbstractJavaScriptEngine<?> engine = page.getWebClient().getJavaScriptEngine();
187             if (engine != null && engine.isScriptRunning()) {
188                 engine.addPostponedAction(new PostponedAction(page, "WebSocket blocked by CSP") {
189                     @Override
190                     public void execute() {
191                         connectionEnded(CLOSE_ABNORMAL, "", true);
192                     }
193                 });
194             }
195             else {
196                 queueTask(() -> connectionEnded(CLOSE_ABNORMAL, "", true));
197             }
198             return;
199         }
200 
201         final WebClient webClient = window.getWebWindow().getWebClient();
202         webSocketImpl_ = webClient.buildWebSocketAdapter(new AdapterListener(scope));
203 
204         try {
205             webSocketImpl_.start();
206             webSocketImpl_.connect(url_, requestedProtocols_);
207         }
208         catch (final Exception e) {
209             if (LOG.isErrorEnabled()) {
210                 LOG.error("WebSocket Error: connecting to '" + url + "' failed.", e);
211             }
212 
213             // nothing was handed out yet, so nobody else will release the client
214             releaseClient();
215 
216             throw JavaScriptEngine.reportRuntimeError("WebSocket Error: connecting to '" + url + "' failed.");
217         }
218 
219         page.addAutoCloseable(this);
220     }
221 
222     /**
223      * Checks the connect-src directive of the Content-Security-Policy of the page.
224      *
225      * @param page the page
226      * @param url the url to connect to
227      * @return {@code true} if the connection is allowed
228      */
229     private static boolean isConnectionAllowed(final HtmlPage page, final URI url) {
230         final URL connectionUrl;
231         try {
232             connectionUrl = UrlUtils.toUrlUnsafe(url.toString());
233         }
234         catch (final MalformedURLException e) {
235             // reported by the connection attempt
236             return true;
237         }
238         return ContentSecurityPolicy.allowsConnection(page, connectionUrl, connectionUrl);
239     }
240 
241     /**
242      * Creates an instance of this object.
243      *
244      * @param cx the current context
245      * @param scope the scope
246      * @param args the constructor arguments
247      * @param ctorObj the function object
248      * @param inNewExpr whether invoked via {@code new}
249      * @return the new {@code WebSocket} instance
250      */
251     @JsxConstructor
252     public static Scriptable jsConstructor(final Context cx, final VarScope scope, final Object[] args,
253             final Function ctorObj, final boolean inNewExpr) {
254         if (!inNewExpr) {
255             throw JavaScriptEngine
256                     .typeError("Failed to construct 'WebSocket': Please use the 'new' operator, "
257                             + "this DOM object constructor cannot be called as a function.");
258         }
259 
260         // the url is required, the protocols are optional, additional arguments are ignored
261         if (args.length < 1) {
262             throw JavaScriptEngine
263                     .typeError("WebSocket Error: constructor needs at least the url as parameter.");
264         }
265 
266         final Window win = getWindow(ctorObj);
267         if (!(win.getWebWindow().getEnclosedPage() instanceof HtmlPage htmlPage)) {
268             throw JavaScriptEngine.typeError("WebSocket Error: WebSocket is only available in HTML pages.");
269         }
270 
271         String urlString = JavaScriptEngine.toString(args[0]);
272         try {
273             URL url = htmlPage.getFullyQualifiedUrl(urlString);
274 
275             if (url.getRef() != null) {
276                 throw JavaScriptEngine.asJavaScriptException(win,
277                         "WebSocket Error: 'url' parameter '" + urlString + "' contains a fragment identifier.",
278                         DOMException.SYNTAX_ERR);
279             }
280 
281             // Per spec: only ws/wss are valid; convert http/https (relative resolution), reject everything else
282             final String scheme = url.getProtocol();
283             if ("http".equals(scheme)) {
284                 url = UrlUtils.getUrlWithNewProtocol(url, "ws");
285             }
286             else if ("https".equals(scheme)) {
287                 url = UrlUtils.getUrlWithNewProtocol(url, "wss");
288             }
289             else if (!"ws".equals(scheme) && !"wss".equals(scheme)) {
290                 throw JavaScriptEngine.asJavaScriptException(win,
291                         "WebSocket Error: 'url' parameter '" + urlString + "' is not a valid url.",
292                         DOMException.SYNTAX_ERR);
293             }
294 
295             // upgrade-insecure-requests of the Content-Security-Policy
296             url = ContentSecurityPolicy.upgradeInsecureRequest(htmlPage, url);
297             urlString = url.toExternalForm();
298         }
299         catch (final MalformedURLException e) {
300             throw JavaScriptEngine.asJavaScriptException(
301                     win,
302                     "WebSocket Error: 'url' parameter '" + urlString + "' is not a valid url.",
303                     DOMException.SYNTAX_ERR);
304         }
305 
306         final URI uri;
307         try {
308             uri = new URI(urlString);
309         }
310         catch (final URISyntaxException e) {
311             throw JavaScriptEngine.asJavaScriptException(win,
312                     "WebSocket Error: 'url' parameter '" + urlString + "' is not a valid url.",
313                     DOMException.SYNTAX_ERR);
314         }
315 
316         final List<String> protocols = toProtocols(cx, scope, args.length > 1 ? args[1] : JavaScriptEngine.UNDEFINED);
317         if (!areValidProtocols(protocols)) {
318             throw JavaScriptEngine.asJavaScriptException(
319                     win,
320                     "WebSocket Error: the protocols must be unique and may only contain token characters.",
321                     DOMException.SYNTAX_ERR);
322         }
323 
324         return new WebSocket(uri, List.copyOf(protocols), getTopLevelScope(scope), win, htmlPage);
325     }
326 
327     /**
328      * Converts the protocols argument, which is a {@code (DOMString or sequence<DOMString>)}: undefined (or no
329      * argument) is the empty list, an array is a sequence, anything else - null and objects that are no array
330      * included - is converted to a single string.
331      *
332      * @param cx the current context
333      * @param scope the scope
334      * @param protocols the argument
335      * @return the protocols
336      */
337     private static List<String> toProtocols(final Context cx, final VarScope scope, final Object protocols) {
338         if (JavaScriptEngine.isUndefined(protocols)) {
339             return Collections.emptyList();
340         }
341 
342         if (protocols instanceof Scriptable protoScriptable) {
343             final List<String> result = new ArrayList<>();
344             if (JavaScriptEngine.iterate(cx, scope, protoScriptable,
345                     elem -> {
346                         if (elem == Scriptable.NOT_FOUND) {
347                             // a hole in the array
348                             result.add(JavaScriptEngine.toString(JavaScriptEngine.UNDEFINED));
349                         }
350                         else {
351                             result.add(JavaScriptEngine.toString(elem));
352                         }
353                     })) {
354                 return result;
355             }
356         }
357 
358         return Collections.singletonList(JavaScriptEngine.toString(protocols));
359     }
360 
361     /**
362      * Checks the protocols: every one has to be a token, and none may be there more than once
363      * (compared case sensitive).
364      *
365      * @param protocols the protocols
366      * @return {@code true} if the protocols are valid
367      */
368     private static boolean areValidProtocols(final List<String> protocols) {
369         final HashSet<String> seen = new HashSet<>();
370         for (final String protocol : protocols) {
371             if (!isValidProtocol(protocol) || !seen.add(protocol)) {
372                 return false;
373             }
374         }
375         return true;
376     }
377 
378     /**
379      * A protocol has to match the token production of RFC 7230: at least one character, only letters, digits
380      * and {@code !#$%&'*+-.^_`|~}. That excludes empty strings, blanks, separators like the comma and all non
381      * ASCII characters.
382      *
383      * @param protocol the protocol
384      * @return {@code true} if the protocol is a token
385      */
386     private static boolean isValidProtocol(final String protocol) {
387         if (protocol.isEmpty()) {
388             return false;
389         }
390         for (int i = 0; i < protocol.length(); i++) {
391             final char c = protocol.charAt(i);
392             final boolean token = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
393                     || "!#$%&'*+-.^_`|~".indexOf(c) >= 0;
394             if (!token) {
395                 return false;
396             }
397         }
398         return true;
399     }
400 
401     /**
402      * Returns the event handler that fires on close.
403      *
404      * @return the event handler that fires on close
405      */
406     @JsxGetter
407     public Function getOnclose() {
408         return getEventHandler(Event.TYPE_CLOSE);
409     }
410 
411     /**
412      * Sets the event handler that fires on close.
413      *
414      * @param closeHandler the event handler that fires on close
415      */
416     @JsxSetter
417     public void setOnclose(final Function closeHandler) {
418         setEventHandler(Event.TYPE_CLOSE, closeHandler);
419     }
420 
421     /**
422      * Returns the event handler that fires on error.
423      *
424      * @return the event handler that fires on error
425      */
426     @JsxGetter
427     public Function getOnerror() {
428         return getEventHandler(Event.TYPE_ERROR);
429     }
430 
431     /**
432      * Sets the event handler that fires on error.
433      *
434      * @param errorHandler the event handler that fires on error
435      */
436     @JsxSetter
437     public void setOnerror(final Function errorHandler) {
438         setEventHandler(Event.TYPE_ERROR, errorHandler);
439     }
440 
441     /**
442      * Returns the event handler that fires on message.
443      *
444      * @return the event handler that fires on message
445      */
446     @JsxGetter
447     public Function getOnmessage() {
448         return getEventHandler(Event.TYPE_MESSAGE);
449     }
450 
451     /**
452      * Sets the event handler that fires on message.
453      *
454      * @param messageHandler the event handler that fires on message
455      */
456     @JsxSetter
457     public void setOnmessage(final Function messageHandler) {
458         setEventHandler(Event.TYPE_MESSAGE, messageHandler);
459     }
460 
461     /**
462      * Returns the event handler that fires on open.
463      *
464      * @return the event handler that fires on open
465      */
466     @JsxGetter
467     public Function getOnopen() {
468         return getEventHandler(Event.TYPE_OPEN);
469     }
470 
471     /**
472      * Sets the event handler that fires on open.
473      *
474      * @param openHandler the event handler that fires on open
475      */
476     @JsxSetter
477     public void setOnopen(final Function openHandler) {
478         setEventHandler(Event.TYPE_OPEN, openHandler);
479     }
480 
481     /**
482      * Returns the origin of the given url, which is the url without path, query and fragment.
483      *
484      * @param url the url of the connection
485      * @return the origin, or {@code null} if the url cannot be converted
486      */
487     private static String originOf(final URI url) {
488         try {
489             final URL originUrl = UrlUtils.getUrlWithoutPathRefQuery(UrlUtils.toUrlUnsafe(url.toString()));
490             return originUrl.toExternalForm();
491         }
492         catch (final MalformedURLException e) {
493             return null;
494         }
495     }
496 
497     /**
498      * Switches from CONNECTING to OPEN.
499      *
500      * @return {@code true} if this call made the transition
501      */
502     private boolean switchToOpen() {
503         return readyState_.compareAndSet(CONNECTING, OPEN);
504     }
505 
506     /**
507      * Return the state that was left, or {@link #NOT_CLOSABLE} if the connection already is CLOSING or CLOSED.
508      *
509      * @return the state that was left, or {@link #NOT_CLOSABLE} if the connection already is CLOSING or CLOSED
510      */
511     private int switchToClosing() {
512         int current = readyState_.get();
513         while (current == CONNECTING || current == OPEN) {
514             final int target = current == CONNECTING ? ABORTED : CLOSING;
515             if (readyState_.compareAndSet(current, target)) {
516                 return current;
517             }
518             current = readyState_.get();
519         }
520         return NOT_CLOSABLE;
521     }
522 
523     /**
524      * Return the state that was left, {@link #CLOSED} if the connection was closed before.
525      *
526      * @return the state that was left, {@link #CLOSED} if the connection was closed before
527      */
528     private int switchToClosed() {
529         return readyState_.getAndSet(CLOSED);
530     }
531 
532     /**
533      * A connection was closed cleanly if the closing handshake was completed, whatever status code it carried.
534      * The codes 1006 and 1015 are never sent, they are reported locally for a connection that was lost or failed.
535      *
536      * @param failed whether the connection failed
537      * @param statusCode the status code of the close event
538      * @return the value of {@code wasClean}
539      */
540     private static boolean wasClean(final boolean failed, final int statusCode) {
541         return !failed && statusCode != CLOSE_ABNORMAL && statusCode != CLOSE_TLS_FAILURE;
542     }
543 
544     /**
545      * Starts the closing handshake with the default status code of the adapter.
546      *
547      * @return {@code false} if this failed, so that no answer of the server has to be waited for
548      */
549     private boolean closeSessions() {
550         return closeSessions(DEFAULT_STATUS_CODE, null);
551     }
552 
553     /**
554      * Starts the closing handshake: the sessions are asked to close, which sends the close frame. The outgoing
555      * session comes first because it is the one that takes the status code and the reason; the incoming session
556      * is the same connection and ignores the second close.
557      *
558      * @param statusCode the status code of the close frame, {@link #NO_STATUS_CODE} for a close frame without
559      *        status code, or {@link #DEFAULT_STATUS_CODE} for the default of the adapter
560      * @param reason the reason of the close frame
561      * @return {@code false} if this failed, so that no answer of the server has to be waited for
562      */
563     private boolean closeSessions(final int statusCode, final String reason) {
564         if (webSocketImpl_ == null) {
565             return false;
566         }
567 
568         boolean success = true;
569         try {
570             if (statusCode == DEFAULT_STATUS_CODE) {
571                 webSocketImpl_.closeOutgoingSession();
572             }
573             else {
574                 webSocketImpl_.closeOutgoingSession(statusCode, reason);
575             }
576         }
577         catch (final Exception e) {
578             LOG.error("WS close error - outgoingSession_.close() failed", e);
579             success = false;
580         }
581 
582         try {
583             webSocketImpl_.closeIncomingSession();
584         }
585         catch (final Exception e) {
586             LOG.error("WS close error - incomingSession_.close() failed", e);
587             success = false;
588         }
589         return success;
590     }
591 
592     private void releaseClient() {
593         if (webSocketImpl_ == null) {
594             return;
595         }
596 
597         try {
598             webSocketImpl_.closeClient();
599         }
600         catch (final Exception e) {
601             LOG.error("WS close error - closeClient() failed", e);
602         }
603     }
604 
605     private void shutdownAdapter() {
606         closeSessions();
607         releaseClient();
608     }
609 
610     /**
611      * The WebIDL conversion to {@code [Clamp] unsigned short}: NaN is 0, the value is clamped to 0..65535
612      * and rounded to the nearest integer, ties going to the even one (so 1000.5 is 1000).
613      *
614      * @param number the number to convert
615      * @return the converted value
616      */
617     private static int clampToUnsignedShort(final double number) {
618         if (Double.isNaN(number)) {
619             return 0;
620         }
621         return (int) Math.rint(Math.min(Math.max(number, 0d), 65535d));
622     }
623 
624     private static boolean isValidCloseCode(final int code) {
625         return code == CLOSE_NORMAL || (code >= 3000 && code <= 4999);
626     }
627 
628     /**
629      * Returns the USVString of the given text: every unpaired surrogate is replaced by U+FFFD.
630      *
631      * @param text the text
632      * @return the text itself if there is nothing to replace, a converted copy otherwise
633      */
634     private static String toUsvString(final String text) {
635         StringBuilder result = null;
636         for (int i = 0; i < text.length(); i++) {
637             final char c = text.charAt(i);
638             if (Character.isHighSurrogate(c) && i + 1 < text.length()
639                     && Character.isLowSurrogate(text.charAt(i + 1))) {
640                 if (result != null) {
641                     result.append(c).append(text.charAt(i + 1));
642                 }
643                 i++;
644             }
645             else if (Character.isSurrogate(c)) {
646                 if (result == null) {
647                     result = new StringBuilder(text.length()).append(text, 0, i);
648                 }
649                 result.append('\uFFFD');
650             }
651             else if (result != null) {
652                 result.append(c);
653             }
654         }
655         return result == null ? text : result.toString();
656     }
657 
658     /**
659      * Returns the length in bytes of the UTF-8 encoding of the USVString of the given text. An unpaired
660      * surrogate is replaced by U+FFFD, which needs three bytes (String.getBytes would use one byte for '?').
661      *
662      * @param text the text
663      * @return the number of bytes
664      */
665     private static int usvUtf8Length(final String text) {
666         int length = 0;
667         for (int i = 0; i < text.length(); i++) {
668             final char c = text.charAt(i);
669             if (c < 0x80) {
670                 length += 1;
671             }
672             else if (c < 0x800) {
673                 length += 2;
674             }
675             else if (Character.isHighSurrogate(c) && i + 1 < text.length()
676                     && Character.isLowSurrogate(text.charAt(i + 1))) {
677                 length += 4;
678                 i++;
679             }
680             else {
681                 // BMP character, or an unpaired surrogate that becomes U+FFFD
682                 length += 3;
683             }
684         }
685         return length;
686     }
687 
688     /**
689      * Returns a copy of the bytes of the given binary data: the content of an ArrayBuffer, the part of its
690      * buffer a typed array or DataView views (offset and length, not the whole buffer), or the content of
691      * a Blob.
692      *
693      * @param content the argument of send()
694      * @return the copy, or {@code null} if the content is not binary data
695      */
696     private static byte[] copyOfBinaryData(final Object content) {
697         if (content instanceof NativeArrayBuffer buffer) {
698             final byte[] bytes = new byte[buffer.getLength()];
699             buffer.getByteBuffer().position(0).get(bytes);
700             return bytes;
701         }
702         if (content instanceof NativeArrayBufferView view) {
703             final byte[] bytes = new byte[view.getByteLength()];
704             view.getBuffer().getByteBuffer().position(view.getByteOffset()).get(bytes);
705             return bytes;
706         }
707         if (content instanceof Blob blob) {
708             return blob.getBytes().clone();
709         }
710         return null;
711     }
712 
713     /**
714      * Returns the number of bytes send() has to count for the given data: the byte length of an ArrayBuffer or
715      * a view on it, the size of a Blob and, for everything else, the UTF-8 length of the converted string.
716      *
717      * @param content the argument of send()
718      * @return the number of bytes
719      */
720     private static long byteLengthOf(final Object content) {
721         if (content instanceof NativeArrayBuffer buffer) {
722             return buffer.getLength();
723         }
724         if (content instanceof NativeArrayBufferView view) {
725             return view.getByteLength();
726         }
727         if (content instanceof Blob blob) {
728             return blob.getSize();
729         }
730         return usvUtf8Length(JavaScriptEngine.toString(content));
731     }
732 
733     /**
734      * The handshake is finished: checks the sub-protocol the server selected, switches to OPEN and fires the
735      * open event. A server that selects a protocol that was not offered makes the connection fail.
736      */
737     private void connectionOpened() {
738         String selected = webSocketImpl_.getSelectedProtocol();
739         if (selected == null) {
740             selected = "";
741         }
742 
743         if (!selected.isEmpty() && !requestedProtocols_.contains(selected)) {
744             // the connection fails (error + close 1006) and must not stay open; the server is told about
745             // the protocol error (1002)
746             closeSessions(CLOSE_PROTOCOL_ERROR, "");
747             connectionEnded(CLOSE_ABNORMAL, "", true);
748             return;
749         }
750 
751         if (!switchToOpen()) {
752             // close() was called while the handshake was in flight: the connection must not stay open
753             // (the first shutdown may have run before there was a session) and no open event is fired
754             shutdownAdapter();
755             return;
756         }
757 
758         // set before the open event, the handlers read it
759         protocol_ = selected;
760         fireOpenEvent();
761     }
762 
763     private void fireOpenEvent() {
764         final AbstractJavaScriptEngine<?> engine = containingPage_.getWebClient().getJavaScriptEngine();
765         if (engine == null) {
766             return;
767         }
768 
769         engine.getContextFactory().call(cx -> {
770             final Event openEvent = new Event(Event.TYPE_OPEN);
771             openEvent.setParentScope(getParentScope());
772             openEvent.setPrototype(getPrototype(openEvent.getClass()));
773             openEvent.setSrcElement(WebSocket.this);
774             openEvent.setTarget(WebSocket.this);
775             executeEventLocally(openEvent);
776 
777             return null;
778         });
779     }
780 
781     /**
782      * Ends the connection: switches to CLOSED and fires the close event (preceded by an error event if the
783      * connection failed). May be called from any thread and any number of times, only the first call fires.
784      * A connection that never was established, or that was aborted by close() while connecting, has failed
785      * whatever the caller reports: error event, close event with code 1006 and an empty reason.
786      *
787      * @param statusCode the status code reported by the adapter
788      * @param reason the reason reported by the adapter
789      * @param reportedAsFailure whether the adapter reported an error
790      */
791     private void connectionEnded(final int statusCode, final String reason, final boolean reportedAsFailure) {
792         final int previous = switchToClosed();
793         if (previous == CLOSED) {
794             return;
795         }
796 
797         // The connection is over, release the client. close() does not do this for an open connection,
798         // because stopping the client right after the close frame was sent cuts the closing handshake.
799         // Not on this thread: it may be one of the adapter's own, and stopping a client from its own
800         // threads can stall.
801         releaseClientAsync();
802 
803         // never established or aborted while connecting: failed, whatever the adapter reports
804         final boolean failed = reportedAsFailure || previous == CONNECTING || previous == ABORTED;
805 
806         final AbstractJavaScriptEngine<?> engine = containingPage_.getWebClient().getJavaScriptEngine();
807         if (engine == null) {
808             return;
809         }
810 
811         engine.getContextFactory().call(cx -> {
812             if (failed) {
813                 final Event errorEvent = new Event(Event.TYPE_ERROR);
814                 errorEvent.setParentScope(getParentScope());
815                 errorEvent.setPrototype(getPrototype(errorEvent.getClass()));
816                 errorEvent.setSrcElement(WebSocket.this);
817                 errorEvent.setTarget(WebSocket.this);
818                 executeEventLocally(errorEvent);
819             }
820 
821             final CloseEvent closeEvent = new CloseEvent();
822             closeEvent.setParentScope(getParentScope());
823             closeEvent.setPrototype(getPrototype(closeEvent.getClass()));
824             closeEvent.setCode(failed ? CLOSE_ABNORMAL : statusCode);
825             closeEvent.setReason(failed || reason == null ? "" : reason);
826             closeEvent.setWasClean(wasClean(failed, statusCode));
827             closeEvent.setTarget(WebSocket.this);
828             executeEventLocally(closeEvent);
829 
830             return null;
831         });
832     }
833 
834     /**
835      * Releases the client of the adapter without blocking the calling thread.
836      * <p>
837      * The release is handed to the executor of the {@link WebClient}, the one the adapter uses for its own
838      * work. It must not run on the calling thread: that may be one of the adapter's threads, and stopping
839      * a client from its own threads can stall. If the executor rejects the task because it is already shut
840      * down (the {@link WebClient} is closing), the release runs on a short-lived daemon thread instead, so
841      * it is never lost.
842      * </p>
843      * <p>
844      * {@link #releaseClient()} logs and swallows its own failures, so there is nothing to report here.
845      * </p>
846      */
847     private void releaseClientAsync() {
848         try {
849             containingPage_.getWebClient().getExecutor().execute(this::releaseClient);
850         }
851         catch (final RejectedExecutionException e) {
852             // the executor is already shut down, which means the WebClient is closing: don't lose the release
853             final Thread thread = new Thread(this::releaseClient, "WebSocket-release");
854             thread.setDaemon(true);
855             thread.start();
856         }
857     }
858 
859     /**
860      * Runs the task later on the JS thread of the page, like the task queue of a browser does. Used for
861      * events that have to follow the running script, e.g. after close() while connecting.
862      *
863      * @param task the task
864      */
865     private void queueTask(final Runnable task) {
866         final JavaScriptJob job = new BasicJavaScriptJob() {
867             @Override
868             public void run() {
869                 task.run();
870             }
871         };
872         containingPage_.getEnclosingWindow().getJobManager().addJob(job, containingPage_);
873     }
874 
875     /**
876      * Returns the current state of the connection.
877      * Possible values are {@link #CONNECTING}, {@link #OPEN}, {@link #CLOSING}, or {@link #CLOSED}.
878      *
879      * @return the current ready state
880      */
881     @JsxGetter
882     public int getReadyState() {
883         final int state = readyState_.get();
884         return state == ABORTED ? CLOSING : state;
885     }
886 
887     /**
888      * Returns the URL of the WebSocket connection.
889      *
890      * @return the URL string
891      */
892     @JsxGetter
893     public String getUrl() {
894         if (url_ == null) {
895             throw JavaScriptEngine.typeError("invalid call");
896         }
897         return url_.toString();
898     }
899 
900     /**
901      * Returns the sub-protocol in use, or an empty string if no sub-protocol was selected.
902      *
903      * @return the sub-protocol
904      */
905     @JsxGetter
906     public String getProtocol() {
907         return protocol_;
908     }
909 
910     /**
911      * Returns the extensions negotiated with the server, or an empty string if no extensions are in use.
912      * The adapter does not report the negotiated extensions, so this is always an empty string.
913      *
914      * @return the extensions in use
915      */
916     @JsxGetter
917     public String getExtensions() {
918         return "";
919     }
920 
921     /**
922      * Returns the number of bytes of data that have been queued but not yet transmitted.
923      * Once the connection is closing or closed this value only increases: every send() adds the size of its
924      * data, which is discarded. Data sent while the connection is open is handed over to the adapter at once
925      * and is not counted, because the adapter does not tell when the data has left.
926      *
927      * @return the buffered amount in bytes
928      */
929     @JsxGetter
930     public long getBufferedAmount() {
931         return bufferedAmount_.get();
932     }
933 
934     /**
935      * Returns the binary data type used when receiving binary messages.
936      *
937      * @return the binary type ({@code "blob"} or {@code "arraybuffer"})
938      */
939     @JsxGetter
940     public String getBinaryType() {
941         return binaryType_;
942     }
943 
944     /**
945      * Sets the binary data type used when receiving binary messages.
946      *
947      * @param type the new binary type; must be {@code "blob"} or {@code "arraybuffer"}
948      */
949     @JsxSetter
950     public void setBinaryType(final String type) {
951         if ("arraybuffer".equals(type) || "blob".equals(type)) {
952             binaryType_ = type;
953         }
954     }
955 
956     /**
957      * {@inheritDoc}
958      */
959     @Override
960     public void close() throws IOException {
961         // called when the page is unloaded: whatever the state is, the client has to be released.
962         // No events are fired here and the state does not reach CLOSED, the page is gone.
963         if (switchToClosing() != NOT_CLOSABLE) {
964             closeSessions();
965         }
966         releaseClient();
967     }
968 
969     /**
970      * Closes the WebSocket connection or connection attempt, if any.
971      * If the connection is already {@link #CLOSING} or {@link #CLOSED}, this method does nothing.
972      * The arguments are validated first, whatever the state is: a code that is neither 1000 nor in the range
973      * 3000 to 4999 results in an {@code InvalidAccessError}, a reason longer than 123 bytes (UTF-8) in a
974      * {@code SyntaxError}.
975      *
976      * @param code a numeric value indicating the status code explaining why the connection is being closed
977      * @param reason a human-readable string explaining why the connection is closing
978      */
979     @JsxFunction
980     public void close(final Object code, final Object reason) {
981         int statusCode = NO_STATUS_CODE;
982         if (!JavaScriptEngine.isUndefined(code)) {
983             statusCode = clampToUnsignedShort(JavaScriptEngine.toNumber(code));
984             if (!isValidCloseCode(statusCode)) {
985                 throw JavaScriptEngine.asJavaScriptException(
986                         getWindow(),
987                         "WebSocket Error: the close code must be 1000 or in the range 3000 to 4999.",
988                         DOMException.INVALID_ACCESS_ERR);
989             }
990         }
991 
992         String closeReason = "";
993         if (!JavaScriptEngine.isUndefined(reason)) {
994             final String usvReason = toUsvString(JavaScriptEngine.toString(reason));
995             if (usvUtf8Length(usvReason) > MAX_CLOSE_REASON_BYTES) {
996                 throw JavaScriptEngine.asJavaScriptException(
997                         getWindow(),
998                         "WebSocket Error: the close reason must not be longer than 123 bytes.",
999                         DOMException.SYNTAX_ERR);
1000             }
1001             if (statusCode != NO_STATUS_CODE) {
1002                 // a reason can only be sent together with a status code
1003                 closeReason = usvReason;
1004             }
1005         }
1006 
1007         final int previous = switchToClosing();
1008         if (previous == NOT_CLOSABLE) {
1009             return;
1010         }
1011 
1012         if (previous == CONNECTING) {
1013             // there is no connection to wait for
1014             shutdownAdapter();
1015         }
1016         else if (closeSessions(statusCode, closeReason)) {
1017             // OPEN: the closing handshake is under way. The adapter reports the end of the connection with the
1018             // status code of the server, and connectionEnded() releases the client then.
1019             return;
1020         }
1021         else {
1022             // the close frame could not be sent, so there is no answer to wait for
1023             releaseClient();
1024         }
1025 
1026         // the adapter has nothing to report for a cancelled attempt: fail the connection ourselves, after
1027         // the running script (error + close 1006)
1028         queueTask(() -> connectionEnded(CLOSE_ABNORMAL, "", true));
1029     }
1030 
1031     /**
1032      * Transmits data to the server over the WebSocket connection.
1033      * Throws an {@code InvalidStateError} while {@link #CONNECTING}; the data is discarded when
1034      * {@link #CLOSING} or {@link #CLOSED}. Anything that is not binary
1035      * is converted to a string and sent as text message. Binary data (an ArrayBuffer, a typed array or
1036      * DataView, which contribute only the part they view, or a Blob) is sent as binary message; it is copied
1037      * before this method returns, so later changes of the buffer do not change what is sent.
1038      *
1039      * @param content the data to send
1040      */
1041     @JsxFunction
1042     public void send(final Object content) {
1043         final int state = readyState_.get();
1044         if (state == CONNECTING) {
1045             throw JavaScriptEngine.asJavaScriptException(
1046                     getWindow(),
1047                     "WebSocket Error: send() is not allowed while the connection is CONNECTING.",
1048                     DOMException.INVALID_STATE_ERR);
1049         }
1050         if (state != OPEN) {
1051             // CLOSING or CLOSED: the data is discarded, but its size is added to bufferedAmount
1052             bufferedAmount_.addAndGet(byteLengthOf(content));
1053             return;
1054         }
1055 
1056         try {
1057             final byte[] bytes = copyOfBinaryData(content);
1058             if (bytes != null) {
1059                 webSocketImpl_.send(ByteBuffer.wrap(bytes));
1060                 return;
1061             }
1062 
1063             // everything else is sent as text, converted like a USVString: ToString (so 42, null, undefined
1064             // and objects become "42", "null", "undefined" and "[object Object]") and every unpaired
1065             // surrogate replaced by U+FFFD (the UTF-8 encoder of Java would write '?' for it)
1066             webSocketImpl_.send(toUsvString(JavaScriptEngine.toString(content)));
1067         }
1068         catch (final IOException e) {
1069             LOG.error("WS send error", e);
1070         }
1071     }
1072 
1073     /**
1074      * Bridges the callbacks of the {@link WebSocketAdapter} to this WebSocket: it switches the ready state and
1075      * fires the events at the scripts. The callbacks come from the threads of the adapter.
1076      */
1077     private final class AdapterListener implements WebSocketListener {
1078 
1079         private final VarScope scope_;
1080 
1081         AdapterListener(final VarScope scope) {
1082             scope_ = scope;
1083         }
1084 
1085         @Override
1086         public void onWebSocketConnecting() {
1087             // nothing to do, CONNECTING is the initial state and is never entered again
1088         }
1089 
1090         @Override
1091         public void onWebSocketOpen() {
1092             connectionOpened();
1093         }
1094 
1095         @Override
1096         public void onWebSocketClose(final int statusCode, final String reason) {
1097             connectionEnded(statusCode, reason, false);
1098         }
1099 
1100         @Override
1101         public void onWebSocketText(final String message) {
1102             if (readyState_.get() != OPEN) {
1103                 // messages received after close() was called are dropped
1104                 return;
1105             }
1106 
1107             final AbstractJavaScriptEngine<?> engine = containingPage_.getWebClient().getJavaScriptEngine();
1108             if (engine != null) {
1109                 engine.getContextFactory().call(cx -> {
1110                     final MessageEvent msgEvent = new MessageEvent(message);
1111                     msgEvent.setParentScope(scope_);
1112                     msgEvent.setPrototype(getPrototype(msgEvent.getClass()));
1113                     if (origin_ != null) {
1114                         msgEvent.setOrigin(origin_);
1115                     }
1116                     msgEvent.setSrcElement(WebSocket.this);
1117                     msgEvent.setTarget(WebSocket.this);
1118                     executeEventLocally(msgEvent);
1119 
1120                     return null;
1121                 });
1122             }
1123         }
1124 
1125         @Override
1126         public void onWebSocketBinary(final ByteBuffer payload) {
1127             if (readyState_.get() != OPEN) {
1128                 // messages received after close() was called are dropped
1129                 return;
1130             }
1131 
1132             final AbstractJavaScriptEngine<?> engine = containingPage_.getWebClient().getJavaScriptEngine();
1133             if (engine != null) {
1134                 engine.getContextFactory().call(cx -> {
1135                     final MessageEvent msgEvent;
1136 
1137                     if ("blob".equals(binaryType_)) {
1138                         final byte[] bytes = new byte[payload.remaining()];
1139                         payload.get(bytes);
1140                         final Blob blob = new Blob(bytes, "application/octet-stream");
1141 
1142                         blob.setParentScope(getParentScope());
1143                         blob.setPrototype(ScriptableObject.getClassPrototype(getParentScope(),
1144                                             blob.getClassName()));
1145 
1146                         msgEvent = new MessageEvent(blob);
1147                     }
1148                     else {
1149                         final NativeArrayBuffer buffer = new NativeArrayBuffer(payload.remaining());
1150                         buffer.getByteBuffer().put(payload);
1151 
1152                         buffer.setParentScope(getParentScope());
1153                         buffer.setPrototype(ScriptableObject.getClassPrototype(getParentScope(),
1154                                                 buffer.getClassName()));
1155 
1156                         msgEvent = new MessageEvent(buffer);
1157                     }
1158 
1159                     msgEvent.setParentScope(scope_);
1160                     msgEvent.setPrototype(getPrototype(msgEvent.getClass()));
1161                     if (origin_ != null) {
1162                         msgEvent.setOrigin(origin_);
1163                     }
1164                     msgEvent.setSrcElement(WebSocket.this);
1165                     msgEvent.setTarget(WebSocket.this);
1166                     executeEventLocally(msgEvent);
1167 
1168                     return null;
1169                 });
1170             }
1171         }
1172 
1173         @Override
1174         public void onWebSocketConnectError(final Throwable cause) {
1175             if (LOG.isErrorEnabled()) {
1176                 LOG.error("WS connect error for url '" + url_ + "':", cause);
1177             }
1178             onWebSocketError(cause);
1179         }
1180 
1181         @Override
1182         public void onWebSocketError(final Throwable cause) {
1183             connectionEnded(CLOSE_ABNORMAL, "", true);
1184         }
1185     }
1186 }