<?xml version="1.0" encoding="US-ASCII"?>
<!-- This template is for creating an Internet Draft using xml2rfc,
     which is available here: http://xml.resource.org. -->
<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
<!ENTITY RFC0792 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.0792.xml">
<!ENTITY RFC2045 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2045.xml">
<!ENTITY RFC2046 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2046.xml">
<!ENTITY RFC2616 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2616.xml">
<!ENTITY RFC3986 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3986.xml">
<!ENTITY RFC4346 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4346.xml">
<!ENTITY RFC4347 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4347.xml">
<!ENTITY RFC4944 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4944.xml">
<!ENTITY RFC5785 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5785.xml">
<!ENTITY I-D.bormann-6lowpan-6lowapp-problem SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.bormann-6lowpan-6lowapp-problem.xml">
<!ENTITY I-D.shelby-6lowapp-encoding SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.shelby-6lowapp-encoding.xml">
<!ENTITY I-D.frank-6lowapp-chopan SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.frank-6lowapp-chopan.xml">
<!ENTITY I-D.gold-6lowapp-sensei SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-gold-6lowapp-sensei-00.xml">
<!ENTITY I-D.martocci-6lowapp-building-applications SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-martocci-6lowapp-building-applications-00.xml">
<!ENTITY I-D.sturek-6lowapp-smartenergy SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-sturek-6lowapp-smartenergy-00.xml">
<!ENTITY I-D.moritz-6lowapp-dpws-enhancements SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-moritz-6lowapp-dpws-enhancements-00.xml">
<!ENTITY I-D.shelby-core-coap-req SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-shelby-core-coap-req-01.xml">
<!ENTITY I-D.nottingham-http-link-header SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-nottingham-http-link-header-09.xml">
<!ENTITY I-D.cheshire-dnsext-multicastdns SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-cheshire-dnsext-multicastdns-11.xml">
]>
<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>
<!-- used by XSLT processors -->
<!-- For a complete list and description of processing instructions (PIs),
     please see http://xml.resource.org/authoring/README.html. -->
<!-- Below are generally applicable Processing Instructions (PIs) that most I-Ds might want to use.
     (Here they are set differently than their defaults in xml2rfc v1.32) -->
<?rfc strict="yes" ?>
<!-- give errors regarding ID-nits and DTD validation -->
<!-- control the table of contents (ToC) -->
<?rfc toc="yes"?>
<!-- generate a ToC -->
<?rfc tocdepth="3"?>
<!-- the number of levels of subsections in ToC. default: 3 -->
<!-- control references -->
<?rfc symrefs="yes"?>
<!-- use symbolic references tags, i.e, [RFC2119] instead of [1] -->
<?rfc sortrefs="yes" ?>
<!-- sort the reference entries alphabetically -->
<!-- control vertical white space
     (using these PIs as follows is recommended by the RFC Editor) -->
<?rfc compact="yes" ?>
<!-- do not start each main section on a new page -->
<?rfc subcompact="no" ?>
<!-- keep one blank line between list items -->
<!-- end of list of popular I-D processing instructions -->
<rfc category="info" ipr="pre5378Trust200902" docName="draft-shelby-core-coap-01">

<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>

