<abstract>This specification defines an XMPP protocol extension for active management of an XML stream between two XMPP entities, including features for stanza acknowledgements and stream resumption.</abstract>
<remark><p>Mark 'h' element as xs:unsignedInt in the schema too, it is already specified to be a 32-bit wrapping unsigned integer in the text.</p></remark>
<remark><p>Simplification based on implementation experience: removed acking per number of stanzas exchanged because either entity can request an ack at any time; moved throttling feature to a separate specification; removed 'stanzas' attribute from <enable/> element; added 'location' attribute to <enabled/> element; clarified several implementation issues in the text; fixed several examples; versioned the XML namespace from urn:xmpp:sm:2 to urn:xmpp:sm:3.</p></remark>
<remark><p>Corrected value of 'h' so that zero means no stanzas have yet been handled; clarified distinction between a cleanly closed stream and an unfinished stream.</p></remark>
<li>Added <t/> element for throttling notifications, including 'stanzas' attribute for dynamic adjustment of the stanzas window.</li>
<li>Simplified protocol by making the sequence number increment per stanza and removing the u attribute (which is now unnecessary).</li>
<li>Removed 'h' attribute from <r/> element.</li>
<li>Added 'max' and 'stanzas' attributes to both <enable/> and <enabled/> elements, and removed those attributes from the <sm/> element.</li>
<li>Incremented the protocol version from 1 to 2.</li>
<remark><p>Removed pings (use XEP-0199, whitespace pings, or TCP keepalives instead); removed section on throttling, since it is unworkable.</p></remark>
<remark><p>Added support for session resumption; re-organized the document; changed name to stream management; changed provisional namespace.</p></remark>
<p>&xmppcore; defines the fundamental streaming XML technology used by XMPP (i.e., stream establishment and termination including authentication and encryption). However, the core XMPP specification does not provide tools for actively managing a live XML stream.</p>
<p>The basic concept behind stream management is that the initiating entity (either a client or a server) and the receiving entity (a server) can exchange "commands" for active management of the stream. The following stream management features are of particular interest because they are expected to improve network reliability and the end-user experience:</p>
<p>Stream management implements these features using short XML elements at the root stream level. These elements are not "stanzas" in the XMPP sense (i.e., not &IQ;, &MESSAGE;, or &PRESENCE; stanzas as defined in <cite>RFC 6120</cite>) and are not counted or acked in stream management, since they exist for the purpose of managing stanzas themselves.</p>
<p>Stream management is used at the level of an XML stream. To check TCP connectivity underneath a given stream, it is RECOMMENDED to use whitespace keepalives (see <cite>RFC 6120</cite>), &xep0199;, or TCP keepalives. By contrast with stream management, &xep0079; and &xep0184; define acks that are sent end-to-end over multiple streams; these facilities are useful in special scenarios but are unnecessary for checking of a direct stream between two XMPP entities.</p>
<p>Note: Stream Management can be used for server-to-server streams as well as for client-to-server streams. However, for convenience this specification discusses client-to-server streams only. The same principles apply to server-to-server streams.</p>
<p>The server returns a stream header to the client along with stream features, where the features include an <sm/> element qualified by the 'urn:xmpp:sm:3' namespace &VNOTE;.</p>
<p>Note: The client cannot negotiate stream management until it has authenticated with the server and has bound a resource; see below for specific restrictions.</p>
<p>If the client wants to be allowed to resume the stream, it includes a boolean 'resume' attribute, which defaults to false &BOOLEANNOTE;. For information about resuming a previous session, see the <linkurl='#resumption'>Resumption</link> section of this document.</p>
<p>The <enable/> element MAY include a 'max' attribute to specify the client's preferred maximum resumption time in seconds.</p>
<p>Upon receiving the enable request, the server MUST reply with an <enabled/> element or a <failed/> element qualified by the 'urn:xmpp:sm:3' namespace. The <failed/> element indicates that there was a problem establishing the stream management "session". The <enabled/> element indicates successful establishment of the stream management session.</p>
<p>The <enabled/> element MAY include a 'max' attribute to specify the server's preferred maximum resumption time.</p>
<p>The <enabled/> element MAY include a 'location' attribute to specify the server's preferred IP address or hostname (optionally with a port) for reconnection, in the form specified in Section 4.9.3.19 of <cite>RFC 6120</cite> (i.e., "domainpart:port", where IPv6 addresses are enclosed in square brackets "[...]" as described in &rfc5952;); if reconnection to that location fails, the standard XMPP connection algorithm specified in <cite>RFC 6120</cite> applies.</p>
<p>The client MUST NOT attempt to negotiate stream management until it is authenticated; i.e., it MUST NOT send an <enable/> element until after authentication (such as SASL, &xep0078; or &xep0220;) has been completed successfully.</p>
<p>For client-to-server connections, the client MUST NOT attempt to enable stream management until after it has completed Resource Binding <em>unless it is resuming a previous session</em> (see <linkurl='#resumption'>Resumption</link>).</p>
<p>The server SHALL enforce this order and return a <failed/> element in response if the order is violated (see <linkurl='#errors'>Error Handling</link>).</p>
<p>Note that a client SHALL only make at most one attempt to enable stream management. If a server receives a second <enable/> element it SHOULD respond with a stream error, thus terminating the client connection.</p>
<p>After enabling stream management, the client or server can send ack elements at any time over the stream. An ack element is one of the following:</p>
<li>The 'h' attribute identifies the last <strong>handled</strong> stanza (i.e., the last stanza that the server will acknowledge as having received).</li>
<pclass='def'><strong>Definition:</strong> Acknowledging a previously-received ack element indicates that the stanza(s) sent since then have been "handled" by the server. By "handled" we mean that the server has accepted responsibility for a stanza or stanzas (e.g., to process the stanza(s) directly, deliver the stanza(s) to a local entity such as another connected client on the same server, or route the stanza(s) to a remote entity at a different server); until a stanza has been affirmed as handled by the server, that stanza is the responsibility of the sender (e.g., to resend it or generate an error if it is never affirmed as handled by the server).</p>
<p>Receipt of an <r/> element does not imply that new stanzas have been transmitted by the peer; receipt of an <a/> element only indicates that new stanzas have been processed if the 'h' attribute has been incremented.</p>
<p>The value of 'h' starts at zero at the point stream management is enabled or requested to be enabled (see note below). The value of 'h' is then incremented to one for the first stanza handled and incremented by one again with each subsequent stanza handled. In the unlikely case that the number of stanzas handled during a stream management session exceeds the number of digits that can be represented by the unsignedInt datatype as specified in &w3xmlschema2; (i.e., 2<spanclass='super'>32</span>), the value of 'h' SHALL be reset from 2<spanclass='super'>32</span>-1 back to zero (rather than being incremented to 2<spanclass='super'>32</span>).</p>
<pclass='box'>Note: Each entity maintains two counters for any given stream: a counter of stanzas it has sent, and a counter of stanzas it has received and handled ('h'). The counter for an entity's own sent stanzas is set to zero and started after sending either <enable/> or <enabled/>. The counter for the received stanzas ('h') is set to zero and started after receiving either <enable/> or <enabled/>.</p>
<p>When an <r/> element ("request") is received, the recipient MUST acknowledge it by sending an <a/> element to the sender containing a value of 'h' that is equal to the number of stanzas handled by the recipient of the <r/> element. The response SHOULD be sent as soon as possible after receiving the <r/> element, and MUST NOT be withheld for any condition other than a timeout. For example, a client with a slow connection might want to collect many stanzas over a period of time before acking, and a server might want to throttle incoming stanzas. The sender does not need to wait for an ack to continue sending stanzas.</p>
<p>Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas, or after a certain period of time), even if it has not received an <r/> element from the other party.
It is RECOMMENDED that initiating entities (usually clients) send an <a/> element right before they gracefully close the stream, in order to inform the peer about received stanzas. Otherwise it can happen that stanzas are re-sent (usually by the server) although they were actually received.
<p>When a party receives an <a/> element, it SHOULD keep a record of the 'h' value returned as the sequence number of the last handled outbound stanza for the current stream (and discard the previous value).</p>
<p>If a stream ends and it is not resumed within the time specified in the original <enabled/> element, the sequence number and any associated state MAY be discarded by both parties. Before the session state is discarded, implementations SHOULD take alternative action regarding any unhandled stanzas (i.e., stanzas sent after the most recent 'h' value received):</p>
<li>A server SHOULD treat unacknowledged stanzas in the same way that it would treat a stanza sent to an unavailable resource, by either returning an error to the sender, delivery to an alternate resource, or committing the stanza to offline storage. (Note that servers SHOULD add a delay element with the original (failed) delivery timestamp, as per &xep0203;).</li>
<li>A user-oriented client SHOULD try to silently resend the stanzas upon reconnection or inform the user of the failure via appropriate user-interface elements. Clients SHOULD also add a delay element with the original (failed) send timestamp, so that the original send date is preserved. Otherwise receiving clients could only display the reconnection timestamp of the sending client, which may confuse users.</li>
<p>Because unacknowledged stanzas might have been received by the other party, resending them might result in duplicates; there is no way to prevent such a result in this protocol, although use of the XMPP 'id' attribute on all stanzas can at least assist the intended recipients in weeding out duplicate stanzas.</p>
<p>It can happen that an XML stream is terminated unexpectedly (e.g., because of network outages). In this case, it is desirable to quickly resume the former stream rather than complete the tedious process of stream establishment, roster retrieval, and presence broadcast.</p>
<p>In addition, this protocol exchanges the sequence numbers of the last received stanzas on the previous connection, allowing entities to establish definitively which stanzas require retransmission and which do not, eliminating duplication through replay.</p>
<p>To request that the stream will be resumable, when enabling stream management the client MUST add a 'resume' attribute to the <enable/> element with a value of "true" or "1" &BOOLEANNOTE;.</p>
<p>If the server will allow the stream to be resumed, it MUST include a 'resume' attribute set to "true" or "1" on the <enabled/> element and MUST include an 'id' attribute that specifies an identifier for the stream.</p>
<pclass='def'><strong>Definition:</strong> The 'id' attribute defines a unique identifier for purposes of stream management (an "SM-ID"). The SM-ID MUST be generated by the server. The client MUST consider the SM-ID to be opaque and therefore MUST NOT assign any semantic meaning to the SM-ID. The server MAY encode any information it deems useful into the SM-ID, such as the full JID &LOCALFULL; of a connected client (e.g., the full JID plus a nonce value). Any characters allowed in an XML attribute are allowed. The SM-ID MUST NOT be reused for simultaneous or subsequent sessions (but the server need not ensure that SM-IDs are unique for all time, only for as long as the server is continuously running). The SM-ID SHOULD NOT be longer than 4000 bytes.</p>
<p>As noted, the <enabled/> element MAY include a 'location' attribute that specifies the server's preferred location for reconnecting (e.g., a particular connection manager that hold session state for the connected client).</p>
<examplecaption='Server prefers reconnection at a particular location'><![CDATA[
<li>After disconnection, the client opens a new TCP connection to the server, preferring the address specified in the 'location' attribute (if any).</li>
<li>Client sends initial stream header.</li>
<li>Server sends response stream header.</li>
<li>Server sends stream features.</li>
<li>Client sends STARTTLS request.</li>
<li>Server informs client to proceed with the TLS negotiation.</li>
<li>The parties complete a TLS handshake. (Note: When performing session resumption and also utilizing TLS, it is RECOMMENDED to take advantage of TLS session resumption &rfc5077; to further optimize the resumption of the XML stream.)</li>
<li>Server sends stream features, requiring SASL negotiation and offering appropriate SASL mechanisms. (Note: If the server considers the information provided during TLS session resumption to be sufficient authentication, it MAY offer the SASL EXTERNAL mechanism; for details, refer to &sasltls;.)</li>
<p>Note: The order of events might differ from those shown above, depending on when the server offers the SM feature, whether the client chooses STARTTLS, etc. Furthermore, in practice server-to-server streams often do not complete SASL negotiation or even TLS negotiation. The foregoing text does not modify any rules about the stream negotiation process specified in <cite>RFC 6120</cite>. However, since stream management applies to the exchange of stanzas (not any other XML elements), it makes sense for the server to offer the SM feature when it will be possible for the other party to start sending stanzas, not before. See also &xep0170;.</p>
<p>To request resumption of the former stream, the client sends a <resume/> element qualified by the 'urn:xmpp:sm:3' namespace. The <resume/> element MUST include a 'previd' attribute whose value is the SM-ID of the former stream and MUST include an 'h' attribute that identifies the sequence number of the last handled stanza sent over the former stream from the server to the client (in the unlikely case that the client never received any stanzas, it would set 'h' to zero).</p>
<p>If the server can resume the former stream, it MUST return a <resumed/> element, which MUST include a 'previd' attribute set to the SM-ID of the former stream and MUST also include an 'h' attribute set to the sequence number of the last handled stanza sent over the former stream from the client to the server (in the unlikely case that the server never received any stanzas, it would set 'h' to zero).</p>
<p>If the server does not support session resumption, it MUST return a <failed/> element, which SHOULD include an error condition of &feature;. If the server does not recognize the 'previd' as an earlier session (e.g., because the former session has timed out), it MUST return a <failed/> element, which SHOULD include an error condition of ¬found;. If the server recogizes the 'previd' as an earlier session that has timed out the server MAY also include a 'h' attribute indicating the number of stanzas received before the timeout. (Note: For this to work the server has to store the SM-ID/sequence number tuple past the time out of the actual session.)</p>
<p>In both of these failure cases, the server SHOULD allow the client to bind a resource at this point rather than forcing the client to restart the stream negotiation process and re-authenticate.</p>
<p>If the former stream is resumed and the server still has the stream for the previously-identified session open at this time, the server SHOULD send a 'conflict' stream error and close that stream.</p>
<examplecaption='Server closes old stream that was replaced by new'><![CDATA[
<li>The sequence values are carried over from the previous session and are not reset for the new stream.</li>
<li>Upon receiving a <resume/> or <resumed/> element the client and server use the 'h' attribute to retransmit any stanzas lost by the disconnection. In effect, it should handle the element's 'h' attribute as it would handle it on an <a/> element (i.e., marking stanzas in its outgoing queue as handled), except that after processing it MUST re-send to the peer any stanzas that are still marked as unhandled.</li>
<li>Both parties SHOULD retransmit any stanzas that were not handled during the previous session, based on the sequence number reported by the peer.</li>
<li>A reconnecting client SHOULD NOT request the roster, because any roster changes that occurred while the client was disconnected will be sent to the client after the stream management session resumes.</li>
<li>The client SHOULD NOT resend presence stanzas in an attempt to restore its former presence state, since this state will have been retained by the server.</li>
<p>If an error occurs with regard to an <enable/> or <resume/> element, the server MUST return a <failed/> element. This element SHOULD contain an error condition, which MUST be one of the stanza error conditions defined in <cite>RFC 6120</cite>.</p>
<p>When a remote entity acknowledges that it has handled a number of stanzas that is higher than the amount of stanzas that it was sent (by sending an 'h' value that is too high), the local entity SHOULD generate an undefined-condition stream error that includes a <handled-count-too-high/> element, and close the stream:</p>
<p>A cleanly closed stream differs from an unfinished stream. If a client wishes to cleanly close its stream and end its session, it MUST send a </stream:stream> so that the server can send unavailable presence on the client's behalf.</p>
<p>If the stream is not cleanly closed then the server SHOULD consider the stream to be unfinished (even if the client closes its TCP connection to the server) and SHOULD maintain the session on behalf of the client for a limited amount of time. The client can send whatever presence it wishes before leaving the stream in an unfinished state.</p>
<p>The following scenarios illustrate several different uses of stream management. The examples are that of a client and a server, but stream management can also be used for server-to-server streams.</p>
<p>The Stream Management protocol can be used to improve reliability using acks without the ability to resume a session. A basic implementation would do the following:</p>
<li>When receiving an <r/> element, immediately respond via an <a/> element where the value of 'h' returned is the sequence number of the last handled stanza.</li>
<li>Keep an integer X for this stream session, initially set to zero. When about to send a stanza, first put the stanza (paired with the current value of X) in an "unacknowleged" queue. Then send the stanza over the wire with <r/> to request acknowledgement of that outbound stanza, and increment X by 1. When receiving an <a/> element with an 'h' attribute, all stanzas whose paired value (X at the time of queueing) is less than or equal to the value of 'h' can be removed from the unacknowledged queue.</li>
<p>This is enough of an implementation to minimally satisfy the peer, and allows basic tracking of each outbound stanza. If the stream connection is broken, the application has a queue of unacknowledged stanzas that it can choose to handle appropriately (e.g., warn a human user or silently send after reconnecting).</p>
<p>The following examples illustrate basic acking (here the client automatically acks each stanza it has received from the server, without first being prompted via an <r/> element).</p>
<p>The client then chooses to acknowledge receipt of the server's stanza (although here it is under no obligation to do so, since the server has not requested an ack), sends initial presence, and immediately sends an <r/> element to request acknowledgement, incrementing by one its internal representation of how many stanzas have been handled by the server.</p>
<examplecaption='Client acks handling of first server stanza, sends a stanza, and requests acknowledgement'><![CDATA[
<p>The server immediately sends an <a/> element to acknowledge handling of the stanza and then broadcasts the user's presence (including to the client itself as shown below).</p>
<p>The server immediately sends an <a/> element to acknowledge handling of the third client stanza and then routes the stanza to the remote contact (not shown here because the server does not send a stanza to the client).</p>
<examplecaption='Server acknowledges handling of third client stanza'><![CDATA[
<p>The basic acking scenario is wasteful because the client requested an ack for each stanza. A more efficient approach is to periodically request acks (e.g., every 5 stanzas). This is shown schematically in the following pseudo-XML.</p>
<p>In particular, on mobile networks, it is advisable to only request and/or send acknowledgements when an entity has other data to send, or in lieu of a whitespace keepalive or XMPP ping (XEP-0199).</p>
<pclass='box'>This section is about &xep0388; (SASL2) and &xep0386; (BIND2) interaction. You don't have to implement this if you don't implement SASL2 and BIND2.</p>
<p>&xep0388; (SASL2) describes a way of inlining the stream resumption into the authentication process to reduce the round-trips needed for authentication and subsequent stream resumption. Similarly &xep0386; (BIND2) defines a way of inlining the stream management <enable/> into the resource binding process to reduce round-trips.</p>
<p>To indicate support for inlining the activation of Stream Management into the resource binding process, the server adds a <feature/> element in the namespace "urn:xmpp:sm:3" into the <inline/> element of BIND2 which is sent in the stream features.</p>
<p>If the client wishes to begin a new session (i.e. it has no prior session to resume), it simply includes the <enable/> element defined by this specification in its &xep0386;<bind/> request which itself is a child of the <authenticate/> element of SASL2.</p>
<section3topic="Failed To Enable Stream Management">
<p>In the unexpected case where the server was able to bind a resource for the client, but unable to enable stream management, it will include a <failed/> element as defined by this specification within the <bound/> response defined by &xep0386;.</p>
<p>To indicate support for inlining stream resumption into the authentication process, the server adds a <resume/> element in the namespace "urn:xmpp:sm:3" to the <inline/> element of SASL2.</p>
<p>If the client wishes to resume an existing session it, it simply includes the <resume/> element defined by this specification in the SASL2 <authenticate/> element.</p>
<pclass="box">Note: If the client included a <resume/> element in its SASL2 <authenticate/> element, that MUST be processed first by the server. If that resumption is successful, the server MUST skip resource binding (a resumed session already has a resource bound) and MUST entirely ignore the <bind/> request that might also be inlined in the <authenticate/> element.</p>
<p>&xep0388; mandates that the <success> element is immeditaly followed by stream features. If a former stream has been successfully resumed using this specification, the stream is considered re-established immediately after the <success/> element instead and stream features MUST NOT be sent in this case.</p>
<p>Sometimes resumption might fail - for example, because the session has been disconnected longer than the server’s resumption timeout. In this case, the server MUST include the <failed/> element defined by this specification in its SASL2 <success/> response, but also MUST continue to process the <bind/> in order to establish a new session for the client.</p>
<p>The client can find details about its new session in the <bound/> response (defined by &xep0386;).</p>
<p>As noted, a server MUST NOT allow a client to resume a stream management session until after the client has authenticated (for some value of "authentication"); this helps to prevent session hijacking.</p>
<p>If SASL2 is used to inline stream resumption implementations must adhere to the security considerations defined in &xep0388; regarding the inclusion of SASL2 requests and inline feature negotiation in TLS 0-RTT ("early data") extensions. That is, they MUST NOT be sent or processed if the stream would be resumed solely based on 0-RTT data, except when appropriate mitigations are in place (which are beyond the scope of this document, but may be defined by others).</p>
<p>Thanks to Bruce Campbell, Jack Erwin, Philipp Hancke, Curtis King, Tobias Markmann, Alexey Melnikov, Pedro Melo, Robin Redeker, Mickaël Rémond, Florian Schmaus, and Tomasz Sterna for their feedback.</p>