Tech-invite3GPPspaceIETFspace
96959493929190898887868584838281807978777675747372717069686766656463626160595857565554535251504948474645444342414039383736353433323130292827262524232221201918171615141312111009080706050403020100
in Index   Prev   Next

RFC 8075

Guidelines for Mapping Implementations: HTTP to the Constrained Application Protocol (CoAP)

Pages: 40
Proposed Standard
Part 2 of 2 – Pages 21 to 40
First   Prev   None

Top   ToC   RFC8075 - Page 21   prevText

7. Response Code Mapping

Table 2 defines the HTTP response status codes to which each CoAP response code SHOULD be mapped. Multiple HTTP status codes in the second column for a given CoAP response code indicates that multiple HTTP responses are possible for the same CoAP response code, depending on the conditions cited in the Notes (see the third column and text below the table). +-------------------------------+----------------------------+------+ | CoAP Response Code | HTTP Status Code | Note | +-------------------------------+----------------------------+------+ | 2.01 Created | 201 Created | 1 | | 2.02 Deleted | 200 OK | 2 | | | 204 No Content | 2 | | 2.03 Valid | 304 Not Modified | 3 | | | 200 OK | 4 | | 2.04 Changed | 200 OK | 2 | | | 204 No Content | 2 | | 2.05 Content | 200 OK | | | 2.31 Continue | N/A | 10 | | 4.00 Bad Request | 400 Bad Request | | | 4.01 Unauthorized | 403 Forbidden | 5 | | 4.02 Bad Option | 400 Bad Request | 6 | | | 500 Internal Server Error | 6 | | 4.03 Forbidden | 403 Forbidden | | | 4.04 Not Found | 404 Not Found | | | 4.05 Method Not Allowed | 400 Bad Request | 7 | | | 405 Method Not Allowed | 7 | | 4.06 Not Acceptable | 406 Not Acceptable | | | 4.08 Request Entity Incomplt. | N/A | 10 | | 4.12 Precondition Failed | 412 Precondition Failed | | | 4.13 Request Ent. Too Large | 413 Payload Too Large | 11 | | 4.15 Unsupported Content-Fmt. | 415 Unsupported Media Type | | | 5.00 Internal Server Error | 500 Internal Server Error | | | 5.01 Not Implemented | 501 Not Implemented | | | 5.02 Bad Gateway | 502 Bad Gateway | | | 5.03 Service Unavailable | 503 Service Unavailable | 8 | | 5.04 Gateway Timeout | 504 Gateway Timeout | | | 5.05 Proxying Not Supported | 502 Bad Gateway | 9 | +-------------------------------+----------------------------+------+ Table 2: CoAP-HTTP Response Code Mappings
Top   ToC   RFC8075 - Page 22
   Notes:

   1.   A CoAP server may return an arbitrary format payload along with
        this response.  If present, this payload MUST be returned as an
        entity in the HTTP 201 response.  Section 6.3.2 of [RFC7231]
        does not put any requirement on the format of the entity.  (In
        the past, [RFC2616] did.  Note that [RFC2616] has been obsoleted
        by [RFC7230].)

   2.   The HTTP code is 200 or 204, respectively, for the case where a
        CoAP server returns a payload or not.  [RFC7231], Section 6.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.

   3.   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 [RFC7232] puts some
        requirements on header fields that must be present in the HTTP
        304 response.

   4.   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 that produces a cache-hit could trigger a revalidation
        (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.

   5.   An HTTP 401 Unauthorized (Section 3.1 of [RFC7235]) response is
        not applicable because there is no equivalent of
        WWW-Authenticate in CoAP, which is mandatory in an HTTP 401
        response.

   6.   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.

   7.   A CoAP 4.05 (Method Not Allowed) response SHOULD normally be
        mapped to an 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 an HTTP reason-phrase in the HTTP status line that starts
        with the string "CoAP server returned 4.05" in order to
Top   ToC   RFC8075 - Page 23
        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 ([CoRE-RD])),
        then it MAY send back an HTTP 405 (Method Not Allowed) with a
        properly filled in "Allow" response-header field (Section 7.4.1
        of [RFC7231]).

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

   9.   This CoAP response can only happen if the proxy itself is
        configured to use a CoAP forward-proxy (Section 5.7 of
        [RFC7252]) to execute some, or all, of its CoAP requests.

   10.  Only used in CoAP block-wise transfer [RFC7959] between HC Proxy
        and CoAP server; never translated into an HTTP response.

   11.  Only returned to the HTTP client if the HC Proxy was unable to
        successfully complete the request by retrying it with CoAP
        block-wise transfer; see Section 8.3.