<?rfc toc="yes" ?>
<?rfc symrefs="yes" ?>
<?rfc sortrefs="yes"?>
<?rfc iprnotified="no" ?>
<?rfc strict="yes" ?>

    <front>
        <title>Constrained Application Protocol (CoAP)</title>

        <author initials="Z" surname="Shelby" fullname="Zach Shelby">
          <organization>
             Sensinode
          </organization>
          <address>
            <postal>
             <street>Kidekuja 2</street>
             <city>Vuokatti</city>
             <code>88600</code>
             <country>FINLAND</country>
            </postal>
            <phone>+358407796297</phone>
            <email>zach@sensinode.com</email>
    </address>
        </author>

    <author initials="B" surname="Frank" fullname="Brian Frank">
          <organization>
             SkyFoundry
          </organization>
          <address>
            <postal>
             <street></street>
             <city>Richmond, VA</city>
             <code></code>
             <country>USA</country>
            </postal>
            <phone></phone>
            <email>brian@skyfoundry.com</email>
    </address>
        </author>

        <author initials="D" surname="Sturek" fullname="Don Sturek">
          <organization>
             Pacific Gas & Electric
          </organization>
          <address>
            <postal>
             <street>77 Beale Street</street>
             <city>San Francisco, CA</city>
             <code></code>
             <country>USA</country>
            </postal>
            <phone>+1-619-504-3615</phone>
            <email>d.sturek@att.net</email>
    </address>
        </author>


  <date year="2010"/>

  <area>Internet</area>

  <workgroup>CoRE</workgroup>
  <keyword>Requirements, CoAP</keyword>

        <abstract>
    <t>
    This document specifies the Constrained Application Protocol (CoAP), a specialized transfer protocol for use with constrained networks and nodes for machine-to-machine applications such as smart energy and building automation. These constrained nodes often have 8-bit microcontrollers with small amounts of ROM and RAM, while networks such as 6LoWPAN often have high packet error rates and typical throughput of 10s of kbps. 
    CoAP provides request/reply and subscribe/notify interaction models between appliciation end-points, supports built-in resource discovery, and includes key web concepts such as URIs and RESTful methods. CoAP easily translates to HTTP for integration with the web while meeting specialized requirements such as multicast support, very low overhead and simplicity for constrained environments.
    </t> 
    
    </abstract>
    </front>

    <middle>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='introduction' title="Introduction">

  <t>
  The use of web services on the Internet has become ubiquitous in most applications, and depends on the fundamental Representational State Transfer (REST) architecture of the web. The proposed Constrained RESTful Environments (CoRE) working group aims at realizing the REST architecture in a suitable form for the most constrained nodes (e.g. 8-bit microcontrollers with limited RAM and ROM) and networks (e.g. 6LoWPAN). One of the main goals of CoRE is to design a generic RESTful protocol for the special requirements of this constrained environment, especially considering energy and building automation applications.
  </t>
  <t>
  This document specifies the RESTful Constrained Application Protocol (CoAP) which easily translates to HTTP for integration with the web while meeting specialized requirements such as multicast support, very low overhead and simplicity for constrained environments <xref target="I-D.shelby-core-coap-req"/>. CoAP has the following main features:

  <list style="symbols">
    <t>RESTful protocol design minimizing the complexity of mapping with HTTP.</t>
    <t>Low header overhead and parsing complexity.</t>
    <t>URI and Content-type support.</t>
    <t>Support for the discovery of resources provided by known CoAP end-points.</t>
    <t>Simple subscription for a resource and a resulting notification mechanism.</t>
    <t>Simple caching based on max-age.</t>
  </list>
  </t>
  <t>
  The mapping of CoAP with HTTP is defined, allowing proxies to be built providing access to CoAP resources via HTTP in a uniform way.
  </t>
  </section>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='protocol' title="Constrained Application Protocol">

  <t>
  This section specifies the basic functionality and processing rules of CoAP.
  </t>

    <section anchor='interaction' title="Interaction Model">

    <t>
    The interaction model of CoAP is client/server with request or notify messages initiating a transaction responded to with a matching response based on a transaction ID if the A bit is set. Machine-to-machine interactions with RESTful design typically result in a CoAP implementation acting in both client and server roles. A CoAP request is equivalent to an HTTP request, and is sent by a client to request an action (using a method) on a resource (identified by a URI) on a server. A CoAP notify is the inverse of a request, where a server sends a notify message to a client about a resource on the server (identified by a URI). A notify includes the representation, Etag and/or Date of the resource. Examples message exchanges can be found from <xref target="examples"/>.
    </t>
    <t>
    This document specifies the interaction of two CoAP end-point acting as a client or server. We can consider an end-point of CoAP to be an application process using one source port for sending or receiving CoAP messages. Thus a host may run any number of CoAP end-points.
    </t>


      <section anchor='request' title="Request messages">
      <t>
      A CoAP end-point acting as a client sends a request with the following rules. The Version field is set to 0. The Type Flag is set to 0 indicating a request. For a UDP binding the A Flag SHOULD be set requesting a response and enabling retransmission in case of timeout (see <xref target="retransmission"/>). The A Flag MAY be unset for TCP bindings or for a UDP binding where reliability is too costly or not useful. The Method field MUST be set with a value of 0-4. The TRANSACTION_ID variable is increased by one, and this value is placed in the Transaction ID Field. See <xref target="opt-proc"/> for options rules.
      </t>
      <t>
      If a payload is to be included in the message, it immediately follows the last option or the Transaction ID if none. If a magic byte header is included, its Length value indicates the length of the message in octets. A magic byte header MUST be included if multiple messages are packed into a single UDP datagram or over TCP.
      </t>
      <t>
      For each request sent with the A flag set, a CoAP end-point keeps track of the destination IP address and Transaction ID of the request for the purpose of matching responses. For unicast destination over UDP, the retransmission procedure is described in <xref target="retransmission"/>.
      </t>

      <t>
      Upon receiving a request, a CoAP end-point performs the following validation and processing:
      </t>
      <t>
        <list>
          <t>o The Version Field MUST be 0.</t>
          <t>o The Type Flag MUST be 0.</t>
          <t>o The Method Field MUST be 0-4.</t>
          <t>o If the Number of Options Field is > 0, then each option is validated and processed as in <xref target="opt-proc"/>. </t>
          <t>o The length of the Payload is taken from the Content-length Option or calculated from the datagram length otherwise.</t>
          <t>o The Method, URI, any options and Payload are passed on to the corresponding application process.</t>
          <t>o If the A bit is set, an appropriate response message MUST be sent to the source IPv6 address and port of the request with the same Transaction ID of the request. If the A bit is unset, a response message MUST NOT be sent.</t>
        </list>
      </t>
      <t>
      TODO: Define the behavior on failure. Error or silent discard?
      </t>
      </section>


      <section anchor='notify' title="Notify messages">

      <t>
      The sending of a notify message is similar to sending a request message, with the following difference:  The Type Flag is set to 2. The processing of a notify message is similar to processing a request message.
      </t>

      </section>

      <section anchor='resp-send' title="Response message">

      <t>
      A response message is created with the following rules. The Version Field is set to 0. The Type Flag is set to 1. The Code is set to one of the supported response codes in <xref target="appendix_codes"/>. The Transaction ID MUST be set to that of the corresponding request. See <xref target="opt-proc"/> for options rules. An optional Payload may be included as appropriate for the request.
      </t>
      <t>
      Upon receiving a response, a CoAP end-point performs the following validation and processing:
      </t>
      <t>
        <list>
          <t>o The Version Field MUST be 0.</t>
          <t>o The Type Flag MUST be 1.</t>
          <t>o The Code Field MUST contain a valid code.</t>
          <t>o If the Number of Options Field is > 0, then each option is validated and processed as in <xref target="opt-proc"/>. </t>
          <t>o The length of the Payload is taken from the Content-length Option or calculated from the datagram length otherwise.</t>
          <t>o The Transaction ID is used to match the response to an open request entry, and the response code, any options and Payload are passed on to the corresponding application process. If no match is found, the message is silently discarded.</t>
        </list>
      </t>
      <t>
      TODO: Define the behavior on failure. Error or silent discard?
      </t>
      </section>


      <section anchor='opt-proc' title="Option fields">
      <t>
      If no options are to be included, the Option Number Field is set to 0 and the Payload (if any) immediately follows the Transaction ID. If options are to be included, the following rules apply. The number of options is placed in the Number of Options Field. Each option is then placed in order of Type, immediately following the Transaction ID with no padding. Unknown options MUST be silently skipped.
      </t>
      <t>
      TODO: Option validation and processing.
      </t>
      </section>

      <section anchor='transactionid' title="Transaction IDs">

      <t>
      The Transaction ID is a unique unsigned integer kept by a CoAP end-point for all of the CoAP request or notify messages it sends. Each CoAP end-point keeps a single Transaction ID variable, which is changed each time a new request or notify message is sent regardless of the destination address or port. The Transaction ID is used to match a response with an outstanding request or notify, for retransmission and to discard duplicate messages. The initial Transaction ID should be randomized.
      </t>

      </section>

    </section>

    <section anchor='methods' title="Methods">
    <t>
    CoAP supports the basic RESTful methods of GET, POST, PUT, DELETE, which are easily mapped to HTTP methods. In this section each method is defined along with its behavior. In addition, CoAP defines a new SUBSCRIBE method for requesting soft-state subscriptions for resources. 
    </t>
    <t>
    As CoAP methods manipulate resources, they have the same properties of safe (only retrieval) and idempotent (you can invoke it multiple times with the same effects) as HTTP <xref target="RFC2616">Section 9.1</xref>. The GET method is safe, therefore it SHOULD NOT take any other action on a resource other than retrieval. The GET, PUT and DELETE methods can be considered idempotent.
    </t>

      <section anchor='read' title="GET">
      <t>
      The GET method retrieves the information of the resource identified by the request URI. Upon success a 200 (OK) response SHOULD be sent.
      </t>
      <t>
      All GET requests MUST be idempotent in that they produce no side-effects.
      </t>
      <t>
      The response to a GET is cacheable if it meets the requirements in <xref target="caching"/>.
      </t>
      </section>

      <section anchor='create' title="POST">
      <t>
      The POST method is used to request the server to create a new resource under the requested URI. If a resource has been created on the server, the response should be 201 (Created) including the URI of the new resource in the header and any possible status in the message body. If the POST does not result in a new resource being created on the server, a 200 (OK) response code is returned.
      </t>
      <t>
      Responses to this method are not cacheable.
      </t>
      </section>

      <section anchor='update' title="PUT">
      <t>
      The PUT method requests that the resource identified by the request URI be updated with the enclosed message body. If a resource exists at that URI the message body SHOULD be considered a modified version of that resource. If no resource exists then the server MAY create a new resource with that URI.
      </t>
      <t>
      All PUT requests MUST be idempotent in that they produce no side-effects.
      </t>
      <t>
      Responses to this method are not cacheable.
      </t>
      </section>

      <section anchor='delete' title="DELETE">
      <t>
      The DELETE method requests that the resource identified by the request URI be deleted.
      The response 200 (OK) SHOULD be sent on success.
      </t>
      <t>
      All DELETE requests MUST be idempotent in that they produce no side-effects.
      </t>
      <t>
      Responses to this method are not cacheable.
      </t>
      </section>

      <section anchor='subscribe' title="SUBSCRIBE">
  
	<t>
	CoAP supports a built-in subscribe/notify push model for an end-point to notify another end-point about a resource of interest. This push is accomplished using the CoAP notify message type, whose URI corresponds to the resource of interest on the end-point sending the notify message. A notify may include the latest representation of the resource in its payload and/or the Etag Option.
	</t>
	<t>
	The SUBSCRIBE method allows an end-point to request notifications about a resource. A request of this method MAY include the Subscription-lifetime Option defined in <xref target="option-subscription"/>. In the absence of this Option, its maximum lifetime is assumed. End-points MUST NOT send notify messages without a valid subscription. Subscriptions are soft-state, and must be refreshed by sending a new SUBSCRIBE message before the end of its lifetime. 
	</t>
	<t>
	Servers keep track of subscriptions its resources, and upon change a notify message is sent to the source address and port of the original SUBSCRIBE request with the URI of the resource in question. Notifications MAY be sent with the A bit set, enabling a server to detect if a subscriber is no longer valid. A subscription SHOULD be removed after MAX_RETRANSMIT failures when the A bit is set. A server is not required to support subscriptions for its resources, and MAY limit the number of simultaneous subscriptions.
	</t>

      </section>


    </section>


    <section anchor='uri' title="URIs">
    <t>
    The Universal Resource Identifier (URI) <xref target="RFC3986"/> is an important feature of the REST architecture, where the relative part of the URI indicates which resource is being manipulated. CoAP supports variable-length string URIs with the Uri Option. As this URI is used as a locator, CoAP only supports Universal Resource Locator features of <xref target="RFC3986"/> although throughout the document we refer to URI. CoAP supports relative references in the Uri Option (e.g. /sensors/temperature) for messages to a CoAP end-point, and absolute URIs for use with a proxy (coap://2001:1ba3::450a/sensors/temperature), and does not support "." and ".." schemes. A CoAP implementation MAY support query "?" processing if needed, however fragment "#" processing is not supported. IRIs are not supported. All URI strings in CoAP MUST use the US-ASCII encoding defined in <xref target="RFC3986"/>. 
    </t>
    <t>
    The CoAP protocol scheme is identified in URIs with "coap://" (TODO: IANA considerations).
    </t>
    <t>
    All resources URIs MUST begin with a leading "/" slash character.  During transmission of the URI in the Uri header, the leading slash MAY be omitted.  If the Uri header does start with a "/" leading slash, then it is implied.
    </t>
    <t>
    TODO: Describe the use of binary URI codes and the Uri-code Option.
    </t>
    </section>

    <section title="CoAP Codes">

    <t>
    When a response message is sent in response to a request or notify message it MUST always include a response code in the header. Notify messages also include a code field, which is set to "200 OK" by default. CoAP makes use of a subset of HTTP response codes as defined in <xref target="appendix_codes"/>.
    </t>
  
<!-- TODO: Decide which codes are valid for use in a notify -->

    </section>

    <section anchor='content-type' title="Content-type encoding">

    <t>
    In order to support heterogeneous uses, CoAP is transparent to the use of different application payloads. In order for the application process receiving a packet to properly parse a payload, its content-type should be explicitly known from the header (as e.g. with HTTP). The use of typical binary encodings for XML is discussed in <xref target="I-D.shelby-6lowapp-encoding"/>.
    </t>
    <t>
    It is obvious that string names of Internet media types <xref target="RFC2046"/> are not appropriate for use in the CoAP header. Instead, CoAP simply assigns identifiers to a subset of common MIME and content transfer encoding types. The content-type identifier is optionally included in the Content-type Option Header of messages to indicate the type of the message body. CoAP Content-type identifiers are defined in <xref target="appendix_content"/>.
    </t>
    
    </section>


  </section>


  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='messages' title="Message Formats">

  <t>
  CoAP makes use of three message types - request, notify and response, using a simple binary header format. This base header may be followed by options in Type-Length-Value (TLV) format. CoAP is by default bound to UDP and optionally to TCP as described in <xref target="binding"/>. In addition, a CoAP magic byte header is used when multiple messages are packed into a UDP payload and over TCP.
  </t>
  <t>
  Any bytes after the headers in the packet are considered the message payload, if any. The length of the message payload is implied by the datagram length or the Length Field of the magic byte header if included. When bound to UDP the entire message MUST fit within a single datagram.  When used with 6LoWPAN <xref target="RFC4944"/>, messages SHOULD fit into a single 802.15.4 frame to minimize fragmentation.
  </t>

    <section anchor='magic' title="CoAP magic byte header">
    <t>
    This section defines the CoAP magic byte header shown in <xref target="fig-magic"/>. This header provides a clear delimiter between CoAP messages and the total message length. The magic byte header MUST be included before the CoAP header when packing multiple messages in a single UDP datagram or over a TCP connection, and MAY be included otherwise. 
    </t>

       <figure anchor='fig-magic' title="CoAP magic byte header">
         <artwork>
Template:

 0                              
 0 1 2 3 4 5 6 7 8 
+-+-+-+-+-+-+-+-+-+
|      'r'      |X|
+-+-+-+-+-+-+-+-+-+

Length of 0-127:

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      'r'      |0|   Length    |        CoAP header ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Length of 128-32768:

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      'r'      |1|           Length            | CoAP header ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

         </artwork>
       </figure>


    <t hangText="Magic Byte Fields:">
       <list style="hanging">
         <t hangText="'r':">
          CoAP magic byte which is US-ASCII character 'r' = 0x72 = 0b01110010. The magic byte 'r' stands for RESTful :-)
         </t>
         <t hangText="X:">
          1-bit Extended Length Flag. When 0 the Length is a 7-bit unsigned integer. When 1 the Length Field is extended by an octet and Length Field is a 15-bit unsigned integer. 
         </t>
         <t hangText="Len:">
          Length Field. When X is 0 Length is a 7-bit unsigned integer allowing values of 0-127 octets. When X is 1 Length is a 15-bit unsigned integer allowing values of 128-32767 octets. The Length field indicates the length of the CoAP message following the Length Field in octets.
         </t>
         <t hangText="CoAP header">
         The CoAP header immediately follows the Length Field. 
         </t>
       </list>
     </t>

    
    </section>


    <section anchor='base' title="CoAP header">
    <t>
    This section defines the CoAP header, which is shared for all message types.
    </t>

    <t hangText="Message Types:">
       <list style="hanging">
         <t hangText="Request:">
         A CoAP request message is sent by a client to request a URI on a server using one of the methods listed in <xref target="tab-method"/>.
         </t>
         <t hangText="Notify:">
         A CoAP notify message is sent by a server to notify a client about a resource (identified by a URI) on the server as a result of a valid subscription for that resource.
         </t>
         <t hangText="Response:">
          A CoAP response message is sent in response to a CoAP request or notify when appropriate. Responses include a Transaction ID corresponding to that of the request. A response is always sent when the A flag is set in a request, and is never sent when the A flag is not set. A response is always sent to the source IP address and port of the corresponding request or notify. 
         </t>
        </list>
    </t>


       <figure anchor='fig-req' title="CoAP header format">
         <artwork>
 
 Template:
 
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| T |   O   | Type Specific |        Transaction ID         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Request (T=0):

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver|0 0|   O   |A|  R  | Meth  |        Transaction ID         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


