<?xml version="1.0" encoding="us-ascii"?>
<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
<!ENTITY RFC2119 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml">
<!ENTITY RFC2616 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2616.xml">
<!ENTITY RFC3040 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3040.xml">
<!ENTITY RFC3986 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3986.xml">
<!ENTITY RFC4732 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4732.xml">
<!ENTITY RFC5234 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5234.xml">
<!ENTITY RFC6454 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.6454.xml">
<!ENTITY RFC6570 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.6570.xml">
<!ENTITY RFC6690 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.6690.xml">
<!ENTITY RFC7049 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7049.xml">
<!ENTITY RFC7228 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7228.xml">
<!ENTITY RFC7230 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7230.xml">
<!ENTITY RFC7231 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7231.xml">
<!ENTITY RFC7232 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7232.xml">
<!ENTITY RFC7235 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7235.xml">
<!ENTITY RFC7252 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7252.xml">
<!ENTITY RFC7390 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7390.xml">
<!ENTITY RFC7641 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7641.xml">
<!ENTITY RFC7925 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7925.xml">
<!ENTITY RFC7959 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7959.xml">
<!ENTITY I-D.ietf-core-resource-directory SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.ietf-core-resource-directory.xml">
<!ENTITY I-D.ietf-core-links-json SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.ietf-core-links-json.xml">
]>
<?xml-stylesheet type="text/xsl" href="rfc2629.xslt"?>
<?rfc strict="no"?>
<?rfc toc="yes"?>
<?rfc tocdepth="3"?>
<?rfc symrefs="yes"?>
<?rfc sortrefs="yes"?>
<?rfc compact="yes"?>
<?rfc subcompact="no"?>
<rfc ipr="trust200902" docName="draft-ietf-core-http-mapping-16" category="info">
  <front>
    <title abbrev="HTTP-to-CoAP Mapping">
     Guidelines for HTTP-to-CoAP Mapping Implementations
    </title>
    <author initials="A.P." surname="Castellani" fullname="Angelo P. Castellani">
      <organization>University of Padova</organization>
      <address>
        <postal>
          <street>Via Gradenigo 6/B</street>
          <code>35131</code>
          <city>Padova</city>
          <country>Italy</country>
        </postal>
        <email>angelo@castellani.net</email>
      </address>
    </author>
    <author initials="S." surname="Loreto" fullname="Salvatore Loreto">
      <organization>Ericsson</organization>
      <address>
        <postal>
          <street>Hirsalantie 11</street>
          <code>02420</code>
          <city>Jorvas</city>
          <country>Finland</country>
        </postal>
        <email>salvatore.loreto@ericsson.com</email>
      </address>
    </author>
    <author initials="A." surname="Rahman" fullname="Akbar Rahman">
      <organization>InterDigital Communications, LLC</organization>
      <address>
        <postal>
          <street>1000 Sherbrooke Street West</street>
          <city>Montreal</city>
          <code>H3A 3G4</code>
          <country>Canada</country>
        </postal>
        <phone>+1 514 585 0761</phone>
        <email>Akbar.Rahman@InterDigital.com</email>
      </address>
    </author>
    <author initials="T." surname="Fossati" fullname="Thomas Fossati">
      <organization>Nokia</organization>
      <address>
        <postal>
          <street>3 Ely Road</street>
          <city>Milton, Cambridge</city>
          <code>CB24 6DD</code>
          <country>UK</country>
        </postal>
        <email>thomas.fossati@nokia.com</email>
      </address>
    </author>
    <author initials="E." surname="Dijk" fullname="Esko Dijk">
      <organization>Philips Lighting</organization>
      <address>
        <postal>
          <street>High Tech Campus 7</street>
          <city>Eindhoven</city>
          <code>5656 AE</code>
          <country>The Netherlands</country>
        </postal>
        <email>esko.dijk@philips.com</email>
      </address>
    </author>
    <date year="2016"/>
    <area>APP</area>
    <workgroup>CoRE Working Group</workgroup>
    <keyword>CoAP</keyword>
    <keyword>HTTP-CoAP mapping</keyword>
    <keyword>HTTP-CoAP translation</keyword>
    <keyword>proxy implementation</keyword>
    <abstract>
      <t>This document provides reference information for implementing a cross-protocol network proxy that performs translation from the HTTP protocol to CoAP (Constrained Application Protocol).  This will enable a HTTP client to access resources on a CoAP server through the proxy.  This document describes how a HTTP request is mapped to a CoAP request, and then how a CoAP response is mapped back to a HTTP response.  This includes guidelines for status code, URI, and media type mappings, as well as additional interworking advice.</t>
    </abstract>
  </front>
  <middle>
    <section title="Introduction">
      <t>CoAP (Constrained Application Protocol) <xref target="RFC7252"/> has been designed with the twofold aim to be an application protocol specialized for constrained environments and to be easily used in Representational State Transfer (REST) <xref target="REST"/> based architectures such as the Web.  The latter goal has led to defining CoAP to easily interoperate with HTTP <xref target="RFC7230"/> through an intermediary proxy which performs cross-protocol conversion.</t>

<!-- XXX(INFORMATIONAL STATUS)-->
      <t>Section 10 of <xref target="RFC7252"/> describes the fundamentals of the CoAP-to-HTTP and the HTTP-to-CoAP cross-protocol mapping process.  However, <xref target="RFC7252"/> focuses on the basic mapping of request methods and simple response code mapping between HTTP and CoAP, while leaving many details of the cross-protocol proxy for future definition.  Therefore, a primary goal of this informational document is to define a consistent set of guidelines that an HTTP-to-CoAP proxy implementation should adhere to. The key benefit to adhering to such guidelines is to reduce variation between proxy implementations, thereby increasing interoperability between an HTTP client and a CoAP server independent of the proxy that implements the cross-protocol mapping. (For example, a proxy conforming to these guidelines made by vendor A can be easily replaced by a proxy from vendor B that also conforms to the guidelines.)</t> 

      <t>This document describes HTTP mappings that apply to protocol elements defined in the base CoAP specification <xref target="RFC7252"/>.  It is up to CoAP protocol extensions (new methods, response codes, options, content-formats) to describe their own HTTP mappings, if applicable.</t>

      <t>This document is organized as follows:
        <list style="symbols">
          <t><xref target="terminology"/> defines proxy terminology;</t>
          <t><xref target="hc"/> introduces the HTTP-to-CoAP proxy;</t>
          <t><xref target="usecases"/> lists use cases in which HTTP clients need to contact CoAP servers;</t>
          <t><xref target="URI-mapping"/> introduces a null, default and advanced HTTP-to-CoAP URI mapping syntax;</t>
          <t><xref target="hc-media"/> describes how to map HTTP media types to CoAP content formats and vice versa;</t>
          <t><xref target="hc-resp"/> describes how to map CoAP responses to HTTP responses;</t>
          <t><xref target="hc-additional"/> describes additional mapping guidelines related to caching, congestion, timeouts, etc.;</t>
          <t><xref target="sec"/> discusses possible security impact of HTTP-to-CoAP protocol mapping.</t>
        </list>
      </t>
    </section>

    <!-- MAIN SECTION ***************************************************************************** -->
    <!-- note the terminology section uses capitalization of all terms, while capitals not used in other sections; similar in style to RFC7252. -->
    <section title="Terminology" anchor="terminology">
      <t>The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in <xref target="RFC2119"/>.</t>
      <t>This specification requires readers to be familiar with the vocabulary and concepts discussed in <xref target="RFC7228"/>, in particular the terms "Constrained Nodes" and "Constrained Networks".  In addition, this specification makes use of the following terms:
      <list style="hanging" hangIndent="4">
        <t hangText="HC Proxy"><vspace/>A proxy performing a cross-protocol mapping, in the context of this document an HTTP-to-CoAP (HC) mapping. Specifically, the HC proxy acts as an HTTP server and a CoAP client.  The HC Proxy can take on the role of a Forward, Reverse or Interception Proxy.</t>

       <t hangText="Forward Proxy (or Forward HC Proxy)"><vspace/>A message forwarding agent that is selected by the HTTP client, usually via local configuration rules, to receive requests for some type(s) of absolute URI and to attempt to satisfy those requests via translation to the protocol indicated by the absolute URI.  The user decides (is willing) to use the proxy as the forwarding/de-referencing agent for a predefined subset of the URI space. In <xref target="RFC7230"/> this is called a Proxy.  <xref target="RFC7252"/> defines Forward-Proxy similarly.</t>

       <t hangText="Reverse Proxy (or Reverse HC Proxy)"><vspace/>As in <xref target="RFC7230"/>, a receiving agent that acts as a layer above some other server(s) and translates the received requests to the underlying server's protocol.  A Reverse HC Proxy behaves as an origin (HTTP) server on its connection from the HTTP client.  The HTTP client uses the "origin-form" (Section 5.3.1 of <xref target="RFC7230"/>) as a request-target URI.  (Note that a Reverse Proxy appears to an HTTP client as an origin server while a Forward Proxy does not. So, when communicating with a Reverse Proxy a client may be unaware it is communicating with a proxy at all.)</t>

       <t hangText="Interception Proxy (or Interception HC Proxy)"><vspace/>As in <xref target="RFC3040"/>, a proxy that receives inbound HTTP traffic flows through the process of traffic redirection; transparent to the HTTP client.</t>
      </list></t>
    </section>

    <!-- MAIN SECTION ***************************************************************************** -->
    <section title="HTTP-to-CoAP Proxy" anchor="hc">
      <t>A HC proxy is accessed by an HTTP client that needs to access a resource on a CoAP server.  The HC proxy handles the HTTP request by mapping it to the equivalent CoAP request, which is then forwarded to the appropriate CoAP server.  The received CoAP response is then mapped to an appropriate HTTP response and finally sent back to the originating HTTP client.</t>

      <!-- note any references to figure entities will use capitalization because they are named instances of the generic entities.  The instance name happens to be equal to the generic name.  -->

      <t>See <xref target="fig-http-coap-deployment"/> for an example deployment scenario. Here a HC proxy is located at the boundary of the Constrained Network domain, to avoid sending any HTTP traffic into the Constrained Network and to avoid any CoAP multicast traffic outside the Constrained Network.  A DNS server (not shown) is used by the HTTP Client to resolve the IP address of the HC proxy and optionally also used by the HC proxy to resolve IP addresses of CoAP servers.</t>

        <figure title="HTTP-To-CoAP Proxy Deployment Scenario" anchor="fig-http-coap-deployment">
          <artwork>
            <![CDATA[
                                            Constrained Network
                                           .-------------------.
                                          /      .------.       \
                                         /       | CoAP |        \
                                        /        |server|         \
                                       ||        '------'         ||
                                       ||                         ||
  .--------.  HTTP Request   .------------.  CoAP Req  .------.   ||
  |  HTTP  |---------------->|HTTP-to-CoAP|----------->| CoAP |   ||
  | Client |<----------------|   Proxy    |<-----------|Server|   ||
  '--------'  HTTP Response  '------------'  CoAP Resp '------'   ||
                                       ||                         ||
                                       ||   .------.              ||
                                       ||   | CoAP |              ||
                                        \   |server|  .------.    /
                                         \  '------'  | CoAP |   /
                                          \           |server|  /
                                           \          '------' /
                                            '-----------------'
            ]]>
          </artwork>
        </figure>