8. Additional Mapping Guidelines

8.1. Caching and Congestion Control

An HC Proxy should cache CoAP responses and reply whenever applicable with a cached representation of the requested resource. If the HTTP client drops the connection after the HTTP request was made, an 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. According to [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 be dropped (returning 503 Service Unavailable). This limit and the proxy queueing/dropping behavior should be configurable. Highly volatile resources that are being frequently requested may be observed [RFC7641] by the HC Proxy to keep their cached representation fresh while minimizing the amount of CoAP traffic in the constrained network (see Section 8.2).
Top   ToC   RFC8075 - Page 24

8.2. Cache Refresh via Observe

There are cases where using the CoAP observe protocol [RFC7641] to handle proxy cache refresh is preferable to the validation mechanism based on the entity-tag (ETag) as defined in [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. 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: a. Its update pattern on the CoAP side b. The request pattern on the HTTP side and uses the formula below to determine whether the observation should be kept alive or shut down. 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 < 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. When observing the resource R, M_R is always upper bounded by 2/T_C.

8.3. Use of CoAP Block-Wise Transfer

An HC Proxy SHOULD support CoAP block-wise transfers [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 endpoints as described in [RFC7252], Section 4.6. An HC Proxy SHOULD attempt to retry a payload-carrying CoAP PUT or POST request with block-wise transfer if the destination CoAP server responded with 4.13 (Request Entity Too Large) to the original request. An HC Proxy SHOULD attempt to use block-wise transfer when sending a CoAP PUT or POST request message that is larger than
Top   ToC   RFC8075 - Page 25
   BLOCKWISE_THRESHOLD bytes.  The value of BLOCKWISE_THRESHOLD is
   implementation specific; for example, it can be:

   o  Calculated based on a known or typical UDP datagram buffer size
      for CoAP endpoints, or

   o  Set to N times the known size of a link-layer frame in a
      constrained network where, e.g., N=5, or

   o  Preset to a known IP MTU value, or

   o  Set to a known Path MTU value.

   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.

   The HC Proxy SHOULD detect CoAP endpoints not supporting block-wise
   transfers.  This can be done by checking for a 4.02 (Bad Option)
   response returned by an endpoint 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 block-wise transfers to CoAP
   servers that do not support it.

8.4. CoAP Multicast

An 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. Details related to supporting CoAP multicast are currently out of scope of this document since in a proxy scenario, an HTTP client typically expects to receive a single response, not multiple. However, an 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 [RFC7230]) to enclose a set of one or more HTTP response messages, each representing the mapping of one CoAP response. For further considerations related to the handling of multicast requests, see Section 10.1.
Top   ToC   RFC8075 - Page 26

8.5. Timeouts

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.5 of [RFC7230]. An 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 T = MAX_RTT + MAX_SERVER_RESPONSE_DELAY where MAX_RTT is defined in [RFC7252] and MAX_SERVER_RESPONSE_DELAY is defined as the worst-case expected response delay of the CoAP server. If unknown, a default value of 250 seconds can be used for MAX_SERVER_RESPONSE_DELAY as in Section 2.5 of [RFC7390].

9. IANA Considerations

9.1. New 'core.hc' Resource Type

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. Attribute Value: core.hc Description: HTTP-to-CoAP mapping base resource. Reference: See Section 5.5 of RFC 8075.

9.2. New 'coap-payload' Internet Media Type

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 ([RFC7252], Section 12.3). The parameter "cf" is the integer defining the CoAP content-format. Type name: application Subtype name: coap-payload Required parameters: "cf" (CoAP Content-Format integer in range 0-65535 denoting the content-format of the CoAP payload carried, as
Top   ToC   RFC8075 - Page 27
   defined by the "CoAP Content-Formats" subregistry that is part of the
   "Constrained RESTful Environments (CoRE) Parameters" registry).

   Optional parameters: None

   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.

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

   Interoperability considerations: This media type can never be used
   directly in CoAP messages because there are no means available to
   encode the mandatory "cf" parameter in CoAP.

   Published specification: RFC 8075

   Applications that use this media type: HTTP-to-CoAP proxies.

   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.

   Additional information:

      Deprecated alias names for this type: N/A

      Magic number(s): N/A

      File extension(s): N/A

      Macintosh file type code(s): N/A

   Person and email address to contact for further information:

      Esko Dijk ("esko@ieee.org")

   Intended usage: COMMON

   Restrictions on usage:

   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.
Top   ToC   RFC8075 - Page 28
   Author: CoRE WG

   Change controller: IETF

   Provisional registration: No

10. Security Considerations

The security considerations in Section 9.2 of [RFC7230] apply in full to the HC Proxy. This section discusses security aspects and requirements that are specific to the deployment and operation of an HC Proxy. An HC Proxy located 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. In particular, its quality of implementation and operation -- i.e., use of current software development practices, careful selection of third-party libraries, sane configuration defaults, and an expedited way to upgrade a running instance -- are all essential attributes of the HC Proxy. The correctness of request parsing in general (including any content transcoding), and of URI translation in particular, is essential to the security of the HC Proxy function. This is especially true when the constrained network hosts devices with genuinely limited capabilities. For this purpose, see also Sections 9.3, 9.4, 9.5 and 9.6 of [RFC7230] for well-known issues related to HTTP request parsing and Section 11.1 of [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. An HC Proxy MUST implement Transport Layer Security (TLS) with a Pre- Shared Key (PSK) [RFC4279] and SHOULD implement TLS [RFC5246] with support for client authentication using X.509 certificates. A prerequisite of the latter is the availability of a Certification Authority (CA) to issue suitable certificates. Although this can be a challenging requirement in certain application scenarios, it is worth noting that there exist open-source tools (e.g., [OpenSSL]) that can be used to set up and operate an application-specific CA. By default, the HC Proxy MUST authenticate all incoming requests prior to forwarding them to the CoAP server. This default behavior MAY be explicitly disabled by an administrator.
Top   ToC   RFC8075 - Page 29
   The following subparagraphs categorize and discuss a set of specific
   security issues related to the translation, caching, and forwarding
   functionality exposed by an HC Proxy.

10.1. Multicast

Multicast requests impose a non-trivial cost on the constrained network and endpoints and might be exploited as a DoS attack vector (see also Section 10.2). 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" resource 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.

10.2. Traffic Overflow

Due to the typically constrained nature of CoAP nodes, particular attention should be given to the implementation of traffic reduction mechanisms (see Section 8.1), because an inefficient proxy implementation can be targeted by unconstrained Internet attackers. Bandwidth or complexity involved in such attacks is very low. An amplification attack to the constrained network may be triggered by a multicast request generated by a single HTTP request that is mapped to a CoAP multicast resource, as discussed in Section 11.3 of [RFC7252]. 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 [RFC4732]) since it does not require direct access to the constrained network. 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.
Top   ToC   RFC8075 - Page 30

10.3. Handling Secured Exchanges

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 [RFC7390]). An 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 Datagram Transport Layer Security (DTLS) sessions [RFC7925]. Such rules will largely depend on the application and network context in which the HC Proxy operates. These rules should be configurable. It is RECOMMENDED that, by default, accessing a 'coaps' URI is only allowed from a corresponding 'https' URI. By default, an 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 Figure 1, the HC Proxy may be configured to translate the incoming HTTPS request using plain CoAP (NoSec mode).

10.4. URI Mapping

The following risks related to the URI mapping described in Section 5 and its use by an HC Proxy have been identified: DoS attack on the constrained/CoAP network. Mitigation: by default, deny any Target CoAP URI whose authority is (or maps to) a multicast address. Then explicitly whitelist multicast resources/authorities that are allowed to be dereferenced. See also Section 8.4. Leaking information on the constrained/CoAP network resources and topology. Mitigation: by default, deny any Target CoAP URI (especially "/.well-known/core" is a resource to be protected), and then explicitly whitelist resources that are allowed to be seen by clients outside the constrained network.
Top   ToC   RFC8075 - Page 31
   The CoAP target resource is totally transparent from outside the
      constrained network.
      Mitigation: implement an HTTPS-only interface, which makes the
      Target CoAP URI totally opaque to a passive attacker outside the
      constrained network.

11. References

11.1. Normative References

[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/RFC2119, March 1997, <http://www.rfc-editor.org/info/rfc2119>. [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, RFC 3986, DOI 10.17487/RFC3986, January 2005, <http://www.rfc-editor.org/info/rfc3986>. [RFC4279] Eronen, P., Ed. and H. Tschofenig, Ed., "Pre-Shared Key Ciphersuites for Transport Layer Security (TLS)", RFC 4279, DOI 10.17487/RFC4279, December 2005, <http://www.rfc-editor.org/info/rfc4279>. [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, DOI 10.17487/RFC5234, January 2008, <http://www.rfc-editor.org/info/rfc5234>. [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security (TLS) Protocol Version 1.2", RFC 5246, DOI 10.17487/RFC5246, August 2008, <http://www.rfc-editor.org/info/rfc5246>. [RFC6570] Gregorio, J., Fielding, R., Hadley, M., Nottingham, M., and D. Orchard, "URI Template", RFC 6570, DOI 10.17487/RFC6570, March 2012, <http://www.rfc-editor.org/info/rfc6570>. [RFC6690] Shelby, Z., "Constrained RESTful Environments (CoRE) Link Format", RFC 6690, DOI 10.17487/RFC6690, August 2012, <http://www.rfc-editor.org/info/rfc6690>. [RFC7230] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing", RFC 7230, DOI 10.17487/RFC7230, June 2014, <http://www.rfc-editor.org/info/rfc7230>.
Top   ToC   RFC8075 - Page 32
   [RFC7231]  Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer
              Protocol (HTTP/1.1): Semantics and Content", RFC 7231,
              DOI 10.17487/RFC7231, June 2014,
              <http://www.rfc-editor.org/info/rfc7231>.

   [RFC7232]  Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer
              Protocol (HTTP/1.1): Conditional Requests", RFC 7232,
              DOI 10.17487/RFC7232, June 2014,
              <http://www.rfc-editor.org/info/rfc7232>.

   [RFC7235]  Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer
              Protocol (HTTP/1.1): Authentication", RFC 7235,
              DOI 10.17487/RFC7235, June 2014,
              <http://www.rfc-editor.org/info/rfc7235>.

   [RFC7252]  Shelby, Z., Hartke, K., and C. Bormann, "The Constrained
              Application Protocol (CoAP)", RFC 7252,
              DOI 10.17487/RFC7252, June 2014,
              <http://www.rfc-editor.org/info/rfc7252>.

   [RFC7641]  Hartke, K., "Observing Resources in the Constrained
              Application Protocol (CoAP)", RFC 7641,
              DOI 10.17487/RFC7641, September 2015,
              <http://www.rfc-editor.org/info/rfc7641>.

   [RFC7959]  Bormann, C. and Z. Shelby, Ed., "Block-Wise Transfers in
              the Constrained Application Protocol (CoAP)", RFC 7959,
              DOI 10.17487/RFC7959, August 2016,
              <http://www.rfc-editor.org/info/rfc7959>.

11.2. Informative References

[CoRE-JSON-CBOR] Li, K., Rahman, A., and C. Bormann, "Representing CoRE Formats in JSON and CBOR", Work in Progress, draft-ietf- core-links-json-06, July 2016. [CoRE-RD] Shelby, Z., Koster, M., Bormann, C., and P. Stok, "CoRE Resource Directory", Work in Progress, draft-ietf-core- resource-directory-09, October 2016. [Fielding] Fielding, R., "Architectural Styles and the Design of Network-based Software Architectures", PhD Dissertation, University of California, Irvine, ISBN 0-599-87118-0, 2000.
Top   ToC   RFC8075 - Page 33
   [OpenSSL]  The OpenSSL Project, , "ca - sample minimal CA
              application", 2000-2016,
              <https://www.openssl.org/docs/manmaster/man1/ca.html>.

   [RFC2616]  Fielding, R., Gettys, J., Mogul, J., Frystyk, H.,
              Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext
              Transfer Protocol -- HTTP/1.1", RFC 2616,
              DOI 10.17487/RFC2616, June 1999,
              <http://www.rfc-editor.org/info/rfc2616>.

   [RFC2663]  Srisuresh, P. and M. Holdrege, "IP Network Address
              Translator (NAT) Terminology and Considerations",
              RFC 2663, DOI 10.17487/RFC2663, August 1999,
              <http://www.rfc-editor.org/info/rfc2663>.

   [RFC3040]  Cooper, I., Melve, I., and G. Tomlinson, "Internet Web
              Replication and Caching Taxonomy", RFC 3040,
              DOI 10.17487/RFC3040, January 2001,
              <http://www.rfc-editor.org/info/rfc3040>.

   [RFC4732]  Handley, M., Ed., Rescorla, E., Ed., and IAB, "Internet
              Denial-of-Service Considerations", RFC 4732,
              DOI 10.17487/RFC4732, December 2006,
              <http://www.rfc-editor.org/info/rfc4732>.

   [RFC6454]  Barth, A., "The Web Origin Concept", RFC 6454,
              DOI 10.17487/RFC6454, December 2011,
              <http://www.rfc-editor.org/info/rfc6454>.

   [RFC7049]  Bormann, C. and P. Hoffman, "Concise Binary Object
              Representation (CBOR)", RFC 7049, DOI 10.17487/RFC7049,
              October 2013, <http://www.rfc-editor.org/info/rfc7049>.

   [RFC7228]  Bormann, C., Ersue, M., and A. Keranen, "Terminology for
              Constrained-Node Networks", RFC 7228,
              DOI 10.17487/RFC7228, May 2014,
              <http://www.rfc-editor.org/info/rfc7228>.

   [RFC7390]  Rahman, A., Ed. and E. Dijk, Ed., "Group Communication for
              the Constrained Application Protocol (CoAP)", RFC 7390,
              DOI 10.17487/RFC7390, October 2014,
              <http://www.rfc-editor.org/info/rfc7390>.

   [RFC7925]  Tschofenig, H., Ed. and T. Fossati, "Transport Layer
              Security (TLS) / Datagram Transport Layer Security (DTLS)
              Profiles for the Internet of Things", RFC 7925,
              DOI 10.17487/RFC7925, July 2016,
              <http://www.rfc-editor.org/info/rfc7925>.
Top   ToC   RFC8075 - Page 34
   [W3C.REC-html5-20141028]
              Hickson, I., Berjon, R., Faulkner, S., Leithead, T.,
              Navara, E., O'Connor, E., and S. Pfeiffer, "HTML5", World
              Wide Web Consortium Recommendation REC-html5-20141028,
              October 2014,
              <http://www.w3.org/TR/2014/REC-html5-20141028>.
Top   ToC   RFC8075 - Page 35

Appendix A. Media Type Mapping Source Code

#!/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 # 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)
Top   ToC   RFC8075 - Page 36
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 the 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-Formats" 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
    # retry 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
Top   ToC   RFC8075 - Page 37
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"))
Top   ToC   RFC8075 - Page 38
    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()))
Top   ToC   RFC8075 - Page 39
    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)

Acknowledgments

An initial version of Table 2 in Section 7 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. 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, and Zach Shelby for helpful comments and discussions that have shaped the document. 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.
Top   ToC   RFC8075 - Page 40

Authors' Addresses

Angelo P. Castellani University of Padova Via Gradenigo 6/B Padova 35131 Italy Email: angelo@castellani.net Salvatore Loreto Ericsson Hirsalantie 11 Jorvas 02420 Finland Email: salvatore.loreto@ericsson.com Akbar Rahman InterDigital Communications, LLC 1000 Sherbrooke Street West Montreal H3A 3G4 Canada Phone: +1 514 585 0761 Email: Akbar.Rahman@InterDigital.com Thomas Fossati Nokia 3 Ely Road Milton, Cambridge CB24 6DD United Kingdom Email: thomas.fossati@nokia.com Esko Dijk Philips Lighting High Tech Campus 7 Eindhoven 5656 AE The Netherlands Email: esko.dijk@philips.com