Response (T=1):

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver|0 1|   O   | R |    Code   |        Transaction ID         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


Notify (T=2):

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver|1 0|   O   |A|R|    Code   |        Transaction ID         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Options (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+


         </artwork>
       </figure>

       <t>
         <list style="hanging">

     <t hangText="Header Fields:">
       <list style="hanging">
         <t hangText="Ver:">
         Version. 2-bit unsigned integer. Indicates the version of CoAP. Implementations of this specification MUST set this field to 0. The values 1-3 are reserved for future versions.
         </t>
         <t hangText="T:">
         2-bit Message Type flag. Indicates if this message is a CoAP request (0), response (1) or notify (2) header. The value 3 is forbidden to avoid collision with the magic byte 'r'.
         </t>
         <t hangText="O:">
         4-bit Number of Options field. Indicates if there are Option Headers following the base header. If set to 0 the payload (if any) immediately follows the base header. If greater than zero the field indicates the number of options to immediately follow the header.
         </t>
         <t hangText="A:">
         1-bit Acknowledgement flag. When set to 1, indicates that the destination MUST respond with a response message matching this request (see <xref target="udp"/>). When set to 0, the destination MUST NOT send a response to this request. 
         </t>
         <t hangText="Meth:">
         4-bit unsigned integer. This field indicates the CoAP Method of the request according to <xref target="tab-method"/>. Methods are described in detail in <xref target="methods"/>. 
         </t>
         <t hangText="Code:">
         6-bit unsigned integer. This field indicates the code of a response or notify message as defined in <xref target="appendix_codes"/>.
         </t>
         <t hangText="Transaction ID:">
         16-bit unsigned integer. A unique Transaction ID assigned by the source and used to match responses. The Transaction ID MUST be changed for each new request (regardless of the end-point) and MUST NOT be changed when retransmitting a request.
         </t>
         <t hangText="R:">
         This field is unused. It MUST be initialized to zero by the sender and MUST be ignored by the receiver.
         </t>         
       </list>
     </t>
    </list>
    </t>

        <texttable anchor='tab-method' title="Method codes">

        <ttcol align='left'>Method</ttcol>
        <ttcol align='left'>Code</ttcol>

        <c>GET</c>
        <c>0</c>

        <c>POST</c>
        <c>1</c>

        <c>PUT</c>
        <c>2</c>

        <c>DELETE</c>
        <c>3</c>

        <c>SUBSCRIBE</c>
        <c>4</c>

        </texttable>

    </section>


    <section anchor='options' title="Header options">
    <t>
    CoAP messages may also include one or more header options in TLV format. Each option has the following format:
    </t>

       <figure anchor='fig-opt' title="Header option format">
         <artwork>
Template:

 0                
 0 1 2 3 4 5  
+-+-+-+-+-+-+
|  Type   |X|
+-+-+-+-+-+-+

Length of 0-4:

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Type   |0|Len|  Option Value ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Length of 5-1024:

 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Type   |1|        Len        |  Option Value ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

         </artwork>
       </figure>

    <t hangText="Option Fields:">
       <list style="hanging">
         <t hangText="Type:">
          5-bit unsigned integer. The type of the option as defined in <xref target="tab-options"/>, allowing for up to 32 options. Future specifications may define new CoAP option types. Option types 30-32 are reserved for experimental purposes.
         </t>
         <t hangText="X:">
          1-bit Extended Length Flag. When 0 the Length is a 2-bit unsigned integer. When 1 the option header is extended by an octet and Length is a 10-bit unsigned integer. 
         </t>
         <t hangText="Len:">
          Length Field. When X is 0 Length is a 2-bit unsigned integer allowing values of 0-4 octets. When X is 1 Length is a 10-bit unsigned integer allowing values of 5-1024 octets.
         </t>
         <t hangText="Option Value">
         The value in the format defined for that option in <xref target="tab-options"/> with a length of Option Len octets. Options may use variable length unsigned integer values of Len Field octets in network byte order as shown in <xref target="fig-variable"/>.
         </t>
       </list>
     </t>


       <figure anchor='fig-variable' title=" Variable length unsigned integer value format">
         <artwork>

             0
             0 1 2 3 4 5 6 7
            +-+-+-+-+-+-+-+-+
Len = 1     |     0-255     |
            +-+-+-+-+-+-+-+-+

             0                   1
             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Len = 2     |            0-65535            |
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Len = 3 is 24 bits, Len = 4 is 32 bits etc.

         </artwork>
       </figure>

    <t>
    The following options are defined in this document.
    </t>

        <texttable anchor='tab-options' title="Option headers">

        <ttcol align='left'>Type</ttcol>
        <ttcol align='left'>Name</ttcol>
        <ttcol align='left'>Data type</ttcol>
        <ttcol align='left'>Length</ttcol>
        <ttcol align='left'>Rules</ttcol>

        <c>0</c>
        <c>Content-type</c>
        <c>Variable uint</c>
        <c>1-2 B</c>
        <c></c>

        <c>1</c>
        <c>Uri</c>
        <c>String</c>
        <c>1-32768 B</c>
        <c>Never in response</c>

        <c>2</c>
        <c>Uri-code</c>
        <c>Variable uint</c>
        <c>1-2 B</c>
        <c>Never with Uri Option</c>

        <c>3</c>
        <c>Max-age</c>
        <c>Variable uint</c>
        <c>1-4 B</c>
        <c></c>

        <c>4</c>
        <c>Etag</c>
        <c>Variable uint</c>
        <c>1-4 B</c>
        <c></c>

        <c>5</c>
        <c>Date</c>
        <c>Variable integer</c>
        <c>4-6 B</c>
        <c>Never in request</c>

        <c>6</c>
        <c>Subscription-lifetime</c>
        <c>Variable uint</c>
        <c>1-3 B</c>
        <c>With SUBSCRIBE or its response</c>

        </texttable>

<!--
  <section anchor='option-length' title="Content-length Option">

  <t>The Content-length Option Indicates the length of the payload in octets. The option is represented as a variable length unsigned integer maximum 16-bits in length. This option MUST be included when packing multiple messages in a single UDP datagram or over a persistent TCP connection. It is not required for a Payload-length Option to be included when a single message is included in a UDP datagram. The Content-length MUST be included with a TCP binding.</t>

  </section>
-->

  <section anchor='option-content' title="Content-type Option">

  <t>The Content-type Identifier Option indicates the Internet Media Type of the message-body, see <xref target="appendix_content"/> for the encoding and identifier tables. A Content-type Identifier Option SHOULD be included if there is a payload included with a CoAP message, and MUST not be included for a zero-length payload.</t>

  </section>

  <section anchor='option-uri' title="Uri Option">

  <t>The Uri Option indicates the string URI of the resource that may be included in request and notify messages. In the absence of this option, the URI is assumed to be "/". <xref target="uri"/> specifies the rules for URIs in CoAP. </t>

  </section>

  <section anchor='option-uri-code' title="Uri-code Option">

  <t>The Uri-code Option is used as an alternative to the Uri Option, and indicates a variable length code assigned globally to well-known URI strings or by the CoAP end-point in a link description entry "code" field (see <xref target="discovery"/>). The Uri-code Option MUST NOT be used at the same time as the Uri Option. If both options appear in a message then the Uri-code Option is ignored. </t>

  </section>

  <section anchor='option-max-age' title="Max-age Option">

  <t>The Max-age Option indicates the maximum age of the resource for use in cache control in seconds. The option is represented as a variable length unsigned integer maximum 32-bits in length.
  </t>
  <t>
  When included in a request, Max-age indicates the maximum age of a cached representation of that resource the client will accept. When included in a response or a notify, Max-age indicates the maximum time the representation may be cached before it MUST be discarded.
  </t>

  </section>

  <section anchor='option-etag' title="Etag Option">

  <t>The Etag Option is a variable length unsigned integer which specifies the version of a resource representation. An Etag may be generated for a resource in any number of ways including a version, checksum, hash or time. An end-point receiving an Etag MUST treat it as opaque and make no assumptions about its format. The Etag MAY be included in a notify message to indicate to a client if a resource has changed. </t>

  </section>


  <section anchor='option-date' title="Date Option">

  <t>The Date Option indicates the creation time and date of a given resource representation. It MAY be used in response and notify messages. The integer value is the number of seconds, excluding leap seconds, after midnight UTC, January 1, 1970. This time format cannot represent time values prior to January 1, 1970. The latest UTC time value that can be represented by a 31 bit integer value is 03:14:07 on January 19, 2038. Time values beyond 03:14:07 on January 19, 2038, are represented by 39 bit integer values which is sufficient     		  
  to represent dates that should be enough for anyone. For applications requiring more accuracy, a 48-bit integer MAY be included representing this value in milliseconds instead of seconds.
  </t>

  </section>
  

  <section anchor='option-subscription' title="Subscription-lifetime Option">

  <t>The Subscription-lifetime Option indicates the subscription lifetime and is optionally included with the SUBSCRIBE method (see <xref target="subscribe"/>). The corresponding response MUST include a Subscription-lifetime Option confirming (or modifying) the subscription lifetime.
  </t>
  <t>
  The value of this option is a variable length unsigned integer up to 24-bits indicating the lifetime of the subscription in seconds with a maximum value of 194 days. In a response the server MAY return a different value that fits its own scheduling better. A value of all 0 in a request indicates cancellation of a subscription and in a response indicates subscription failure or rejection.
  </t>
  
  </section>


  </section>

  </section>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='binding' title="Transport Binding">

  <t>
  The CoAP protocol will operate by default over UDP. There may be optional functions in CoAP (e.g. delivery of larger chunks of data) which if implemented are implemented over TCP. This section defines the binding of CoAP over UDP and TCP.
  </t>

    <section anchor='udp' title="UDP">
    <t>
    The goal of binding CoAP to UDP is to provide the bare minimum features for the protocol to operate over UDP, without trying to re-create the full feature set of TCP. CoAP over UDP has the following features:
    </t>
    <t>
      <list style="symbols">
        <t>Simple stop-and-wait retransmission reliability with exponential back-off as described in <xref target="retransmission"/> when the A Flag is set.</t>
        <t>Transaction ID for response matching as described in <xref target="transactionid"/>.</t>
        <t>Multicast support without retransmission. CoAP supports the use of multicast destination addresses when bound to UDP. Although the A bit may be used to force a response, retransmission MUST NOT be performed.</t>
      </list>
    </t>
    <t>
    When a single CoAP message is sent using UDP, the length of the Payload can be calculated from the datagram length. Multiple CoAP messages MAY also be concatenated in a single UDP payload. In this case each message header MUST be precluded by a magic byte header making the start and length of each message explicit. When multiple messages are packed in a UDP payload, they are processed by the CoAP end-point in order and independently. The responses to packed messages SHOULD also be packed if space permits. 
    </t>
    <t>
    When bound to UDP the entire message MUST fit within a single datagram of length 576 octets over IPv4 and 1280 octets over IPv6.  When used with 6LoWPAN <xref target="RFC4944"/>, messages SHOULD fit into a single link-layer frame to minimize fragmentation (often on the order of 60-90 octets). 
    </t>
 
 <section anchor='retransmission' title="Retransmission">
      <t>
      A CoAP end-point keeps track of open request or notify messages expecting a response (A Flag set) using a conceptual data structure or entries awaiting a response. Each entry includes at least the destination address and port of the original message, the message itself, a retransmission counter (UDP only) and a timeout. When a request of notify message is sent with the A Flag set, an entry is made for that message with a default initial timeout of RESPONSE_TIMEOUT and the retransmission counter set to 0. When a matching response is received for an entry, the entry is removed. When a timeout is triggered for an entry and the retransmission counter is less than MAX_RETRANSMIT, the original message is retransmitted to the destination without modification, the retransmission counter is incremented, and the timeout is doubled. If the retransmission couter reaches MAX_RETRANSMIT on a timeout, then the entry is removed and the application process informed of delivery failure.
      </t>
      <t>
      For CoAP messages sent to IP multicast addresses, retransmission MUST NOT be performed. Therefore MAX_RETRANSMIT is always set to 0 when the destination address is multicast.
      </t>
      </section>

    </section>

    <section anchor='dtls' title="Datagram TLS">

    <t>
    CoAP may also be bound to Datagram Transport Layer Security <xref target="RFC4347"/> in order to prevent eavesdropping, tampering, or message forgery.
    </t>
    <t>
    TODO: Define the DTLS binding in detail. Expected as a contribution from security people in the WG. Use the simplest possible configuration and AES-128 encryption as this is usually supported by e.g. IEEE 802.15.4 hardware. The current suggestion is to make AES, RSA, and SHA1 mandatory to implement and one with SHA256 RECOMMENDED.
    </t>

    </section>

    <section anchor='tcp' title="TCP">
    <t>
    The CoAP protocol also may also be bound to TCP in special cases. As TCP provides a reliable stream this binding does not require anything special from the CoAP protocol design. Retransmission MUST BE disabled, thus MAX_RETRANSMIT is always set to 0. The Transaction ID MUST also be used over TCP and the magic byte header MUST always be included. CoAP end-points are not expected to support both UDP and TCP, and SHOULD NOT attempt to dynamically negotiate between transports.
    </t>
    <t>
    The following cases have been identified where TCP MAY be used:
      <list style="symbols">
        <t>When an application returns large resource representations, which do not fit in a single datagram.</t>
        <t>For providing congestion control if CoAP is being applied across the wider Internet in a topology where congestion is a concern.</t>
      </list>
      </t>
    <t>
    It should be noted that using a similar configuration. CoAP could be used over other stream media such as serial ports. Such a configuration is however out of scope of this document. 
    </t>
    </section>

    <section anchor='tls' title="TLS">

    <t>
    CoAP may also be bound to Transport Layer Security <xref target="RFC4346"/> in order to prevent eavesdropping, tampering, or message forgery.
    </t>
    <t>
    TODO: Define the TLS binding in detail. Expected as a contribution from security people in the WG. Use the simplest possible configuration and AES-128 encryption as this is usually supported by e.g. IEEE 802.15.4 hardware. The current suggestion is to make AES, RSA, and SHA1 mandatory to implement and one with SHA256 RECOMMENDED.
    </t>

    </section>

    <section anchor='port' title="Default Port">
    <t>
    CoAP has a default port of 61616 (TODO: IANA) which is within the compressed UDP port space defined in <xref target="RFC4944"/>. This default port is the same for UDP and TCP.
    </t>
    </section>

  </section>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='caching' title="Caching">

  <t>
  CoAP end-points are by definition constrained by bandwidth and processing power.  To optimize the performance of data transfer under these constraints, we leverage caching features consistent with HTTP.  Caching includes the following concepts:
    <list style="symbols">
      <t>cache life of a resource is controlled via the Max-Age header option</t>
      <t>cache refresh and versioning of a resource is controlled via the Etag header option</t>
      <t>proxies between a client and end-point may participate in the caching process on behalf of sleeping end-points and to avoid unnecessary traffic on the constrained network</t>
    </list>
  </t>


    <section anchor='cache-control' title="Cache control">
    <t>
    When an end-point publishes a resource for a GET request, it SHOULD specify the Max-Age header option.  The Max-Age specifies the cache life of the resource in seconds.  Resources which change rapidly will have a short cache life, and resources which change infrequently should specify a long cache life.  If Max-Age is unspecified in a GET response, then it is assumed to be 60 seconds.  If an end-point wishes to disable caching, it must explicitly specify a Max-Age of zero seconds.
    </t>

    <t>
    When a client reads the response from a GET request, it should cache the resource representation for the cache lifetime as specified by the Max-Age header.  During the cache lifetime, the client SHOULD use its cached version and avoid performing additional GETs for the resource.
    </t>

    <t>
    In general, the origin server end-point is responsible for determining cache age. However, in some cases a client may wish to determine its own tolerance for cache staleness.  In this case, a client may specify the Max-Age header during a GET request.  If the client's Max-Age is of a shorter duration than the age of a cached resource, then the proxy or end-point SHOULD perform a cache refresh.  If the client specifies a Max-Age of zero seconds, then the response MUST discard the cached representation and return a fresh representation.
    </t>
    </section>

    <section anchor='cache-refreshing' title="Cache refresh">
    <t>
    After the expiration of the cache lifetime, clients and proxies must refresh their cached representation of a resource.  Cache refresh is accomplished using GET request which will return a representation of the resource's current state.
    </t>

    <t>
    If the end-point has the capability to version the resource, then the end-point should include the Etag header option in the response to a GET request.  The Etag is a variable length integer which captures a version checksum of the resource.  The Etag is an opaque identifier; clients MUST NOT infer any semantics from the Etag value.
    </t>

    <t>
    If an end-point specifies the Etag header option, then the client SHOULD specify a matching Etag header option in their GET request during cache refresh.  If the end-point's version of the resource is unmodified, then it SHOULD specify a 304 response with no payload to avoid retransmitting the resource representation.
    </t>

    </section>

    <section anchor='proxying' title="Proxying">
    <t>
    See <xref target="I-D.frank-6lowapp-chopan"/>.
    </t>
    <t>
    TODO:
    <list style="symbols">
      <t>Are interception proxies are still required to deal with a) sleeping nodes and b) protecting Internet HTTP traffic from overwhelming the CoAP network?</t>
      <t>But interception proxies breaks end-to-end IP encapsulation and requires support at the routing level</t>
      <t>Often the interception proxy is the same as the HTTP-to-CoAP gateway, so we need to decide how these topics dovetail</t>
      <t>In Chopan, the sleeping problem was tackled by having sleeping nodes check-in with their proxies while awake, notify model might solve this problem to some extent but still have to coordinate the sleep/awake times</t>
      <t>In Chopan we actually used caching to deal with POSTs, etc because otherwise how do you send a request to a sleeping node? The current caching sections are to be exclusive to GETs, but we still need to solve the problem for other types if methods.</t>
    </list>
    </t>

    </section>


  </section>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='discovery' title="Resource Discovery">

  <t>
  The discovery of resources offered by a CoAP end-point is extremely important in machine-to-machine applications where there are no humans in the loop and static interfaces results in fragility. The discovery of resources provided by an HTTP Web Server is called Web Discovery. In this document we refer to the discovery of resources offered by a CoAP end-point as Resource Discovery.
  </t>
  <t>
  CoAP makes the assumption that end-points are available on the default CoAP port, or otherwise have been configured or discovered using some general service discovery mechanism such as <xref target="I-D.cheshire-dnsext-multicastdns"/>. This section assumes that such a configuration or service discovery has already been performed, if needed.
  </t>
  <t>
  Resource Discovery in CoAP is accomplished through the use of well-known resources which describe the links offered by that CoAP end-point. Well-known resources have the URI form "/.well-known/" as specified in <xref target="RFC5785"/>. Every CoAP end-point MUST support this well-known resource. The resource representation of this is described in <xref target="link_format"/>.
  </t>
  <t>
  CoAP requests the following well-known URL for discovery: "/.well-known/resources" (TODO: Formal description for use in request as per <xref target="RFC5785"/>).
  </t>
  <t>
  CoAP Resource Discovery supports the following interactions:
    <list style="symbols">
      <t>[request GET /.well-known/resources] returns the list of links available from a CoAP end-point. </t>
      <t>A CoAP end-point may notify interested clients when this description has changed by sending [notify /.well-known/resources]. This resources MAY support subscription.</t>
      <t>More capable end-points such as proxies MAY support a resource directory by accepting [request POST /.well-known/resources] messages from other CoAP end-points. This adds the resources of other end-points to an agent directory in which absolute URIs are included for the links.</t>
    </list>
  </t>
  
  <t>
  End-points with a large number of resources SHOULD organize their resource descriptions into a hierarchy of link resources. This is done by including links in the /.well-known/resources list which point to other resource lists, e.g. /.well-known/resources/sensors. 
  </t>

    <section anchor='link_format' title="Link Format">

    <t>
    CoAP resource discovery makes use of the HTTP Link Header format specified in <xref target="I-D.nottingham-http-link-header"/>. This specification allows for the use of this simple link format by other protocols, thus not limiting it to the actual HTTP Link Header. The format does not require special XML or binary parsing, and is extensible.
    </t>
    <t>
    CoAP defines a subset of the <xref target="I-D.nottingham-http-link-header"/> features and specific parameters that have known meaning for CoAP resource discovery. A CoAP end-point MAY make use of link extension parameters as needed. The CoAP link format does not start with the "Link:" text. The following formal description is used for forming and parsing this link format:
    </t>

       <figure>
         <artwork><![CDATA[

   link-value        = "<" URI-Reference ">" *( ";" link-param )
   link-param        = ( ( "rel" "=" URI )
                     | ( "name" "=" quoted-string )
                     | ( "type" "=" ( media-type | media-code) )
                     | ( "id" "=" integer )
                     | ( "code" "=" integer )
                     | ( link-extension ) )
   link-extension    = ( parmname [ "=" ( ptoken | quoted-string ) ] )
   ptoken            = 1*ptokenchar
   ptokenchar        = "!" | "#" | "$" | "%" | "&" | "'" | "("
                     | ")" | "*" | "+" | "-" | "." | "/" | DIGIT
                     | ":" | "<" | "=" | ">" | "?" | "@" | ALPHA
                     | "[" | "]" | "^" | "_" | "`" | "{" | "|"
                     | "}" | "~"
   media-code        = see Appendix B
   media-type        = type-name "/" subtype-name

         ]]></artwork>
       </figure>

  <t>
  The link-value is the relative URI of the resource on that end-point or an absolute URI in the case of a directory agent. The rel parameter is a URI that points to the definition of that resource interface, for example in WADL. The name parameter is a descriptive or ontology name of the resource class. This name parameter SHOULD be in an m-DNS <xref target="I-D.cheshire-dnsext-multicastdns"/> compatible form. The type parameter includes Internet media type this resource returns in ascii or code format. The id field is a unique identifier (e.g. UUID) for this resource for use in e.g. search directories. Finally, the code field is used to identify this resource for reference with the Uri-code Option. All link parameters are optional and custom link-extensions may be defined.

