TOC |
|
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).
Please send feedback to the hybi@ietf.org mailing list.
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.
This Internet-Draft is submitted in 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 on March 4, 2011.
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.
1.
Introduction
1.1.
Background
1.2.
Protocol overview
1.3.
Opening handshake
1.4.
Closing handshake
1.5.
Design philosophy
1.6.
Security model
1.7.
Relationship to TCP and HTTP
1.8.
Establishing a connection
1.9.
Subprotocols using the WebSocket protocol
2.
Conformance requirements
2.1.
Terminology
3.
WebSocket URLs
3.1.
Parsing WebSocket URLs
3.2.
Constructing WebSocket URLs
3.3.
Valid WebSocket URLs
4.
Data Framing
4.1.
Overview
4.2.
Base Framing Protocol
4.3.
Fragmentation
4.4.
Control Frames
4.5.
Data Frames
4.6.
Examples
4.7.
Extensibility
5.
Opening Handshake
5.1.
Client Requirements
5.2.
Server-side requirements
5.2.1.
Reading the client's opening handshake
5.2.2.
Sending the server's opening handshake
6.
Error Handling
6.1.
Handling errors in UTF-8 from the server
6.2.
Handling errors in UTF-8 from the client
7.
Closing the connection
7.1.
Client-initiated closure
7.2.
Server-initiated closure
7.3.
Closure
8.
Security considerations
9.
IANA considerations
9.1.
Registration of ws: scheme
9.2.
Registration of wss: scheme
9.3.
Registration of the "WebSocket" HTTP Upgrade keyword
9.4.
Sec-WebSocket-Key1 and Sec-WebSocket-Key2
9.5.
Sec-WebSocket-Location
9.6.
Sec-WebSocket-Origin
9.7.
Sec-WebSocket-Protocol
10.
Using the WebSocket protocol from other specifications
11.
Acknowledgements
12.
Normative References
§
Author's Address
TOC |
TOC |
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:
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] (Hickson, I., “The Web Sockets API,” August 2010.)
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.
TOC |
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] (Crocker, D. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF,” January 2008.)
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.
Clients and servers, after a successful 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 in 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 frame is sent from one peer to ask that the other peer close the connection. Details are specified in Section 7 (Closing the connection).
The protocol is designed to support other frame types in future. Currently only four frame types are defined -- continuation (used for fragmented messages), control frames, text frames, and binary data frames. Eight frame types are reserved for future use, and four frame types are reserved for private use.
This wire format for the data transfer part is described by the ABNF given in detail in Section 4 (Data Framing). A high level overview of the framing is given in the following figure. [RFC5234] (Crocker, D. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF,” January 2008.)
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 the 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 the 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 as a 16 bit unsigned integer are the payload length. If 127, the following 8 bytes interpreted as a 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 of the Application Data. The length of the Extension data may be zero, in which case the Payload length is the length of the Application data.- Extension 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 frame after any extension data. The length of the Application data is equal to the payload length minus the length of the Extension data.
TOC |
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 naïve 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.
TOC |
This section is non-normative.
The closing handshake is far simpler than the opening handshake.
Either peer can send a control frame with data containing a specified control sequence to begin the closing handshake. Upon receiving such a frame, the other peer sends an identical frame in acknowledgement, if it hasn't already sent one. Upon receiving that control frame, the first peer then closes the connection, safe in the knowledge that no further data is forthcoming.
After sending a control frame indicating the connection should be closed, a peer does not send any further data; after receiving a 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.
TOC |
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.
TOC |
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|.
TOC |
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.
TOC |
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.
TOC |
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 "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.
TOC |
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] (Bradner, S., “Key words for use in RFCs to Indicate Requirement Levels,” March 1997.)
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.
TOC |
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] (Hickson, I., “HTML,” August 2010.)
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.
TOC |
TOC |
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.
TOC |
The steps to construct a WebSocket URL from a /host/, a /port/, a /resource name/, and a /secure/ flag, are as follows:
TOC |
For a WebSocket URL to be considered valid, the following conditions MUST hold.
Any WebSocket URLs not meeting the above criteria are considered invalid, and a client MUST NOT attempt to make a connection to an invalid WebSocket URL. A client SHOULD attempt to parse a URL obtained from any external source (such as a web site or a user) using the steps specified in Section 3.1 (Parsing WebSocket URLs) to obtain a valid WebSocket URL, but MUST NOT attempt to connect with such an unparsed URL, and instead only use the parsed version and only if that version is considered valid by the criteria above.
TOC |
TOC |
The base framing protocol is deliberately kept simple so that simple implementations may ignore advanced features. In the absence of extensions negotiated during the opening handshake (Section 5 (Opening Handshake)), all reserved bits must be 0 and no reserved opcode values may be used.
TOC |
The base framing protocol is defined by the following ABNF [RFC5234] (Crocker, D. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF,” January 2008.):
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 ) ; to be defined later application-data = *( %x00-FF )
TOC |
The following rules apply to fragmentation:
TOC |
The Close (0x01), Ping (0x02), and Pong (0x03) frames are contol frames -- they do not supply data to the ultimate endpoint, but instead are used to carry out tasks related to the WebSocket connection itself.
A receiver MUST take the following action upon receiving control frames:
- Close:
Upon receipt of a close frame, an endpoint SHOULD send a Close frame to the remote recipient, if it has not already done so, deliver a close event to the application if necessary, and then close the WebSocket.- Ping
Upon receipt of a Ping message, an endpoint SHOULD send a Pong response as soon as is practical. The Pong response MUST contain the payload provided in the Ping message, though an implementation MAY truncate the message at an implementation-defined size which MUST be at least 8 (TBD) bytes.
Ping frames MAY be sent as a 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 the connection. Otherwise, the endpoint SHOULD update any liveness timer it may have for the connection.
TOC |
All frame types not listed above are data frames, which transport application-layer data. The opcode determines the interpretation of the application 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 of the protocol.
TOC |
This section is non-normative.
TOC |
Extensions will be defined which extend the base protocol, but only if their use is negotiated during the handshake. The following mechanisms will be used for extension:
TOC |
TOC |
When the user agent is to establish a WebSocket connection to a 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 the following steps. [ORIGIN] (Barth, A., Jackson, C., and I. Hickson, “The HTTP Origin Header,” September 2009.)
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/.EXAMPLE: For example, if the user agent uses an HTTP proxy for all traffic, then if it was to try to connect to port 80 on server example.com, it might send the following lines to the 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=
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.
- -> If the byte is 0x0D (ASCII CR)
- If the /name/ byte array is empty, then jump to the fields processing step. Otherwise, fail the WebSocket connection and abort these steps.
- -> If the byte is 0x0A (ASCII LF)
- Fail the WebSocket connection and abort these steps.
- -> If the byte is 0x3A (ASCII :)
- Move on to the next step.
- -> If the byte is in the range 0x41 to 0x5A (ASCII A-Z)
- Append a byte whose value is the byte's value plus 0x20 to the /name/ byte array and redo this step for the next byte.
- -> Otherwise
- Append the byte to the /name/ 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.
- -> If the 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.
- -> Otherwise
- Append the byte to the /value/ byte array and redo this step for the next byte.
- -> If the entry's name is "upgrade"
- If the value is not exactly equal to the string "WebSocket", then fail the WebSocket connection and abort these steps.
- -> If the entry's name is "connection"
- If the value, converted to ASCII lowercase, is not exactly equal to the string "upgrade", then fail the WebSocket connection and abort these steps.
- -> If the entry's name is "sec-websocket-origin"
- If the value is not exactly equal to /origin/, then fail the WebSocket connection and abort these steps. [ORIGIN] (Barth, A., Jackson, C., and I. Hickson, “The HTTP Origin Header,” September 2009.)
- -> If the entry's name is "sec-websocket-location"
- If the value is not exactly equal to a string obtained from the steps to construct a WebSocket URL from /host/, /port/, /resource name/, and the /secure/ flag, then fail the WebSocket connection and abort these steps.
- -> If the entry's name is "sec-websocket-protocol"
- If there was a /protocol/ specified, and the value is not exactly equal to /protocol/, 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, handle the cookie as defined by the appropriate specification, with the resource being the one with the host /host/, the port /port/, the path (and possibly query parameters) /resource name/, and the scheme |http| if /secure/ is false and |https| if /secure/ is true. [RFC2109] (Kristol, D. and L. Montulli, “HTTP State Management Mechanism,” February 1997.) [RFC2965] (Kristol, D. and L. Montulli, “HTTP State Management Mechanism,” October 2000.)
If the relevant specification is not supported by the user agent, then the field must be ignored.- -> Any other name
- Ignore it.
TOC |
This section only applies to servers.
TOC |
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.
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-insensitive match 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] (Barth, A., Jackson, C., and I. Hickson, “The HTTP Origin Header,” September 2009.)
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 one of the origins the server is expecting to communicate with, to avoid vulnerability to cross-protocol attacks and cross-site scripting attacks.- |Sec-WebSocket-Protocol|
- The value gives the name of a subprotocol that the client is intending to select. It would be interesting if the server supports multiple protocols or protocol versions.
Can be safely ignored, though the server may abort the WebSocket connection if the field is absent but the conventions for communicating with the server are such that the field is expected; and the server should abort the WebSocket connection if the field has a value that does not match one of the subprotocols that the server supports, to avoid integrity errors once the connection is established.- |Sec-WebSocket-Key1|
- |Sec-WebSocket-Key2|
- The values provide the information required for computing the server's handshake, as described in the next section.
- Other fields
- Other fields can be used, such as "Cookie", for authentication purposes. Their semantics are equivalent to the semantics of the HTTP headers with the same names.
Unrecognized fields can be safely ignored, and are probably either the result of intermediaries injecting fields unrelated to the operation of the WebSocket protocol, or clients that support future versions of the protocol offering options that the server doesn't support.
TOC |
When a client establishes a WebSocket connection to a server, the server must run the following steps.
- /host/
- The host name or IP address of the WebSocket server, as it is to be addressed by clients. The host name must be punycode-encoded if necessary. If the server can respond to requests to multiple 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 number on which the server expected and/or received the connection.
- /resource name/
- An identifier for the service provided by the server. If the server provides multiple services, then the value should be derived from the resource name given in the client's handshake.
- /secure flag/
- True if the connection is encrypted or if the server expected it to be encrypted; false otherwise.
- /origin/
- The ASCII serialization of the origin that the server is willing to communicate with, converted to ASCII lowercase. If the server can respond to requests from multiple origins (or indeed, all origins), then the value should be derived from the client's handshake, specifically from the "Origin" field. [ORIGIN] (Barth, A., Jackson, C., and I. Hickson, “The HTTP Origin Header,” September 2009.)
- /subprotocol/
- Either null, or a string representing the subprotocol the server is ready to use. If the server supports multiple subprotocols, then the value should be derived from the client's handshake, specifically from the "Sec-WebSocket-Protocol" field. The absence of such a field is equivalent to the null value. The empty string is not the same as the null value for these purposes.
- /key_1/
- The value of the "Sec-WebSocket-Key1" field in the client's handshake.
- /key_2/
- The value of the "Sec-WebSocket-Key2" field in the client's handshake.
- /key_3/
- The eight random bytes sent after the first 0x0D 0x0A 0x0D 0x0A sequence in the client's handshake.
EXAMPLE: For example, assume that the client 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/ would be the number 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.
HTTP/1.1 101 WebSocket Protocol Handshake
Optionally, include "Set-Cookie", "Set-Cookie2", or other cookie-related fields, with values equal to the values that would be used for the identically named HTTP headers. [RFC2109] (Kristol, D. and L. Montulli, “HTTP State Management Mechanism,” February 1997.) [RFC2965] (Kristol, D. and L. Montulli, “HTTP State Management Mechanism,” October 2000.)
- |Upgrade|
- The value must be the string "WebSocket".
- |Connection|
- The value must be the string "Upgrade".
- |Sec-WebSocket-Location|
- The value must be /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, the value must be /subprotocol/
This completes the server's handshake. If the server finishes these steps without aborting the WebSocket connection, and if the client does not then fail the connection, then the connection is established and the server may begin and receiving sending data, as described in the next section.
TOC |
TOC |
When a client is to interpret a byte stream as UTF-8 but finds that the byte stream is not in fact a valid UTF-8 stream, then any bytes or sequences of bytes that are not valid UTF-8 sequences must be interpreted as a U+FFFD REPLACEMENT CHARACTER.
TOC |
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.
TOC |
TOC |
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:
TOC |
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.
TOC |
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.
TOC |
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.
TOC |
TOC |
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] (Crocker, D. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF,” January 2008.) [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.)
"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] (Faltstrom, P., Hoffman, P., and A. Costello, “Internationalizing Domain Names in Applications (IDNA),” March 2003.)
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] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) [RFC3987] (Duerst, M. and M. Suignard, “Internationalized Resource Identifiers (IRIs),” January 2005.)- 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.
TOC |
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] (Crocker, D. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF,” January 2008.) [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.)
"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] (Faltstrom, P., Hoffman, P., and A. Costello, “Internationalizing Domain Names in Applications (IDNA),” March 2003.)
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] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) [RFC3987] (Duerst, M. and M. Suignard, “Internationalized Resource Identifiers (IRIs),” January 2005.)- 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.
TOC |
- Name of token.
- WebSocket
- Author/Change controller.
- Ian Hickson <ian@hixie.ch>
- Contact.
- Ian Hickson <ian@hixie.ch>
- References.
- This document.
TOC |
This section describes two header fields for registration in the Permanent Message Header Field Registry. [RFC3864] (Klyne, G., Nottingham, M., and J. Mogul, “Registration Procedures for Message Header Fields,” September 2004.)
- 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.
TOC |
This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] (Klyne, G., Nottingham, M., and J. Mogul, “Registration Procedures for Message Header Fields,” September 2004.)
- 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.
TOC |
This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] (Klyne, G., Nottingham, M., and J. Mogul, “Registration Procedures for Message Header Fields,” September 2004.)
- 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.
TOC |
This section describes a header field for registration in the Permanent Message Header Field Registry. [RFC3864] (Klyne, G., Nottingham, M., and J. Mogul, “Registration Procedures for Message Header Fields,” September 2004.)
- 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.
TOC |
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:
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".
TOC |
Special thanks are due to Ian Hickson, who was the original author and editor of this protocol. The initial design of this specification benefitted from the participation of many people in the WHATWG and WHATWG mailing list. Contributions to that specification are not tracked by section, but a list of all who contributed to that specification is given in the WHATWG HTML specification. [HTML] (Hickson, I., “HTML,” August 2010.)
Special thanks also to John Tamplin for providing a significant amount of text for the Data Framing section of this specification.
TOC |
TOC |
Ian Fette | |
Google, Inc. | |
Email: | ifette+ietf@google.com |
URI: | http://www.ianfette.com/ |