NetworkHyBi Working Group I.HicksonFette Internet-Draft Google, Inc. Intended status: Standards TrackMay 23,August 31, 2010 Expires:November 24, 2010March 4, 2011 The WebSocket protocoldraft-ietf-hybi-thewebsocketprotocol-00draft-ietf-hybi-thewebsocketprotocol-01 Abstract The WebSocket protocol enables two-way communication between a user agent running untrusted code running in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the Origin-based security model commonly used by Web browsers. The protocol consists of an initial handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling).NOTE! THIS COPY OF THIS DOCUMENT IS OBSOLETE. For an up-to-date copy of this specification, please see: http://www.whatwg.org/specs/web-socket-protocol/ Author's note This document is automatically generated from the same source document as the HTML specification. [HTML]Please send feedback toeitherthe hybi@ietf.orglist or the whatwg@whatwg.orgmailing list. Note This draft is meant to reflect changes in direction in the HyBi working group. There is not yet consensus on everything in this draft. Specifically, details about the framing are still under discussion, however this draft is much closer to what the group is discussing than the previous draft. There have also been proposals to change the handshake, so the handshake is also not in a final form. Status of this Memo This Internet-Draft is submittedto IETFin full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire onNovember 24, 2010.March 4, 2011. Copyright Notice Copyright (c) 2010 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . .45 1.1. Background . . . . . . . . . . . . . . . . . . . . . . . .45 1.2. Protocol overview . . . . . . . . . . . . . . . . . . . .45 1.3. Opening handshake . . . . . . . . . . . . . . . . . . . .79 1.4. Closing handshake . . . . . . . . . . . . . . . . . . . .1012 1.5. Design philosophy . . . . . . . . . . . . . . . . . . . .1113 1.6. Security model . . . . . . . . . . . . . . . . . . . . . .1214 1.7. Relationship to TCP and HTTP . . . . . . . . . . . . . . .1214 1.8. Establishing a connection . . . . . . . . . . . . . . . .1214 1.9. Subprotocols using the WebSocket protocol . . . . . . . .1315 2. Conformance requirements . . . . . . . . . . . . . . . . . . .1517 2.1. Terminology . . . . . . . . . . . . . . . . . . . . . . .1517 3. WebSocket URLs . . . . . . . . . . . . . . . . . . . . . . . .1719 3.1. Parsing WebSocket URLs . . . . . . . . . . . . . . . . . .1719 3.2. Constructing WebSocket URLs . . . . . . . . . . . . . . .18 4. Client-side requirements20 3.3. Valid WebSocket URLs . . . . . . . . . . . . . . . . . . .19 4.1. Opening handshake20 4. Data Framing . . . . . . . . . . . . . . . . . . . .19 4.2. Data framing. . . . . 21 4.1. Overview . . . . . . . . . . . . . . . . . .28 4.3. Handling errors in UTF-8 from the server. . . . . . . 21 4.2. Base Framing Protocol . .30 5. Server-side requirements. . . . . . . . . . . . . . . . 21 4.3. Fragmentation . . .32 5.1. Reading the client's opening handshake. . . . . . . . . .32 5.2. Sending the server's opening handshake. . . . . . . . . 22 4.4. Control Frames .35 5.3. Data framing. . . . . . . . . . . . . . . . . . . . . 23 4.5. Data Frames . .39 5.4. Handling errors in UTF-8 from the client. . . . . . . . .41 6. Closing the connection. . . . . . . . . . . . 24 4.6. Examples . . . . . . . .42 6.1. Client-initiated closure. . . . . . . . . . . . . . . . .42 6.2. Server-initiated closure24 4.7. Extensibility . . . . . . . . . . . . . . . . .42 6.3. Closure. . . . . 25 5. Opening Handshake . . . . . . . . . . . . . . . . . . . .42 7. Security considerations. . 26 5.1. Client Requirements . . . . . . . . . . . . . . . . .44 8. IANA considerations. . 26 5.2. Server-side requirements . . . . . . . . . . . . . . . . . 35 5.2.1. Reading the client's opening handshake . .45 8.1. Registration of ws: scheme. . . . . . 35 5.2.2. Sending the server's opening handshake . . . . . . . . 38 6. Error Handling . .45 8.2. Registration of wss: scheme. . . . . . . . . . . . . . .46 8.3. Registration of the "WebSocket" HTTP Upgrade keyword. . .47 8.4. Sec-WebSocket-Key1 and Sec-WebSocket-Key2. . . . 43 6.1. Handling errors in UTF-8 from the server . . . .47 8.5. Sec-WebSocket-Location. . . . . 43 6.2. Handling errors in UTF-8 from the client . . . . . . . . . 43 7. Closing the connection . . . .48 8.6. Sec-WebSocket-Origin. . . . . . . . . . . . . . . . 44 7.1. Client-initiated closure . . .49 8.7. Sec-WebSocket-Protocol. . . . . . . . . . . . . . 44 7.2. Server-initiated closure . . . .50 9. Using. . . . . . . . . . . . . 44 7.3. Closure . . . . . . . . . . . . . . . . . . . . . . . . . 44 8. Security considerations . . . . . . . . . . . . . . . . . . . 46 9. IANA considerations . . . . . . . . . . . . . . . . . . . . . 47 9.1. Registration of ws: scheme . . . . . . . . . . . . . . . . 47 9.2. Registration of wss: scheme . . . . . . . . . . . . . . . 48 9.3. Registration of the "WebSocket" HTTP Upgrade keyword . . . 49 9.4. Sec-WebSocket-Key1 and Sec-WebSocket-Key2 . . . . . . . . 49 9.5. Sec-WebSocket-Location . . . . . . . . . . . . . . . . . . 50 9.6. Sec-WebSocket-Origin . . . . . . . . . . . . . . . . . . . 51 9.7. Sec-WebSocket-Protocol . . . . . . . . . . . . . . . . . . 52 10. Using the WebSocket protocol from other specifications . . . .51 10.53 11. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . .52 11.54 12. Normative References . . . . . . . . . . . . . . . . . . . . .5355 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . .5557 1. Introduction 1.1. Background _This section is non-normative._ Historically, creating an instant messenger chat client as a Web application has required an abuse of HTTP to poll the server for updates while sending upstream notifications as distinct HTTP calls. This results in a variety of problems: o The server is forced to use a number of different underlying TCP connections for each client: one for sending information to the client, and a new one for each incoming message. o The wire protocol has a high overhead, with each client-to-server message having an HTTP header. o The client-side script is forced to maintain a mapping from the outgoing connections to the incoming connection to track replies. A simpler solution would be to use a single TCP connection for traffic in both directions. This is what the WebSocket protocol provides. Combined with the WebSocket API, it provides an alternative to HTTP polling for two-way communication from a Web page to a remote server. [WSAPI] The same technique can be used for a variety of Web applications: games, stock tickers, multiuser applications with simultaneous editing, user interfaces exposing server-side services in real time, etc. 1.2. Protocol overview _This section is non-normative._ The protocol has two parts: a handshake, and then the data transfer. The handshake from the client looks as follows: GET /demo HTTP/1.1 Host: example.com Connection: Upgrade Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 Sec-WebSocket-Protocol: sample Upgrade: WebSocket Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 Origin: http://example.com ^n:ds[4U The handshake from the server looks as follows: HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Location: ws://example.com/demo Sec-WebSocket-Protocol: sample 8jKS'y:G*Co,Wxa- The leading line from the client follows the Request-Line format. The leading line from the server follows the Status-Line format. The Request-Line and Status-Line productions are defined in the HTTP specification. After the leading line in both cases come an unordered ASCII case- insensitive set of fields, one per line, that each match the following non-normative ABNF: [RFC5234] field = 1*name-char colon [ space ] *any-char cr lf colon = %x003A ; U+003A COLON (:) space = %x0020 ; U+0020 SPACE cr = %x000D ; U+000D CARRIAGE RETURN (CR) lf = %x000A ; U+000A LINE FEED (LF) name-char = %x0000-0009 / %x000B-000C / %x000E-0039 / %x003B-10FFFF ; a Unicode character other than ; U+000A LINE FEED (LF), ; U+000D CARRIAGE RETURN (CR), ; or U+003A COLON (:) any-char = %x0000-0009 / %x000B-000C / %x000E-10FFFF ; a Unicode character other than ; U+000A LINE FEED (LF) ; or U+000D CARRIAGE RETURN (CR) NOTE: The character set for the above ABNF is Unicode. The fields themselves are encoded as UTF-8. Lines that don't match the above production cause the connection to be aborted. Finally, after the last field, the client sends 10 bytes starting with 0x0D 0x0A and followed by 8 random bytes, part of a challenge, and the server sends 18 bytes starting with 0x0D 0x0A and followed by 16 bytes consisting of a challenge response. The details of this challenge and other parts of the handshake are described in the next section. Once the client and server have both sent their handshakes, and if the handshake was successful, then the data transfer part starts. This is a two-way communication channel where each side can, independently from the other, send data at will.Data is sent in the form of UTF-8 text. Each frame of data starts with a 0x00 byteClients andends withservers, after a0xFF byte, with the UTF-8 textsuccessful handshake, transfer data back and forth in conceptual units referred to in this specification as "messages". A message is a complete unit of data at an application level, with the expectation that many or most applications implementing this protocol (such as web user agents) provide APIs in terms of sending and receiving messages. On the network layer, a message may be represented as one or more frames. Data is sent on the wire inbetween.the form of frames that have an associated type. Broadly speaking, there are types for textual data, which is interpreted as UTF-8 text, binary data (whose interpretation is left up to the application), and control frames, which are not intended to carry data for the application, but instead for protocol- level signalling, such as to signal that the connection should be closed. The WebSocket protocol uses this framing so that specifications that use the WebSocket protocol can expose such connections using an event-based mechanism instead of requiring users of those specifications to implement buffering and piecing together of messages manually. To close the connection cleanly, a control frameconsisting of just a 0xFF byte followed by a 0x00 byteis sent from one peer to ask that the other peer close the connection. Details are specified in Section 7. The protocol is designed to support other frame types in future.Instead of the 0x00 and 0xFF bytes, other bytes might in future be defined. Frames denoted by bytes that do not have the high bit set (0x00 to 0x7F)Currently only four frame types aretreated as a stream of bytes terminated by 0xFF. Frames denoted by bytes that have the high bit set (0x80 to 0xFF) have a leading length indicator, which is encoded as a series of 7-bit bytes stored in octets with the 8th bit being setdefined -- continuation (used forall but the last byte. The remainder of the frame is then as much data as was specified. (The closing handshake contains nofragmented messages), control frames, text frames, and binary data frames. Eight frame types are reserved for future use, andtherefore has a length byte of 0x00.)four frame types are reserved for private use. This wire format for the data transfer part is described by thefollowing non-normative ABNF, which isABNF given intwo alternative forms: the first describingdetail in Section 4. A high level overview of thewire format as allowed by this specification, andframing is given in thesecond describing how an arbitrary bytestream would be parsed.following figure. [RFC5234];0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |M|R|R|R| opcode|R| Payload len | Extended payload length | |O|S|S|S| (4) |S| (7) | (16/63) | |R|V|V|V| |V| | (if payload len==126/127) | |E|1|2|3| |4| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | | Extension data | +-------------------------------+ - - - - - - - - - - - - - - - + : : +---------------------------------------------------------------+ : Application data : +---------------------------------------------------------------+ MORE: 1 bit Indicates more fragments follow in thewire protocol as allowed by this specification frames = *frame frame = text-frame / closing-frame text-frame = %x00 *( UTF8-char ) %xFF closing-frame = %xFF %x00 ;current message RSV1, RSV2, RSV3, RSV4: 1 bit each Must be 0 unless an extension is negotiated which defines meanings for non-zero values Opcode: 4 bits Defines thewire protocol including error-handling and forward-compatible parsing rules frames = *frame frame = text-frame / binary-frame text-frame = (%x00-7F) *(%x00-FE) %xFF binary-frame = (%x80-FF)interpretation of the payload data Payload length: 7 bits The length<of the payload: if 0-125, that is the payload length. If 126, the following 2 bytes interpreted asmanya 16 bit unsigned integer are the payload length. If 127, the following 8 bytes interpreted asgiven bya 64-bit unsigned integer (the high bit must be 0) are the payload length. The payload length is the length>of the Extension data + the length= *(%x80-FF) (%x00-7F)of the Application Data. TheUTF8-char rule is definedlength of the Extension data may be zero, in which case theUTF-8 specification. [RFC3629] NOTE: The above ABNFPayload length isintended for a binary octet environment. !!! WARNING: At this time,theWebSocket protocol cannot be used to send binarylength of the Application data.Using anyExtension data: n bytes Only present if an extension is negotiated during the handshake which defines it. If present, it is included in the total payload length. Application data: n bytes Arbitrary application data, taking up the remainder of the frametypes other than 0x00 and 0xFFafter any extension data. The length of the Application data isinvalid. All other frame types are reserved for future use by future versionsequal to the payload length minus the length ofthis protocol. The following diagram summarisestheprotocol: Handshake | V Frame type byte <--------------------------------------. | | | | `--> (0x00 to 0x7F) --> Data... --> 0xFF -->-+ | | `--> (0x80 to 0xFE) --> Length --> Data... ------->-'Extension data. 1.3. Opening handshake _This section is non-normative._ The opening handshake is intended to be compatible with HTTP-based server-side software, so that a single port can be used by both HTTP clients talking to that server and WebSocket clients talking to that server. To this end, the WebSocket client's handshake appears to HTTP servers to be a regular GET request with an Upgrade offer: GET / HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Fields in the handshake are sent by the client in a random order; the order is not meaningful. Additional fields are used to select options in the WebSocket protocol. The only options available in this version are the subprotocol selector, |Sec-WebSocket-Protocol|, and |Cookie|, which can used for sending cookies to the server (e.g. as an authentication mechanism). The |Sec-WebSocket-Protocol| field takes an arbitrary string: Sec-WebSocket-Protocol: chat This field indicates the subprotocol (the application-level protocol layered over the WebSocket protocol) that the client intends to use. The server echoes this field in its handshake to indicate that it supports that subprotocol. The other fields in the handshake are all security-related. The |Host| field is used to protect against DNS rebinding attacks and to allow multiple domains to be served from one IP address. Host: example.com The server includes the hostname in the |Sec-WebSocket-Location| field of its handshake, so that both the client and the server can verify that they agree on which host is in use. The |Origin| field is used to protect against unauthorized cross- origin use of a WebSocket server by scripts using the |WebSocket| API in a Web browser. The server specifies which origin it is willing to receive requests from by including a |Sec-WebSocket-Origin| field with that origin. If multiple origins are authorized, the server echoes the value in the |Origin| field of the client's handshake. Origin: http://example.com Finally, the server has to prove to the client that it received the client's WebSocket handshake, so that the server doesn't accept connections that are not WebSocket connections. This prevents an attacker from tricking a WebSocket server by sending it carefully- crafted packets using |XMLHttpRequest| or a |form| submission. To prove that the handshake was received, the server has to take three pieces of information and combine them to form a response. The first two pieces of information come from the |Sec-WebSocket-Key1| and |Sec-WebSocket-Key2| fields in the client handshake: Sec-WebSocket-Key1: 18x 6]8vM;54 *(5: { U1]8 z [ 8 Sec-WebSocket-Key2: 1_ tx7X d < nw 334J702) 7]o}` 0 For each of these fields, the server has to take the digits from the value to obtain a number (in this case 1868545188 and 1733470270 respectively), then divide that number by the number of spaces characters in the value (in this case 12 and 10) to obtain a 32-bit number (155712099 and 173347027). These two resulting numbers are then used in the server handshake, as described below. The counting of spaces is intended to make it impossible to smuggle this field into the resource name; making this even harder is the presence of _two_ such fields, and the use of a newline as the only reliable indicator that the end of the key has been reached. The use of random characters interspersed with the spaces and the numbers ensures that the implementor actually looks for spaces and newlines, instead of being treating any character like a space, which would make it again easy to smuggle the fields into the path and trick the server. Finally, _dividing_ by this number of spaces is intended to make sure that even the most naive of implementations will check for spaces, since if ther server does not verify that there are some spaces, the server will try to divide by zero, which is usually fatal (a correct handshake will always have at least one space). The third piece of information is given after the fields, in the last eight bytes of the handshake, expressed here as they would be seen if interpreted as ASCII: Tm[K T2u The concatenation of the number obtained from processing the |Sec- WebSocket-Key1| field, expressed as a big-endian 32 bit number, the number obtained from processing the |Sec-WebSocket-Key2| field, again expressed as a big-endian 32 bit number, and finally the eight bytes at the end of the handshake, form a 128 bit string whose MD5 sum is then used by the server to prove that it read the handshake. The handshake from the server is much simpler than the client handshake. The first line is an HTTP Status-Line, with the status code 101 (the HTTP version and reason phrase aren't important): HTTP/1.1 101 WebSocket Protocol Handshake The fields follow. Two of the fields are just for compatibility with HTTP: Upgrade: WebSocket Connection: Upgrade Two of the fields are part of the security model described above, echoing the origin and stating the exact host, port, resource name, and whether the connection is expected to be encrypted: Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Location: ws://example.com/ These fields are checked by the Web browser when it is acting as a |WebSocket| client for scripted pages. A server that only handles one origin and only serves one resource can therefore just return hard-coded values and does not need to parse the client's handshake to verify the correctness of the values. Option fields can also be included. In this version of the protocol, the main option field is |Sec-WebSocket-Protocol|, which indicates the subprotocol that the server speaks. Web browsers verify that the server included the same value as was specified in the |WebSocket| constructor, so a server that speaks multiple subprotocols has to make sure it selects one based on the client's handshake and specifies the right one in its handshake. Sec-WebSocket-Protocol: chat The server can also set cookie-related option fields to _set_ cookies, as in HTTP. After the fields, the server sends the aforementioned MD5 sum, a 16 byte (128 bit) value, shown here as if interpreted as ASCII: fQJ,fN/4F4!~K~MH This value depends on what the client sends, as described above. If it doesn't match what the client is expecting, the client would disconnect. Having part of the handshake appear after the fields ensures that both the server and the client verify that the connection is not being interrupted by an HTTP intermediary such as a man-in-the-middle cache or proxy. 1.4. Closing handshake _This section is non-normative._ The closing handshake is far simpler than the opening handshake. Either peer can send a0xFFcontrol frame withlength 0x00data containing a specified control sequence to begin the closing handshake. Upon receiving such a0xFFframe, the other peer sends an identical0xFFframe in acknowledgement, if it hasn't already sent one. Upon receiving _that_0xFFcontrol frame, the first peer then closes the connection, safe in the knowledge that no further data is forthcoming. After sending a0xFF frame,control frame indicating the connection should be closed, a peer does not send any further data; after receiving a0xFF frame,control frame frame indicating the connection should be closed, a peer discards any further data received. It is safe for both peers to initiate this handshake simultaneously. The closing handshake is intended to replace the TCP closing handshake (FIN/ACK), on the basis that the TCP closing handshake is not always reliable end-to-end, especially in the presence of man-in- the-middle proxies and other intermediaries. 1.5. Design philosophy _This section is non-normative._ The WebSocket protocol is designed on the principle that there should be minimal framing (the only framing that exists is to make the protocol frame-based instead of stream-based, and to support a distinction between Unicode text and binary frames). It is expected that metadata would be layered on top of WebSocket by the application layer, in the same way that metadata is layered on top of TCP by the application layer (HTTP). Conceptually, WebSocket is really just a layer on top of TCP that adds a Web "origin"-based security model for browsers; adds an addressing and protocol naming mechanism to support multiple services on one port and multiple host names on one IP address; layers a framing mechanism on top of TCP to get back to the IP packet mechanism that TCP is built on, but without length limits; and reimplements the closing handshake in-band. Other than that, it adds nothing. Basically it is intended to be as close to just exposing raw TCP to script as possible given the constraints of the Web. It's also designed in such a way that its servers can share a port with HTTP servers, by having its handshake be a valid HTTP Upgrade handshake also. The protocol is intended to be extensible; future versions will likely introduce a mechanism to compress data and might support sending binary data. 1.6. Security model _This section is non-normative._ The WebSocket protocol uses the origin model used by Web browsers to restrict which Web pages can contact a WebSocket server when the WebSocket protocol is used from a Web page. Naturally, when the WebSocket protocol is used by a dedicated client directly (i.e. not from a Web page through a Web browser), the origin model is not useful, as the client can provide any arbitrary origin string. This protocol is intended to fail to establish a connection with servers of pre-existing protocols like SMTP or HTTP, while allowing HTTP servers to opt-in to supporting this protocol if desired. This is achieved by having a strict and elaborate handshake, and by limiting the data that can be inserted into the connection before the handshake is finished (thus limiting how much the server can be influenced). It is similarly intended to fail to establish a connection when data from other protocols, especially HTTP, is sent to a WebSocket server, for example as might happen if an HTML |form| were submitted to a WebSocket server. This is primarily achieved by requiring that the server prove that it read the handshake, which it can only do if the handshake contains the appropriate parts which themselves can only be sent by a WebSocket handshake; in particular, fields starting with |Sec-| cannot be set by an attacker from a Web browser, even when using |XMLHttpRequest|. 1.7. Relationship to TCP and HTTP _This section is non-normative._ The WebSocket protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. Based on the expert recommendation of the IANA, the WebSocket protocol by default uses port 80 for regular WebSocket connections and port 443 for WebSocket connections tunneled over TLS. 1.8. Establishing a connection _This section is non-normative._ There are several options for establishing a WebSocket connection. On the face of it, the simplest method would seem to be to use port 80 to get a direct connection to a WebSocket server. Port 80 traffic, however, will often be intercepted by man-in-the-middle HTTP proxies, which can lead to the connection failing to be established. The most reliable method, therefore, is to use TLS encryption and port 443 to connect directly to a WebSocket server. This has the advantage of being more secure; however, TLS encryption can be computationally expensive. When a connection is to be made to a port that is shared by an HTTP server (a situation that is quite likely to occur with traffic to ports 80 and 443), the connection will appear to the HTTP server to be a regular GET request with an Upgrade offer. In relatively simple setups with just one IP address and a single server for all traffic to a single hostname, this might allow a practical way for systems based on the WebSocket protocol to be deployed. In more elaborate setups (e.g. with load balancers and multiple servers), a dedicated set of hosts for WebSocket connections separate from the HTTP servers is probably easier to manage. 1.9. Subprotocols using the WebSocket protocol _This section is non-normative._ The client can request that the server use a specific subprotocol by including the |Sec-Websocket-Protocol| field in its handshake. If it is specified, the server needs to include the same field and value in its response for the connection to be established. These subprotocol names do not need to be registered, but if a subprotocol is intended to be implemented by multiple independent WebSocket servers, potential clashes with the names of subprotocols defined independently can be avoided by using names that contain the domain name of the subprotocol's originator. For example, if Example Corporation were to create a Chat subprotocol to be implemented by many servers around the Web, they could name it "chat.example.com". If the Example Organisation called their competing subprotocol "example.org's chat protocol", then the two subprotocols could be implemented by servers simultaneously, with the server dynamically selecting which subprotocol to use based on the value sent by the client. Subprotocols can be versioned in backwards-incompatible ways by changing the subprotocol name, eg. going from "bookings.example.net" to"bookings.example.net2"."v2.bookings.example.net". These subprotocols would be considered completely separate by WebSocket clients. Backwards-compatible versioning can be implemented by reusing the same subprotocol string but carefully designing the actual subprotocol to support this kind of extensibility. 2. Conformance requirements All diagrams, examples, and notes in this specification are non- normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative. The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119] Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm. Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.) Implementations may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations. The conformance classes defined by this specification are user agents and servers. 2.1. Terminology *Converting a string to ASCII lowercase* means replacing all characters in the range U+0041 to U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) with the corresponding characters in the range U+0061 to U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z). Comparing two strings in an *ASCII case-insensitive* manner means comparing them exactly, code point for code point, except that the characters in the range U+0041 to U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding characters in the range U+0061 to U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are considered to also match. The term "URL" is used in this section in a manner consistent with the terminology used in HTML, namely, to denote a string that might or might not be a valid URI or IRI and to which certain error handling behaviors will be applied when the string is parsed. [HTML] When an implementation is required to _send_ data as part of the WebSocket protocol, the implementation may delay the actual transmission arbitrarily, e.g. buffering data so as to send fewer IP packets. 3. WebSocket URLs 3.1. Parsing WebSocket URLs The steps to *parse a WebSocket URL's components* from a string /url/ are as follows. These steps return either a /host/, a /port/, a /resource name/, and a /secure/ flag, or they fail. 1. If the /url/ string is not an absolute URL, then fail this algorithm. [WEBADDRESSES] 2. Resolve the /url/ string using the resolve a Web address algorithm defined by the Web addresses specification, with the URL character encoding set to UTF-8. [WEBADDRESSES] [RFC3629] NOTE: It doesn't matter what it is resolved relative to, since we already know it is an absolute URL at this point. 3. If /url/ does not have a <scheme> component whose value, when converted to ASCII lowercase, is either "ws" or "wss", then fail this algorithm. 4. If /url/ has a <fragment> component, then fail this algorithm. 5. If the <scheme> component of /url/ is "ws", set /secure/ to false; otherwise, the <scheme> component is "wss", set /secure/ to true. 6. Let /host/ be the value of the <host> component of /url/, converted to ASCII lowercase. 7. If /url/ has a <port> component, then let /port/ be that component's value; otherwise, there is no explicit /port/. 8. If there is no explicit /port/, then: if /secure/ is false, let /port/ be 80, otherwise let /port/ be 443. 9. Let /resource name/ be the value of the <path> component (which might be empty) of /url/. 10. If /resource name/ is the empty string, set it to a single character U+002F SOLIDUS (/). 11. If /url/ has a <query> component, then append a single U+003F QUESTION MARK character (?) to /resource name/, followed by the value of the <query> component. 12. Return /host/, /port/, /resource name/, and /secure/. 3.2. Constructing WebSocket URLs The steps to *construct a WebSocket URL* from a /host/, a /port/, a /resource name/, and a /secure/ flag, are as follows: 1. Let /url/ be the empty string. 2. If the /secure/ flag is false, then append the string "ws://" to /url/. Otherwise, append the string "wss://" to /url/. 3. Append /host/ to /url/. 4. If the /secure/ flag is false and port is not 80, or if the /secure/ flag is true and port is not 443, then append the string ":" followed by /port/ to /url/. 5. Append /resource name/ to /url/. 6. Return /url/.4. Client-side requirements _This section only applies to user agents, not to servers._ NOTE: This specification doesn't currently define a limit to the number of simultaneous connections that a client can establish to a server. 4.1. Opening handshake When the user agent is to *establish3.3. Valid WebSocket URLs For a WebSocketconnection*URL toa host /host/, on a port /port/, from an origin whose ASCII serialization is /origin/, with a flag /secure/, with a string giving a /resource name/, and optionally with a string giving a /protocol/, it must runbe considered valid, the followingsteps.conditions MUST hold. o The /host/ must be ASCII-only (i.e. it must have beenpunycode-encodedpunycode- encoded already if necessary). o The /origin/ must not contain characters in the range U+0041 to U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z). o The /resource name/ and /protocol/ strings must be non-empty strings of ASCII characters in the range U+0020 to U+007E. o The /resource name/ string must start with a U+002F SOLIDUS character (/) and must not contain a U+0020 SPACE character.[ORIGIN] 1. IfAny WebSocket URLs not meeting theuser agent already hasabove criteria are considered invalid, and aWebSocket connectionclient MUST NOT attempt tothe remote host (IP address) identified by /host/, even if known by another name, wait until that connection has been established or for thatmake a connection tohave failed. If multiple connectionsan invalid WebSocket URL. A client SHOULD attempt tothe same IP address are attempted simultaneously, the user agent must serialize them so that there is no more than one connection atparse atime running through the following steps. NOTE: This makes it harder forURL obtained from any external source (such as ascript to performweb site or adenial of service attack by just openinguser) using the steps specified in Section 3.1 to obtain alarge number ofvalid WebSocketconnections to a remote host. NOTE: There is no limit to the number of established WebSocket connections a user agent can have with a single remote host. Servers can refuseURL, but MUST NOT attempt to connectuserswith such anexcessive number of connections, or disconnect resource-hogging users when suffering high load. 2. _Connect_: Ifunparsed URL, and instead only use theuser agentparsed version and only if that version isconfigured to use a proxy when usingconsidered valid by theWebSocketcriteria above. 4. Data Framing 4.1. Overview The base framing protocolto connect to host /host/ and/or port /port/, then connect tois deliberately kept simple so thatproxy and ask it to open a TCP connection tosimple implementations may ignore advanced features. In thehost given by /host/ andabsence of extensions negotiated during theport givenopening handshake (Section 5), all reserved bits must be 0 and no reserved opcode values may be used. 4.2. Base Framing Protocol The base framing protocol is defined by/port/. EXAMPLE: For example, iftheuser agent uses an HTTP proxy for all traffic, then if it was to try to connectfollowing ABNF [RFC5234]: ws-frame = frame-more frame-rsv1 frame-rsv2 frame-rsv3 frame-opcode frame-rsv4 frame-length frame-extension application-data; frame-more = %x0 ; final frame of message / %x1 ; more frames of this message follow frame-rsv1 = %x0 ; 1 bit, must be 0 frame-rsv2 = %x0 ; 1 bit, must be 0 frame-rsv3 = %x0 ; 1 bit, must be 0 frame-opcode = %x0 ; continuation frame / %x1 ; connection close / %x2 ; ping / %x3 ; pong / %x4 ; text frame / %x5 ; binary frame / %x6-F ; reserved frame-rsv4 = %x0 ; 1 bit, must be 0 frame-length = %x00-7D / %x7E frame-length-16 / %x7F frame-length-63 frame-length-16 = %x0000-FFFF frame-length-63 = %x0000000000000000-7FFFFFFFFFFFFFFF frame-extension = *( %x00-FF ) ; toport 80 on server example.com, it might send thebe defined later application-data = *( %x00-FF ) 4.3. Fragmentation The followinglinesrules apply tothe proxy server: CONNECT example.com:80 HTTP/1.1 Host: example.com If there was a password, the connection might look like: CONNECT example.com:80 HTTP/1.1 Host: example.com Proxy-authorization: Basic ZWRuYW1vZGU6bm9jYXBlcyE= Otherwise, if the user agent is not configured to use a proxy, then open a TCP connection to the host given by /host/ and the port given by /port/. NOTE: Implementations that do not expose explicit UI for selecting a proxy for WebSocket connections separate from other proxies are encouraged to use a SOCKS proxy for WebSocket connections, if available, or failing that, to prefer the proxy configured for HTTPS connections over the proxy configured for HTTP connections. For the purposefragmentation: o An unfragmented message consists ofproxy autoconfiguration scripts, the URL to pass the function must be constructed from /host/, /port/, /resource name/, and the /secure/ flag using the steps to construct a WebSocket URL. NOTE: The WebSocket protocol can be identified in proxy autoconfiguration scripts from the scheme ("ws:" for unencrypted connections and "wss:" for encrypted connections). 3. If the connection could not be opened, then fail the WebSocket connection and abort these steps. 4. If /secure/ is true, performaTLS handshake over the connection. If this fails (e.g. the server's certificate could not be verified), then failsingle frame with theWebSocket connectionMORE bit clear andabort these steps. Otherwise, all further communication on this channel must run through the encrypted tunnel. [RFC2246] User agents must use the Server Name Indication extension in the TLS handshake. [RFC4366] 5. Send the UTF-8 string "GET" followed by a UTF-8-encoded U+0020 SPACE character to the remote side (the server). Send the /resource name/ value, encoded as UTF-8. Send another UTF-8-encoded U+0020 SPACE character, followed by the UTF-8 string "HTTP/1.1", followed by a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). 6. Let /fields/ be an empty list of strings. 7. Add the string "Upgrade: WebSocket" to /fields/. 8. Add the string "Connection: Upgrade" to /fields/. 9. Let /hostport/ beanempty string. 10. Append the /host/ value, converted to ASCII lowercase, to /hostport/. 11. If /secure/ is false, and /port/ is not 80, or if /secure/ is true, and /port/ is not 443, then append a U+003A COLON character (:) followed by the valueopcode other than 0. o A fragmented message consists of/port/, expressed asabase-ten integer, to /hostport/. 12. Add the string consisting ofsingle frame with theconcatenation ofMORE bit set and an opcode other than 0, followed by zero or more frames with thestring "Host:", a U+0020 SPACE character,MORE bit set and/hostport/,the opcode set to/fields/. 13. Add0, and terminated by a single frame with thestring consistingMORE bit clear and an opcode of 0. Its content is the concatenation of thestring "Origin:", a U+0020 SPACE character, and the /origin/ value, to /fields/. 14. If thereapplication data from each of those frames in order. o _Note: There isno /protocol/, then skip this step. Otherwise, addan open question as to whether control frames be interjected in thestring consistingmiddle ofthe concatenationa fragmented message. If so, it must be decided whether they be fragmented (which would require keeping a stack ofthe string "Sec-WebSocket-Protocol:","in-progress" messages)._ o A sender MAY arbitrarily fragment aU+0020 SPACE character, and the /protocol/ value,single message (which allows generation of dynamic content without having to/fields/. 15. Ifbuffer theclient has any cookies that woulddata in order to count it). o A receiver MUST berelevantprepared toa resource accessed over HTTP, if /secure/ is false, or HTTPS,accept arbitrarily fragmented messages, even if the sender sent the message in a single frame. o An intermediary MAY fragment a message arbitrarily, except that itis true, on host /host/, port /port/,MUST NOT fragment or otherwise modify any message with/resource name/ asany reserved bits set or using any reserved opcode, unless it observed thepath (and possibly query parameters), then addnegotiation of an extension which it understands and which defines the interpretation of those values. 4.4. Control Frames The Close (0x01), Ping (0x02), and Pong (0x03) frames are contol frames -- they do not supply data to/fields/ any HTTP headers that would be appropriate for that information. [RFC2616] [RFC2109] [RFC2965] This includes "HttpOnly" cookies (cookies withthehttp-only- flag setultimate endpoint, but instead are used to carry out tasks related totrue);the WebSocketprotocol is not considered a non-HTTP API forconnection itself. A receiver MUST take thepurposefollowing action upon receiving control frames: Close: Upon receipt ofcookie processing. 16. Let /spaces_1/ bearandom integer from 1close frame, an endpoint SHOULD send a Close frame to12 inclusive. Let /spaces_2/ bethe remote recipient, if it has not already done so, deliver arandom integer from 1close event to12 inclusive. EXAMPLE: For example, 5the application if necessary, and9. 17. Let /max_1/ bethen close thelargest integer not greater than 4,294,967,295 divided by /spaces_1/. Let /max_2/ beWebSocket. Ping Upon receipt of a Ping message, an endpoint SHOULD send a Pong response as soon as is practical. The Pong response MUST contain thelargest integer not greater than 4,294,967,295 divided by /spaces_2/. EXAMPLE: Continuingpayload provided in theexample, 858,993,459 and 477,218,588. 18. Let /number_1/Ping message, though an implementation MAY truncate the message at an implementation-defined size which MUST bea random integer from 0 to /max_1/ inclusive. Let /number_2/at least 8 _(TBD)_ bytes. Ping frames MAY be sent as arandom integer from 0 to /max_2/ inclusive. EXAMPLE: For example, 777,007,543 and 114,997,259. 19. Let /product_1/keep-alive mechanism, but if so the interval SHOULD be configurable. Pong If a Pong message is received without a matching Ping message being sent, an endpoint MUST drop theresultconnection. Otherwise, the endpoint SHOULD update any liveness timer it may have for the connection. 4.5. Data Frames All frame types not listed above are data frames, which transport application-layer data. The opcode determines the interpretation ofmultiplying /number_1/ and /spaces_1/ together. Let /product_2/ betheresultapplication data: Text The payload data is text data encoded as UTF-8. Binary The payload data is arbitrary binary data whose interpretation is solely up to the application layer. Additional data frame types will be defined in extensions or in a subsequent version ofmultiplying /number_2/ and /spaces_2/ together. EXAMPLE: Continuingtheexample, 3,885,037,715protocol. 4.6. Examples _This section is non-normative._ o A single-frame text message * 0x04 0x05 "Hello" o A fragmented text message * 0x84 0x03 "Hel" * 0x00 0x02 "lo" o Ping request and1,034,975,331. 20. Let /key_1/ beresponse * 0x02 0x05 "Hello" * 0x03 0x05 "Hello" o 256 bytes binary message in astring consistingsingle frame * 0x05 0x7E 0x0100 [256 bytes of/product_1/, expressedbinary data] o 64KiB binary message in a single frame * 0x05 0x7F 0x0000000000010000 [65536 bytes of binary data] 4.7. Extensibility Extensions will be defined which extend the baseten usingprotocol, but only if their use is negotiated during thenumeralshandshake. The following mechanisms will be used for extension: o Extension data may be placed in therange U+0030 DIGIT ZERO (0)payload before the application data. o Reserved bits can be allocated for per-frame needs. o Reserved opcode values can be defined. o Reserved bits can be allocated toU+0039 DIGIT NINE (9). Let /key_2/the opcode field if more opcode values are needed. o A reserved bit or an "extension" opcode can bea string consistingdefined which allocates additional bits out of/product_2/, expressed in base ten using the numerals intherange U+0030 DIGIT ZERO (0)payload area toU+0039 DIGIT NINE (9). EXAMPLE: Continuing the example, "3885037715" and "1034975331". 21. Insert between one and twelve random characters fromdefine larger opcodes or more per-frame bits. 5. Opening Handshake 5.1. Client Requirements When theranges U+0021user agent is toU+002F and U+003A*establish a WebSocket connection* toU+007E into /key_1/ at random positions. Insert between one and twelve random charactersa host /host/, on a port /port/, from an origin whose ASCII serialization is /origin/, with a flag /secure/, with a string giving a /resource name/, and optionally with a string giving a /protocol/, it must run theranges U+0021 to U+002Ffollowing steps. [ORIGIN] 1. Verify that the WebSocket URL andU+003A to U+007E into /key_2/ at random positions. NOTE: This correspondsits components are valid according torandom printable ASCII characters other thanSection 3.3. If any of the requirements are not met, the client MUST fail thedigitsWebSocket connection and abort these steps. 2. If theU+0020 SPACE character. EXAMPLE: Continuing the example, this could leaduser agent already has a WebSocket connection to"P388O503D& ul7{K%gX(%715" and "1N?|kUT0or3o4I97N5-S3O31". 22. Insert /spaces_1/ U+0020 SPACE characters into /key_1/ at random positions other thanthestartremote host (IP address) identified by /host/, even if known by another name, wait until that connection has been established orend of the string. Insert /spaces_2/ U+0020 SPACE characters into /key_2/ at random positions other thanfor that connection to have failed. If multiple connections to thestart or end ofsame IP address are attempted simultaneously, thestring. EXAMPLE: Continuinguser agent must serialize them so that there is no more than one connection at a time running through theexample, this could leadfollowing steps. NOTE: This makes it harder for a script to"P388 O503D& ul7 {K%gX( %7 15" and "1 N ?|k UT0or 3o 4 I97N 5-S3O 31". 23. Add the string consistingperform a denial ofthe concatenationservice attack by just opening a large number ofthe string "Sec-WebSocket-Key1:",WebSocket connections to aU+0020 SPACE character, and the /key_1/ value,remote host. NOTE: There is no limit to/fields/. Addthestring consistingnumber ofthe concatenationestablished WebSocket connections a user agent can have with a single remote host. Servers can refuse to connect users with an excessive number of connections, or disconnect resource-hogging users when suffering high load. 3. _Connect_: If thestring "Sec-WebSocket-Key2:",user agent is configured to use aU+0020 SPACE character,proxy when using the WebSocket protocol to connect to host /host/ and/or port /port/, then connect to that proxy andthe /key_2/ value,ask it to/fields/. 24. For each string in /fields/, inopen arandom order: sendTCP connection to thestring, encoded as UTF-8, followedhost given bya UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). It is important that the fields be output in a random order so that servers not depend on/host/ and theparticular order usedport given byany particular client. 25. Send a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). 26. Let /key3/ be a string consisting of eight random bytes (or equivalently, a random 64 bit integer encoded in big-endian order)./port/. EXAMPLE: For example,0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58. 27. Send /key3/ to the server. 28. Read bytes fromif the user agent uses an HTTP proxy for all traffic, then if it was to try to connect to port 80 on serveruntil eitherexample.com, it might send theconnection closes, or a 0x0A byte is read. Let /field/ be these bytes, includingfollowing lines to the0x0A byte.proxy server: CONNECT example.com:80 HTTP/1.1 Host: example.com If/field/ is not at least seven bytes long, or ifthere was a password, thelast two bytes aren't 0x0D and 0x0A respectively, orconnection might look like: CONNECT example.com:80 HTTP/1.1 Host: example.com Proxy-authorization: Basic ZWRuYW1vZGU6bm9jYXBlcyE= Otherwise, ifit doesthe user agent is notcontain at least two 0x20 bytes,configured to use a proxy, thenfail the WebSocketopen a TCP connection to the host given by /host/ andabort these steps. User agents may applythe port given by /port/. NOTE: Implementations that do not expose explicit UI for selecting atimeoutproxy for WebSocket connections separate from other proxies are encouraged tothis step, failing theuse a SOCKS proxy for WebSocketconnectionconnections, if available, or failing that, to prefer theserver does not send back data in a suitable time period. 29. Let /code/ beproxy configured for HTTPS connections over thesubstringproxy configured for HTTP connections. For the purpose of/field/ that starts fromproxy autoconfiguration scripts, thebyte afterURL to pass thefirst 0x20 byte,function must be constructed from /host/, /port/, /resource name/, andends withthebyte before/secure/ flag using thesecond 0x20 byte. 30.steps to construct a WebSocket URL. NOTE: The WebSocket protocol can be identified in proxy autoconfiguration scripts from the scheme ("ws:" for unencrypted connections and "wss:" for encrypted connections). 4. If/code/ is not three bytes long, or if any ofthebytes in /code/ areconnection could notin the range 0x30 to 0x39,be opened, then fail the WebSocket connection and abort these steps.31.5. If/code/, interpreted as UTF-8,/secure/ is"101", then move totrue, perform a TLS handshake over thenext step.connection. If/code/, interpreted as UTF-8, is "407", then either closethis fails (e.g. theconnection and jump back to step 2, providing appropriate authentication information, orserver's certificate could not be verified), then fail the WebSocketconnection. 407 isconnection and abort these steps. Otherwise, all further communication on this channel must run through thecode used by HTTP meaning "Proxy Authentication Required".encrypted tunnel. [RFC2246] User agentsthat support proxy authenticationmustinterpretuse the Server Name Indication extension in the TLS handshake. [RFC4366] 6. Send theresponse as definedUTF-8 string "GET" followed byHTTP (e.g.a UTF-8-encoded U+0020 SPACE character tofind and interpretthe|Proxy-Authenticate| header). Otherwise, failremote side (the server). Send theWebSocket connection and abort these steps. 32./resource name/ value, encoded as UTF-8. Send another UTF-8-encoded U+0020 SPACE character, followed by the UTF-8 string "HTTP/1.1", followed by a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). 7. Let /fields/ beaan empty list ofname-value pairs, initially empty. 33. _Field_:strings. 8. Add the string "Upgrade: WebSocket" to /fields/. 9. Add the string "Connection: Upgrade" to /fields/. 10. Let/name/ and /value//hostport/ be an emptybyte arrays. 34. Read a byte fromstring. 11. Append theserver./host/ value, converted to ASCII lowercase, to /hostport/. 12. Ifthe connection closes before this byte/secure/ isreceived, then fail the WebSocket connectionfalse, andabort these steps. Otherwise, handle/port/ is not 80, or if /secure/ is true, and /port/ is not 443, then append a U+003A COLON character (:) followed by thebytevalue of /port/, expressed asdescribed ina base-ten integer, to /hostport/. 13. Add theappropriate entry below: -> Ifstring consisting of thebyte is 0x0D (ASCII CR) Ifconcatenation of the/name/ byte array is empty, then jumpstring "Host:", a U+0020 SPACE character, and /hostport/, to /fields/. 14. Add thefields processing step. Otherwise, failstring consisting of theWebSocket connectionconcatenation of the string "Origin:", a U+0020 SPACE character, andabort these steps. -> Ifthebyte/origin/ value, to /fields/. 15. If there is0x0A (ASCII LF) Failno /protocol/, then skip this step. Otherwise, add the string consisting of theWebSocket connectionconcatenation of the string "Sec-WebSocket-Protocol:", a U+0020 SPACE character, andabort these steps. -> Ifthebyte is 0x3A (ASCII :) Move on/protocol/ value, tothe next step. ->/fields/. 16. If thebyte is in the range 0x41client has any cookies that would be relevant to0x5A (ASCII A-Z) Appendabyte whose valueresource accessed over HTTP, if /secure/ is false, or HTTPS, if it is true, on host /host/, port /port/, with /resource name/ as thebyte's value plus 0x20path (and possibly query parameters), then add tothe /name/ byte array and redo this step/fields/ any HTTP headers that would be appropriate for that information. [RFC2616] [RFC2109] [RFC2965] This includes "HttpOnly" cookies (cookies with thenext byte. -> Otherwise Append the bytehttp-only- flag set to true); the/name/ byte array and redo this stepWebSocket protocol is not considered a non-HTTP API for thenext byte. NOTE: This readspurpose of cookie processing. 17. Let /spaces_1/ be afield name, terminated byrandom integer from 1 to 12 inclusive. Let /spaces_2/ be acolon, converting upper-case ASCII lettersrandom integer from 1 tolowercase,12 inclusive. EXAMPLE: For example, 5 andaborting if a stray CR or LF is found. 35.9. 18. Let/count/ equal 0. NOTE: This is used in/max_1/ be thenext step to skip past a space character afterlargest integer not greater than 4,294,967,295 divided by /spaces_1/. Let /max_2/ be thecolon, if necessary. 36. Readlargest integer not greater than 4,294,967,295 divided by /spaces_2/. EXAMPLE: Continuing the example, 858,993,459 and 477,218,588. 19. Let /number_1/ be a random integer from 0 to /max_1/ inclusive. Let /number_2/ be abyterandom integer fromthe server0 to /max_2/ inclusive. EXAMPLE: For example, 777,007,543 andincrement /count/ by 1. If the connection closes before this byte is received, then fail114,997,259. 20. Let /product_1/ be theWebSocket connectionresult of multiplying /number_1/ andabort these steps. Otherwise, handle the byte as described in the appropriate entry below: -> If/spaces_1/ together. Let /product_2/ be thebyte is 0x20 (ASCII space)result of multiplying /number_2/ and/count/ equals 1 Ignore/spaces_2/ together. EXAMPLE: Continuing thebyteexample, 3,885,037,715 andredo this step for1,034,975,331. 21. Let /key_1/ be a string consisting of /product_1/, expressed in base ten using thenext byte. -> Ifnumerals in thebyte is 0x0D (ASCII CR) Move onrange U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). Let /key_2/ be a string consisting of /product_2/, expressed in base ten using thenext step. -> Ifnumerals in thebyte is 0x0A (ASCII LF) Failrange U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9). EXAMPLE: Continuing theWebSocket connectionexample, "3885037715" andabort these steps. -> Otherwise Append"1034975331". 22. Insert between one and twelve random characters from thebyteranges U+0021 tothe /value/ byte arrayU+002F andredo this step forU+003A to U+007E into /key_1/ at random positions. Insert between one and twelve random characters from thenext byte.ranges U+0021 to U+002F and U+003A to U+007E into /key_2/ at random positions. NOTE: Thisreads a field value, terminated by a CRLF, skipping past a single space after the colon if there is one. 37. Read a byte fromcorresponds to random printable ASCII characters other than theserver. Ifdigits and theconnection closes beforeU+0020 SPACE character. EXAMPLE: Continuing the example, thisbyte is received,could lead to "P388O503D& ul7{K%gX(%715" and "1N?|kUT0or3o4I97N5-S3O31". 23. Insert /spaces_1/ U+0020 SPACE characters into /key_1/ at random positions other than the start orifend of thebyte is not a 0x0A byte (ASCII LF), then failstring. Insert /spaces_2/ U+0020 SPACE characters into /key_2/ at random positions other than theWebSocket connectionstart or end of the string. EXAMPLE: Continuing the example, this could lead to "P388 O503D& ul7 {K%gX( %7 15" andabort these steps. NOTE: This skips past"1 N ?|k UT0or 3o 4 I97N 5-S3O 31". 24. Add theLF bytestring consisting of theCRLF afterconcatenation of thefield. 38. Append an entrystring "Sec-WebSocket-Key1:", a U+0020 SPACE character, and the /key_1/ value, to /fields/. Add the/fields/ list that hasstring consisting of thename given byconcatenation of the stringobtained by interpreting the /name/ byte array as"Sec-WebSocket-Key2:", aUTF-8 byte streamU+0020 SPACE character, and thevalue given by the/key_2/ value, to /fields/. 25. For each stringobtained by interpretingin /fields/, in a random order: send the/value/ byte arraystring, encoded as UTF-8, followed by aUTF-8 byte stream. 39. ReturnUTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). It is important that the fields be output in a random order so that servers not depend on the particular order used by any particular client. 26. Send a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). 27. Let /key3/ be a string consisting of eight random bytes (or equivalently, a random 64 bit integer encoded in big-endian order). EXAMPLE: For example, 0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58. 28. Send /key3/ to the"Field" step above. 40. _Fields processing_:server. 29. Reada bytebytes from theserver. Ifserver until either the connectioncloses before this byte is received,closes, orif the byte is nota 0x0A byte(ASCII LF), then fail the WebSocket connection and abortis read. Let /field/ be thesesteps. NOTE: This skips past the LF byte of the CRLF after the blank line afterbytes, including thefields. 41.0x0A byte. Ifthere is not exactly one entry in the /fields/ list whose name is "upgrade", or if there is not exactly one entry in the /fields/ list whose name is "connection", or if there/field/ is notexactly one entry in the /fields/ list whose name is "sec- websocket-origin",at least seven bytes long, or ifthere is not exactly one entry inthe/fields/ list whose name is "sec-websocket-location",last two bytes aren't 0x0D and 0x0A respectively, or ifthe /protocol/ was specified but there isit does notexactly one entry in the /fields/ list whose name is "sec-websocket-protocol", or if there are any entries in the /fields/ list whose names are the empty string,contain at least two 0x20 bytes, then fail the WebSocket connection and abort these steps.Otherwise, handle each entry in the /fields/ list as follows: -> IfUser agents may apply a timeout to this step, failing theentry's name is "upgrade" IfWebSocket connection if thevalue isserver does notexactly equal tosend back data in a suitable time period. 30. Let /code/ be the substring of /field/ that starts from thestring "WebSocket", then failbyte after theWebSocket connectionfirst 0x20 byte, andabort these steps. -> Ifends with theentry's name is "connection" Ifbyte before thevalue, converted to ASCII lowercase,second 0x20 byte. 31. If /code/ is notexactly equal tothree bytes long, or if any of thestring "upgrade",bytes in /code/ are not in the range 0x30 to 0x39, then fail the WebSocket connection and abort these steps.->32. Ifthe entry's name/code/, interpreted as UTF-8, is"sec-websocket-origin" If"101", then move to thevaluenext step. If /code/, interpreted as UTF-8, isnot exactly equal to /origin/,"407", thenfaileither close theWebSocketconnection andabort these steps. [ORIGIN] -> Ifjump back to step 2, providing appropriate authentication information, or fail theentry's nameWebSocket connection. 407 is"sec-websocket-location" Ifthevalue is not exactly equal to a string obtained fromcode used by HTTP meaning "Proxy Authentication Required". User agents that support proxy authentication must interpret thestepsresponse as defined by HTTP (e.g. toconstruct a WebSocket URL from /host/, /port/, /resource name/,find and interpret the/secure/ flag, then|Proxy-Authenticate| header). Otherwise, fail the WebSocket connection and abort these steps.-> If the entry's name is "sec-websocket-protocol" If there was33. Let /fields/ be a/protocol/ specified,list of name-value pairs, initially empty. 34. _Field_: Let /name/ and /value/ be empty byte arrays. 35. Read a byte from thevalueserver. If the connection closes before this byte isnot exactly equal to /protocol/,received, then fail the WebSocket connection and abort these steps.(If no /protocol/ was specified, the field is ignored.) -> If the entry's name is "set-cookie" or "set-cookie2" or another cookie-related field name If the relevant specification is supported by the user agent,Otherwise, handle thecookiebyte asdefined bydescribed in the appropriatespecification, with the resource beingentry below: -> If theone withbyte is 0x0D (ASCII CR) If thehost /host/,/name/ byte array is empty, then jump to theport /port/,fields processing step. Otherwise, fail thepath (and possibly query parameters) /resource name/,WebSocket connection and abort these steps. -> If thescheme |http| if /secure/byte isfalse0x0A (ASCII LF) Fail the WebSocket connection and|https| if /secure/ is true. [RFC2109] [RFC2965]abort these steps. -> If therelevant specificationbyte isnot supported by the user agent, then0x3A (ASCII :) Move on to thefield must be ignored.next step. ->Any other name Ignore it. 42. Let /challenge/ be the concatenation of /number_1/, expressed as a big-endian 32 bit integer, /number_2/, expressed as a big- endian 32 bit integer, andIf theeight bytes of /key_3/byte is in theorder they were sent onrange 0x41 to 0x5A (ASCII A-Z) Append a byte whose value is thewire. EXAMPLE: Usingbyte's value plus 0x20 to theexamples given earlier,/name/ byte array and redo thisleads tostep for the16 bytes 0x2E 0x50 0x31 0xB7 0x06 0xDA 0xB8 0x0B 0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58. 43. Let /expected/ benext byte. -> Otherwise Append theMD5 fingerprint of /challenge/ as a big- endian 128 bit string. [RFC1321] EXAMPLE: Usingbyte to theexamples given earlier,/name/ byte array and redo thisleadsstep for the next byte. NOTE: This reads a field name, terminated by a colon, converting upper-case ASCII letters to lowercase, and aborting if a stray CR or LF is found. 36. Let /count/ equal 0. NOTE: This is used in the16 bytes 0x30 0x73 0x74 0x33 0x52 0x6C 0x26 0x71 0x2D 0x32 0x5A 0x55 0x5E 0x77 0x65 0x75. In ASCII, these bytes correspondnext step to skip past a space character after thestring "0st3Rl&q-2ZU^weu". 44.colon, if necessary. 37. Readsixteen bytesa byte from theserver. Let /reply/ be those bytes.server and increment /count/ by 1. If the connection closes beforethese bytes arethis byte is received, then fail the WebSocket connection and abort these steps.45.Otherwise, handle the byte as described in the appropriate entry below: -> If/reply/ does not exactly equal /expected/, then failthe byte is 0x20 (ASCII space) and /count/ equals 1 Ignore the byte and redo this step for the next byte. -> If the byte is 0x0D (ASCII CR) Move on to the next step. -> If the byte is 0x0A (ASCII LF) Fail the WebSocket connection and abort these steps.46. The *WebSocket connection is established*. Now-> Otherwise Append theuser agent must send and receivebyte to the /value/ byte array and redo this step for the next byte. NOTE: This reads a field value, terminated by a CRLF, skipping past a single space after the colon if there is one. 38. Read a byte from the server. If the connectionas described incloses before this byte is received, or if thenext section. 4.2. Data framing Oncebyte is not a 0x0A byte (ASCII LF), then fail the WebSocket connectionis established,and abort these steps. NOTE: This skips past theuser agent must run throughLF byte of the CRLF after the field. 39. Append an entry to the /fields/ list that has the name given by the string obtained by interpreting thefollowing state machine for/name/ byte array as a UTF-8 byte stream and thebytes sentvalue given by theserver. If at any point during these steps a read is attempted but fails becausestring obtained by interpreting theWebSocket connection is closed, then abort. 1. Try/value/ byte array as a UTF-8 byte stream. 40. Return toreadthe "Field" step above. 41. _Fields processing_: Read a byte from the server.Let /frame type/ be that byte. 2. Let /error/ be false. 3. Handle the /frame type/ byte as follows:If thehigh-order bit of the /frame type/connection closes before this byte isset (i.e.received, or if/frame type/ _and_ed with 0x80 returns 0x80) Run these steps: 1. Let /length/ be zero. 2. _Length_: Readthe byte is not abyte, let /b/ be that byte. 3. Let /b_v/ be an integer corresponding to0x0A byte (ASCII LF), then fail thelow 7 bits of /b/ (the value you would get by _and_ing /b/ with 0x7F). 4. Multiply /length/ by 128, add /b_v/ to that result,WebSocket connection andstoreabort these steps. NOTE: This skips past thefinal result in /length/. 5.LF byte of the CRLF after the blank line after the fields. 42. If there is not exactly one entry in thehigh-order bit of /b//fields/ list whose name isset (i.e."upgrade", or if/b/ _and_ed with 0x80 returns 0x80), then return tothere is not exactly one entry in thestep above labeled _length_. 6. Read /length/ bytes. !!! WARNING: It/fields/ list whose name ispossible for a server to (innocently"connection", ormaliciously) send frames with lengths greater than 2**(31)if there is not exactly one entry in the /fields/ list whose name is "sec- websocket-origin", or2**(32) bytes, overflowing a signedif there is not exactly one entry in the /fields/ list whose name is "sec-websocket-location", orunsigned 32bit integer. User agents may therefore impose implementation-specific limits onif thelengths of invalid frames that they will skip; even supporting frames 2GB in length/protocol/ was specified but there isconsidered, atnot exactly one entry in thetime of writing, as going well above and beyond/fields/ list whose name is "sec-websocket-protocol", or if there are any entries in thecall of duty. 7. Discard/fields/ list whose names are theread bytes. 8. Ifempty string, then fail the/frame type/ is 0xFFWebSocket connection and abort these steps. Otherwise, handle each entry in the/length/ was 0, then run/fields/ list as follows: -> If thefollowing substeps: 1.entry's name is "upgrade" If theWebSocket closing handshake hasvalue is notyet started, then start the WebSocket closing handshake. 2. Wait until eitherexactly equal to theWebSocket closing handshake has started orstring "WebSocket", then fail the WebSocket connection and abort these steps. -> If the entry's name isclosed. 3."connection" If theWebSocket connectionvalue, converted to ASCII lowercase, is notalready closed,exactly equal to the string "upgrade", thenclosefail the WebSocketconnection: *The WebSocket closing handshake has finished*. (If theconnectioncloses before this happens, then the closing handshake doesn't finish.) 4. Abortand abort these steps.Any data on the connection after the 0xFF frame is discarded. Otherwise, let /error/ be true.-> If thehigh-order bit of the /frame type/ byteentry's name is_not_ set (i.e. if /frame type/ _and_ed with 0x80 returns 0x00) Run these steps: 1. Let /raw data/ be an empty byte array. 2. _Data_: Read a byte, let /b/ be that byte. 3."sec-websocket-origin" If/b/the value is not0xFF, then append /b/ to /raw data/ and returnexactly equal to /origin/, then fail theprevious step (labeled _data_). 4. Interpret /raw data/ as a UTF-8 string,WebSocket connection andstore that string in /data/. 5.abort these steps. [ORIGIN] -> If/frame type/ is 0x00, then *a WebSocket message has been received* with text /data/. Otherwise, discardthedata and let /error/ be true. 4.entry's name is "sec-websocket-location" If/error/the value istrue, then *a WebSocket error has been detected*. 5. Returnnot exactly equal to a string obtained from thefirst stepsteps toreadconstruct a WebSocket URL from /host/, /port/, /resource name/, and thenext byte./secure/ flag, then fail the WebSocket connection and abort these steps. -> If theuser agententry's name isfaced with content that"sec-websocket-protocol" If there was a /protocol/ specified, and the value istoo large to be handled appropriately, runs out of resources for buffering incoming data, or hits an artificial resource limit intendednot exactly equal toavoid resource starvation,/protocol/, thenit mustfail the WebSocketconnection. Once a WebSocketconnection and abort these steps. (If no /protocol/ was specified, the field isestablished, but beforeignored.) -> If theWebSocket closing handshake has started,entry's name is "set-cookie" or "set-cookie2" or another cookie-related field name If the relevant specification is supported by the useragent must useagent, handle thefollowing steps to *send /data/ usingcookie as defined by theWebSocket*: 1. Send a 0x00 byte toappropriate specification, with theserver. 2. Encode /data/ using UTF-8 and sendresource being theresulting byte stream toone with theserver. 3. Send a 0xFF byte tohost /host/, theserver. Onceport /port/, theWebSocket closing handshake has started,path (and possibly query parameters) /resource name/, and theuser agent must not send any further data onscheme |http| if /secure/ is false and |https| if /secure/ is true. [RFC2109] [RFC2965] If theconnection. Once a WebSocket connectionrelevant specification isestablished,not supported by the useragentagent, then the field mustusebe ignored. -> Any other name Ignore it. 43. Let /challenge/ be the concatenation of /number_1/, expressed as a big-endian 32 bit integer, /number_2/, expressed as a big- endian 32 bit integer, and the eight bytes of /key_3/ in the order they were sent on thefollowing stepswire. EXAMPLE: Using the examples given earlier, this leads to*starttheWebSocket closing handshake*. These steps must16 bytes 0x2E 0x50 0x31 0xB7 0x06 0xDA 0xB8 0x0B 0x47 0x30 0x22 0x2D 0x5A 0x3F 0x47 0x58. 44. Let /expected/ berun asynchronously relative to whatever algorithm invoked this one. 1. IftheWebSocket closing handshake has started, then abort these steps. 2. SendMD5 fingerprint of /challenge/ as a0xFF bytebig- endian 128 bit string. [RFC1321] EXAMPLE: Using the examples given earlier, this leads to theserver. 3. Send a 0x00 byte16 bytes 0x30 0x73 0x74 0x33 0x52 0x6C 0x26 0x71 0x2D 0x32 0x5A 0x55 0x5E 0x77 0x65 0x75. In ASCII, these bytes correspond to theserver. 4. *The WebSocket closing handshake has started*. 5. Wait a user-agent-determined length of time, or untilstring "0st3Rl&q-2ZU^weu". 45. Read sixteen bytes from theWebSocket connection is closed. 6.server. Let /reply/ be those bytes. If theWebSocketconnectionis not already closed,closes before these bytes are received, thenclosefail the WebSocketconnection. (If this happens, then the closing handshake doesn't finish.) NOTE: The closing handshake finishes once the server returns the 0xFF packet, as described above.connection and abort these steps. 46. Ifat any point there is a fatal problem with sending data to the server, the user agent must/reply/ does not exactly equal /expected/, then fail the WebSocketconnection. 4.3. Handling errors in UTF-8 from the server When a client is to interpret a byte stream as UTF-8 but finds that the byte streamconnection and abort these steps. 47. The *WebSocket connection isnot in fact a valid UTF-8 stream, then any bytes or sequences of bytes that are not valid UTF-8 sequencesestablished*. Now the user agent mustbe interpretedsend and receive to and from the connection asa U+FFFD REPLACEMENT CHARACTER. 5.described in the next section. 5.2. Server-side requirements _This section only applies to servers._5.1.5.2.1. Reading the client's opening handshake When a client starts a WebSocket connection, it sends its part of the opening handshake. The server must parse at least part of this handshake in order to obtain the necessary information to generate the server part of the handshake. The client handshake consists of the following parts. If the server, while reading the handshake, finds that the client did not send a handshake that matches the description below, the server should abort the WebSocket connection. 1. The three-character UTF-8 string "GET". 2. A UTF-8-encoded U+0020 SPACE character (0x20 byte). 3. A string consisting of all the bytes up to the next UTF-8-encoded U+0020 SPACE character (0x20 byte). The result of decoding this string as a UTF-8 string is the name of the resource requested by the server. If the server only supports one resource, then this can safely be ignored; the client verifies that the right resource is supported based on the information included in the server's own handshake. The resource name will begin with U+002F SOLIDUS character (/) and will only include characters in the range U+0021 to U+007E. 4. A string of bytes terminated by a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). All the characters from the second 0x20 byte up to the first 0x0D 0x0A byte pair in the data from the client can be safely ignored. (It will probably be the string "HTTP/1.1".) 5. A series of fields. Each field is terminated by a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). The end of the fields is denoted by the terminating CRLF pair being followed immediately by another CRLF pair. NOTE: In other words, the fields start with the first 0x0D 0x0A byte pair, end with the first 0x0D 0x0A 0x0D 0x0A byte sequence, and are separate from each other by 0x0D 0x0A byte pairs. The fields are encoded as UTF-8. Each field consists of a name, consisting of one or more characters in the ranges U+0021 to U+0039 and U+003B to U+007E, followed by a U+003A COLON character (:) and a U+0020 SPACE character, followed by zero or more characters forming the value. The expected field names, the meaning of their corresponding values, and the processing servers are required to apply to those fields, are described below, after the description of the client handshake. 6. After the first 0x0D 0x0A 0x0D 0x0A byte sequence, indicating the end of the fields, the client sends eight random bytes. These are used in constructing the server handshake. The expected field names, and the meaning of their corresponding values, are as follows. Field names must be compared in an ASCII case-insensitive manner. |Upgrade| Invariant part of the handshake. Will always have a value that is an ASCII case-insensitivematch for the string "WebSocket". Can be safely ignored, though the server should abort the WebSocket connection if this field is absent or has a different value, to avoid vulnerability to cross-protocol attacks. |Connection| Invariant part of the handshake. Will always have a value that is an ASCII case-insensitive match for the string "Upgrade". Can be safely ignored, though the server should abort the WebSocket connection if this field is absent or has a different value, to avoid vulnerability to cross-protocol attacks. |Host| The value gives the hostname that the client intended to use when opening the WebSocket. It would be of interest in particular to virtual hosting environments, where one server might serve multiple hosts, and might therefore want to return different data. Can be safely ignored, though the server should abort the WebSocket connection if this field is absent or has a value that does not match the server's host name, to avoid vulnerability to cross-protocol attacks and DNS rebinding attacks. |Origin| The value gives the scheme, hostname, and port (if it's not the default port for the given scheme) of the page that asked the client to open the WebSocket. It would be interesting if the server's operator had deals with operators of other sites, since the server could then decide how to respond (or indeed, _whether_ to respond) based on which site was requesting a connection. [ORIGIN]match for the string "WebSocket". Can be safely ignored, though the server should abort the WebSocket connection if this field is absent or has avalue that does not match one of the origins the server is expecting to communicate with,different value, to avoid vulnerability to cross-protocolattacks and cross-site scriptingattacks.|Sec-WebSocket-Protocol| The value gives the name|Connection| Invariant part of the handshake. Will always have asubprotocolvalue thatthe clientisintending to select. It would be interesting ifan ASCII case-insensitive match for theserver supports multiple protocols or protocol versions.string "Upgrade". Can be safely ignored, though the servermayshould abort the WebSocket connection ifthethis field is absentbut the conventions for communicating with the server are such that the field is expected; and the server should abort the WebSocket connection if the fieldor has avalue that does not match one of the subprotocols that the server supports,different value, to avoidintegrity errors once the connection is established. |Sec-WebSocket-Key1| |Sec-WebSocket-Key2|vulnerability to cross-protocol attacks. |Host| Thevalues provide the information required for computingvalue gives theserver's handshake, as described inhostname that thenext section. Other fields Other fields can be used, such as "Cookie", for authentication purposes. Their semantics are equivalentclient intended to use when opening thesemantics of the HTTP headers with the same names. Unrecognized fields canWebSocket. It would besafely ignored, and are probably either the resultofintermediaries injecting fields unrelatedinterest in particular tothe operation of the WebSocket protocol, or clients that support future versions of the protocol offering options that thevirtual hosting environments, where one serverdoesn't support. 5.2. Sending the server's opening handshake When a client establishes a WebSocket connectionmight serve multiple hosts, and might therefore want toa server, the server must run the following steps. 1. Ifreturn different data. Can be safely ignored, though the serversupports encryption, perform a TLS handshake overshould abort theconnection. IfWebSocket connection if thisfails (e.g. the client indicatedfield is absent or has ahost name in the extended client hello "server_name" extensionvalue thatthe serverdoes nothost), then close the connection; otherwise, all further communication formatch theconnection (includingserver's host name, to avoid vulnerability to cross-protocol attacks and DNS rebinding attacks. |Origin| The value gives theserver handshake) must run throughscheme, hostname, and port (if it's not theencrypted tunnel. [RFC2246] 2. Establishdefault port for thefollowing information: /host/ The host name or IP addressgiven scheme) of theWebSocket server, as it ispage that asked the client to open the WebSocket. It would beaddressed by clients. The host name must be punycode- encodedinteresting ifnecessary. Ifthe server's operator had deals with operators of other sites, since the servercan respondcould then decide how torequestsrespond (or indeed, _whether_ tomultiple hosts (e.g. in a virtual hosting environment), then the value should be derived from the client's handshake, specifically from the "Host" field. /port/ The port numberrespond) based on whichthe server expected and/or received thesite was requesting a connection./resource name/ An identifier for the service provided by the server. If[ORIGIN] Can be safely ignored, though the serverprovides multiple services, then the valueshouldbe derived from the resource name given in the client's handshake. /secure flag/ True ifabort the WebSocket connection if this field isencryptedabsent orif the server expected it to be encrypted; false otherwise. /origin/ The ASCII serializationhas a value that does not match one of theorigin thatorigins the server iswillingexpecting to communicate with,convertedtoASCII lowercase. If the server can respondavoid vulnerability torequests from multiple origins (or indeed, all origins), then thecross-protocol attacks and cross-site scripting attacks. |Sec-WebSocket-Protocol| The valueshould be derived from the client's handshake, specifically fromgives the"Origin" field. [ORIGIN] /subprotocol/ Either null, orname of astring representing thesubprotocol that theserverclient isreadyintending touse. Ifselect. It would be interesting if the server supports multiplesubprotocols, then the value shouldprotocols or protocol versions. Can bederived fromsafely ignored, though theclient's handshake, specifically fromserver may abort the"Sec-WebSocket- Protocol" field. The absence of such a field is equivalent toWebSocket connection if thenull value. The empty stringfield isnot the same asabsent but thenull valueconventions forthese purposes. /key_1/ The value of the "Sec-WebSocket-Key1" field incommunicating with theclient's handshake. /key_2/ The value ofserver are such that the"Sec-WebSocket-Key2"fieldin the client's handshake. /key_3/ The eight random bytes sent afteris expected; and thefirst 0x0D 0x0A 0x0D 0x0A sequence inserver should abort theclient's handshake. 3. Let /location/ beWebSocket connection if thestring that results from constructingfield has aWebSocket URL from /host/, /port/, /resource name/, and /secure flag/. 4. Let /key-number_1/ bevalue that does not match one of thedigits (characters insubprotocols that therange U+0030 DIGIT ZERO (0)server supports, toU+0039 DIGIT NINE (9)) in /key_1/, interpreted as a base ten integer, ignoring all other characters in /key_1/. Let /key-number_2/ beavoid integrity errors once thedigits (characters inconnection is established. |Sec-WebSocket-Key1| |Sec-WebSocket-Key2| The values provide therange U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)) in /key_2/, interpretedinformation required for computing the server's handshake, asa base ten integer, ignoring all other charactersdescribed in/key_2/. EXAMPLE: For example, assume thattheclient handshake was: GET / HTTP/1.1 Connection: Upgrade Host: example.com Upgrade: WebSocket Sec-WebSocket-Key1: 3e6b263 4 17 80 Origin: http://example.com Sec-WebSocket-Key2: 17 9 G`ZD9 2 2b 7X 3 /r90 WjN}|M(6 The /key-number_1/ wouldnext section. Other fields Other fields can be used, such as "Cookie", for authentication purposes. Their semantics are equivalent to thenumber 3,626,341,780, andsemantics of the/key-number_2/ would beHTTP headers with thenumber 1,799,227,390. In this example, incidentally, /key_3/ is "WjN}|M(6", or 0x57 0x6A 0x4E 0x7D 0x7C 0x4D 0x28 0x36. 5. Let /spaces_1/same names. Unrecognized fields can be safely ignored, and are probably either thenumberresult ofU+0020 SPACE characters in /key_1/. Let /spaces_2/ beintermediaries injecting fields unrelated to thenumberoperation ofU+0020 SPACE characters in /key_2/. If either /spaces_1/the WebSocket protocol, or/spaces_2/ is zero, then abortclients that support future versions of the protocol offering options that the server doesn't support. 5.2.2. Sending the server's opening handshake When a client establishes a WebSocketconnection. This isconnection to asymptom ofserver, the server must run the following steps. 1. If the server supports encryption, perform across-protocol attack. EXAMPLE: InTLS handshake over theexample above, /spaces_1/ would be 4 and /spaces_2/ would be 10. 6.connection. If/key-number_1/ isthis fails (e.g. the client indicated a host name in the extended client hello "server_name" extension that the server does notan integral multiple of /spaces_1/,host), thenabortclose theWebSocket connection. If /key-number_2/ is not an integral multipleconnection; otherwise, all further communication for the connection (including the server handshake) must run through the encrypted tunnel. [RFC2246] 2. Establish the following information: /host/ The host name or IP address of/spaces_2/, then abortthe WebSocketconnection. NOTE: This can only happen if the clientserver, as it isnot a conforming WebSocket client. 7. Let /part_1/ be /key-number_1/ divided by /spaces_1/. Let /part_2/to be/key-number_2/ dividedaddressed by/spaces_2/. EXAMPLE: In the example above, /part_1/ would be 906,585,445 and /part_2/ would be 179,922,739. 8. Let /challenge/clients. The host name must be punycode- encoded if necessary. If theconcatenation of /part_1/, expressed as a big-endian 32 bit integer, /part_2/, expressed as a big-endian 32 bit integer, and the eight bytes of /key_3/server can respond to requests to multiple hosts (e.g. in a virtual hosting environment), then theorder they were sent on the wire. EXAMPLE: In the example above, this wouldvalue should be derived from the16 bytes 0x36 0x09 0x65 0x65 0x0A 0xB9 0x67 0x33 0x57 0x6A 0x4E 0x7D 0x7C 0x4D 0x28 0x36. 9. Let /response/ beclient's handshake, specifically from theMD5 fingerprint of /challenge/ as a big- endian 128 bit string. [RFC1321] EXAMPLE: In"Host" field. /port/ The port number on which theexample above, this would beserver expected and/or received the16 bytes 0x6E 0x60 0x39 0x65 0x42 0x6B 0x39 0x7A 0x24 0x52 0x38 0x70 0x4F 0x74 0x56 0x62, or "n`9eBk9z$R8pOtVb" in ASCII. 10. Sendconnection. /resource name/ An identifier for thefollowing line, terminatedservice provided by thetwo characters U+000D CARRIAGE RETURN and U+000A LINE FEED (CRLF) and encoded as UTF-8, toserver. If the server provides multiple services, then theclient: HTTP/1.1 101 WebSocket Protocol Handshake This line mayvalue should besent differently if necessary, but must matchderived from theStatus-Line production definedresource name given in theHTTP specification, with the Status-Code havingclient's handshake. /secure flag/ True if thevalue 101. 11. Sendconnection is encrypted or if thefollowing fieldsserver expected it tothe client. Each field mustbesent as a line consistingencrypted; false otherwise. /origin/ The ASCII serialization of thefield name, which must be anorigin that the server is willing to communicate with, converted to ASCIIcase-insensitive match forlowercase. If thefield name inserver can respond to requests from multiple origins (or indeed, all origins), then thelist below, followed by a U+003A COLON character (:) andvalue should be derived from the client's handshake, specifically from the "Origin" field. [ORIGIN] /subprotocol/ Either null, or aU+0020 SPACE character, followed bystring representing thefield value as specified insubprotocol thelist below, followed byserver is ready to use. If the server supports multiple subprotocols, then thetwo characters U+000D CARRIAGE RETURN and U+000A LINE FEED (CRLF). The lines must be encoded as UTF-8. The lines may be sent in any order. |Upgrade| Thevaluemustshould be derived from thestring "WebSocket". |Connection|client's handshake, specifically from the "Sec-WebSocket- Protocol" field. Thevalue must beabsence of such a field is equivalent to thestring "Upgrade". |Sec-WebSocket-Location|null value. The empty string is not the same as the null valuemust be /location/ |Sec-WebSocket-Origin|for these purposes. /key_1/ The valuemust be /origin/ |Sec-WebSocket-Protocol| Thisof the "Sec-WebSocket-Key1" fieldmust be included if /subprotocol/ is not null, and must not be included if /subprotocol/ is null. If included,in the client's handshake. /key_2/ The valuemust be /subprotocol/ Optionally, include "Set-Cookie", "Set-Cookie2", or other cookie-related fields, with values equal toof thevalues that would be used for"Sec-WebSocket-Key2" field in theidentically named HTTP headers. [RFC2109] [RFC2965] 12. Send twoclient's handshake. /key_3/ The eight random bytes sent after the first 0x0D 0x0A(ASCII CRLF). 13. Send /response/. This completes0x0D 0x0A sequence in theserver'sclient's handshake.If the server finishes these steps without aborting3. Let /location/ be the string that results from constructing a WebSocketconnection,URL from /host/, /port/, /resource name/, andif/secure flag/. 4. Let /key-number_1/ be theclient does not then faildigits (characters in theconnection, thenrange U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)) in /key_1/, interpreted as a base ten integer, ignoring all other characters in /key_1/. Let /key-number_2/ be theconnection is established anddigits (characters in theserver may begin and receiving sending data,range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)) in /key_2/, interpreted asdescribeda base ten integer, ignoring all other characters in /key_2/. EXAMPLE: For example, assume that thenext section. 5.3. Data framingclient handshake was: GET / HTTP/1.1 Connection: Upgrade Host: example.com Upgrade: WebSocket Sec-WebSocket-Key1: 3e6b263 4 17 80 Origin: http://example.com Sec-WebSocket-Key2: 17 9 G`ZD9 2 2b 7X 3 /r90 WjN}|M(6 Theserver must run through/key-number_1/ would be thefollowing steps to processnumber 3,626,341,780, and the /key-number_2/ would be the number 1,799,227,390. In this example, incidentally, /key_3/ is "WjN}|M(6", or 0x57 0x6A 0x4E 0x7D 0x7C 0x4D 0x28 0x36. 5. Let /spaces_1/ be thebytes sent bynumber of U+0020 SPACE characters in /key_1/. Let /spaces_2/ be theclient.number of U+0020 SPACE characters in /key_2/. Ifat any point during these steps a readeither /spaces_1/ or /spaces_2/ isattempted but fails becausezero, then abort the WebSocketconnectionconnection. This isclosed, then abort. 1. _Frame_: Readabyte fromsymptom of a cross-protocol attack. EXAMPLE: In theclient. Let /type/example above, /spaces_1/ would bethat byte. 2.4 and /spaces_2/ would be 10. 6. Ifthe most significant bit of /type//key-number_1/ is notset,an integral multiple of /spaces_1/, thenrunabort thefollowing steps: 1.WebSocket connection. If/type//key-number_2/ is nota 0x00 byte,an integral multiple of /spaces_2/, thenthe server mayabortthese steps and either immediately disconnect fromtheclient or setWebSocket connection. NOTE: This can only happen if the/client terminated/ flag. 2.client is not a conforming WebSocket client. 7. Let/raw data//part_1/ bean empty byte array. 3. _Data_: Read a byte, let /b//key-number_1/ divided by /spaces_1/. Let /part_2/ bethat byte. 4. If /b/ is not 0xFF, then append /b/ to /raw data//key-number_2/ divided by /spaces_2/. EXAMPLE: In the example above, /part_1/ would be 906,585,445 andreturn to/part_2/ would be 179,922,739. 8. Let /challenge/ be theprevious step (labeled _data_). 5. If /type/ was 0x00, interpret /raw data/concatenation of /part_1/, expressed as aUTF-8 string,big-endian 32 bit integer, /part_2/, expressed as a big-endian 32 bit integer, andapply whatever server-specific processing is to occur for the resulting string (the message from the client). Otherwise,themost significant biteight bytes of/type/ is set. Run/key_3/ in thefollowing steps. 6. If /type/ is not a 0xFF byte, thenorder they were sent on theserver may abort these steps and either immediately disconnect fromwire. EXAMPLE: In theclient or setexample above, this would be the/client terminated/ flag. 7.16 bytes 0x36 0x09 0x65 0x65 0x0A 0xB9 0x67 0x33 0x57 0x6A 0x4E 0x7D 0x7C 0x4D 0x28 0x36. 9. Let/length//response/ bezero. 8. _Length_: Readthe MD5 fingerprint of /challenge/ as abyte, let /b/big- endian 128 bit string. [RFC1321] EXAMPLE: In the example above, this would bethat byte. 9. If /b/ is not a 0x00 byte, then run these substeps: 1. The server may abort these steps and either immediately disconnect fromtheclient16 bytes 0x6E 0x60 0x39 0x65 0x42 0x6B 0x39 0x7A 0x24 0x52 0x38 0x70 0x4F 0x74 0x56 0x62, orset the /client terminated/ flag. 2. Let /b_v/ be an integer corresponding to"n`9eBk9z$R8pOtVb" in ASCII. 10. Send thelow 7 bits of /b/ (the value you would get by _and_ing /b/ with 0x7F). 3. Multiply /length/following line, terminated by128, add /b_v/ to that result,the two characters U+000D CARRIAGE RETURN andstoreU+000A LINE FEED (CRLF) and encoded as UTF-8, to thefinal resultclient: HTTP/1.1 101 WebSocket Protocol Handshake This line may be sent differently if necessary, but must match the Status-Line production defined in/length/. 4. Ifthehigh-order bit of /b/ is set (i.e. if /b/ _and_edHTTP specification, with0x80 returns 0x80), then return tothestep above labeled _length_. 5. Read /length/ bytes. !!! WARNING: It is possible for a malicious clientStatus-Code having the value 101. 11. Send the following fields tosend frames with lengths greater than 2**(31) or 2**(32) bytes, overflowing a signed or unsigned 32bit integer. Servers may therefore impose implementation-specific limits onthelengths of invalid frames that they will skip, if they support skipping such frames at all. If a server cannot correctly skip pastclient. Each field must be sent as along frame, thenline consisting of theserverfield name, which mustabort these steps (discarding all future data), and should either immediately disconnect from the client or setbe an ASCII case-insensitive match for the/client terminated/ flag. 6. Discardfield name in theread bytes. 10. If /type/ is 0xFFlist below, followed by a U+003A COLON character (:) and/length/ is 0, then seta U+0020 SPACE character, followed by the/client terminated/ flagfield value as specified in the list below, followed by the two characters U+000D CARRIAGE RETURN andabort these steps. All further dataU+000A LINE FEED (CRLF). The lines must be encoded as UTF-8. The lines may be sentbyin any order. |Upgrade| The value must be theclient shouldstring "WebSocket". |Connection| The value must bediscarded. 3. Return tothestep labeled _frame_.string "Upgrade". |Sec-WebSocket-Location| Theservervalue mustrun throughbe /location/ |Sec-WebSocket-Origin| The value must be /origin/ |Sec-WebSocket-Protocol| This field must be included if /subprotocol/ is not null, and must not be included if /subprotocol/ is null. If included, thefollowing steps to send stringsvalue must be /subprotocol/ Optionally, include "Set-Cookie", "Set-Cookie2", or other cookie-related fields, with values equal to theclient: 1. Send a 0x00 byte tovalues that would be used for theclient to indicateidentically named HTTP headers. [RFC2109] [RFC2965] 12. Send two bytes 0x0D 0x0A (ASCII CRLF). 13. Send /response/. This completes thestart of a string. 2. Encode /data/ using UTF-8 and sendserver's handshake. If theresulting byte stream toserver finishes these steps without aborting theclient. 3. Send a 0xFF byte toWebSocket connection, and if the clientto indicate the end ofdoes not then fail themessage. At any time,connection, then the connection is established and the server maydecide to terminatebegin and receiving sending data, as described in theWebSocket connection by running throughnext section. 6. Error Handling 6.1. Handling errors in UTF-8 from thefollowing steps: 1. Send a 0xFF byte andserver When a0x00 byte to theclient is toindicate the start of the closing handshake. 2. Wait until the /client terminated/ flag has been set, or untilinterpret aserver-defined timeout expires. 3. Close the WebSocket connection. Once these steps have started,byte stream as UTF-8 but finds that theserver mustbyte stream is notsendin fact a valid UTF-8 stream, then anyfurther data to the server. The 0xFF 0x00bytesindicate the endor sequences ofthe server's data, and furtherbyteswillthat are not valid UTF-8 sequences must bediscarded by the client. 5.4.interpreted as a U+FFFD REPLACEMENT CHARACTER. 6.2. Handling errors in UTF-8 from the client When a server is to interpret a byte stream as UTF-8 but finds that the byte stream is not in fact a valid UTF-8 stream, behavior is undefined. A server could close the connection, convert invalid byte sequences to U+FFFD REPLACEMENT CHARACTERs, store the data verbatim, or perform application-specific processing. Subprotocols layered on the WebSocket protocol might define specific behavior for servers.6.7. Closing the connection6.1.7.1. Client-initiated closure Certain algorithms require the user agent to *fail the WebSocket connection*. To do so, the user agent must close the WebSocket connection, and may report the problem to the user (which would be especially useful for developers). Except as indicated above or as specified by the application layer (e.g. a script using the WebSocket API), user agents should not close the connection. User agents must not convey any failure information to scripts in a way that would allow a script to distinguish the following situations: o A server whose host name could not be resolved. o A server to which packets could not successfully be routed. o A server that refused the connection on the specified port. o A server that did not complete the opening handshake (e.g. because it was not a WebSocket server). o A WebSocket server that sent a correct opening handshake, but that specified options that caused the client to drop the connection (e.g. the server specified an origin that differed from the script's). o A WebSocket server that abruptly closed the connection after successfully completing the opening handshake.6.2.7.2. Server-initiated closure Certain algorithms require or recommend that the server *abort the WebSocket connection* during the opening handshake. To do so, the server must simply close the WebSocket connection.6.3.7.3. Closure To *close the WebSocket connection*, the user agent or server must close the TCP connection, using whatever mechanism possible (e.g. either the TCP RST or FIN mechanisms). When a user agent notices that the server has closed its connection, it must immediately close its side of the connection also. Whether the user agent or the server closes the connection first, it is said that the *WebSocket connection is closed*. If the connection was closed after the client finished the WebSocket closing handshake, then the WebSocket connection is said to have been closed _cleanly_. Servers may close the WebSocket connection whenever desired. User agents should not close the WebSocket connection arbitrarily.7.8. Security considerations While this protocol is intended to be used by scripts in Web pages, it can also be used directly by hosts. Such hosts are acting on their own behalf, and can therefore send fake "Origin" fields, misleading the server. Servers should therefore be careful about assuming that they are talking directly to scripts from known origins, and must consider that they might be accessed in unexpected ways. In particular, a server should not trust that any input is valid. EXAMPLE: For example, if the server uses input as part of SQL queries, all input text should be escaped before being passed to the SQL server, lest the server be susceptible to SQL injection. Servers that are not intended to process input from any Web page but only for certain sites should verify the "Origin" field is an origin they expect, and should only respond with the corresponding "Sec- WebSocket-Origin" if it is an accepted origin. Servers that only accept input from one origin can just send back that value in the "Sec-WebSocket-Origin" field, without bothering to check the client's value. If at any time a server is faced with data that it does not understand, or that violates some criteria by which the server determines safety of input, or when the server sees a handshake that does not correspond to the values the server is expecting (e.g. incorrect path or origin), the server should just disconnect. It is always safe to disconnect. The biggest security risk when sending text data using this protocol is sending data using the wrong encoding. If an attacker can trick the server into sending data encoded as ISO-8859-1 verbatim (for instance), rather than encoded as UTF-8, then the attacker could inject arbitrary frames into the data stream.8.9. IANA considerations8.1.9.1. Registration of ws: scheme A |ws:| URL identifies a WebSocket server and resource name. URI scheme name. ws Status. Permanent. URI scheme syntax. In ABNF terms using the terminals from the URI specifications: [RFC5234] [RFC3986] "ws" ":" hier-part [ "?" query ] The path and query components form the resource name sent to the server to identify the kind of service desired. Other components have the meanings described in RFC3986. URI scheme semantics. The only operation for this scheme is to open a connection using the WebSocket protocol. Encoding considerations. Characters in the host component that are excluded by the syntax defined above must be converted from Unicode to ASCII by applying the IDNA ToASCII algorithm to the Unicode host name, with both the AllowUnassigned and UseSTD3ASCIIRules flags set, and using the result of this algorithm as the host in the URI. [RFC3490] Characters in other components that are excluded by the syntax defined above must be converted from Unicode to ASCII by first encoding the characters as UTF-8 and then replacing the corresponding bytes using their percent-encoded form as defined in the URI and IRI specification. [RFC3986] [RFC3987] Applications/protocols that use this URI scheme name. WebSocket protocol. Interoperability considerations. None. Security considerations. See "Security considerations" section above. Contact. Ian Hickson <ian@hixie.ch> Author/Change controller. Ian Hickson <ian@hixie.ch> References. This document.8.2.9.2. Registration of wss: scheme A |wss:| URL identifies a WebSocket server and resource name, and indicates that traffic over that connection is to be encrypted. URI scheme name. wss Status. Permanent. URI scheme syntax. In ABNF terms using the terminals from the URI specifications: [RFC5234] [RFC3986] "wss" ":" hier-part [ "?" query ] The path and query components form the resource name sent to the server to identify the kind of service desired. Other components have the meanings described in RFC3986. URI scheme semantics. The only operation for this scheme is to open a connection using the WebSocket protocol, encrypted using TLS. Encoding considerations. Characters in the host component that are excluded by the syntax defined above must be converted from Unicode to ASCII by applying the IDNA ToASCII algorithm to the Unicode host name, with both the AllowUnassigned and UseSTD3ASCIIRules flags set, and using the result of this algorithm as the host in the URI. [RFC3490] Characters in other components that are excluded by the syntax defined above must be converted from Unicode to ASCII by first encoding the characters as UTF-8 and then replacing the corresponding bytes using their percent-encoded form as defined in the URI and IRI specification. [RFC3986] [RFC3987] Applications/protocols that use this URI scheme name. WebSocket protocol over TLS. Interoperability considerations. None. Security considerations. See "Security considerations" section above. Contact. Ian Hickson <ian@hixie.ch> Author/Change controller. Ian Hickson <ian@hixie.ch> References. This document.8.3.9.3. Registration of the "WebSocket" HTTP Upgrade keyword Name of token. WebSocket Author/Change controller. Ian Hickson <ian@hixie.ch> Contact. Ian Hickson <ian@hixie.ch> References. This document.8.4.9.4. Sec-WebSocket-Key1 and Sec-WebSocket-Key2 This section describes two header fields for registration in the Permanent Message Header Field Registry. [RFC3864] Header field name Sec-WebSocket-Key1 Applicable protocol http Status reserved; do not use outside WebSocket handshake Author/Change controller IETF Specification document(s) This document is the relevant specification. Related information None. Header field name Sec-WebSocket-Key2 Applicable protocol http Status reserved; do not use outside WebSocket handshake Author/Change controller IETF Specification document(s) This document is the relevant specification. Related information None. The |Sec-WebSocket-Key1| and |Sec-WebSocket-Key2| headers are used in the WebSocket handshake. They are sent from the client to the server to provide part of the information used by the server to prove that it received a valid WebSocket handshake. This helps ensure that the server does not accept connections from non-Web-Socket clients (e.g. HTTP clients) that are being abused to send data to unsuspecting WebSocket servers.8.5.9.5. Sec-WebSocket-Location This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] Header field name Sec-WebSocket-Location Applicable protocol http Status reserved; do not use outside WebSocket handshake Author/Change controller IETF Specification document(s) This document is the relevant specification. Related information None. The |Sec-WebSocket-Location| header is used in the WebSocket handshake. It is sent from the server to the client to confirm the URL of the connection. This enables the client to verify that the connection was established to the right server, port, and path, instead of relying on the server to verify that the requested host, port, and path are correct.8.6.9.6. Sec-WebSocket-Origin This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] Header field name Sec-WebSocket-Origin Applicable protocol http Status reserved; do not use outside WebSocket handshake Author/Change controller IETF Specification document(s) This document is the relevant specification. Related information None. The |Sec-WebSocket-Origin| header is used in the WebSocket handshake. It is sent from the server to the client to confirm the origin of the script that opened the connection. This enables user agents to verify that the server is willing to serve the script that opened the connection.8.7.9.7. Sec-WebSocket-Protocol This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] Header field name Sec-WebSocket-Protocol Applicable protocol http Status reserved; do not use outside WebSocket handshake Author/Change controller IETF Specification document(s) This document is the relevant specification. Related information None. The |Sec-WebSocket-Protocol| header is used in the WebSocket handshake. It is sent from the client to the server and back from the server to the client to confirm the subprotocol of the connection. This enables scripts to both select a subprotocol and be sure that the server agreed to serve that subprotocol.9.10. Using the WebSocket protocol from other specifications The WebSocket protocol is intended to be used by another specification to provide a generic mechanism for dynamic author- defined content, e.g. in a specification defining a scripted API. Such a specification first needs to "establish a WebSocket connection", providing that algorithm with: o The destination, consisting of a /host/ and a /port/. o A /resource name/, which allows for multiple services to be identified at one host and port. o A /secure/ flag, which is true if the connection is to be encrypted, and false otherwise. o An ASCII serialization of an origin that is being made responsible for the connection. [ORIGIN] o Optionally a string identifying a protocol that is to be layered over the WebSocket connection. The /host/, /port/, /resource name/, and /secure/ flag are usually obtained from a URL using the steps to parse a WebSocket URL's components. These steps fail if the URL does not specify a WebSocket. If a connection can be established, then it is said that the "WebSocket connection is established". If at any time the connection is to be closed, then the specification needs to use the "close the WebSocket connection" algorithm. When the connection is closed, for any reason including failure to establish the connection in the first place, it is said that the "WebSocket connection is closed". While a connection is open, the specification will need to handle the cases when "a WebSocket message has been received" with text /data/. To send some text /data/ to an open connection, the specification needs to "send /data/ using the WebSocket".10.11. AcknowledgementsThe WebSocket protocol isSpecial thanks are due to Ian Hickson, who was theresult of many years of development,original author andas such hundredseditor ofpeople have contributed to thethis protocol. The initial design of this specificationduring its lifetime. Unfortunately, sincebenefitted from thespecification started as nothing but a minor sectionparticipation of many people in thelargerWHATWGWeb Applications 1.0 specification,andlater the HTML5 specification, no record was kept of who exactly contributedWHATWG mailing list. Contributions towhat ended up becoming thisthat specificationas opposed toare not tracked by section, but a list of all who contributed toother parts ofthatdocument. The readerspecification istherefore referred to the Acknowledgements section ofgiven in the WHATWG HTMLspecificationspecification. [HTML] Special thanks also to John Tamplin for providing afull listsignificant amount ofall contributions that have been made totext for thesource document from whichData Framing section of thisspecification is generated. [HTML] 11.specification. 12. Normative References [HTML] Hickson, I., "HTML",MayAugust 2010, <http://whatwg.org/html5>. [ORIGIN] Barth, A., Jackson, C., and I. Hickson, "The HTTP Origin Header", draft-abarth-origin (work in progress), September 2009, <http://tools.ietf.org/html/draft-abarth-origin>. [RFC1321] Rivest, R., "The MD5 Message-Digest Algorithm", RFC 1321, April 1992. [RFC2109] Kristol, D. and L. Montulli, "HTTP State Management Mechanism", RFC 2109, February 1997. [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", RFC 2246, January 1999. [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999. [RFC2965] Kristol, D. and L. Montulli, "HTTP State Management Mechanism", RFC 2965, October 2000. [RFC3490] Faltstrom, P., Hoffman, P., and A. Costello, "Internationalizing Domain Names in Applications (IDNA)", RFC 3490, March 2003. [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, RFC 3629, November 2003. [RFC3864] Klyne, G., Nottingham, M., and J. Mogul, "Registration Procedures for Message Header Fields", BCP 90, RFC 3864, September 2004. [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, RFC 3986, January 2005. [RFC3987] Duerst, M. and M. Suignard, "Internationalized Resource Identifiers (IRIs)", RFC 3987, January 2005. [RFC4366] Blake-Wilson, S., Nystrom, M., Hopwood, D., Mikkelsen, J., and T. Wright, "Transport Layer Security (TLS) Extensions", RFC 4366, April 2006. [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008. [WEBADDRESSES] Connolly, D. and C. Sperberg-McQueen, "Web addresses in HTML 5", May 2009, <http://www.w3.org/html/wg/href/draft>. [WSAPI] Hickson, I., "The Web Sockets API",MayAugust 2010, <http://dev.w3.org/html5/websockets/>. Author's Address IanHicksonFette Google, Inc. Email:ian@hixie.chifette+ietf@google.com URI:http://ln.hixie.ch/http://www.ianfette.com/