<!-- TODO: Explain the m-DNS stuff in more detail. -->  
  
  An example of a typical CoAP link description in this format would be:
  </t>

       <figure>
         <artwork><![CDATA[

</sensor/temp>; rel="sensor.wadl"; name="TemperatureC"; type=text/plain
</sensor/light>; rel="sensor.wadl"; name="LightLux"; type=text/plain

         ]]></artwork>
       </figure>
       
<!-- TODO: Yeah I know, name should be in mDNS format... -->

    </section>

  </section>



  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='http' title="HTTP Mapping">

<!-- Don -->

  <t>
  TODO.
  </t>


  </section>


  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->

  <section anchor='constants' title="Protocol Constants">

  <t>
    This section defines the relevant protocol constants defined in this document:

         <list style="hanging" hangIndent="40">
          <t hangText="RESPONSE_TIMEOUT">0.5 seconds</t>
          <t hangText="MAX_RETRANSMIT">5</t>
        </list>
  </t>

  </section>


  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <section anchor='examples' title="Examples">

  <t>
  <xref target="fig-example-1"/> shows a basic request/response sequence. A client makes a GET request for the resource /temp to the server. The A Flag is set, requesting a response and the Transaction ID is 1234. The request includes one Uri Option "temp" of Len = 4. This request is 9 octets long. The corresponding response is of code 200 OK and includes a text/plain Payload of "22.3 C". The Transaction ID is 1234, thus the transaction is successfully completed. The response is 10 octets long.
  </t>