<!-- XXX(INFORMATIONAL STATUS TEXT)-->
      <t>Normative requirements on the translation of HTTP requests to CoAP requests and of the CoAP responses back to HTTP responses are defined in Section 10.2 of <xref target="RFC7252"/>.  However, <xref target="RFC7252"/> focuses on the basic mapping of request methods and simple response code mapping between HTTP and CoAP, and leaves many details of the cross-protocol HC proxy for future definition.  This document provides additional guidelines and more details for the implementation of a HC Proxy, which should be followed in addition to the normative requirements. Note that the guidelines apply to all forms of an HC proxy (i.e., Reverse, Forward, Intercepting) unless explicitly otherwise noted.</t>
    </section>


    <!-- ******************* MAIN SECTION ******************** -->
    <section anchor="usecases" title="Use Cases">
      <t>To illustrate a few situations in which HTTP to CoAP protocol translation may be used, three use cases are described below.
        <list style="numbers">
          <t>Legacy building control application without CoAP: A building control application that uses HTTP but not CoAP can check the status of CoAP sensors and/or control actuators via a HC proxy.</t>
          <t>Making sensor data available to 3rd parties on the Web: For demonstration or public interest purposes, a HC proxy may be configured to expose the contents of a CoAP sensor to the world via the web (HTTP and/or HTTPS).  Some sensors may only accept secure 'coaps' requests, therefore the proxy is configured to translate requests to those devices accordingly.  The HC proxy is furthermore configured to only pass through GET requests in order to protect the constrained network.</t>
          <t>Smartphone and home sensor: A smartphone can access directly a CoAP home sensor using a mutually authenticated 'https' request, provided its home router runs a HC proxy and is configured with the appropriate certificate.  An HTML5 <xref target="W3C.REC-html5-20141028"/> application on the smartphone can provide a friendly UI using the standard (HTTP) networking functions of HTML5.</t>
        </list>
      </t>

      <t>A key point in the above use cases is the expected nature of the URI to be used by the HTTP client initiating the HTTP request to the HC proxy.  Specifically, in use case #1, there will be no 'coap' or 'coaps' related information embedded in the HTTP URI as it is a legacy HTTP client sending the request. Use case #2 is also expected to be similar.  In contrast, in use case #3, it is likely that the HTTP client will specifically embed 'coap' or 'coaps' related information in the HTTP URI of the HTTP request to the HC proxy.</t>
    </section>

    <!-- ******************* MAIN SECTION ******************** -->
    <section anchor="URI-mapping" title="URI Mapping">
      <t>Though, in principle, a CoAP URI could be directly used by a HTTP client to de-reference a CoAP resource through a HC proxy, the reality is that all major web browsers, networking libraries and command line tools do not allow making HTTP requests using URIs with a scheme 'coap' or 'coaps'.</t>

      <t>Thus, there is a need for web applications to embed or "pack" a CoAP URI into a HTTP URI so that it can be (non-destructively) transported from the HTTP client to the HC proxy.  The HC proxy can then "unpack" the CoAP URI and finally de-reference it via a CoAP request to the target Server.</t>

      <t>URI Mapping is the term used in this document to describe the process through which the URI of a CoAP resource is transformed into an HTTP URI so that:
        <list style="symbols">
          <t>The requesting HTTP client can handle it;</t>
          <t>The receiving HC proxy can extract the intended CoAP URI unambiguously.</t>
        </list>
      </t>

      <t>To this end, the remainder of this section will identify:
        <list style="symbols">
          <t>The default mechanism to map a CoAP URI into a HTTP URI;</t>
          <t>The URI template format to express a class of CoAP-HTTP URI mapping functions;</t>
          <t>The discovery mechanism based on CoRE Link Format <xref target="RFC6690"/> through which clients of a HC proxy can dynamically discover information about the supported URI Mapping Template(s), as well as the URI where the HC proxy function is anchored.</t>
        </list>
      </t>

      <section title="URI Terminology">
        <t>In the remainder of this section, the following terms will be used with a distinctive meaning:
          <list style="hanging" hangIndent="8">
            <t hangText="HC Proxy URI:"><vspace/>URI which refers to the HC proxy function.  It conforms to syntax defined in Section 2.7 of <xref target="RFC7230"/>.</t>
            <t hangText="Target CoAP URI:"><vspace/>URI which refers to the (final) CoAP resource that has to be de-referenced.  It conforms to syntax defined in Section 6 of <xref target="RFC7252"/>.  Specifically, its scheme is either 'coap' or 'coaps'.</t>
            <t hangText="Hosting HTTP URI:"><vspace/>URI that conforms to syntax in Section 2.7 of <xref target="RFC7230"/>.  Its authority component refers to a HC proxy, whereas path (and query) component(s) embed the information used by a HC proxy to extract the Target CoAP URI.</t>
          </list>
        </t>
      </section>

      <section title="Null Mapping" anchor="section.null-mapping">
        <t>The null mapping is the case where there is no Target CoAP URI appended to the HC Proxy URI.  In other words, it is a "pure" HTTP URI that is sent to the HC Proxy.  This would typically occur in situations like Use Case #1 described in <xref target="usecases"/>, and the Proxy would typically be a Reverse Proxy. In this scenario, the HC Proxy will determine through its own private algorithms what the Target CoAP URI should be.</t>
      </section>

      <section title="Default Mapping" anchor="section.default-mapping">
        <t>The default mapping is for the Target CoAP URI to be appended as-is (with the only caveat discussed in <xref target="section.encoding-caveats"/>) to the HC Proxy URI, to form the Hosting HTTP URI.  This is the Effective Request URI (see section 5.5 of <xref target="RFC7230"/>) that will then be sent by the HTTP client in the HTTP request to the HC proxy.</t>

        <t>For example: given a HC Proxy URI https://p.example.com/hc/ and a Target CoAP URI coap://s.example.com/light, the resulting Hosting HTTP URI would be https://p.example.com/hc/coap://s.example.com/light.</t>

        <t>Provided a correct Target CoAP URI, the Hosting HTTP URI resulting from the default mapping will be a syntactically valid HTTP URI.  Furthermore, the Target CoAP URI can always be extracted unambiguously from the Hosting HTTP URI.</t>
        <!-- XXX(tho) not true e.g. consider this proxy URI: 'https://p.example.com/hc?target_coap_uri=
        <t>Also, it is worth noting that, using the default mapping, a query component in the target CoAP resource URI is naturally encoded into the query component of the Hosting URI, e.g., coap://s.example.com/light?dim=5 becomes https://p.example.com/hc/coap://s.example.com/light?dim=5.</t>
        -->
        <t>There is no default for the HC Proxy URI.  Therefore, it is either known in advance, e.g., as a configuration preset, or dynamically discovered using the mechanism described in <xref target="section.discovery"/>.</t>

        <t>The default URI mapping function SHOULD be implemented and SHOULD be activated by default in a HC proxy, unless there are valid reasons, e.g., application specific, to use a different mapping function.</t>

        <section title="Optional Scheme Omission" anchor="section.optional-scheme">
          <t>When constructing a Hosting HTTP URI by embedding a Target CoAP URI, the scheme (i.e., 'coap' or 'coaps'), the scheme component delimiter (":"), and the double slash ("//") preceding the authority MAY be omitted if a local default - not defined by this document - applies.  If no prior mutual agreement exists between the client and the HC proxy, then a Target CoAP URI without the scheme component is syntactically incorrect, and therefore:
          <list style="symbols">
            <t>It MUST NOT be emitted by clients;</t>
            <t>It MUST elicit a suitable client error status (i.e., 4xx) by the HC proxy.</t>
          </list>
          </t>
        </section> <!-- Optional scheme -->

        <section title="Encoding Caveats" anchor="section.encoding-caveats">
          <t>When the authority of the Target CoAP URI is given as an IPv6address, then the surrounding square brackets must be percent-encoded in the Hosting HTTP URI, in order to comply with the syntax defined in Section 3.3. of <xref target="RFC3986"/> for a URI path segment.  E.g.: coap://[2001:db8::1]/light?on becomes https://p.example.com/hc/coap://%5B2001:db8::1%5D/light?on.  (Note that the percent-encoded square brackets shall be reverted to their non-percent-encoded form when the HC proxy unpacks the Target CoAP URI.)</t>
          <t>Everything else can be safely copied verbatim from the Target CoAP URI to the Hosting HTTP URI.</t>
        </section> <!-- Encoding Caveats -->
      </section> <!-- Default Mapping -->

      <section title="URI Mapping Template">
        <t>This section defines a format for the URI template <xref target="RFC6570"/> used by a HC proxy to inform its clients about the expected syntax for the Hosting HTTP URI.  This will then be used by the HTTP client to construct the Effective Request URI to be sent in the HTTP request to the HC proxy.</t>

        <t>When instantiated, an URI Mapping Template is always concatenated to a HC Proxy URI provided by the HC proxy via discovery (see <xref target="section.discovery"/>), or by other means.</t>

        <t>A simple form (<xref target="section.simple-form"/>) and an enhanced form (<xref target="section.enhanced-form"/>) are provided to fit different users' requirements.</t>

        <t>Both forms are expressed as level 2 URI templates <xref target="RFC6570"/> to take care of the expansion of values that are allowed to include reserved URI characters.  The syntax of all URI formats is specified in this section in Augmented Backus-Naur Form (ABNF) <xref target="RFC5234"/>.</t>

        <section title="Simple Form" anchor="section.simple-form">
          <t>The simple form MUST be used for mappings where the Target CoAP URI is going to be copied (using rules of <xref target="section.encoding-caveats"/>) at some fixed position into the Hosting HTTP URI.</t>

          <t>The "tu" template variable is intended to be used in a template definition to represent a Target CoAP URI:
            <figure>
              <artwork>
                <![CDATA[
    tu = [ ( "coap:" / "coaps:" ) "//" ] host [ ":" port ] path-abempty
         [ "?" query ]
                ]]>
              </artwork>
            </figure>
          </t>
          <t>Note that the same considerations as in <xref target="section.optional-scheme"/> apply, in that the CoAP scheme may be omitted from the Hosting HTTP URI.</t>

          <section title="Examples">
	          <t>All the following examples (given as a specific URI mapping template, a Target CoAP URI, and the produced Hosting HTTP URI) use https://p.example.com/hc/ as the HC Proxy URI.  Note that these examples all define mapping templates that deviate from the default template of <xref target="section.default-mapping"/> to be able to illustrate the use of the above template variables.</t>
            <t>
              <list style="numbers">
                <t>Target CoAP URI is a query argument of the Hosting HTTP URI:

                  <figure>
                    <artwork>
                      <![CDATA[
?target_uri={+tu}

coap://s.example.com/light

=> https://p.example.com/hc/?target_uri=coap://s.example.com/light

whereas

coaps://s.example.com/light

=> https://p.example.com/hc/?target_uri=coaps://s.example.com/light
                      ]]>
                    </artwork>
                  </figure>
                </t>

                <t>Target CoAP URI in the path component of the Hosting HTTP URI:
                  <figure>
                    <artwork>
                      <![CDATA[
forward/{+tu}

coap://s.example.com/light

=> https://p.example.com/hc/forward/coap://s.example.com/light

whereas

coaps://s.example.com/light

=> https://p.example.com/hc/forward/coaps://s.example.com/light
                      ]]>
                    </artwork>
                  </figure>
                </t>

                <t>'coap' URI is a query argument of the Hosting HTTP URI; client decides to omit scheme because a default scheme is agreed beforehand between client and proxy:
                  <figure>
                    <artwork>
                      <![CDATA[
?coap_uri={+tu}

coap://s.example.com/light

=> https://p.example.com/hc/?coap_uri=s.example.com/light
                      ]]>
                    </artwork>
                  </figure>
                </t>
              </list>
            </t>
          </section> <!-- Examples -->
        </section> <!-- Simple Form -->

        <section title="Enhanced Form" anchor="section.enhanced-form">
          <t>The enhanced form can be used to express more sophisticated mappings of the Target CoAP URI into the Hosting HTTP URI, i.e., mappings that do not fit into the simple form.</t>
          <t>There MUST be at most one instance of each of the following template variables in a template definition:
            <figure>
              <artwork>
                <![CDATA[
    s  = "coap" / "coaps" ; from [RFC7252], Sections 6.1 and 6.2
    hp = host [":" port]  ; from [RFC3986], Sections 3.2.2 and 3.2.3
    p  = path-abempty     ; from [RFC3986], Section 3.3
    q  = query            ; from [RFC3986], Section 3.4 
    qq = [ "?" query ]    ; qq is empty if and only if 'query' is empty
                ]]>
              </artwork>
            </figure>
          </t>
          <t>The qq form is used when the path and the (optional) query components are to be copied verbatim from the Target CoAP URI into the Hosting HTTP URI, i.e., as "{+p}{+qq}".  Instead, the q form is used when the query and path are mapped as separate entities, e.g., as in "coap_path={+p}&amp;coap_query={+q}".</t>

          <section title="Examples">
	    <t>All the following examples (given as a specific URI mapping template, a Target CoAP URI, and the produced Hosting HTTP URI) use https://p.example.com/hc/ as the HC Proxy URI.</t>
            <t>
              <list style="numbers">
                <t>Target CoAP URI components in path segments, and optional query in query component:
                  <figure>
                    <artwork>
                      <![CDATA[
    {+s}/{+hp}{+p}{+qq}

    coap://s.example.com/light

    => https://p.example.com/hc/coap/s.example.com/light

    whereas

    coap://s.example.com/light?on

    => https://p.example.com/hc/coap/s.example.com/light?on
                      ]]>
                    </artwork>
                  </figure>
                </t>

                <t>Target CoAP URI components split in individual query arguments:
                  <figure>
                    <artwork>
                      <![CDATA[
    ?s={+s}&hp={+hp}&p={+p}&q={+q}

    coap://s.example.com/light

    => https://p.example.com/hc/?s=coap&hp=s.example.com&p=/light&q=

    whereas

    coaps://s.example.com/light?on

    => https://p.example.com/hc/?s=coaps&hp=s.example.com&p=/light&q=on
                      ]]>
                    </artwork>
                  </figure>
                </t>
              </list>
            </t>
          </section> <!-- Examples -->
        </section> <!-- Enhanced Form -->
      </section> <!-- URI Mapping Template -->

      <section title="Discovery" anchor="section.discovery">
        <t>In order to accommodate site specific needs while allowing third parties to discover the proxy function, the HC proxy SHOULD publish information related to the location and syntax of the HC proxy function using the CoRE Link Format <xref target="RFC6690"/> interface.</t>

        <t>To this aim a new Resource Type, "core.hc", is defined in this document. It can be used as the value for the "rt" attribute in a query to the /.well-known/core in order to locate the URI where the HC proxy function is anchored, i.e., the HC Proxy URI.</t>
  
        <t>Along with it, the new target attribute "hct" is defined in this document. This attribute MAY be returned in a "core.hc" link to provide the URI Mapping Template associated to the mapping resource.  The default template given in <xref target="section.default-mapping"/>, i.e., {+tu}, MUST be assumed if no "hct" attribute is found in the returned link.  If a "hct" attribute is present in the returned link, then a client MUST use it to create the Hosting HTTP URI.</t>

        <t>The URI mapping SHOULD be discoverable (as specified in <xref target="RFC6690" />) on both the HTTP and the CoAP side of the HC proxy, with one important difference: on the CoAP side the link associated to the "core.hc" resource needs an explicit anchor referring to the HTTP origin <xref target="RFC6454"/>, while on the HTTP interface the link context is already the HTTP origin carried in the request's Host header, and doesn't have to be made explicit.</t>


        <section title="Examples">
          <t>
            <list style="symbols">
              <t>The first example exercises the CoAP interface, and assumes that the default template, {+tu}, is used.  For example, in use case #3 in section <xref target="usecases"/>, the smartphone may discover the public HC proxy before leaving the home network.  Then when outside the home network, the smartphone will be able to query the appropriate home sensor.
                <figure>
                  <artwork>
                    <![CDATA[
    Req:  GET coap://[ff02::1]/.well-known/core?rt=core.hc

    Res:  2.05 Content
          </hc/>;anchor="https://p.example.com";rt="core.hc"
                    ]]>
                  </artwork>
                </figure>
              </t>
 
              <t>The second example - also on the CoAP side of the HC proxy - uses a custom template, i.e., one where the CoAP URI is carried inside the query component, thus the returned link carries the URI template to be used in an explicit "hct" attribute:
                <figure>
                  <artwork>
                    <![CDATA[
    Req:  GET coap://[ff02::1]/.well-known/core?rt=core.hc

    Res:  2.05 Content
          </hc/>;anchor="https://p.example.com";
          rt="core.hc";hct="?uri={+tu}"
                    ]]>
                  </artwork>
                </figure>
              </t>
            </list>

        On the HTTP side, link information can be serialized in more than one way:
            <list style="symbols">
              <t>using the 'application/link-format' content type:
                <figure>
                  <artwork>
                    <![CDATA[
    Req:  GET /.well-known/core?rt=core.hc HTTP/1.1
          Host: p.example.com

    Res:  HTTP/1.1 200 OK
          Content-Type: application/link-format
          Content-Length: 18

          </hc/>;rt="core.hc"
                    ]]>
                    </artwork>
                  </figure>
                </t>
 
                <t>using the 'application/link-format+json' content type as defined in <xref target="I-D.ietf-core-links-json"/>:
                  <figure>
                    <artwork>
                      <![CDATA[
    Req:  GET /.well-known/core?rt=core.hc HTTP/1.1
          Host: p.example.com

    Res:  HTTP/1.1 200 OK
          Content-Type: application/link-format+json
          Content-Length: 31

          [{"href":"/hc/","rt":"core.hc"}]
                    ]]>
                  </artwork>
                </figure>
              </t>
 
              <t>using the Link header:
                <figure>
                  <artwork>
                    <![CDATA[
    Req:  GET /.well-known/core?rt=core.hc HTTP/1.1
          Host: p.example.com

    Res:  HTTP/1.1 200 OK
          Link: </hc/>;rt="core.hc"
                    ]]>
                  </artwork>
                </figure>
              </t>
            </list>
          </t>
        </section> <!-- Examples -->
      </section> <!-- Discovery -->
    </section> <!-- URI Mapping -->


    <!-- ******************* MAIN SECTION ******************** -->
    <section title="Media Type Mapping" anchor="hc-media">
      <section title="Overview">
        <t>A HC proxy needs to translate HTTP media types (Section 3.1.1.1 of <xref target="RFC7231"/>) and content encodings (Section 3.1.2.2 of <xref target="RFC7231"/>) into CoAP content formats (Section 12.3 of <xref target="RFC7252"/>) and vice versa.</t>
        <t>Media type translation can happen in GET, PUT or POST requests going from HTTP to CoAP, and in 2.xx (i.e., successful) responses going from CoAP to HTTP.  Specifically, PUT and POST need to map both the Content-Type and Content-Encoding HTTP headers into a single CoAP Content-Format option, whereas GET needs to map Accept and Accept-Encoding HTTP headers into a single CoAP Accept option.  To generate the HTTP response, the CoAP Content-Format option is mapped back to a suitable HTTP Content-Type and Content-Encoding combination.</t>

        <t>An HTTP request carrying a Content-Type and Content-Encoding combination which the HC proxy is unable to map to an equivalent CoAP Content-Format, SHALL elicit a 415 (Unsupported Media Type) response by the HC proxy.</t>

        <t>On the content negotiation side, failure to map Accept and Accept-* headers SHOULD be silently ignored: the HC proxy SHOULD therefore forward as a CoAP request with no Accept option.  The HC proxy thus disregards the Accept/Accept-* header fields by treating the response as if it is not subject to content negotiation, as mentioned in Sections 5.3.* of <xref target="RFC7231"/>.  However, a HC proxy implementation is free to attempt mapping a single Accept header in a GET request to multiple CoAP GET requests, each with a single Accept option, which are then tried in sequence until one succeeds.  Note that an HTTP Accept */* MUST be mapped to a CoAP request without Accept option.</t>

        <t>While the CoAP to HTTP direction has always a well defined mapping (with the exception examined in <xref target="sec-application-coap-payload"/>), the HTTP to CoAP direction is more problematic because the source set, i.e., potentially 1000+ IANA registered media types, is much bigger than the destination set, i.e., the mere 6 values initially defined in Section 12.3 of <xref target="RFC7252"/>.</t>

        <t>Depending on the tight/loose coupling with the application(s) for which it proxies, the HC proxy could implement different media type mappings.</t>

        <t>When tightly coupled, the HC proxy knows exactly which content formats are supported by the applications, and can be strict when enforcing its forwarding policies in general, and the media type mapping in particular.</t>

        <t>On the other hand, when the HC proxy is a general purpose application layer gateway, being too strict could significantly reduce the amount of traffic that it would be able to successfully forward.  In this case, the "loose" media type mapping detailed in <xref target="sec-loose-mt-mapping"/> MAY be implemented.</t>

        <!-- TODO/tbd move it to Sec Cons -->
        <t>The latter grants more evolution of the surrounding ecosystem, at the cost of allowing more attack surface.  In fact, as a result of such strategy, payloads would be forwarded more liberally across the unconstrained/constrained network boundary of the communication path.</t>
<!-- Therefore, when applied, some form of access control must be set in place to avoid unauthorized users to deplete or abuse systems and network resources. -->
      </section>  <!-- Overview -->

      <section title="'application/coap-payload' Media Type" anchor="sec-application-coap-payload">
        <t>If the HC proxy receives a CoAP response with a Content-Format that it does not recognize (e.g., because the value has been registered after the proxy has been deployed, or the CoAP server uses an experimental value which is not registered), then the HC proxy SHALL return a generic "application/coap-payload" media type with numeric parameter "cf" as defined in <xref target="sec-coap-payload-reg"/>.</t>

        <t>For example, the CoAP content format '60' ("application/cbor") would be represented by "application/coap-payload;cf=60", if the HC Proxy doesn't recognize the content format '60'.</t>

        <t>A HTTP client may use the media type "application/coap-payload" as a means to send a specific content format to a CoAP server via a HC Proxy if the client has determined that the HC Proxy does not directly support the type mapping it needs.  This case may happen when dealing for example with newly registered, yet to be registered, or experimental CoAP content formats.  However, unless explicitly configured to allow pass-through of unknown content formats, the HC proxy SHOULD NOT forward requests carrying a Content-Type or Accept header with an "application/coap-payload", and return an appropriate client error instead.</t>
      </section>  <!-- Content Format to Media Type Mapping -->

      <section title="Loose Media Type Mapping" anchor="sec-loose-mt-mapping">
        <t>By structuring the type information in a super-class (e.g., "text") followed by a finer grained sub-class (e.g., "html"), and optional parameters (e.g., "charset=utf-8"), Internet media types provide a rich and scalable framework for encoding the type of any given entity.</t>

        <t>This approach is not applicable to CoAP, where Content Formats conflate an Internet media type (potentially with specific parameters) and a content encoding into one small integer value.</t>

        <t>To remedy this loss of flexibility, we introduce the concept of a "loose" media type mapping, where media types that are specializations of a more generic media type can be aliased to their super-class and then mapped (if possible) to one of the CoAP content formats.  For example, "application/soap+xml" can be aliased to "application/xml", which has a known conversion to CoAP.  In the context of this "loose" media type mapping, "application/octet-stream" can be used as a fallback when no better alias is found for a specific media type.</t>

        <t><xref target="tab-generalised-mt"/> defines the default lookup table for the "loose" media type mapping.  It is expected that an implementation can refine it either given application-specific knowledge, or because new Content-Formats are defined.  Given an input media type, the table returns its best generalized media type using the most specific match i.e., the table entries are compared to the input in top to bottom order until an entry matches.</t>

        <texttable anchor="tab-generalised-mt" title="Media type generalization lookup table">
          <ttcol align="left">Internet media type pattern</ttcol>
          <ttcol align="left">Generalized media type</ttcol>
          <c>application/*+xml</c>
          <c>application/xml</c>
          <c>application/*+json</c>
          <c>application/json</c>
          <c>application/*+cbor</c>
          <c>application/cbor</c>
          <c>text/xml</c>
          <c>application/xml</c>
          <c>text/*</c>
          <c>text/plain</c>
          <c>*/*</c>
          <c>application/octet-stream</c>
        </texttable>
        <t>The "loose" media type mapping is an OPTIONAL feature.  Implementations supporting this kind of mapping should provide a flexible way to define the set of media type generalizations allowed.</t>
      </section>  <!-- Loose Media Type Mapping -->

      <section title="Media Type to Content Format Mapping Algorithm" anchor="sec-mt2cf">
        <t>This section defines the algorithm used to map an HTTP Internet media type to its correspondent CoAP content format; it can be used as a building block for translating HTTP Content-Type and Accept headers into CoAP Content-Format and Accept Options.</t>

        <t>The algorithm uses an IANA-maintained table, "CoAP Content-Formats", as established by Section 12.3 of <xref target="RFC7252"/> plus, possibly, any locally defined extension of it.  Optionally, the table and lookup mechanism described in <xref target="sec-loose-mt-mapping"/> can be used if the implementation chooses so.</t>

        <t>Note that the algorithm assumes an "identity" Content-Encoding and expects the resource body has been already successfully content-decoded or transcoded to the desired format.</t>

        <t>In the following (<xref target="fig-mt2cf"/>):
          <list style="symbols">
            <t>media_type is the media type to translate;</t>
            <t>coap_cf_registry is a lookup table matching the CoAP Content Format Registry;</t>
            <t>loose_mapper is an optional lookup table describing the loose media type mappings (e.g., the one defined in <xref target="tab-generalised-mt"/>);</t>
          </list>
          The full source code is provided in <xref target="appendix-mt2cf-impl"/>.
        </t>
        <figure anchor="fig-mt2cf">
          <artwork>
            <![CDATA[
def mt2cf(media_type, encoding=None,
          coap_cf_registry=CoAPContentFormatRegistry(),
          loose_mapper=None):
    """Return a CoAP Content-Format given an Internet Media Type and
       its optional encoding.  The current (as of 2016/10/24) CoAP
       Content Format Registry is supplied by default.  An optional
       'loose-mapping' implementation can be supplied by the caller."""
    assert media_type is not None
    assert coap_cf_registry is not None

    # Lookup the CoAP Content-Formats registry
    content_format = coap_cf_registry.lookup(media_type, encoding)

    # If an exact match is not found and a loose mapper has been
    # supplied, try to use it to get a media type with which to
    # re-try the CoAP Content-Formats registry lookup.
    if content_format is None and loose_mapper is not None:
        content_format = coap_cf_registry.lookup(
            loose_mapper.lookup(media_type), encoding)

    return content_format
            ]]>
          </artwork>
        </figure>
        <!-- TODO add text to describe the algorithm? -->
        <!-- TODO provide examples -->
      </section>  <!-- Media Type to Content Format Mapping Algorithm -->

      <section title="Content Transcoding" anchor="sec-content-trans">
        <section title="General">
          <t>Payload content transcoding (e.g., see steps 11-14 of <xref target="fig-mt2cf"/>) is an OPTIONAL feature.  Implementations supporting this feature should provide a flexible way to define the set of transcodings allowed.</t>

          <t>As noted in <xref target="sec-mt2cf"/>, the process of mapping the media type can have side effects on the forwarded entity body.  This may be caused by the removal or addition of a specific content encoding, or because the HC proxy decides to transcode the representation to a different (compatible) format.  The latter proves useful when an optimized version of a specific format exists.  For example a XML-encoded resource could be transcoded to Efficient XML Interchange (EXI) format, or a JSON-encoded resource into CBOR <xref target="RFC7049"/>, effectively achieving compression without losing any information.</t>
        
          <t>However, there are a few important factors to keep in mind when enabling a transcoding function:
            <list style="numbers">
              <t>Maliciously crafted inputs coming from the HTTP side might inflate in size (see for example Section 4.2 of <xref target="RFC7049" />), therefore creating a security threat for both the HC proxy and the target resource;</t>
              <t>Transcoding can lose information in non-obvious ways.  For example, encoding a XML document using schema-informed EXI encoding leads to a loss of information when the destination does not know the exact schema version used by the encoder.  That means that whenever the HC proxy transcodes an application/XML to application/EXI in-band metadata could be lost.</t>
              <t>When content-type is mapped, there is a risk that the content with the destination type would have malware not active in the source type.</t>
            </list>
            Therefore, it is crucial that these risks are well understood and carefully weighed against the actual benefits before deploying the transcoding function.
          </t>
        </section>  <!-- General -->

        <section title="CoRE Link Format">
          <t>The CoRE Link Format <xref target="RFC6690"/> is a set of links (i.e., URIs and their formal relationships) which is carried as content payload in a CoAP response.  These links usually include CoAP URIs that might be translated by the HC proxy to the correspondent HTTP URIs using the implemented URI mapping function (see <xref target="URI-mapping"/>).  Such a process would inspect the forwarded traffic and attempt to re-write the body of resources with an application/link-format media type, mapping the embedded CoAP URIs to their HTTP counterparts.  Some potential issues with this approach are:
            <list style="numbers">
              <t>The client may be interested to retrieve original (unaltered) CoAP payloads through the HC proxy, not modified versions.</t>
              <t>Tampering with payloads is incompatible with resources that are integrity protected (although this is a problem with transcoding in general).</t>
              <t>The HC proxy needs to fully understand <xref target="RFC6690"/> syntax and semantics, otherwise there is an inherent risk to corrupt the payloads.</t>
            </list>
            Therefore, CoRE Link Format payload should only be transcoded at the risk and discretion of the proxy implementer.</t>
        </section>  <!-- CoRE Link Format -->

        <section title="Diagnostic Messages" anchor="sec-diagnostic">
          <t>CoAP responses may, in certain error cases, contain a diagnostic message in the payload explaining the error situation, as described in Section 5.5.2 of <xref target="RFC7252"/>.  If present, the CoAP response diagnostic payload SHOULD be copied in the HTTP response body.  The CoAP diagnostic message MUST NOT be copied into the HTTP reason-phrase, since it potentially contains CR-LF characters which are incompatible with HTTP reason-phrase syntax.</t>
        </section>  <!-- Diagnostic Messages" -->
      </section> <!-- Content Transcoding -->
    </section> <!-- Media Type Mapping -->

    <!-- ******************* MAIN SECTION ******************** -->
    <section title="Response Code Mapping" anchor="hc-resp">
      <t><xref target="tab-http-coap"/> defines the HTTP response status codes to which each CoAP response code SHOULD be mapped.  Multiple appearances of a HTTP status code in the second column indicates multiple equivalent HTTP responses are possible based on the same CoAP response code, depending on the conditions cited in the Notes (third column and text below table).</t>

      <texttable anchor="tab-http-coap" title="CoAP-HTTP Response Code Mappings">
        <ttcol align="left">CoAP Response Code</ttcol>
        <ttcol align="left">HTTP Status Code</ttcol>
        <ttcol align="left">Notes</ttcol>
        <c>2.01 Created                </c>
        <c>201 Created                 </c>
        <c>1</c>
        <c>2.02 Deleted                </c>
        <c>200 OK                      </c>
        <c>2</c>
        <c>                            </c>
        <c>204 No Content              </c>
        <c>2</c>
        <c>2.03 Valid                  </c>
        <c>304 Not Modified            </c>
        <c>3</c>
        <c>                            </c>
        <c>200 OK                      </c>
        <c>4</c>
        <c>2.04 Changed                </c>
        <c>200 OK                      </c>
        <c>2</c>
        <c>                            </c>
        <c>204 No Content              </c>
        <c>2</c>
        <c>2.05 Content                </c>
        <c>200 OK                      </c>
        <c> </c>
        <c>4.00 Bad Request            </c>
        <c>400 Bad Request             </c>
        <c> </c>
        <c>4.01 Unauthorized           </c>
        <c>403 Forbidden               </c>
        <c>5</c>
        <c>4.02 Bad Option             </c>
        <c>400 Bad Request             </c>
        <c>6</c>
        <c>4.02 Bad Option             </c>
        <c>500 Internal Server Error   </c>
        <c>6</c>
        <c>4.03 Forbidden              </c>
        <c>403 Forbidden               </c>
        <c> </c>
        <c>4.04 Not Found              </c>
        <c>404 Not Found               </c>
        <c> </c>
        <c>4.05 Method Not Allowed     </c>
        <c>400 Bad Request             </c>
        <c>7</c>
        <c>4.06 Not Acceptable         </c>
        <c>406 Not Acceptable          </c>
        <c> </c>
        <c>4.12 Precondition Failed    </c>
        <c>412 Precondition Failed     </c>
        <c> </c>
        <c>4.13 Request Ent. Too Large </c>
        <c>413 Request Repr. Too Large </c>
        <c> </c>
        <c>4.15 Unsupported Media Type </c>
        <c>415 Unsupported Media Type  </c>
        <c> </c>
        <c>5.00 Internal Server Error  </c>
        <c>500 Internal Server Error   </c>
        <c> </c>
        <c>5.01 Not Implemented        </c>
        <c>501 Not Implemented         </c>
        <c> </c>
        <c>5.02 Bad Gateway            </c>
        <c>502 Bad Gateway             </c>
        <c> </c>
        <c>5.03 Service Unavailable    </c>
        <c>503 Service Unavailable     </c>
        <c>8</c>
        <c>5.04 Gateway Timeout        </c>
        <c>504 Gateway Timeout         </c>
        <c> </c>
        <c>5.05 Proxying Not Supported </c>
        <c>502 Bad Gateway             </c>
        <c>9</c>
      </texttable>
      <t>Notes:
        <list style="numbers">
          <t>A CoAP server may return an arbitrary format payload along with this response. If present, this payload MUST be returned as entity in the HTTP 201 response. Section 7.3.2 of <xref target="RFC7231"/> does not put any requirement on the format of the entity. (In the past, <xref target="RFC2616"/> did.)</t>

          <t>The HTTP code is 200 or 204 respectively for the case that a CoAP server returns a payload or not. <xref target="RFC7231"/> Section 5.3 requires code 200 in case a representation of the action result is returned for DELETE/POST/PUT, and code 204 if not. Hence, a proxy MUST transfer any CoAP payload contained in a CoAP 2.02 response to the HTTP client using a 200 OK response.</t>
 
          <t>HTTP code 304 (Not Modified) is sent if the HTTP client performed a conditional HTTP request and the CoAP server responded with 2.03 (Valid) to the corresponding CoAP validation request. Note that Section 4.1 of <xref target="RFC7232"/> puts some requirements on header fields that must be present in the HTTP 304 response.</t>
 
          <t>A 200 response to a CoAP 2.03 occurs only when the HC proxy, for efficiency reasons, is running a local cache.  An unconditional HTTP GET which produces a cache-hit, could trigger a re-validation (i.e., a conditional GET) on the CoAP side.  The proxy receiving 2.03 updates the freshness of its cached representation and returns it to the HTTP client.</t>
 
          <t>A HTTP 401 Unauthorized (Section 3.1 of <xref target="RFC7235"/>) response is not applicable because there is no equivalent in CoAP of WWW-Authenticate which is mandatory in a HTTP 401 response.</t>
 
          <t>If the proxy has a way to determine that the Bad Option is due to the straightforward mapping of a client request header into a CoAP option, then returning HTTP 400 (Bad Request) is appropriate.  In all other cases, the proxy MUST return HTTP 500 (Internal Server Error) stating its inability to provide a suitable translation to the client's request.</t>

          <t>A CoAP 4.05 (Method Not Allowed) response SHOULD normally be mapped to a HTTP 400 (Bad Request) code, because the HTTP 405 response would require specifying the supported methods - which are generally unknown.  In this case the HC Proxy SHOULD also return a HTTP reason-phrase in the HTTP status line that starts with the string "CoAP server returned 4.05" in order to facilitate troubleshooting.  However, if the HC proxy has more granular information about the supported methods for the requested resource (e.g., via a Resource Directory (<xref target="I-D.ietf-core-resource-directory"/>)) then it MAY send back a HTTP 405 (Method Not Allowed) with a properly filled in "Allow" response-header field (Section 7.4.1 of <xref target="RFC7231"/>).</t>

          <t>The value of the HTTP "Retry-After" response-header field is taken from the value of the CoAP Max-Age Option, if present.</t>

          <t>This CoAP response can only happen if the proxy itself is configured to use a CoAP forward-proxy (Section 5.7 of <xref target="RFC7252"/>) to execute some, or all, of its CoAP requests.</t>
        </list>
      </t>
    </section> <!-- Response Mapping -->

    <!-- ******************* MAIN SECTION ******************** -->
    <section title="Additional Mapping Guidelines" anchor="hc-additional">
      <section title="Caching and Congestion Control" anchor="hc-caching">
        <!-- discuss cache-control -->
        <t>A HC proxy should cache CoAP responses, and reply whenever applicable with a cached representation of the requested resource.</t>

          <!-- The same consideration applies if multiple active HTTP subscriptions involve the same observe relationship -->
        <!--
        <t>Duplicate idempotent pending requests by a HC proxy to the same CoAP resource SHOULD in general be avoided, by using the same response for multiple requesting HTTP clients without duplicating the CoAP request.</t>
        -->

        <t>If the HTTP client drops the connection after the HTTP request was made, a HC proxy should wait for the associated CoAP response and cache it if possible.  Subsequent requests to the HC proxy for the same resource can use the result present in cache, or, if a response has still to come, the HTTP requests will wait on the open CoAP request.</t>

        <t>According to <xref target="RFC7252"/>, a proxy must limit the number of outstanding requests to a given CoAP server to NSTART. To limit the amount of aggregate traffic to a constrained network, the HC proxy should also put a limit on the number of concurrent CoAP requests pending on the same constrained network; further incoming requests may either be queued or dropped (returning 503 Service Unavailable). This limit and the proxy queueing/dropping behavior should be configurable.</t>

        <t>Highly volatile resources that are being frequently requested may be observed <xref target="RFC7641"/> by the HC proxy to keep their cached representation fresh while minimizing the amount of CoAP traffic in the constrained network.  See <xref target="refresh_via_observe"/>.</t>
      </section>  <!-- Caching and Congestion Control -->

      <section title="Cache Refresh via Observe" anchor="refresh_via_observe">
        <t>There are cases where using the CoAP observe protocol <xref target="RFC7641"/> to handle proxy cache refresh is preferable to the validation mechanism based on ETag as defined in <xref target="RFC7252"/>.  Such scenarios include sleepy CoAP nodes - with possibly high variance in requests' distribution - which would greatly benefit from a server driven cache update mechanism.  Ideal candidates for CoAP observe are also crowded or very low throughput networks, where reduction of the total number of exchanged messages is an important requirement.</t>

        <t>This subsection aims at providing a practical evaluation method to decide whether refreshing a cached resource R is more efficiently handled via ETag validation or by establishing an observation on R.  The idea being that the HC proxy proactively installs an observation on a "popular enough" resource and actively monitors:
          <list style="letters">
            <t>Its update pattern on the CoAP side; and</t>
            <t>The request pattern on the HTTP side;</t>
          </list>
          and uses the formula below to determine whether the observation should be kept alive or shut down.
        </t>

        <t>Let T_R be the mean time between two client requests to resource R, let T_C be the mean time between two representation changes of R, and let M_R be the mean number of CoAP messages per second exchanged to and from resource R.  If we assume that the initial cost for establishing the observation is negligible, an observation on R reduces M_R if and only if T_R &lt; 2*T_C with respect to using ETag validation, that is if and only if the mean arrival rate of requests for resource R is greater than half the change rate of R.</t>

        <t>When observing the resource R, M_R is always upper bounded by 2/T_C.</t>
      </section>  <!-- Cache Refresh via Observe -->

      <section title="Use of CoAP Blockwise Transfer" anchor="hc-block">
        <t>A HC proxy SHOULD support CoAP blockwise transfers <xref target="RFC7959"/> to allow transport of large CoAP payloads while avoiding excessive link-layer fragmentation in constrained networks, and to cope with small datagram buffers in CoAP end-points as described in <xref target="RFC7252"/> Section 4.6.</t>

        <t>A HC proxy SHOULD attempt to retry a payload-carrying CoAP PUT or POST request with blockwise transfer if the destination CoAP server responded with 4.13 (Request Entity Too Large) to the original request.  A HC proxy SHOULD attempt to use blockwise transfer when sending a CoAP PUT or POST request message that is larger than BLOCKWISE_THRESHOLD bytes. The value of BLOCKWISE_THRESHOLD is implementation-specific, for example it can be:
          <list style="symbols">
            <t>Calculated based on a known or typical UDP datagram buffer size for CoAP end-points, or</t>
            <t>Set to N times the known size of a link-layer frame in a constrained network where e.g., N=5, or</t>
            <t>Preset to a known IP MTU value, or</t>
            <t>Set to a known Path MTU value.</t>
          </list>
          The value BLOCKWISE_THRESHOLD, or the parameters from which it is calculated, should be configurable in a proxy implementation. The maximum block size the proxy will attempt to use in CoAP requests should also be configurable.</t>

        <t>The HC proxy SHOULD detect CoAP end-points not supporting blockwise transfers.  This can be done by checking for a 4.02 (Bad Option) response returned by an end-point in response to a CoAP request with a Block* Option, and subsequent absence of the 4.02 in response to the same request without Block* Options.  This allows the HC proxy to be more efficient, not attempting repeated blockwise transfers to CoAP servers that do not support it.</t>

      </section>  <!-- Use of CoAP Blockwise Transfer -->

      <section title="CoAP Multicast" anchor="hc-multicast">
        <t>A HC proxy MAY support CoAP multicast. If it does, the HC proxy sends out a multicast CoAP request if the Target CoAP URI's authority is a multicast IP literal or resolves to a multicast IP address.  If the HC proxy does not support CoAP multicast, it SHOULD respond 403 (Forbidden) to any valid HTTP request that maps to a CoAP multicast request.</t>

        <t>Details related to supporting CoAP multicast are currently out of scope of this document since in a proxy scenario a HTTP client typically expects to receive a single response, not multiple.  However, a HC proxy that implements CoAP multicast may include application-specific functions to aggregate multiple CoAP responses into a single HTTP response.  We suggest using the "application/http" internet media type (Section 8.3.2 of <xref target="RFC7230"/>) to enclose a set of one or more HTTP response messages, each representing the mapping of one CoAP response.</t>

        <t>For further considerations related to the handling of multicast requests, see <xref target="sec.multicast" />.</t>
      </section>  <!-- CoAP Multicast -->

      <section title="Timeouts" anchor="hc-timeouts">
        <t>If the CoAP server takes a long time in responding, the HTTP client or any other proxy in between may timeout.  Further discussion of timeouts in HTTP is available in Section 6.2.4 of <xref target="RFC7230"/>.</t>

        <t>A HC proxy MUST define an internal timeout for each pending CoAP request, because the CoAP server may silently die before completing the request.  Assuming the Proxy uses confirmable CoAP requests, such timeout value T SHOULD be at least</t>

        <t>T = MAX_RTT + MAX_SERVER_RESPONSE_DELAY</t>

        <t>where MAX_RTT is defined in <xref target="RFC7252" /> and MAX_SERVER_RESPONSE_DELAY is defined in <xref target="RFC7390"/>.</t>
      </section>  <!-- Timeouts -->

    </section> <!-- Additional Guidelines -->

    <!-- ******************* MAIN SECTION ******************** -->
    <section anchor="IANA" title="IANA Considerations">
      <section anchor="sec-core-hc-reg" title="New 'core.hc' Resource Type">
        <t>This document registers a new Resource Type (rt=) Link Target Attribute, 'core.hc', in the "Resource Type (rt=) Link Target Attribute Values" subregistry under the "Constrained RESTful Environments (CoRE) Parameters" registry.</t>

        <t>Attribute Value: core.hc</t>
        <t>Description: HTTP to CoAP mapping base resource.</t>
        <t>Reference: See <xref target="section.discovery"/>.</t>
      </section>  <!-- New 'core.hc' Resource Type -->

      <section anchor="sec-coap-payload-reg" title="New 'coap-payload' Internet Media Type">
        <t>This document defines the "application/coap-payload" media type with a single parameter "cf". This media type represents any payload that a CoAP message can carry, having a content format that can be identified by an integer in range 0-65535 corresponding to a CoAP Content-Format parameter (<xref target="RFC7252"/>, Section 12.3).  The parameter "cf" is the integer defining the CoAP content format.</t>

        <t>Type name: application</t>
        <t>Subtype name: coap-payload</t>

        <t>Required parameters: cf (CoAP Content-Format integer in range 0-65535 denoting the content format of the CoAP payload carried, as defined by the "CoAP Content-Formats" subregistry that is part of the "Constrained RESTful Environments (CoRE) Parameters" registry.)</t>

        <t>Optional parameters: None</t>

        <t>Encoding considerations: Common use is BINARY.  The specific CoAP content format encoding considerations for the selected Content-Format (cf parameter) apply.  The encoding can vary based on the value of the cf parameter.</t>

        <t>Security considerations: The specific CoAP content format security considerations for the selected Content-Format (cf parameter) apply.</t>

        <t>Interoperability considerations: This media type can never be used directly in CoAP messages because there is no means available to encode the mandatory 'cf' parameter in CoAP.</t>
		
		<t>Published specification: (this I-D - TBD)</t>

        <t>Applications that use this media type: HTTP-to-CoAP Proxies.</t>

        <t>Fragment identifier considerations: CoAP does not support URI fragments; therefore a CoAP payload fragment cannot be identified. Fragments are not applicable for this media type.</t>

        <t>Additional information:
          <list style="hanging">
            <t>Deprecated alias names for this type: N/A</t>
            <t>Magic number(s): N/A</t>
            <t>File extension(s): N/A</t>
            <t>Macintosh file type code(s): N/A</t>
          </list>
        </t>

        <t>Person and email address to contact for further information:
          <list style="hanging">
            <t>Esko Dijk ("esko@ieee.org")</t>
          </list>
        </t>
        <t>Intended usage: COMMON</t>
        <t>Restrictions on usage:</t>
        <t>An application (or user) can only use this media type if it has to represent a CoAP payload of which the specified CoAP Content-Format is an unrecognized number; such that a proper translation directly to the equivalent HTTP media type is not possible.</t>
        <t>Author: CoRE WG</t>
        <t>Change controller: IETF</t>
        <t>Provisional registration: No</t>
      </section>  <!-- "New 'coap-payload' Internet Media Type" -->
    </section>  <!-- IANA Considerations -->

    <!-- ******************* MAIN SECTION ******************** -->
    <section title="Security Considerations" anchor="sec">
      <t>The security concerns raised in Section 9.2 of <xref target="RFC7230" /> also apply to the HC proxy scenario.</t>

      <t>A HC proxy deployed at the boundary of a constrained network is an easy single point of failure for reducing availability.  As such, special care should be taken in designing, developing and operating it, keeping in mind that, in most cases, it has fewer limitations than the constrained devices it is serving.</t>

      <t>The correctness of the request parsing in general (including any content transcoding), and of the URI translation process in particular, is essential to the security of the HC proxy function.  This is especially true when the internal network hosts devices with genuinely limited capabilities.  The quality of implementation and operation - i.e., careful implementation and/or selection of the third party libraries, sane configuration defaults, an expedite way to upgrade a running instance, etc. - is therefore an essential attribute of the HC proxy.  For this purpose, see also Sections 9.3, 9.4, 9.5 and 9.6 of <xref target="RFC7230" /> for well known issues related to HTTP request parsing, and section 11.1 of <xref target="RFC7252" /> for an overview of CoAP specific concerns related to URI processing - in particular the potential impact on access control mechanisms that are based on URIs.</t>

      <t>The following sub paragraphs categorize and discuss a set of specific security issues related to the translation, caching and forwarding functionality exposed by a HC proxy.</t>

      <section title="Multicast" anchor="sec.multicast">
      <t>Multicast requests impose a non-trivial cost on the constrained network and endpoints, and might be exploited as a DoS attack vector (see also <xref target="sec.traffic-overflow"/>).  From a privacy perspective, they can be used to gather detailed information about the resources hosted in the constrained network.  For example, an outsider that is able to successfully query the /.well-known/core could obtain a comprehensive list of the target's home appliances and devices.  From a security perspective, they can be used to carry out a network reconnaissance attack to gather information about possible vulnerabilities that could be exploited at a later point in time.  For these reasons, it is RECOMMENDED that requests to multicast resources are access controlled with a default-deny policy.  It is RECOMMENDED that the requestor of a multicast resource be strongly authenticated.  If privacy and / or security are first class requirements, for example whenever the HTTP request transits through the public Internet, the request SHOULD be transported over a mutually authenticated and encrypted TLS connection.</t>
      </section>  <!-- Multicast -->

      <section title="Traffic Overflow" anchor="sec.traffic-overflow">
        <t>Due to the typically constrained nature of CoAP nodes, particular attention should be given to the implementation of traffic reduction mechanisms (see <xref target="hc-caching"/>), because inefficient proxy implementations can be targeted by unconstrained Internet attackers.  Bandwidth or complexity involved in such attacks is very low.</t>

        <t>An amplification attack to the constrained network may be triggered by a multicast request generated by a single HTTP request which is mapped to a CoAP multicast resource, as discussed in Section 11.3 of <xref target="RFC7252"/>.</t>

        <t>The risk likelihood of this amplification technique is higher than an amplification attack carried out by a malicious constrained device (e.g., ICMPv6 flooding, like Packet Too Big, or Parameter Problem on a multicast destination <xref target="RFC4732"/>), since it does not require direct access to the constrained network.</t>

        <t>The feasibility of this attack which disrupts availability of the targeted CoAP server can be limited by access controlling the exposed multicast resources, so that only known/authorized users can access such URIs.</t>
      </section>  <!-- Traffic Overflow -->

      <section title="Handling Secured Exchanges" anchor="sec-exchanges">
        <t>An HTTP request can be sent to the HC proxy over a secured connection.  However, there may not always exist a secure connection mapping to CoAP.  For example, a secure distribution method for multicast traffic is complex and may not be implemented (see <xref target="RFC7390" />).</t>

        <t>A HC proxy should implement rules for security context translations.  For example all 'https' unicast requests are translated to 'coaps' requests, or 'https' requests are translated to unsecured 'coap' requests.  Another rule could specify the security policy and parameters used for DTLS sessions <xref target="RFC7925"/>. Such rules will largely depend on the application and network context in which the HC proxy operates.  These rules should be configurable.</t>

        <t>It is RECOMMENDED that, by default, accessing a 'coaps' URI is only allowed from a corresponding 'https' URI.</t>

        <t>By default, a HC proxy SHOULD reject any secured CoAP client request (i.e., one with a 'coaps' scheme) if there is no configured security policy mapping.  This recommendation may be relaxed in case the destination network is believed to be secured by other means.  Assuming that CoAP nodes are isolated behind a firewall as in the HC proxy deployment shown in <xref target="fig-http-coap-deployment"/>, the HC proxy may be configured to translate the incoming HTTPS request using plain CoAP (NoSec mode).</t>
 
      </section>  <!-- Handling Secured Exchanges -->

      <section title="URI Mapping">
        <t>The following risks related to the URI mapping described in <xref target="URI-mapping"/> and its use by HC proxies have been identified:
          <list style="hanging">
            <t hangText="DoS attack on the constrained/CoAP network."><vspace/>Mitigation: by default deny any Target CoAP URI whose authority is (or maps to) a multicast address.  Then explicitly white-list multicast resources/authorities that are allowed to be de-referenced. See also <xref target="hc-multicast"/>.</t>
            <t hangText="Leaking information on the constrained/CoAP network resources and topology."><vspace/>Mitigation: by default deny any Target CoAP URI (especially /.well-known/core is a resource to be protected), and then explicitly white-list resources that are allowed to be seen from outside.</t>
            <t hangText="The internal CoAP Target resource is totally transparent from outside."><vspace/>Mitigation: implement a HTTPS-only interface, which makes the Target CoAP URI totally opaque to a passive attacker.</t>
          </list>
        </t>
      </section> <!-- Security and privacy considerations for "URI Mapping" -->
    </section>  <!-- Security Considerations -->

    <section title="Acknowledgments">
      <t>An initial version of <xref target="tab-http-coap"/> in <xref target="hc-resp"/> has been provided in revision -05 of the CoRE CoAP I-D.  Special thanks to Peter van der Stok for countless comments and discussions on this document, that contributed to its current structure and text.</t>

      <t>Thanks to
      Abhijan Bhattacharyya,
      Alexey Melnikov,
      Brian Frank,
      Carsten Bormann,
      Christian Amsuess,
      Christian Groves,
      Cullen Jennings,
      Dorothy Gellert,
      Francesco Corazza,
      Francis Dupont,
      Hannes Tschofenig,
      Jaime Jimenez,
      Kathleen Moriarty,
      Kepeng Li,
      Kerry Lynn,
      Klaus Hartke,
      Larry Masinter,
      Linyi Tian,
      Michele Rossi,
      Michele Zorzi,
      Nicola Bui,
      Peter Saint-Andre,
      Sean Leonard,
      Spencer Dawkins,
      Stephen Farrell,
      Suresh Krishnan,
      Zach Shelby
      for helpful comments and discussions that have shaped the document.</t>
 
      <t>The research leading to these results has received funding from the European Community's Seventh Framework Programme [FP7/2007-2013] under grant agreement n.251557.</t>
    </section>
  </middle>

  <back>
    <references title="Normative References">
      &RFC2119;
      &RFC3986;
      &RFC5234;
      &RFC6570;
      &RFC6690;
      &RFC7230;
      &RFC7231;
      &RFC7232;
      &RFC7235;
      &RFC7252;
      &RFC7641;
      &RFC7959;
    </references>
    <references title="Informative References">
      &RFC2616;
      &RFC3040;
      &RFC4732;
      &RFC6454;
      &RFC7049;
      &RFC7228;
      &RFC7390;
      &RFC7925;
      &I-D.ietf-core-resource-directory;
      &I-D.ietf-core-links-json;
      <reference anchor="W3C.REC-html5-20141028" target="http://www.w3.org/TR/2014/REC-html5-20141028">
        <front>
          <title>HTML5</title>
          <author initials="I.H." surname="Hickson">
            <organization/>
          </author>
          <author initials="R.B." surname="Berjon">
            <organization/>
          </author>
          <author initials="S.F." surname="Faulkner">
            <organization/>
          </author>
          <author initials="T.L." surname="Leithead">
            <organization/>
          </author>
          <author initials="E.D.N." surname="Navara">
            <organization/>
          </author>
          <author initials="E.O." surname="O'Connor">
            <organization/>
          </author>
          <author initials="S.P." surname="Pfeiffer">
            <organization/>
          </author>
          <date year="2014"/>
        </front>
        <seriesInfo name="W3C Recommendation" value="REC-html5-20141028" />
      </reference>
      <reference anchor="REST">
        <front>
          <title>
            Architectural Styles and the Design of Network-based Software Architectures
          </title>
          <author initials="R.T.F." surname="Fielding">
            <organization>IEEE</organization>
          </author>
          <date year="2000"/>
        </front>
        <seriesInfo name="PhD Dissertation," value="University of California, Irvine"/>
        <seriesInfo name="ISBN" value="0-599-87118-0"/>
      </reference>
    </references>

    <section title="Media Type Mapping Source Code" anchor="appendix-mt2cf-impl">
      <t>
        <figure>
          <artwork>
            <![CDATA[
#!/usr/bin/env python

import unittest
import re


class CoAPContentFormatRegistry(object):
    """Map an Internet media type (and optional inherent encoding) to a
       CoAP content format.
    """
    TEXT_PLAIN = 0
    LINK_FORMAT = 40
    XML = 41
    OCTET_STREAM = 42
    EXI = 47
    JSON = 50
    CBOR = 60
    GROUP_JSON = 256

# http://www.iana.org/assignments/core-parameters/core-parameters.xhtml
# as of 2016/10/24.
    LOOKUP_TABLE = {
        ("text/plain;charset=utf-8", None): TEXT_PLAIN,
        ("application/link-format", None): LINK_FORMAT,
        ("application/xml", None): XML,
        ("application/octet-stream", None): OCTET_STREAM,
        ("application/exi", None): EXI,
        ("application/json", None): JSON,
        ("application/cbor", None): CBOR,
        ("application/coap-group+json", "utf-8"): GROUP_JSON,
    }

    def lookup(self, media_type, encoding):
        """Return the CoAP Content Format matching the supplied
           media type (and optional encoding), or None if no
           match can be found."""
        return CoAPContentFormatRegistry.LOOKUP_TABLE.get(
            (media_type, encoding), None)


class LooseMediaTypeMapper(object):
    # Order matters in this table: more specific types have higher rank
    # compared to less specific types.
    # This code only performs a shallow validation of acceptable
    # characters, and assumes overall validation of media type and
    # subtype has been done beforehand.
    LOOKUP_TABLE = [
        (re.compile("application/.+\+xml$"), "application/xml"),
        (re.compile("application/.+\+json$"), "application/json"),
        (re.compile("application/.+\+cbor$"), "application/cbor"),
        (re.compile("text/xml$"), "application/xml"),
        (re.compile("text/[a-z\.\-\+]+$"), "text/plain;charset=utf-8"),
        (re.compile("[a-z]+/[a-z\.\-\+]+$"), "application/octet-stream")
    ]

    def lookup(self, media_type):
        """Return the best loose media type match available using
           the contents of LOOKUP_TABLE."""
        for entry in LooseMediaTypeMapper.LOOKUP_TABLE:
            if entry[0].match(media_type) is not None:
                return entry[1]
        return None


def mt2cf(media_type, encoding=None,
          coap_cf_registry=CoAPContentFormatRegistry(),
          loose_mapper=None):
    """Return a CoAP Content-Format given an Internet Media Type and
       its optional encoding.  The current (as of 2016/10/24) CoAP
       Content Format Registry is supplied by default.  An optional
       'loose-mapping' implementation can be supplied by the caller."""
    assert media_type is not None
    assert coap_cf_registry is not None

    # Lookup the CoAP Content-Formats registry
    content_format = coap_cf_registry.lookup(media_type, encoding)

    # If an exact match is not found and a loose mapper has been
    # supplied, try to use it to get a media type with which to
    # re-try the CoAP Content-Formats registry lookup.
    if content_format is None and loose_mapper is not None:
        content_format = coap_cf_registry.lookup(
            loose_mapper.lookup(media_type), encoding)

    return content_format


class TestMT2CF(unittest.TestCase):

    def testMissingContentType(self):
        with self.assertRaises(AssertionError):
            mt2cf(None)

    def testMissingContentFormatRegistry(self):
        with self.assertRaises(AssertionError):
            mt2cf(None, coap_cf_registry=None)

    def testTextPlain(self):
        self.assertEqual(mt2cf("text/plain;charset=utf-8"),
                         CoAPContentFormatRegistry.TEXT_PLAIN)

    def testLinkFormat(self):
        self.assertEqual(mt2cf("application/link-format"),
                         CoAPContentFormatRegistry.LINK_FORMAT)

    def testXML(self):
        self.assertEqual(mt2cf("application/xml"),
                         CoAPContentFormatRegistry.XML)

    def testOctetStream(self):
        self.assertEqual(mt2cf("application/octet-stream"),
                         CoAPContentFormatRegistry.OCTET_STREAM)

    def testEXI(self):
        self.assertEqual(mt2cf("application/exi"),
                         CoAPContentFormatRegistry.EXI)

    def testJSON(self):
        self.assertEqual(mt2cf("application/json"),
                         CoAPContentFormatRegistry.JSON)

    def testCBOR(self):
        self.assertEqual(mt2cf("application/cbor"),
                         CoAPContentFormatRegistry.CBOR)

    def testCoAPGroupJSON(self):
        self.assertEqual(mt2cf("application/coap-group+json",
                               "utf-8"),
                         CoAPContentFormatRegistry.GROUP_JSON)

    def testUnknownMediaType(self):
        self.assertFalse(mt2cf("unknown/media-type"))

    def testLooseXML1(self):
        self.assertEqual(
            mt2cf(
                "application/somesubtype+xml",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.XML)

    def testLooseXML2(self):
        self.assertEqual(
            mt2cf(
                "text/xml",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.XML)

    def testLooseJSON(self):
        self.assertEqual(
            mt2cf(
                "application/somesubtype+json",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.JSON)

    def testLooseCBOR(self):
        self.assertEqual(
            mt2cf(
                "application/somesubtype+cbor",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.CBOR)

    def testLooseText(self):
        self.assertEqual(
            mt2cf(
                "text/somesubtype",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.TEXT_PLAIN)

    def testLooseUnknown(self):
        self.assertEqual(
            mt2cf(
                "application/somesubtype-of-some-sort+format",
                loose_mapper=LooseMediaTypeMapper()),
            CoAPContentFormatRegistry.OCTET_STREAM)

    def testLooseInvalidStartsWithNonAlpha(self):
        self.assertFalse(
            mt2cf(
                " application/somesubtype",
                loose_mapper=LooseMediaTypeMapper()))

    def testLooseInvalidEndsWithUnexpectedChar(self):
        self.assertFalse(
            mt2cf(
                "application/somesubtype ",
                loose_mapper=LooseMediaTypeMapper()))

    def testLooseInvalidUnexpectedCharInTheMiddle(self):
        self.assertFalse(
            mt2cf(
                "application /somesubtype",
                loose_mapper=LooseMediaTypeMapper()))

    def testLooseInvalidNoSubType1(self):
        self.assertFalse(
            mt2cf(
                "application",
                loose_mapper=LooseMediaTypeMapper()))

    def testLooseInvalidNoSubType2(self):
        self.assertFalse(
            mt2cf(
                "application/",
                loose_mapper=LooseMediaTypeMapper()))

if __name__ == "__main__":
    unittest.main(verbosity=2)
            ]]>
          </artwork>
        </figure>
      </t>
    </section>

    <section title="Change Log">
      <t>[Note to RFC Editor: Please remove this section before publication.]</t>
      <t>Changes from ietf-15 to ietf-16 (Apps-Dir review):
        <list style="symbols">
          <t>Larry Masinter's comments.</t>
        </list>
      </t>

      <t>Changes from ietf-14 to ietf-15 (IESG review):
        <list style="symbols">
          <t>Kathleen Moriarty's DISCUSS and COMMENT;</t>
          <t>Stephen Farrell's COMMENT;</t>
          <t>Suresh Krishnan DISCUSS;</t>
          <t>Spencer Dawkins' DISCUSS and COMMENT;</t>
        </list>
      </t>

      <t>Changes from ietf-13 to ietf-14:
        <list style="symbols">
          <t>Addressed Gen-ART and AD review comments.</t>
        </list>
      </t>

      <t>Changes from ietf-12 to ietf-13 (Christian Amsuess' comments):
        <list style="symbols">
          <t>More missing slashes in URI mapping template examples.</t>
        </list>
      </t>

      <t>Changes from ietf-11 to ietf-12 (2nd WGLC):
        <list style="symbols">
          <t>Addressed a few editorial issues (including a clarification on when to use qq vs q in the URI mapping template).</t>
          <t>Fixed missing slash in one template example.</t>
          <t>Added para about the need for future CoAP protocol elements to define their own HTTP mappings.</t>
        </list>
      </t>

      <t>Changes from ietf-10 to ietf-11 (Chair review):
        <list style="symbols">
          <t>Removed cu/su distinction from the URI mapping template.</t>
          <t>Addressed a few editorial issues.</t>
        </list>
      </t>

      <t>Changes from ietf-09 to ietf-10:
        <list style="symbols">
          <t>Addressed Ticket #401 - Clarified that draft covers not only Reverse HC Proxy but that many parts also apply to Forward and Interception Proxies.</t>
		  <t>Clarified that draft concentrates on the HTTP-to-CoAP mapping direction (i.e., the HC proxy is a HTTP server and a CoAP client).</t>
		  <t>Clarified the "null mapping" case where no CoAP URI information is embedded in the HTTP request URI.</t>
		  <t>Moved multicast related security text to the "Security Considerations" to consolidate all security information in one location.</t>
		  <t>Removed references to "placement" of proxy (e.g., server-side vs client-side) as is confusing and provides little added value.</t>
		  <t>Fixed version numbers on references that were corrupted in last revision due to outdated xml2rfc conversion tool local cache.</t>
		  <t>Various editorial improvements.</t>
        </list>
      </t>

      <t>Changes from ietf-08 to ietf-09:
        <list style="symbols">
          <t>Clean up requirements language as per Klaus' comment.</t>
        </list>
      </t>

      <t>Changes from ietf-07 to ietf-08:
        <list style="symbols">
          <t>Addressed WGLC review comments from Klaus Hartke as per the correspondence of March 9, 2016 on the CORE WG mailing list. </t>
        </list>
      </t>

      <t>Changes from ietf-06 to ietf-07:
        <list style="symbols">
          <t>Addressed Ticket #384 - Section 5.4.1 describes briefly (informative) how to discover CoAP resources from an HTTP client.</t>
          <t>Addressed Ticket #378 - For HTTP media type to CoAP content format mapping and vice versa: a new draft (TBD) may be proposed in CoRE which describes an approach for automatic updating of the media type mapping.  This was noted in Section 6.1 but is otherwise outside the scope of this draft.</t>
          <t>Addressed Ticket #377 - Added IANA section that defines a new HTTP media type "application/coap-payload" and created new <xref target="sec-application-coap-payload"/> on how to use it.</t>
          <t>Addressed Ticket #376 - Updated Table 2 (and corresponding note 7) to indicate that a CoAP 4.05 (Method Not Allowed) Response Code should be mapped to a HTTP 400 (Bad Request).</t>
          <t>Added note to comply to ABNF when translating CoAP diagnostic payload to reason-phrase in <xref target="sec-diagnostic"/>.</t>
        </list>
      </t>

      <t>Changes from ietf-05 to ietf-06:
        <list style="symbols">
          <t>Fully restructured the draft, bringing introductory text more to the front and allocating main sections to each of the key topics; addressing Ticket #379;</t>
          <t>Addressed Ticket #382, fix of enhanced form URI template definition of q in Section 5.3.2;</t>
          <t>Addressed Ticket #381, found a mapping 4.01 to 401 Unauthorized in Section 7;</t>
          <t>Addressed Ticket #380 (Add IANA registration for "core.hc" Resource Type) in Section 9;</t>
          <t>Addressed Ticket #376 (CoAP 4.05 response can't be translated to HTTP 405 by HC proxy) in Section 7 by use of empty 'Allow' header;</t>
          <t>Removed details on the pros and cons of HC proxy placement options;</t>
          <t>Addressed review comments of Carsten Bormann;</t>
          <t>Clarified failure in mapping of HTTP Accept headers (Section 6.3);</t>
          <t>Clarified detection of CoAP servers not supporting blockwise (Section 8.3);</t>
          <t>Changed CoAP request timeout min value to MAX_RTT + MAX_SERVER_RESPONSE_DELAY (Section 8.6);</t>
          <t>Added security section item (Section 10.3) related to use of CoAP blockwise transfers;</t>
          <t>Many editorial improvements.</t>
        </list>
      </t>

      <t>Changes from ietf-04 to ietf-05:
        <list style="symbols">
          <t>Addressed Ticket #366 (Mapping of CoRE Link Format payloads to be valid in HTTP Domain?) in Section 6.3.3.2 (Content Transcoding - CORE Link Format);</t>
          <t>Addressed Ticket #375 (Add requirement on mapping of CoAP diagnostic payload) in Section 6.3.3.3 (Content Transcoding - Diagnostic Messages);</t>
          <t>Addressed comment from Yusuke (http://www.ietf.org/mail-archive/web/core/current/msg05491.html) in Section 6.3.3.1 (Content Transcoding - General);</t>
          <t>Various editorial improvements.</t>
        </list>
      </t>

      <t>Changes from ietf-03 to ietf-04:
        <list style="symbols">
          <t>Expanded use case descriptions in Section 4;</t>
          <t>Fixed/enhanced discovery examples in Section 5.4.1;</t>
          <t>Addressed Ticket #365 (Add text on media type conversion by HTTP-CoAP proxy) in new Section 6.3.1 (Generalized media type mapping) and new Section 6.3.2 (Content translation);</t>
          <t>Updated HTTPBis WG draft references to recently published RFC numbers.</t>
          <t>Various editorial improvements.</t>
        </list>
      </t>

      <t>Changes from ietf-02 to ietf-03:
        <list style="symbols">
          <t>Closed Ticket #351 "Add security implications of proposed default HTTP-CoAP URI mapping";</t>
          <t>Closed Ticket #363 "Remove CoAP scheme in default HTTP-CoAP URI mapping";</t>
          <t>Closed Ticket #364  "Add discovery of HTTP-CoAP mapping resource(s)".</t>
        </list>
      </t>

      <t>Changes from ietf-01 to ietf-02:
        <list style="symbols">
          <t>Selection of single default URI mapping proposal as proposed to WG mailing list 2013-10-09.</t>
        </list>
      </t>

      <t>Changes from ietf-00 to ietf-01:
        <list style="symbols">
          <t>Added URI mapping proposals to Section 4 as per the Email proposals to WG mailing list from Esko.</t>
        </list>
      </t>
    </section>
  </back>
</rfc>
<!-- LocalWords: xref CDATA exploders BUA -->