<figure anchor='fig-example-1'
 title="Basic request/response">
<artwork><![CDATA[

CLIENT                                                     SERVER
  |                                                          |
  |     ----------  GET /temp [A, TID=1234]   -------->      |
  |                                                          |


 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0 | 0 |   1   |1|  R  |   0   |           TID=1234            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|    1    |0| 4 |               "temp" (4 Octets)               
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                |
+-+-+-+-+-+-+-+-+


CLIENT                                                     SERVER
  |                                                          |
  |          <-------- 200 OK [TID=1234] ---------           |
  |                                                          |


 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0 | 1 |   0   | R |  Code=0   |           TID=1234            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    "22.3 C" (6 Octets)                      
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

]]></artwork>
</figure>

  <t>
  TODO: Request with multiple packed messages (magic byte example..)
  </t>
  
  <t>
  TODO: Request - Response (with retransmission)
  </t>  
  
  <t>
  TODO: Request - Response (discovery)
  </t>

  <t>
  TODO: Request - Response (with subscription)...
  Resulting Notify - Response
  </t>


  </section>


  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->

  <section title="Security Considerations">
         <t>
         TODO: Expand this section to a full security analysis, including how to use CoAP with various security options.
         </t>
         <t>
         Some of the features considered in this document will need further security considerations during a protocol design. For example the use of string URLs may have entail security risks due to complex processing on limited microcontroller implementations.
         </t>
         <t>
     The CoAP protocol will be designed for use with e.g. (D)TLS or object security. A protocol design should consider how integration with these security methods will be done, how to secure the CoAP header and other implications.
     </t>

  </section>

  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->

  <section title="IANA Considerations">
         <t>
         TODO (See IANA comments in the document).
     </t>
<section anchor="appendix_codes" title="Codes">

  <t>
  CoAP makes use of (a subset of) the HTTP status codes defined in <xref target="RFC2616"/>. The HTTP status code is encoded into a 6-bit unsigned integer code with the mapping defined in <xref target="tab-codes"/>. The use of these codes is defined throughout this document using the HTTP Name.
  </t>

  <texttable anchor='tab-codes' title="CoAP Codes">

    <ttcol align='left'>Code</ttcol>
    <ttcol align='left'>HTTP Name</ttcol>

    <!-- Success 0-10 -->
    <c>0</c><c>200 OK</c>
    <c>1</c><c>201 Created</c>

    <!-- Redirection 10-20 -->
    <c>14</c><c>304 Not Modified</c>

    <!-- Error Codes 20-40 -->
    <c>20</c><c>400 Bad Request</c>
    <c>21</c><c>401 Unauthorized</c>
    <c>23</c><c>403 Forbidden</c>
    <c>24</c><c>404 Not Found</c>
    <c>25</c><c>405 Method Not Allowed</c>
    <c>29</c><c>409 Conflict</c>
    <c>35</c><c>415 Unsupported Media Type</c>
    <c></c><c></c>

    <!-- Server Error 40-50 -->
    <c>40</c><c>500 Internal Server Error</c>
    <c>43</c><c>503 Service Unavailable</c>
    <c>44</c><c>504 Gateway Timeout</c>

    <!-- 51-55 for experimentation? -->

  </texttable>

</section>


<section anchor="appendix_content" title="Content Types">

<!-- TODO: Convert to a flat space -->

  <t>
  Internet media types are identified by a string in HTTP, such as "application/xml". This string is made up of a top-level type "application" and a sub-type "xml" <xref target="RFC2046"/>. In order to minimize the overhead of using these media types to indicate the type of message payload, CoAP defines an identifier encoding scheme for a subset of Internet media types. It is expected that this table of identifiers will be extensible and maintained by IANA.
  </t>
  <t>
  The Content-type Option is formatted as a variable length unsigned integer, thus the most common media types are encoded into an 8-bit unsigned integer. This identifier is encoded as follows. Regardless of the length of the integer, the most significant 3 bits indicates the top-level media type (text, application etc.) as defined in <xref target="tab-content-class"/>. The five initial top-level types defined in <xref target="RFC2046"/> are supported. Composite high-level types (multipart and message) are not supported. The remaining bits indicate the sub-types <xref target="RFC2046"/>. This allows for up to 8 high-level types, with up to 32 sub-types for each in an 8-bit identifier and up to 8192 sub-types in a 16-bit identifier.
  </t>
  <t>
  For example, "application/xml" would be encoded in 8-bits as:
  </t>

       <figure>
         <artwork><![CDATA[
5 << 5 | 00  =  10100000
         ]]></artwork>
       </figure>

  <texttable anchor='tab-content-class' title="Top-level type identifiers">

    <ttcol align='left'>Top-level type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <c>text</c><c>1</c>
    <c>image</c><c>2</c>
    <c>audio</c><c>3</c>
    <c>video</c><c>4</c>
    <c>application</c><c>5</c>


  </texttable>

  <texttable anchor='tab-content-text' title="text sub-type identifiers">

    <ttcol align='left'>Sub-type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <!-- text -->
    <c>xml</c><c>0</c>
    <c>plain</c><c>1</c>
    <c>csv</c><c>2</c>
    <c>html</c><c>3</c>

  </texttable>

  <texttable anchor='tab-content-image' title="image sub-type identifiers">

    <ttcol align='left'>Sub-type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <!-- image -->
    <c>gif</c><c>0</c>
    <c>jpeg</c><c>1</c>
    <c>png</c><c>2</c>
    <c>tiff</c><c>3</c>

  </texttable>

    <texttable anchor='tab-content-audio' title="audio sub-type identifiers">

    <ttcol align='left'>Sub-type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <!-- audio -->
    <c>raw</c><c>0</c>

  </texttable>

    <texttable anchor='tab-content-video' title="video sub-type identifiers">

    <ttcol align='left'>Sub-type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <!-- video -->
    <c>raw</c><c>0</c>


  </texttable>

    <texttable anchor='tab-content-application' title="application sub-type identifiers">

    <ttcol align='left'>Sub-type</ttcol>
    <ttcol align='left'>Identifier</ttcol>

    <!-- application -->
    <c>xml</c><c>0</c>
    <c>octet-stream</c><c>1</c>
    <c>rdf+xml</c><c>2</c>
    <c>soap+xml</c><c>3</c>
    <c>atom+xml</c><c>4</c>
    <c>xmpp+xml</c><c>5</c>
    <c>exi</c><c>6</c> <!-- http://www.w3.org/TR/2009/CR-exi-20091208/#mediaTypeRegistration -->
    <c>x-bxml</c><c>7</c>
    <c>fastinfoset</c><c>8</c>
    <c>soap+fastinfoset</c><c>9</c>
    <c>json</c><c>10</c>

  </texttable>


</section>     
     
  </section>

<!------------------------------------------------------>
<!--  SECTION: ACKNOWLEDGMENTS          -->
<!------------------------------------------------------>

<section title="Acknowledgments">
<t>Thanks to Carsten Bormann, Michael Stuber, Richard Kelsey, Cullen Jennings, Guido Moritz, Peter Van Der Stok, Adriano Pezzuto, Lisa Dussealt, Alexey Melnikov, Gilbert Clark, Salvatore Loreto, Petri Mutka, Szymon Sasin, Robert Quattlebaum, Robert Cragie, Angelo Castellani and David Ryan for helpful comments and discussions.</t>
</section>

  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->
  <!-- **************************************************************** -->

  <section title="Changelog">

    <t>Changes from -00 to -01:
      <list>
        <t>o Unified the message header and added a notify message type.</t>
        <t>o Renamed methods with HTTP names and removed the NOTIFY method.</t>
        <t>o Added a number of options field to the header.</t>
        <t>o Combines the Option Type and Length into an 8-bit field.</t>
        <t>o Added the magic byte header.</t>
        <t>o Added new Etag option.</t>
        <t>o Added new Date option.</t>
        <t>o Added new Subscription option.</t>
        <t>o Completed the HTTP Code - CoAP Code mapping table appendix.</t>
        <t>o Completed the Content-type Identifier appendix and tables.</t>
        <t>o Added more simplifications for URI support.</t>
        <t>o Initial subscription and discovery sections.</t>
        <t>o A Flag requirements simplified.</t>
      </list>
    </t>

  </section>

    </middle>

    <back>
    <references title='Normative References'>
       &RFC2046;
       &RFC2616;
       &RFC3986;
       &RFC4346;
       &RFC4347;
       &RFC5785;
       &I-D.nottingham-http-link-header;
       &I-D.frank-6lowapp-chopan;
    </references>

    <references title='Informative References'>
       &RFC4944;
       &I-D.cheshire-dnsext-multicastdns;
       &I-D.shelby-6lowapp-encoding;
       &I-D.shelby-core-coap-req;
    </references>
    </back>

</rfc>
