From bd3ae9694c0e8669c8ce53aef685e8afede14f33 Mon Sep 17 00:00:00 2001 From: Guido Günther Date: Sun, 13 Dec 2015 17:47:14 +0100 Subject: Initial commit --- .gitignore | 6 + COPYING | 674 ++++ Makefile | 34 + README.md | 19 + include/coaperl.hrl | 52 + include/corerl.hrl | 8 + rebar | Bin 0 -> 160323 bytes rebar.config | 3 + rfc/core-parameters.txt | 237 ++ rfc/draft-ietf-core-block-17.txt | 1848 +++++++++++ rfc/draft-ietf-core-observe-16.txt | 1904 +++++++++++ rfc/rfc6690.txt | 1235 +++++++ rfc/rfc7252.txt | 6275 ++++++++++++++++++++++++++++++++++++ src/coap_parse.erl | 137 + src/coap_unparse.erl | 195 ++ src/coaperl.app.src | 11 + src/coaperl_sup.erl | 29 + src/corerl.erl | 72 + test/coap_parse_test.erl | 19 + test/coap_unparse_test.erl | 31 + 20 files changed, 12789 insertions(+) create mode 100644 .gitignore create mode 100644 COPYING create mode 100644 Makefile create mode 100644 README.md create mode 100644 include/coaperl.hrl create mode 100644 include/corerl.hrl create mode 100755 rebar create mode 100644 rebar.config create mode 100644 rfc/core-parameters.txt create mode 100644 rfc/draft-ietf-core-block-17.txt create mode 100644 rfc/draft-ietf-core-observe-16.txt create mode 100644 rfc/rfc6690.txt create mode 100644 rfc/rfc7252.txt create mode 100644 src/coap_parse.erl create mode 100644 src/coap_unparse.erl create mode 100644 src/coaperl.app.src create mode 100644 src/coaperl_sup.erl create mode 100644 src/corerl.erl create mode 100644 test/coap_parse_test.erl create mode 100644 test/coap_unparse_test.erl diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b575ce9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*~ +.eunit/ +.rebar/ +deps/ +ebin/ +doc/ diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a329f76 --- /dev/null +++ b/Makefile @@ -0,0 +1,34 @@ +ERL ?= erl +APP := coaperl + +.PHONY: deps + +all: deps + @./rebar compile + +deps: + @./rebar get-deps + +clean: + @./rebar clean + +distclean: clean + @./rebar delete-deps + +docs: + @erl -noshell -run edoc_run application '$(APP)' '"."' '[]' + +test: all + @(./rebar skip_deps=true eunit) + +tags: + find . -name "*.[he]rl" -print | etags - + +DEPSOLVER_PLT=$(CURDIR)/.depsolver_plt +$(DEPSOLVER_PLT): + dialyzer --output_plt $(DEPSOLVER_PLT) --build_plt \ + --apps erts kernel stdlib crypto public_key # -r deps + +dialyzer: $(DEPSOLVER_PLT) + dialyzer --plt $(DEPSOLVER_PLT) -Wrace_conditions --src src + diff --git a/README.md b/README.md new file mode 100644 index 0000000..de5494f --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +Some erlang helpers for COAP messages (RFC7252) + +Copyright 2015 Guido Günther + +This is by no means a full coap implementation. It merely allows to ease +parsing of messages a bit by putting things into a record. + +Let's assume you receive UDP datagrams in a gen_server. You can then match on +the incoming coap message like: + + handle_info({udp, Socket, Host, Port, Bin}, State) -> + Msg = coap_parse:parse(Bin), + case Msg of + #coap_request{method=post, path= <<"/switches">>, query=[<<"name=", Name/binary>>], payload=Payload} -> + ... + +Which would allow you to process a request like: + + echo '{"mode": "on"}' | coap-client -f- -t application/json -m post "coap://[::1]/switches?name=Lever1" diff --git a/include/coaperl.hrl b/include/coaperl.hrl new file mode 100644 index 0000000..be3b0f1 --- /dev/null +++ b/include/coaperl.hrl @@ -0,0 +1,52 @@ + +% RFC7252, Section 12.2 +% 0 (Reserved) +% 1 if-match +% 3 uri-host +% 4 eTag +% 5 if-none-match +% 7 uri-port +% 8 location-path +-define(COAP_OPTION_URI_PATH, 11). +-define(COAP_OPTION_CONTENT_FORMAT, 12). +% 14 max-age +-define(COAP_OPTION_URI_QUERY, 15). +% 17 accept +% 20 location-query +% 35 proxy-uri +% 39 proxy-scheme +% 60 size1 +%128 (Reserved) +%132 (Reserved) +%136 (Reserved) +%140 (Reserved) + +% draft-ietf-core-block-17 +-define(COAP_OPTION_BLOCK2, 23). +-define(COAP_OPTION_BLOCK1, 27). +-define(COAP_OPTION_SIZE2, 28). + +-define(COAP_PAYLOAD_MARKER, 16#FF). + +-record(coap_request, { + method, + path, + query, + mid, + ct, + payload + }). + +-record(coap_response, { + class, % response class + detail, % repsonse detail + mid, % the meassage id + ct, % the content type + block2, % block2 option + options, % all coap options + payload}). +% 2.01 Location-Path, Location-Query +% 2.03 ETag, Max-Age +% 4.13 Size1 + +-record(coap_empty_message, {mid}). diff --git a/include/corerl.hrl b/include/corerl.hrl new file mode 100644 index 0000000..80b93ba --- /dev/null +++ b/include/corerl.hrl @@ -0,0 +1,8 @@ + +-record(core_link, {uri, + title, + sz, % size + rt, % resouce type + ct, % content type + 'if' % interface + }). diff --git a/rebar b/rebar new file mode 100755 index 0000000..14e5c22 Binary files /dev/null and b/rebar differ diff --git a/rebar.config b/rebar.config new file mode 100644 index 0000000..9f18e25 --- /dev/null +++ b/rebar.config @@ -0,0 +1,3 @@ +{erl_opts, [ + debug_info +]}. diff --git a/rfc/core-parameters.txt b/rfc/core-parameters.txt new file mode 100644 index 0000000..659d0e2 --- /dev/null +++ b/rfc/core-parameters.txt @@ -0,0 +1,237 @@ + Constrained RESTful Environments (CoRE) Parameters + + Created + 2012-06-08 + + Last Updated + 2015-07-03 + + Available Formats + [IMG] + XML [IMG] + HTML [IMG] + Plain text + + Registries included below + + * Resource Type (rt=) Link Target Attribute Values + * Interface Description (if=) Link Target Attribute Values + * CoAP Codes + + * CoAP Method Codes + * CoAP Response Codes + + * CoAP Option Numbers + * CoAP Content-Formats + +Resource Type (rt=) Link Target Attribute Values + + Expert(s) + + Unassigned + + Reference + [RFC6690] + + Available Formats + [IMG] + CSV + + Range Registration Procedures + value starts with "core" IETF Review + all other values Specification Required + + Value Description Reference Notes + core.gp Group Configuration resource. This resource is used to query/manage the group membership of a CoAP [RFC7390, Section 2.6.2] + server. + +Interface Description (if=) Link Target Attribute Values + + Expert(s) + + Unassigned + + Reference + [RFC6690] + + Range Registration Procedures + value starts with "core" IETF Review + all other values Specification Required + + Value Description Reference Notes + No registrations at this time. + +CoAP Codes + + Registration Procedure(s) + + Reserved ranges may be allocated in accordance with section 4.3 of [RFC5226]. + + Reference + [RFC7252, Section 12.1] + + Available Formats + [IMG] + CSV + + Code Description Reference + 0.00 Indicates an Empty message. [RFC7252, section 4.1] + 0.01-0.31 Indicates a request. Values in this range are assigned by the [CoAP Method Codes] sub-registry. [RFC7252, section 12.1.1] + 1.00-1.31 Reserved [RFC7252] + 2.00-5.31 Indicates a response. Values in this range are assigned by the [CoAP Response Codes] sub-registry. [RFC7252, section 12.1.2] + 6.00-7.31 Reserved [RFC7252] + + CoAP Method Codes + + Registration Procedure(s) + + IETF Review or IESG Approval + + Reference + [RFC7252, Section 12.1.1] + + Available Formats + [IMG] + CSV + + Code Name Reference + 0.01 GET [RFC7252] + 0.02 POST [RFC7252] + 0.03 PUT [RFC7252] + 0.04 DELETE [RFC7252] + 0.05-0.31 Unassigned + + CoAP Response Codes + + Registration Procedure(s) + + IETF Review or IESG Approval + + Reference + [RFC7252, Section 12.1.2] + + Available Formats + [IMG] + CSV + + Code Description Reference + 2.00 Unassigned + 2.01 Created [RFC7252] + 2.02 Deleted [RFC7252] + 2.03 Valid [RFC7252] + 2.04 Changed [RFC7252] + 2.05 Content [RFC7252] + 2.06-2.31 Unassigned + 3.00-3.31 Reserved [RFC7252] + 4.00 Bad Request [RFC7252] + 4.01 Unauthorized [RFC7252] + 4.02 Bad Option [RFC7252] + 4.03 Forbidden [RFC7252] + 4.04 Not Found [RFC7252] + 4.05 Method Not Allowed [RFC7252] + 4.06 Not Acceptable [RFC7252] + 4.07-4.11 Unassigned + 4.12 Precondition Failed [RFC7252] + 4.13 Request Entity Too Large [RFC7252] + 4.14 Unassigned + 4.15 Unsupported Content-Format [RFC7252] + 4.16-4.31 Unassigned + 5.00 Internal Server Error [RFC7252] + 5.01 Not Implemented [RFC7252] + 5.02 Bad Gateway [RFC7252] + 5.03 Service Unavailable [RFC7252] + 5.04 Gateway Timeout [RFC7252] + 5.05 Proxying Not Supported [RFC7252] + 5.06-5.31 Unassigned + +CoAP Option Numbers + + Expert(s) + + Zach Shelby + + Reference + [RFC7252, Section 12.2] + + Available Formats + [IMG] + CSV + + Range Registration Procedures + 0-255 IETF Review or IESG Approval + 256-2047 Specification Required + 2048-64999 Expert Review + 65000-65535 Experimental use (no operational use) + + Number Name Reference + 0 Reserved [RFC7252] + 1 If-Match [RFC7252] + 2 Unassigned + 3 Uri-Host [RFC7252] + 4 ETag [RFC7252] + 5 If-None-Match [RFC7252] + 6 Observe [RFC-ietf-core-observe-16] + 7 Uri-Port [RFC7252] + 8 Location-Path [RFC7252] + 9-10 Unassigned + 11 Uri-Path [RFC7252] + 12 Content-Format [RFC7252] + 13 Unassigned + 14 Max-Age [RFC7252] + 15 Uri-Query [RFC7252] + 16 Unassigned + 17 Accept [RFC7252] + 18-19 Unassigned + 20 Location-Query [RFC7252] + 21-34 Unssigned + 35 Proxy-Uri [RFC7252] + 36-38 Unassigned + 39 Proxy-Scheme [RFC7252] + 40-59 Unassigned + 60 Size1 [RFC7252] + 61-127 Unassigned + 128 Reserved [RFC7252] + 129-131 Unassigned + 132 Reserved [RFC7252] + 133-135 Unassigned + 136 Reserved [RFC7252] + 137-139 Unassigned + 140 Reserved [RFC7252] + 141-283 Unassigned + 284 No-Response [draft-tcs-coap-no-response-option] + 285-64999 Unassigned + 65000-65535 Reserved for Experimental Use [RFC7252] + +CoAP Content-Formats + + Expert(s) + + Zach Shelby + + Reference + [RFC7252, Section 12.3] + + Available Formats + [IMG] + CSV + + Range Registration Procedures + 0-255 Expert Review + 256-9999 IETF Review or IESG Approval + 10000-64999 First Come First Served + 65000-65535 Experimental use (no operational use) + + Media Type Encoding ID Reference + text/plain; charset=utf-8 0 [RFC2046][RFC3676][RFC5147] + Unassigned 1-39 + application/link-format 40 [RFC6690] + application/xml 41 [RFC3023] + application/octet-stream 42 [RFC2045][RFC2046] + Unassigned 43-46 + application/exi 47 ["Efficient XML Interchange (EXI) Format 1.0 (Second Edition)", February 2014] + Unassigned 48-49 + application/json 50 [RFC4627] + Unassigned 51-59 + application/cbor 60 [RFC7049] + Unassigned 61-64999 + Reserved for Experimental Use 65000-65535 [RFC7252] diff --git a/rfc/draft-ietf-core-block-17.txt b/rfc/draft-ietf-core-block-17.txt new file mode 100644 index 0000000..60bed7a --- /dev/null +++ b/rfc/draft-ietf-core-block-17.txt @@ -0,0 +1,1848 @@ + + + + +CoRE Working Group C. Bormann +Internet-Draft Universitaet Bremen TZI +Intended status: Standards Track Z. Shelby, Ed. +Expires: September 10, 2015 ARM + March 09, 2015 + + + Block-wise transfers in CoAP + draft-ietf-core-block-17 + +Abstract + + CoAP is a RESTful transfer protocol for constrained nodes and + networks. Basic CoAP messages work well for the small payloads we + expect from temperature sensors, light switches, and similar + building-automation devices. Occasionally, however, applications + will need to transfer larger payloads -- for instance, for firmware + updates. With HTTP, TCP does the grunt work of slicing large + payloads up into multiple packets and ensuring that they all arrive + and are handled in the right order. + + CoAP is based on datagram transports such as UDP or DTLS, which + limits the maximum size of resource representations that can be + transferred without too much fragmentation. Although UDP supports + larger payloads through IP fragmentation, it is limited to 64 KiB + and, more importantly, doesn't really work well for constrained + applications and networks. + + Instead of relying on IP fragmentation, this specification extends + basic CoAP with a pair of "Block" options, for transferring multiple + blocks of information from a resource representation in multiple + request-response pairs. In many important cases, the Block options + enable a server to be truly stateless: the server can handle each + block transfer separately, with no need for a connection setup or + other server-side memory of previous block transfers. + + In summary, the Block options provide a minimal way to transfer + larger representations in a block-wise fashion. + +Status of This Memo + + This Internet-Draft is submitted in full conformance with the + provisions of BCP 78 and BCP 79. + + Internet-Drafts are working documents of the Internet Engineering + Task Force (IETF). Note that other groups may also distribute + working documents as Internet-Drafts. The list of current Internet- + Drafts is at http://datatracker.ietf.org/drafts/current/. + + + +Bormann & Shelby Expires September 10, 2015 [Page 1] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + Internet-Drafts are draft documents valid for a maximum of six months + and may be updated, replaced, or obsoleted by other documents at any + time. It is inappropriate to use Internet-Drafts as reference + material or to cite them other than as "work in progress." + + This Internet-Draft will expire on September 10, 2015. + +Copyright Notice + + Copyright (c) 2015 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 3 + 2. Block-wise transfers . . . . . . . . . . . . . . . . . . . . 5 + 2.1. The Block2 and Block1 Options . . . . . . . . . . . . . . 5 + 2.2. Structure of a Block Option . . . . . . . . . . . . . . . 6 + 2.3. Block Options in Requests and Responses . . . . . . . . . 8 + 2.4. Using the Block2 Option . . . . . . . . . . . . . . . . . 10 + 2.5. Using the Block1 Option . . . . . . . . . . . . . . . . . 12 + 2.6. Combining Block-wise Transfers with the Observe Option . 13 + 2.7. Combining Block1 and Block2 . . . . . . . . . . . . . . . 14 + 2.8. Combining Block2 with Multicast . . . . . . . . . . . . . 14 + 2.9. Response Codes . . . . . . . . . . . . . . . . . . . . . 14 + 2.9.1. 2.31 Continue . . . . . . . . . . . . . . . . . . . . 15 + 2.9.2. 4.08 Request Entity Incomplete . . . . . . . . . . . 15 + 2.9.3. 4.13 Request Entity Too Large . . . . . . . . . . . . 15 + 2.10. Caching Considerations . . . . . . . . . . . . . . . . . 15 + 3. Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 16 + 3.1. Block2 Examples . . . . . . . . . . . . . . . . . . . . . 16 + 3.2. Block1 Examples . . . . . . . . . . . . . . . . . . . . . 20 + 3.3. Combining Block1 and Block2 . . . . . . . . . . . . . . . 21 + 3.4. Combining Observe and Block2 . . . . . . . . . . . . . . 23 + 4. The Size2 and Size1 Options . . . . . . . . . . . . . . . . . 26 + 5. HTTP Mapping Considerations . . . . . . . . . . . . . . . . . 27 + 6. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 29 + 7. Security Considerations . . . . . . . . . . . . . . . . . . . 29 + + + +Bormann & Shelby Expires September 10, 2015 [Page 2] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + 7.1. Mitigating Resource Exhaustion Attacks . . . . . . . . . 30 + 7.2. Mitigating Amplification Attacks . . . . . . . . . . . . 31 + 8. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 31 + 9. References . . . . . . . . . . . . . . . . . . . . . . . . . 31 + 9.1. Normative References . . . . . . . . . . . . . . . . . . 31 + 9.2. Informative References . . . . . . . . . . . . . . . . . 32 + Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 32 + +1. Introduction + + The work on Constrained RESTful Environments (CoRE) aims at realizing + the REST architecture in a suitable form for the most constrained + nodes (such as microcontrollers with limited RAM and ROM [RFC7228]) + and networks (such as 6LoWPAN, [RFC4944]) [RFC7252]. The CoAP + protocol is intended to provide RESTful [REST] services not unlike + HTTP [RFC7230], while reducing the complexity of implementation as + well as the size of packets exchanged in order to make these services + useful in a highly constrained network of themselves highly + constrained nodes. + + This objective requires restraint in a number of sometimes + conflicting ways: + + o reducing implementation complexity in order to minimize code size, + + o reducing message sizes in order to minimize the number of + fragments needed for each message (in turn to maximize the + probability of delivery of the message), the amount of + transmission power needed and the loading of the limited-bandwidth + channel, + + o reducing requirements on the environment such as stable storage, + good sources of randomness or user interaction capabilities. + + CoAP is based on datagram transports such as UDP, which limit the + maximum size of resource representations that can be transferred + without creating unreasonable levels of IP fragmentation. In + addition, not all resource representations will fit into a single + link layer packet of a constrained network, which may cause + adaptation layer fragmentation even if IP layer fragmentation is not + required. Using fragmentation (either at the adaptation layer or at + the IP layer) for the transport of larger representations would be + possible up to the maximum size of the underlying datagram protocol + (such as UDP), but the fragmentation/reassembly process burdens the + lower layers with conversation state that is better managed in the + application layer. + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 3] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + The present specification defines a pair of CoAP options to enable + _block-wise_ access to resource representations. The Block options + provide a minimal way to transfer larger resource representations in + a block-wise fashion. The overriding objective is to avoid the need + for creating conversation state at the server for block-wise GET + requests. (It is impossible to fully avoid creating conversation + state for POST/PUT, if the creation/replacement of resources is to be + atomic; where that property is not needed, there is no need to create + server conversation state in this case, either.) + + In summary, this specification adds a pair of Block options to CoAP + that can be used for block-wise transfers. Benefits of using these + options include: + + o Transfers larger than what can be accommodated in constrained- + network link-layer packets can be performed in smaller blocks. + + o No hard-to-manage conversation state is created at the adaptation + layer or IP layer for fragmentation. + + o The transfer of each block is acknowledged, enabling individual + retransmission if required. + + o Both sides have a say in the block size that actually will be + used. + + o The resulting exchanges are easy to understand using packet + analyzer tools and thus quite accessible to debugging. + + o If needed, the Block options can also be used (without changes) to + provide random access to power-of-two sized blocks within a + resource representation. + + The key words "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 RFC + 2119, BCP 14 [RFC2119] and indicate requirement levels for compliant + CoAP implementations. + + In this document, the term "byte" is used in its now customary sense + as a synonym for "octet". + + Where bit arithmetic is explained, this document uses the notation + familiar from the programming language C, except that the operator + "**" stands for exponentiation. + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 4] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +2. Block-wise transfers + + As discussed in the introduction, there are good reasons to limit the + size of datagrams in constrained networks: + + o by the maximum datagram size (~ 64 KiB for UDP) + + o by the desire to avoid IP fragmentation (MTU of 1280 for IPv6) + + o by the desire to avoid adaptation layer fragmentation (60-80 bytes + for 6LoWPAN [RFC4919]) + + When a resource representation is larger than can be comfortably + transferred in the payload of a single CoAP datagram, a Block option + can be used to indicate a block-wise transfer. As payloads can be + sent both with requests and with responses, this specification + provides two separate options for each direction of payload transfer. + In identifying these options, we use the number 1 to refer to the + transfer of the resource representation that pertains to the request, + and the number 2 to refer to the transfer of the resource + representation for the response. + + In the following, the term "payload" will be used for the actual + content of a single CoAP message, i.e. a single block being + transferred, while the term "body" will be used for the entire + resource representation that is being transferred in a block-wise + fashion. The Content-Format option applies to the body, not to the + payload, in particular the boundaries between the blocks may be in + places that are not separating whole units in terms of the structure, + encoding, or content-coding used by the Content-Format. + + In most cases, all blocks being transferred for a body (except for + the last one) will be of the same size. The block size is not fixed + by the protocol. To keep the implementation as simple as possible, + the Block options support only a small range of power-of-two block + sizes, from 2**4 (16) to 2**10 (1024) bytes. As bodies often will + not evenly divide into the power-of-two block size chosen, the size + need not be reached in the final block (but even for the final block, + the chosen power-of-two size will still be indicated in the block + size field of the Block option). + +2.1. The Block2 and Block1 Options + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 5] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + +-----+---+---+---+---+--------+--------+--------+---------+ + | No. | C | U | N | R | Name | Format | Length | Default | + +-----+---+---+---+---+--------+--------+--------+---------+ + | 23 | C | U | - | - | Block2 | uint | 0-3 | (none) | + | | | | | | | | | | + | 27 | C | U | - | - | Block1 | uint | 0-3 | (none) | + +-----+---+---+---+---+--------+--------+--------+---------+ + + Table 1: Block Option Numbers + + Both Block1 and Block2 options can be present both in request and + response messages. In either case, the Block1 Option pertains to the + request payload, and the Block2 Option pertains to the response + payload. + + Hence, for the methods defined in [RFC7252], Block1 is useful with + the payload-bearing POST and PUT requests and their responses. + Block2 is useful with GET, POST, and PUT requests and their payload- + bearing responses (2.01, 2.02, 2.04, 2.05 -- see section "Payload" of + [RFC7252]). + + Where Block1 is present in a request or Block2 in a response (i.e., + in that message to the payload of which it pertains) it indicates a + block-wise transfer and describes how this specific block-wise + payload forms part of the entire body being transferred ("descriptive + usage"). Where it is present in the opposite direction, it provides + additional control on how that payload will be formed or was + processed ("control usage"). + + Implementation of either Block option is intended to be optional. + However, when it is present in a CoAP message, it MUST be processed + (or the message rejected); therefore it is identified as a critical + option. It MUST NOT occur more than once. + +2.2. Structure of a Block Option + + Three items of information may need to be transferred in a Block + (Block1 or Block2) option: + + o The size of the block (SZX); + + o whether more blocks are following (M); + + o the relative number of the block (NUM) within a sequence of blocks + with the given size. + + The value of the Block Option is a variable-size (0 to 3 byte) + unsigned integer (uint, see Section 3.2 of [RFC7252]). This integer + + + +Bormann & Shelby Expires September 10, 2015 [Page 6] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + value encodes these three fields, see Figure 1. (Due to the CoAP + uint encoding rules, when all of NUM, M, and SZX happen to be zero, a + zero-byte integer will be sent.) + + 0 + 0 1 2 3 4 5 6 7 + +-+-+-+-+-+-+-+-+ + | NUM |M| SZX | + +-+-+-+-+-+-+-+-+ + + 0 1 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | NUM |M| SZX | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + 0 1 2 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | NUM |M| SZX | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Figure 1: Block option value + + The block size is encoded using a three-bit unsigned integer (0 for + 2**4 to 6 for 2**10 bytes), which we call the "SZX" ("size + exponent"); the actual block size is then "2**(SZX + 4)". SZX is + transferred in the three least significant bits of the option value + (i.e., "val & 7" where "val" is the value of the option). + + The fourth least significant bit, the M or "more" bit ("val & 8"), + indicates whether more blocks are following or the current block-wise + transfer is the last block being transferred. + + The option value divided by sixteen (the NUM field) is the sequence + number of the block currently being transferred, starting from zero. + The current transfer is therefore about the "size" bytes starting at + byte "NUM << (SZX + 4)". + + Implementation note: As an implementation convenience, "(val & ~0xF) + << (val & 7)", i.e., the option value with the last 4 bits masked + out, shifted to the left by the value of SZX, gives the byte + position of the first byte of the block being transferred. + + More specifically, within the option value of a Block1 or Block2 + Option, the meaning of the option fields is defined as follows: + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 7] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + NUM: Block Number, indicating the block number being requested or + provided. Block number 0 indicates the first block of a body + (i.e., starting with the first byte of the body). + + M: More Flag ("not last block"). For descriptive usage, this flag, + if unset, indicates that the payload in this message is the last + block in the body; when set it indicates that there are one or + more additional blocks available. When a Block2 Option is used in + a request to retrieve a specific block number ("control usage"), + the M bit MUST be sent as zero and ignored on reception. (In a + Block1 Option in a response, the M flag is used to indicate + atomicity, see below.) + + SZX: Block Size. The block size is represented as three-bit + unsigned integer indicating the size of a block to the power of + two. Thus block size = 2**(SZX + 4). The allowed values of SZX + are 0 to 6, i.e., the minimum block size is 2**(0+4) = 16 and the + maximum is 2**(6+4) = 1024. The value 7 for SZX (which would + indicate a block size of 2048) is reserved, i.e. MUST NOT be sent + and MUST lead to a 4.00 Bad Request response code upon reception + in a request. + + There is no default value for the Block1 and Block2 Options. Absence + of one of these options is equivalent to an option value of 0 with + respect to the value of NUM and M that could be given in the option, + i.e. it indicates that the current block is the first and only block + of the transfer (block number 0, M bit not set). However, in + contrast to the explicit value 0, which would indicate an SZX of 0 + and thus a size value of 16 bytes, there is no specific explicit size + implied by the absence of the option -- the size is left unspecified. + (As for any uint, the explicit value 0 is efficiently indicated by a + zero-length option; this, therefore, is different in semantics from + the absence of the option.) + +2.3. Block Options in Requests and Responses + + The Block options are used in one of three roles: + + o In descriptive usage, i.e., a Block2 Option in a response (such as + a 2.05 response for GET), or a Block1 Option in a request (a PUT + or POST): + + * The NUM field in the option value describes what block number + is contained in the payload of this message. + + * The M bit indicates whether further blocks need to be + transferred to complete the transfer of that body. + + + + +Bormann & Shelby Expires September 10, 2015 [Page 8] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + * The block size implied by SZX MUST match the size of the + payload in bytes, if the M bit is set. (SZX does not govern + the payload size if M is unset). For Block2, if the request + suggested a larger value of SZX, the next request MUST move SZX + down to the size given in the response. (The effect is that, + if the server uses the smaller of (1) its preferred block size + and (2) the block size requested, all blocks for a body use the + same block size.) + + o A Block2 Option in control usage in a request (e.g., GET): + + * The NUM field in the Block2 Option gives the block number of + the payload that is being requested to be returned in the + response. + + * In this case, the M bit has no function and MUST be set to + zero. + + * The block size given (SZX) suggests a block size (in the case + of block number 0) or repeats the block size of previous blocks + received (in the case of a non-zero block number). + + o A Block1 Option in control usage in a response (e.g., a 2.xx + response for a PUT or POST request): + + * The NUM field of the Block1 Option indicates what block number + is being acknowledged. + + * If the M bit was set in the request, the server can choose + whether to act on each block separately, with no memory, or + whether to handle the request for the entire body atomically, + or any mix of the two. + + + If the M bit is also set in the response, it indicates that + this response does not carry the final response code to the + request, i.e. the server collects further blocks from the + same endpoint and plans to implement the request atomically + (e.g., acts only upon reception of the last block of + payload). In this case, the response MUST NOT carry a + Block2 option. + + + Conversely, if the M bit is unset even though it was set in + the request, it indicates the block-wise request was enacted + now specifically for this block, and the response carries + the final response to this request (and to any previous ones + with the M bit set in the response's Block1 Option in this + sequence of block-wise transfers); the client is still + + + + +Bormann & Shelby Expires September 10, 2015 [Page 9] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + expected to continue sending further blocks, the request + method for which may or may not also be enacted per-block. + + * Finally, the SZX block size given in a control Block1 Option + indicates the largest block size preferred by the server for + transfers toward the resource that is the same or smaller than + the one used in the initial exchange; the client SHOULD use + this block size or a smaller one in all further requests in the + transfer sequence, even if that means changing the block size + (and possibly scaling the block number accordingly) from now + on. + + Using one or both Block options, a single REST operation can be split + into multiple CoAP message exchanges. As specified in [RFC7252], + each of these message exchanges uses their own CoAP Message ID. + + The Content-Format Option sent with the requests or responses MUST + reflect the content-format of the entire body. If blocks of a + response body arrive with different content-format options, it is up + to the client how to handle this error (it will typically abort any + ongoing block-wise transfer). If blocks of a request arrive at a + server with mismatching content-format options, the server MUST NOT + assemble them into a single request; this usually leads to a 4.08 + (Request Entity Incomplete, Section 2.9.2) error response on the + mismatching block. + +2.4. Using the Block2 Option + + When a request is answered with a response carrying a Block2 Option + with the M bit set, the requester may retrieve additional blocks of + the resource representation by sending further requests with the same + options as the initial request and a Block2 Option giving the block + number and block size desired. In a request, the client MUST set the + M bit of a Block2 Option to zero and the server MUST ignore it on + reception. + + To influence the block size used in a response, the requester MAY + also use the Block2 Option on the initial request, giving the desired + size, a block number of zero and an M bit of zero. A server MUST use + the block size indicated or a smaller size. Any further block-wise + requests for blocks beyond the first one MUST indicate the same block + size that was used by the server in the response for the first + request that gave a desired size using a Block2 Option. + + Once the Block2 Option is used by the requester and a first response + has been received with a possibly adjusted block size, all further + requests in a single block-wise transfer SHOULD ultimately use the + same size, except that there may not be enough content to fill the + + + +Bormann & Shelby Expires September 10, 2015 [Page 10] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + last block (the one returned with the M bit not set). (Note that the + client may start using the Block2 Option in a second request after a + first request without a Block2 Option resulted in a Block2 option in + the response.) The server SHOULD use the block size indicated in the + request option or a smaller size, but the requester MUST take note of + the actual block size used in the response it receives to its initial + request and proceed to use it in subsequent requests. The server + behavior MUST ensure that this client behavior results in the same + block size for all responses in a sequence (except for the last one + with the M bit not set, and possibly the first one if the initial + request did not contain a Block2 Option). + + Block-wise transfers can be used to GET resources the representations + of which are entirely static (not changing over time at all, such as + in a schema describing a device), or for dynamically changing + resources. In the latter case, the Block2 Option SHOULD be used in + conjunction with the ETag Option, to ensure that the blocks being + reassembled are from the same version of the representation: The + server SHOULD include an ETag option in each response. If an ETag + option is available, the client's reassembler, when reassembling the + representation from the blocks being exchanged, MUST compare ETag + Options. If the ETag Options do not match in a GET transfer, the + requester has the option of attempting to retrieve fresh values for + the blocks it retrieved first. To minimize the resulting + inefficiency, the server MAY cache the current value of a + representation for an ongoing sequence of requests. (The server may + identify the sequence by the combination of the requesting end-point + and the URI being the same in each block-wise request.) Note well + that this specification makes no requirement for the server to + establish any state; however, servers that offer quickly changing + resources may thereby make it impossible for a client to ever + retrieve a consistent set of blocks. Clients that want to retrieve + all blocks of a resource SHOULD strive to do so without undue delay. + Servers can fully expect to be free to discard any cached state after + a period of EXCHANGE_LIFETIME ([RFC7252], Section 4.8.2) after the + last access to the state, however, there is no requirement to always + keep the state for as long. + + The Block2 option provides no way for a single endpoint to perform + multiple concurrently proceeding block-wise response payload transfer + (e.g., GET) operations to the same resource. This is rarely a + requirement, but as a workaround, a client may vary the cache key + (e.g., by using one of several URIs accessing resources with the same + semantics, or by varying a proxy-safe elective option). + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 11] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +2.5. Using the Block1 Option + + In a request with a request payload (e.g., PUT or POST), the Block1 + Option refers to the payload in the request (descriptive usage). + + In response to a request with a payload (e.g., a PUT or POST + transfer), the block size given in the Block1 Option indicates the + block size preference of the server for this resource (control + usage). Obviously, at this point the first block has already been + transferred by the client without benefit of this knowledge. Still, + the client SHOULD heed the preference indicated and, for all further + blocks, use the block size preferred by the server or a smaller one. + Note that any reduction in the block size may mean that the second + request starts with a block number larger than one, as the first + request already transferred multiple blocks as counted in the smaller + size. + + To counter the effects of adaptation layer fragmentation on packet + delivery probability, a client may want to give up retransmitting a + request with a relatively large payload even before MAX_RETRANSMIT + has been reached, and try restating the request as a block-wise + transfer with a smaller payload. Note that this new attempt is then + a new message-layer transaction and requires a new Message ID. + (Because of the uncertainty whether the request or the + acknowledgement was lost, this strategy is useful mostly for + idempotent requests.) + + In a block-wise transfer of a request payload (e.g., a PUT or POST) + that is intended to be implemented in an atomic fashion at the + server, the actual creation/replacement takes place at the time the + final block, i.e. a block with the M bit unset in the Block1 Option, + is received. In this case, all success responses to non-final blocks + carry the response code 2.31 (Continue, Section 2.9.1). If not all + previous blocks are available at the server at the time of processing + the final block, the transfer fails and error code 4.08 (Request + Entity Incomplete, Section 2.9.2) MUST be returned. A server MAY + also return a 4.08 error code for any (final or non-final) Block1 + transfer that is not in sequence; clients that do not have specific + mechanisms to handle this case therefore SHOULD always start with + block zero and send the following blocks in order. + + One reason that a client might encounter a 4.08 error code is that + the server has already timed out and discarded the partial request + body being assembled. Clients SHOULD strive to send all blocks of a + request without undue delay. Servers can fully expect to be free to + discard any partial request body when a period of EXCHANGE_LIFETIME + ([RFC7252], Section 4.8.2) has elapsed after the most recent block + + + + +Bormann & Shelby Expires September 10, 2015 [Page 12] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + was transferred; however, there is no requirement on a server to + always keep the partial request body for as long. + + The error code 4.13 (Request Entity Too Large) can be returned at any + time by a server that does not currently have the resources to store + blocks for a block-wise request payload transfer that it would intend + to implement in an atomic fashion. (Note that a 4.13 response to a + request that does not employ Block1 is a hint for the client to try + sending Block1, and a 4.13 response with a smaller SZX in its Block1 + option than requested is a hint to try a smaller SZX.) + + The Block1 option provides no way for a single endpoint to perform + multiple concurrently proceeding block-wise request payload transfer + (e.g., PUT or POST) operations to the same resource. Starting a new + block-wise sequence of requests to the same resource (before an old + sequence from the same endpoint was finished) simply overwrites the + context the server may still be keeping. (This is probably exactly + what one wants in this case - the client may simply have restarted + and lost its knowledge of the previous sequence.) + +2.6. Combining Block-wise Transfers with the Observe Option + + The Observe Option provides a way for a client to be notified about + changes over time of a resource [I-D.ietf-core-observe]. Resources + observed by clients may be larger than can be comfortably processed + or transferred in one CoAP message. The following rules apply to the + combination of block-wise transfers with notifications. + + Observation relationships always apply to an entire resource; the + Block2 option does not provide a way to observe a single block of a + resource. + + As with basic GET transfers, the client can indicate its desired + block size in a Block2 Option in the GET request establishing or + renewing the observation relationship. If the server supports block- + wise transfers, it SHOULD take note of the block size and apply it as + a maximum size to all notifications/responses resulting from the GET + request (until the client is removed from the list of observers or + the entry in that list is updated by the server receiving a new GET + request for the resource from the client). + + When sending a 2.05 (Content) notification, the server only sends the + first block of the representation. The client retrieves the rest of + the representation as if it had caused this first response by a GET + request, i.e., by using additional GET requests with Block2 options + containing NUM values greater than zero. (This results in the + transfer of the entire representation, even if only some of the + blocks have changed with respect to a previous notification.) + + + +Bormann & Shelby Expires September 10, 2015 [Page 13] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + As with other dynamically changing resources, to ensure that the + blocks being reassembled are from the same version of the + representation, the server SHOULD include an ETag option in each + response, and the reassembling client MUST compare the ETag options + (Section 2.4). Even more so than for the general case of Block2, + clients that want to retrieve all blocks of a resource they have been + notified about with a first block SHOULD strive to do so without + undue delay. + + See Section 3.4 for examples. + +2.7. Combining Block1 and Block2 + + In PUT and particularly in POST exchanges, both the request body and + the response body may be large enough to require the use of block- + wise transfers. First, the Block1 transfer of the request body + proceeds as usual. In the exchange of the last slice of this block- + wise transfer, the response carries the first slice of the Block2 + transfer (NUM is zero). To continue this Block2 transfer, the client + continues to send requests similar to the requests in the Block1 + phase, but leaves out the Block1 options and includes a Block2 + request option with non-zero NUM. + + Block2 transfers that retrieve the response body for a request that + used Block1 MUST be performed in sequential order. + +2.8. Combining Block2 with Multicast + + A client can use the Block2 option in a multicast GET request with + NUM = 0 to aid in limiting the size of the response. + + Similarly, a response to a multicast GET request can use a Block2 + option with NUM = 0 if the representation is large, or to further + limit the size of the response. + + In both cases, the client retrieves any further blocks using unicast + exchanges; in the unicast requests, the client SHOULD heed any block + size preferences indicated by the server in the response to the + multicast request. + + Other uses of the Block options in conjunction with multicast + messages are for further study. + +2.9. Response Codes + + Two response codes are defined by this specification beyond those + already defined in [RFC7252], and another response code is extended + in its meaning. + + + +Bormann & Shelby Expires September 10, 2015 [Page 14] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +2.9.1. 2.31 Continue + + This new success status code indicates that the transfer of this + block of the request body was successful and that the server + encourages sending further blocks, but that a final outcome of the + whole block-wise request cannot yet be determined. No payload is + returned with this response code. + +2.9.2. 4.08 Request Entity Incomplete + + This new client error status code indicates that the server has not + received the blocks of the request body that it needs to proceed. + The client has not sent all blocks, not sent them in the order + required by the server, or has sent them long enough ago that the + server has already discarded them. + +2.9.3. 4.13 Request Entity Too Large + + In [RFC7252], section 5.9.2.9, the response code 4.13 (Request Entity + Too Large) is defined to be like HTTP 413 "Request Entity Too Large". + [RFC7252] also recommends that this response SHOULD include a Size1 + Option (Section 4) to indicate the maximum size of request entity the + server is able and willing to handle, unless the server is not in a + position to make this information available. + + The present specification allows the server to return this response + code at any time during a Block1 transfer to indicate that it does + not currently have the resources to store blocks for a transfer that + it would intend to implement in an atomic fashion. It also allows + the server to return a 4.13 response to a request that does not + employ Block1 as a hint for the client to try sending Block1. + Finally, a 4.13 response to a request with a Block1 option (control + usage, see Section 2.3) where the response carries a smaller SZX in + its Block1 option is a hint to try that smaller SZX. + +2.10. Caching Considerations + + This specification attempts to leave a variety of implementation + strategies open for caches, in particular those in caching proxies. + E.g., a cache is free to cache blocks individually, but also could + wait to obtain the complete representation before it serves parts of + it. Partial caching may be more efficient in a cross-proxy + (equivalent to a streaming HTTP proxy). A cached block (partial + cached response) can be used in place of a complete response to + satisfy a block-wise request that is presented to a cache. Note that + different blocks can have different Max-Age values, as they are + transferred at different times. A response with a block updates the + freshness of the complete representation. Individual blocks can be + + + +Bormann & Shelby Expires September 10, 2015 [Page 15] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + validated, and validating a single block validates the complete + representation. A response with a Block1 Option in control usage + with the M bit set invalidates cached responses for the target URI. + + A cache or proxy that combines responses (e.g., to split blocks in a + request or increase the block size in a response, or a cross-proxy) + may need to combine 2.31 and 2.01/2.04 responses; a stateless server + may be responding with 2.01 only on the first Block1 block + transferred, which dominates any 2.04 responses for later blocks. + + If-None-Match only works correctly on Block1 requests with (NUM=0) + and MUST NOT be used on Block1 requests with NUM != 0. + +3. Examples + + This section gives a number of short examples with message flows for + a block-wise GET, and for a PUT or POST. These examples demonstrate + the basic operation, the operation in the presence of + retransmissions, and examples for the operation of the block size + negotiation. + + In all these examples, a Block option is shown in a decomposed way + indicating the kind of Block option (1 or 2) followed by a colon, and + then the block number (NUM), more bit (M), and block size exponent + (2**(SZX+4)) separated by slashes. E.g., a Block2 Option value of 33 + would be shown as 2:2/0/32), or a Block1 Option value of 59 would be + shown as 1:3/1/128. + +3.1. Block2 Examples + + The first example (Figure 2) shows a GET request that is split into + three blocks. The server proposes a block size of 128, and the + client agrees. The first two ACKs contain 128 bytes of payload each, + and third ACK contains between 1 and 128 bytes. + + + + + + + + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 16] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + CLIENT SERVER + | | + | CON [MID=1234], GET, /status ------> | + | | + | <------ ACK [MID=1234], 2.05 Content, 2:0/1/128 | + | | + | CON [MID=1235], GET, /status, 2:1/0/128 ------> | + | | + | <------ ACK [MID=1235], 2.05 Content, 2:1/1/128 | + | | + | CON [MID=1236], GET, /status, 2:2/0/128 ------> | + | | + | <------ ACK [MID=1236], 2.05 Content, 2:2/0/128 | + + Figure 2: Simple block-wise GET + + In the second example (Figure 3), the client anticipates the block- + wise transfer (e.g., because of a size indication in the link-format + description [RFC6690]) and sends a block size proposal. All ACK + messages except for the last carry 64 bytes of payload; the last one + carries between 1 and 64 bytes. + + CLIENT SERVER + | | + | CON [MID=1234], GET, /status, 2:0/0/64 ------> | + | | + | <------ ACK [MID=1234], 2.05 Content, 2:0/1/64 | + | | + | CON [MID=1235], GET, /status, 2:1/0/64 ------> | + | | + | <------ ACK [MID=1235], 2.05 Content, 2:1/1/64 | + : : + : ... : + : : + | CON [MID=1238], GET, /status, 2:4/0/64 ------> | + | | + | <------ ACK [MID=1238], 2.05 Content, 2:4/1/64 | + | | + | CON [MID=1239], GET, /status, 2:5/0/64 ------> | + | | + | <------ ACK [MID=1239], 2.05 Content, 2:5/0/64 | + + Figure 3: Block-wise GET with early negotiation + + In the third example (Figure 4), the client is surprised by the need + for a block-wise transfer, and unhappy with the size chosen + unilaterally by the server. As it did not send a size proposal + initially, the negotiation only influences the size from the second + + + +Bormann & Shelby Expires September 10, 2015 [Page 17] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + message exchange onward. Since the client already obtained both the + first and second 64-byte block in the first 128-byte exchange, it + goes on requesting the third 64-byte block ("2/0/64"). None of this + is (or needs to be) understood by the server, which simply responds + to the requests as it best can. + + CLIENT SERVER + | | + | CON [MID=1234], GET, /status ------> | + | | + | <------ ACK [MID=1234], 2.05 Content, 2:0/1/128 | + | | + | CON [MID=1235], GET, /status, 2:2/0/64 ------> | + | | + | <------ ACK [MID=1235], 2.05 Content, 2:2/1/64 | + | | + | CON [MID=1236], GET, /status, 2:3/0/64 ------> | + | | + | <------ ACK [MID=1236], 2.05 Content, 2:3/1/64 | + | | + | CON [MID=1237], GET, /status, 2:4/0/64 ------> | + | | + | <------ ACK [MID=1237], 2.05 Content, 2:4/1/64 | + | | + | CON [MID=1238], GET, /status, 2:5/0/64 ------> | + | | + | <------ ACK [MID=1238], 2.05 Content, 2:5/0/64 | + + Figure 4: Block-wise GET with late negotiation + + In all these (and the following) cases, retransmissions are handled + by the CoAP message exchange layer, so they don't influence the block + operations (Figure 5, Figure 6). + + + + + + + + + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 18] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + CLIENT SERVER + | | + | CON [MID=1234], GET, /status ------> | + | | + | <------ ACK [MID=1234], 2.05 Content, 2:0/1/128 | + | | + | CON [MID=1235], GE///////////////////////// | + | | + | (timeout) | + | | + | CON [MID=1235], GET, /status, 2:2/0/64 ------> | + | | + | <------ ACK [MID=1235], 2.05 Content, 2:2/1/64 | + : : + : ... : + : : + | CON [MID=1238], GET, /status, 2:5/0/64 ------> | + | | + | <------ ACK [MID=1238], 2.05 Content, 2:5/0/64 | + + Figure 5: Block-wise GET with late negotiation and lost CON + + CLIENT SERVER + | | + | CON [MID=1234], GET, /status ------> | + | | + | <------ ACK [MID=1234], 2.05 Content, 2:0/1/128 | + | | + | CON [MID=1235], GET, /status, 2:2/0/64 ------> | + | | + | //////////////////////////////////tent, 2:2/1/64 | + | | + | (timeout) | + | | + | CON [MID=1235], GET, /status, 2:2/0/64 ------> | + | | + | <------ ACK [MID=1235], 2.05 Content, 2:2/1/64 | + : : + : ... : + : : + | CON [MID=1238], GET, /status, 2:5/0/64 ------> | + | | + | <------ ACK [MID=1238], 2.05 Content, 2:5/0/64 | + + Figure 6: Block-wise GET with late negotiation and lost ACK + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 19] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +3.2. Block1 Examples + + The following examples demonstrate a PUT exchange; a POST exchange + looks the same, with different requirements on atomicity/idempotence. + Note that, similar to GET, the responses to the requests that have a + more bit in the request Block1 Option are provisional and carry the + response code 2.31 (Continue); only the final response tells the + client that the PUT did succeed. + + CLIENT SERVER + | | + | CON [MID=1234], PUT, /options, 1:0/1/128 ------> | + | | + | <------ ACK [MID=1234], 2.31 Continue, 1:0/1/128 | + | | + | CON [MID=1235], PUT, /options, 1:1/1/128 ------> | + | | + | <------ ACK [MID=1235], 2.31 Continue, 1:1/1/128 | + | | + | CON [MID=1236], PUT, /options, 1:2/0/128 ------> | + | | + | <------ ACK [MID=1236], 2.04 Changed, 1:2/0/128 | + + Figure 7: Simple atomic block-wise PUT + + A stateless server that simply builds/updates the resource in place + (statelessly) may indicate this by not setting the more bit in the + response (Figure 8); in this case, the response codes are valid + separately for each block being updated. This is of course only an + acceptable behavior of the server if the potential inconsistency + present during the run of the message exchange sequence does not lead + to problems, e.g. because the resource being created or changed is + not yet or not currently in use. + + + + + + + + + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 20] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + CLIENT SERVER + | | + | CON [MID=1234], PUT, /options, 1:0/1/128 ------> | + | | + | <------ ACK [MID=1234], 2.04 Changed, 1:0/0/128 | + | | + | CON [MID=1235], PUT, /options, 1:1/1/128 ------> | + | | + | <------ ACK [MID=1235], 2.04 Changed, 1:1/0/128 | + | | + | CON [MID=1236], PUT, /options, 1:2/0/128 ------> | + | | + | <------ ACK [MID=1236], 2.04 Changed, 1:2/0/128 | + + Figure 8: Simple stateless block-wise PUT + + Finally, a server receiving a block-wise PUT or POST may want to + indicate a smaller block size preference (Figure 9). In this case, + the client SHOULD continue with a smaller block size; if it does, it + MUST adjust the block number to properly count in that smaller size. + + CLIENT SERVER + | | + | CON [MID=1234], PUT, /options, 1:0/1/128 ------> | + | | + | <------ ACK [MID=1234], 2.31 Continue, 1:0/1/32 | + | | + | CON [MID=1235], PUT, /options, 1:4/1/32 ------> | + | | + | <------ ACK [MID=1235], 2.31 Continue, 1:4/1/32 | + | | + | CON [MID=1236], PUT, /options, 1:5/1/32 ------> | + | | + | <------ ACK [MID=1235], 2.31 Continue, 1:5/1/32 | + | | + | CON [MID=1237], PUT, /options, 1:6/0/32 ------> | + | | + | <------ ACK [MID=1236], 2.04 Changed, 1:6/0/32 | + + Figure 9: Simple atomic block-wise PUT with negotiation + +3.3. Combining Block1 and Block2 + + Block options may be used in both directions of a single exchange. + The following example demonstrates a block-wise POST request, + resulting in a separate block-wise response. + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 21] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + CLIENT SERVER + | | + | CON [MID=1234], POST, /soap, 1:0/1/128 ------> | + | | + | <------ ACK [MID=1234], 2.31 Continue, 1:0/1/128 | + | | + | CON [MID=1235], POST, /soap, 1:1/1/128 ------> | + | | + | <------ ACK [MID=1235], 2.31 Continue, 1:1/1/128 | + | | + | CON [MID=1236], POST, /soap, 1:2/0/128 ------> | + | | + | <------ ACK [MID=1236], 2.04 Changed, 2:0/1/128, 1:2/0/128 | + | | + | CON [MID=1237], POST, /soap, 2:1/0/128 ------> | + | (no payload for requests with Block2 with NUM != 0) | + | (could also do late negotiation by requesting e.g. 2:2/0/64) | + | | + | <------ ACK [MID=1237], 2.04 Changed, 2:1/1/128 | + | | + | CON [MID=1238], POST, /soap, 2:2/0/128 ------> | + | | + | <------ ACK [MID=1238], 2.04 Changed, 2:2/1/128 | + | | + | CON [MID=1239], POST, /soap, 2:3/0/128 ------> | + | | + | <------ ACK [MID=1239], 2.04 Changed, 2:3/0/128 | + + Figure 10: Atomic block-wise POST with block-wise response + + This model does provide for early negotiation input to the Block2 + block-wise transfer, as shown below. + + + + + + + + + + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 22] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + CLIENT SERVER + | | + | CON [MID=1234], POST, /soap, 1:0/1/128 ------> | + | | + | <------ ACK [MID=1234], 2.31 Continue, 1:0/1/128 | + | | + | CON [MID=1235], POST, /soap, 1:1/1/128 ------> | + | | + | <------ ACK [MID=1235], 2.31 Continue, 1:1/1/128 | + | | + | CON [MID=1236], POST, /soap, 1:2/0/128, 2:0/0/64 ------> | + | | + | <------ ACK [MID=1236], 2.04 Changed, 1:2/0/128, 2:0/1/64 | + | | + | CON [MID=1237], POST, /soap, 2:1/0/64 ------> | + | (no payload for requests with Block2 with NUM != 0) | + | | + | <------ ACK [MID=1237], 2.04 Changed, 2:1/1/64 | + | | + | CON [MID=1238], POST, /soap, 2:2/0/64 ------> | + | | + | <------ ACK [MID=1238], 2.04 Changed, 2:2/1/64 | + | | + | CON [MID=1239], POST, /soap, 2:3/0/64 ------> | + | | + | <------ ACK [MID=1239], 2.04 Changed, 2:3/0/64 | + + Figure 11: Atomic block-wise POST with block-wise response, early + negotiation + +3.4. Combining Observe and Block2 + + In the following example, the server first sends a direct response + (Observe sequence number 62350) to the initial GET request (the + resulting block-wise transfer is as in Figure 4 and has therefore + been left out). The second transfer is started by a 2.05 + notification that contains just the first block (Observe sequence + number 62354); the client then goes on to obtain the rest of the + blocks. + + CLIENT SERVER + | | + +----->| Header: GET 0x41011636 + | GET | Token: 0xfb + | | Uri-Path: status-icon + | | Observe: (empty) + | | + |<-----+ Header: 2.05 0x61451636 + + + +Bormann & Shelby Expires September 10, 2015 [Page 23] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + | 2.05 | Token: 0xfb + | | Block2: 0/1/128 + | | Observe: 62350 + | | ETag: 6f00f38e + | | Payload: [128 bytes] + | | + | | (Usual GET transfer left out) + ... + | | (Notification of first block:) + | | + |<-----+ Header: 2.05 0x4145af9c + | 2.05 | Token: 0xfb + | | Block2: 0/1/128 + | | Observe: 62354 + | | ETag: 6f00f392 + | | Payload: [128 bytes] + | | + +- - ->| Header: 0x6000af9c + | | + | | (Retrieval of remaining blocks) + | | + +----->| Header: GET 0x41011637 + | GET | Token: 0xfc + | | Uri-Path: status-icon + | | Block2: 1/0/128 + | | + |<-----+ Header: 2.05 0x61451637 + | 2.05 | Token: 0xfc + | | Block2: 1/1/128 + | | ETag: 6f00f392 + | | Payload: [128 bytes] + | | + +----->| Header: GET 0x41011638 + | GET | Token: 0xfc + | | Uri-Path: status-icon + | | Block2: 2/0/128 + | | + |<-----+ Header: 2.05 0x61451638 + | 2.05 | Token: 0xfc + | | Block2: 2/0/128 + | | ETag: 6f00f392 + | | Payload: [53 bytes] + + + Figure 12: Observe sequence with block-wise response + + (Note that the choice of token 0xfc in this examples is arbitrary; + tokens are just shown in this example to illustrate that the requests + + + +Bormann & Shelby Expires September 10, 2015 [Page 24] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + for additional blocks cannot make use of the token of the Observation + relationship. As a general comment on tokens, there is no other + mention of tokens in this document, as block-wise transfers handle + tokens like any other CoAP exchange. As usual the client is free to + choose tokens for each exchange as it likes.) + + In the following example, the client also uses early negotiation to + limit the block size to 64 bytes. + + CLIENT SERVER + | | + +----->| Header: GET 0x41011636 + | GET | Token: 0xfb + | | Uri-Path: status-icon + | | Observe: (empty) + | | Block2: 0/0/64 + | | + |<-----+ Header: 2.05 0x61451636 + | 2.05 | Token: 0xfb + | | Block2: 0/1/64 + | | Observe: 62350 + | | ETag: 6f00f38e + | | Max-Age: 60 + | | Payload: [64 bytes] + | | + | | (Usual GET transfer left out) + ... + | | (Notification of first block:) + | | + |<-----+ Header: 2.05 0x4145af9c + | 2.05 | Token: 0xfb + | | Block2: 0/1/64 + | | Observe: 62354 + | | ETag: 6f00f392 + | | Payload: [64 bytes] + | | + +- - ->| Header: 0x6000af9c + | | + | | (Retrieval of remaining blocks) + | | + +----->| Header: GET 0x41011637 + | GET | Token: 0xfc + | | Uri-Path: status-icon + | | Block2: 1/0/64 + | | + |<-----+ Header: 2.05 0x61451637 + | 2.05 | Token: 0xfc + | | Block2: 1/1/64 + + + +Bormann & Shelby Expires September 10, 2015 [Page 25] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + | | ETag: 6f00f392 + | | Payload: [64 bytes] + .... + | | + +----->| Header: GET 0x41011638 + | GET | Token: 0xfc + | | Uri-Path: status-icon + | | Block2: 4/0/64 + | | + |<-----+ Header: 2.05 0x61451638 + | 2.05 | Token: 0xfc + | | Block2: 4/0/64 + | | ETag: 6f00f392 + | | Payload: [53 bytes] + + Figure 13: Observe sequence with early negotiation + +4. The Size2 and Size1 Options + + In many cases when transferring a large resource representation block + by block, it is advantageous to know the total size early in the + process. Some indication may be available from the maximum size + estimate attribute "sz" provided in a resource description [RFC6690]. + However, the size may vary dynamically, so a more up-to-date + indication may be useful. + + This specification defines two CoAP Options, Size1 for indicating the + size of the representation transferred in requests, and Size2 for + indicating the size of the representation transferred in responses. + (Size1 is already defined in [RFC7252] for the narrow case of + indicating in 4.13 responses the maximum size of request payload that + the server is able and willing to handle.) + + The Size2 Option may be used for two purposes: + + o in a request, to ask the server to provide a size estimate along + with the usual response ("size request"). For this usage, the + value MUST be set to 0. + + o in a response carrying a Block2 Option, to indicate the current + estimate the server has of the total size of the resource + representation, measured in bytes ("size indication"). + + Similarly, the Size1 Option may be used for two purposes: + + o in a request carrying a Block1 Option, to indicate the current + estimate the client has of the total size of the resource + representation, measured in bytes ("size indication"). + + + +Bormann & Shelby Expires September 10, 2015 [Page 26] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + o in a 4.13 response, to indicate the maximum size that would have + been acceptable [RFC7252], measured in bytes. + + Apart from conveying/asking for size information, the Size options + have no other effect on the processing of the request or response. + If the client wants to minimize the size of the payload in the + resulting response, it should add a Block2 option to the request with + a small block size (e.g., setting SZX=0). + + The Size Options are "elective", i.e., a client MUST be prepared for + the server to ignore the size estimate request. The Size Options + MUST NOT occur more than once. + + +-----+---+---+---+---+-------+--------+--------+---------+ + | No. | C | U | N | R | Name | Format | Length | Default | + +-----+---+---+---+---+-------+--------+--------+---------+ + | 60 | | | x | | Size1 | uint | 0-4 | (none) | + | | | | | | | | | | + | 28 | | | x | | Size2 | uint | 0-4 | (none) | + +-----+---+---+---+---+-------+--------+--------+---------+ + + Table 2: Size Option Numbers + + Implementation Notes: + + o As a quality of implementation consideration, block-wise transfers + for which the total size considerably exceeds the size of one + block are expected to include size indications, whenever those can + be provided without undue effort (preferably with the first block + exchanged). If the size estimate does not change, the indication + does not need to be repeated for every block. + + o The end of a block-wise transfer is governed by the M bits in the + Block Options, _not_ by exhausting the size estimates exchanged. + + o As usual for an option of type uint, the value 0 is best expressed + as an empty option (0 bytes). There is no default value for + either Size Option. + + o The Size Options are neither critical nor unsafe, and are marked + as No-Cache-Key. + +5. HTTP Mapping Considerations + + In this subsection, we give some brief examples for the influence the + Block options might have on intermediaries that map between CoAP and + HTTP. + + + + +Bormann & Shelby Expires September 10, 2015 [Page 27] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + For mapping CoAP requests to HTTP, the intermediary may want to map + the sequence of block-wise transfers into a single HTTP transfer. + E.g., for a GET request, the intermediary could perform the HTTP + request once the first block has been requested and could then + fulfill all further block requests out of its cache. A constrained + implementation may not be able to cache the entire object and may use + a combination of TCP flow control and (in particular if timeouts + occur) HTTP range requests to obtain the information necessary for + the next block transfer at the right time. + + For PUT or POST requests, historically there was more variation in + how HTTP servers might implement ranges; recently, [RFC7233] has + defined that Range header fields received with a request method other + than GET are not to be interpreted. So, in general, the CoAP-to-HTTP + intermediary will have to try sending the payload of all the blocks + of a block-wise transfer for these other methods within one HTTP + request. If enough buffering is available, this request can be + started when the last CoAP block is received. A constrained + implementation may want to relieve its buffering by already starting + to send the HTTP request at the time the first CoAP block is + received; any HTTP 408 status code that indicates that the HTTP + server became impatient with the resulting transfer can then be + mapped into a CoAP 4.08 response code (similarly, 413 maps to 4.13). + + For mapping HTTP to CoAP, the intermediary may want to map a single + HTTP transfer into a sequence of block-wise transfers. If the HTTP + client is too slow delivering a request body on a PUT or POST, the + CoAP server might time out and return a 4.08 response code, which in + turn maps well to an HTTP 408 status code (again, 4.13 maps to 413). + HTTP range requests received on the HTTP side may be served out of a + cache and/or mapped to GET requests that request a sequence of blocks + overlapping the range. + + (Note that, while the semantics of CoAP 4.08 and HTTP 408 differ, + this difference is largely due to the different way the two protocols + are mapped to transport. HTTP has an underlying TCP connection, + which supplies connection state, so a HTTP 408 status code can + immediately be used to indicate that a timeout occurred during + transmitting a request through that active TCP connection. The CoAP + 4.08 response code indicates one or more missing blocks, which may be + due to timeouts or resource constraints; as there is no connection + state, there is no way to deliver such a response immediately; + instead, it is delivered on the next block transfer. Still, HTTP 408 + is probably the best mapping back to HTTP, as the timeout is the most + likely cause for a CoAP 4.08. Note that there is no way to + distinguish a timeout from a missing block for a server without + creating additional state, the need for which we want to avoid.) + + + + +Bormann & Shelby Expires September 10, 2015 [Page 28] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +6. IANA Considerations + + This draft adds the following option numbers to the CoAP Option + Numbers registry of [RFC7252]: + + +--------+--------+-----------+ + | Number | Name | Reference | + +--------+--------+-----------+ + | 23 | Block2 | [RFCXXXX] | + | | | | + | 27 | Block1 | [RFCXXXX] | + | | | | + | 28 | Size2 | [RFCXXXX] | + +--------+--------+-----------+ + + Table 3: CoAP Option Numbers + + This draft adds the following response code to the CoAP Response + Codes registry of [RFC7252]: + + +------+---------------------------+-----------+ + | Code | Description | Reference | + +------+---------------------------+-----------+ + | 2.31 | Continue | [RFCXXXX] | + | | | | + | 4.08 | Request Entity Incomplete | [RFCXXXX] | + +------+---------------------------+-----------+ + + Table 4: CoAP Response Codes + +7. Security Considerations + + Providing access to blocks within a resource may lead to surprising + vulnerabilities. Where requests are not implemented atomically, an + attacker may be able to exploit a race condition or confuse a server + by inducing it to use a partially updated resource representation. + Partial transfers may also make certain problematic data invisible to + intrusion detection systems; it is RECOMMENDED that an intrusion + detection system (IDS) that analyzes resource representations + transferred by CoAP implement the Block options to gain access to + entire resource representations. Still, approaches such as + transferring even-numbered blocks on one path and odd-numbered blocks + on another path, or even transferring blocks multiple times with + different content and obtaining a different interpretation of + temporal order at the IDS than at the server, may prevent an IDS from + seeing the whole picture. These kinds of attacks are well understood + from IP fragmentation and TCP segmentation; CoAP does not add + fundamentally new considerations. + + + +Bormann & Shelby Expires September 10, 2015 [Page 29] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + Where access to a resource is only granted to clients making use of + specific security associations, all blocks of that resource MUST be + subject to the same security checks; it MUST NOT be possible for + unprotected exchanges to influence blocks of an otherwise protected + resource. As a related consideration, where object security is + employed, PUT/POST should be implemented in the atomic fashion, + unless the object security operation is performed on each access and + the creation of unusable resources can be tolerated. + + A stateless server might be susceptible to an attack where the + adversary sends a Block1 (e.g., PUT) block with a high block number: + A naive implementation might exhaust its resources by creating a huge + resource representation. + + Misleading size indications may be used by an attacker to induce + buffer overflows in poor implementations, for which the usual + considerations apply. + +7.1. Mitigating Resource Exhaustion Attacks + + Certain block-wise requests may induce the server to create state, + e.g. to create a snapshot for the block-wise GET of a fast-changing + resource to enable consistent access to the same version of a + resource for all blocks, or to create temporary resource + representations that are collected until pressed into service by a + final PUT or POST with the more bit unset. All mechanisms that + induce a server to create state that cannot simply be cleaned up + create opportunities for denial-of-service attacks. Servers SHOULD + avoid being subject to resource exhaustion based on state created by + untrusted sources. But even if this is done, the mitigation may + cause a denial-of-service to a legitimate request when it is drowned + out by other state-creating requests. Wherever possible, servers + should therefore minimize the opportunities to create state for + untrusted sources, e.g. by using stateless approaches. + + Performing segmentation at the application layer is almost always + better in this respect than at the transport layer or lower (IP + fragmentation, adaptation layer fragmentation), for instance because + there is application layer semantics that can be used for mitigation + or because lower layers provide security associations that can + prevent attacks. However, it is less common to apply timeouts and + keepalive mechanisms at the application layer than at lower layers. + Servers MAY want to clean up accumulated state by timing it out (cf. + response code 4.08), and clients SHOULD be prepared to run block-wise + transfers in an expedient way to minimize the likelihood of running + into such a timeout. + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 30] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +7.2. Mitigating Amplification Attacks + + [RFC7252] discusses the susceptibility of CoAP end-points for use in + amplification attacks. + + A CoAP server can reduce the amount of amplification it provides to + an attacker by offering large resource representations only in + relatively small blocks. With this, e.g., for a 1000 byte resource, + a 10-byte request might result in an 80-byte response (with a 64-byte + block) instead of a 1016-byte response, considerably reducing the + amplification provided. + +8. Acknowledgements + + Much of the content of this draft is the result of discussions with + the [RFC7252] authors, and via many CoRE WG discussions. + + Charles Palmer provided extensive editorial comments to a previous + version of this draft, some of which the authors hope to have covered + in this version. Esko Dijk reviewed a more recent version, leading + to a number of further editorial improvements, a solution to the 4.13 + ambiguity problem, and the section about combining Block and + multicast. Markus Becker proposed getting rid of an ill-conceived + default value for the Block2 and Block1 options. Peter Bigot + insisted on a more systematic coverage of the options and response + code. + + Kepeng Li, Linyi Tian, and Barry Leiba wrote up an early version of + the Size Option, which has informed this draft. Klaus Hartke wrote + some of the text describing the interaction of Block2 with Observe. + Matthias Kovatsch provided a number of significant simplifications of + the protocol. + +9. References + +9.1. Normative References + + [I-D.ietf-core-observe] + Hartke, K., "Observing Resources in CoAP", draft-ietf- + core-observe-16 (work in progress), December 2014. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC7252] Shelby, Z., Hartke, K., and C. Bormann, "The Constrained + Application Protocol (CoAP)", RFC 7252, June 2014. + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 31] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + +9.2. Informative References + + [REST] Fielding, R., "Architectural Styles and the Design of + Network-based Software Architectures", Ph.D. Dissertation, + University of California, Irvine, 2000, + . + + [RFC4919] Kushalnagar, N., Montenegro, G., and C. Schumacher, "IPv6 + over Low-Power Wireless Personal Area Networks (6LoWPANs): + Overview, Assumptions, Problem Statement, and Goals", RFC + 4919, August 2007. + + [RFC4944] Montenegro, G., Kushalnagar, N., Hui, J., and D. Culler, + "Transmission of IPv6 Packets over IEEE 802.15.4 + Networks", RFC 4944, September 2007. + + [RFC6690] Shelby, Z., "Constrained RESTful Environments (CoRE) Link + Format", RFC 6690, August 2012. + + [RFC7228] Bormann, C., Ersue, M., and A. Keranen, "Terminology for + Constrained-Node Networks", RFC 7228, May 2014. + + [RFC7230] Fielding, R. and J. Reschke, "Hypertext Transfer Protocol + (HTTP/1.1): Message Syntax and Routing", RFC 7230, June + 2014. + + [RFC7233] Fielding, R., Lafon, Y., and J. Reschke, "Hypertext + Transfer Protocol (HTTP/1.1): Range Requests", RFC 7233, + June 2014. + +Authors' Addresses + + Carsten Bormann + Universitaet Bremen TZI + Postfach 330440 + Bremen D-28359 + Germany + + Phone: +49-421-218-63921 + Email: cabo@tzi.org + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 32] + +Internet-Draft Block-wise transfers in CoAP March 2015 + + + Zach Shelby (editor) + ARM + 150 Rose Orchard + San Jose, CA 95134 + USA + + Phone: +1-408-203-9434 + Email: zach.shelby@arm.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Bormann & Shelby Expires September 10, 2015 [Page 33] diff --git a/rfc/draft-ietf-core-observe-16.txt b/rfc/draft-ietf-core-observe-16.txt new file mode 100644 index 0000000..2494f43 --- /dev/null +++ b/rfc/draft-ietf-core-observe-16.txt @@ -0,0 +1,1904 @@ + + + +CoRE Working Group K. Hartke +Internet-Draft Universitaet Bremen TZI +Intended status: Standards Track December 30, 2014 +Expires: July 3, 2015 + + + Observing Resources in CoAP + draft-ietf-core-observe-16 + +Abstract + + The Constrained Application Protocol (CoAP) is a RESTful application + protocol for constrained nodes and networks. The state of a resource + on a CoAP server can change over time. This document specifies a + simple protocol extension for CoAP that enables CoAP clients to + "observe" resources, i.e., to retrieve a representation of a resource + and keep this representation updated by the server over a period of + time. The protocol follows a best-effort approach for sending new + representations to clients and provides eventual consistency between + the state observed by each client and the actual resource state at + the server. + +Status of This Memo + + This Internet-Draft is submitted in full conformance with the + provisions of BCP 78 and BCP 79. + + Internet-Drafts are working documents of the Internet Engineering + Task Force (IETF). Note that other groups may also distribute + working documents as Internet-Drafts. The list of current Internet- + Drafts is at http://datatracker.ietf.org/drafts/current/. + + Internet-Drafts are draft documents valid for a maximum of six months + and may be updated, replaced, or obsoleted by other documents at any + time. It is inappropriate to use Internet-Drafts as reference + material or to cite them other than as "work in progress." + + This Internet-Draft will expire on July 3, 2015. + +Copyright Notice + + Copyright (c) 2014 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + + + +Hartke Expires July 3, 2015 [Page 1] + +Internet-Draft Observing Resources in CoAP December 2014 + + + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 3 + 1.1. Background . . . . . . . . . . . . . . . . . . . . . . . . 3 + 1.2. Protocol Overview . . . . . . . . . . . . . . . . . . . . 3 + 1.3. Consistency Model . . . . . . . . . . . . . . . . . . . . 5 + 1.4. Observable Resources . . . . . . . . . . . . . . . . . . . 6 + 1.5. Requirements Notation . . . . . . . . . . . . . . . . . . 7 + 2. The Observe Option . . . . . . . . . . . . . . . . . . . . . . 7 + 3. Client-side Requirements . . . . . . . . . . . . . . . . . . . 8 + 3.1. Request . . . . . . . . . . . . . . . . . . . . . . . . . 8 + 3.2. Notifications . . . . . . . . . . . . . . . . . . . . . . 8 + 3.3. Caching . . . . . . . . . . . . . . . . . . . . . . . . . 9 + 3.4. Reordering . . . . . . . . . . . . . . . . . . . . . . . . 10 + 3.5. Transmission . . . . . . . . . . . . . . . . . . . . . . . 11 + 3.6. Cancellation . . . . . . . . . . . . . . . . . . . . . . . 11 + 4. Server-side Requirements . . . . . . . . . . . . . . . . . . . 12 + 4.1. Request . . . . . . . . . . . . . . . . . . . . . . . . . 12 + 4.2. Notifications . . . . . . . . . . . . . . . . . . . . . . 13 + 4.3. Caching . . . . . . . . . . . . . . . . . . . . . . . . . 13 + 4.4. Reordering . . . . . . . . . . . . . . . . . . . . . . . . 14 + 4.5. Transmission . . . . . . . . . . . . . . . . . . . . . . . 15 + 5. Intermediaries . . . . . . . . . . . . . . . . . . . . . . . . 18 + 6. Web Linking . . . . . . . . . . . . . . . . . . . . . . . . . 19 + 7. Security Considerations . . . . . . . . . . . . . . . . . . . 19 + 8. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 20 + 9. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 20 + 10. References . . . . . . . . . . . . . . . . . . . . . . . . . . 21 + 10.1. Normative References . . . . . . . . . . . . . . . . . . . 21 + 10.2. Informative References . . . . . . . . . . . . . . . . . . 21 + Appendix A. Examples . . . . . . . . . . . . . . . . . . . . . . 22 + A.1. Client/Server Examples . . . . . . . . . . . . . . . . . . 22 + A.2. Proxy Examples . . . . . . . . . . . . . . . . . . . . . . 26 + Appendix B. Changelog . . . . . . . . . . . . . . . . . . . . . . 28 + + + + + + + + + + + +Hartke Expires July 3, 2015 [Page 2] + +Internet-Draft Observing Resources in CoAP December 2014 + + +1. Introduction + +1.1. Background + + The Constrained Application Protocol (CoAP) [RFC7252] is intended to + provide RESTful services [REST] not unlike HTTP [RFC7230] while + reducing the complexity of implementation as well as the size of + packets exchanged in order to make these services useful in a highly + constrained network of themselves highly constrained nodes [RFC7228]. + + The model of REST is that of a client exchanging representations of + resources with a server, where a representation captures the current + or intended state of a resource. The server is the authority for + representations of the resources in its namespace. A client + interested in the state of a resource initiates a request to the + server, the server then returns a response with a representation of + the resource that is current at the time of the request. + + This model does not work well when a client is interested in having a + current representation of a resource over a period of time. Existing + approaches from HTTP, such as repeated polling or HTTP long polling + [RFC6202], generate significant complexity and/or overhead and thus + are less applicable in a constrained environment. + + The protocol specified in this document extends the CoAP core + protocol with a mechanism for a CoAP client to "observe" a resource + on a CoAP server: the client retrieves a representation of the + resource and requests this representation be updated by the server + as long as the client is interested in the resource. + + The protocol keeps the architectural properties of REST. It enables + high scalability and efficiency through the support of caches and + proxies. There is no intention, though, to solve the full set of + problems that the existing HTTP solutions solve, or to replace + publish/subscribe networks that solve a much more general problem + [RFC5989]. + +1.2. Protocol Overview + + The protocol is based on the well-known observer design pattern + [GOF]. In this design pattern, components called "observers" + register at a specific, known provider called the "subject" that they + are interested in being notified whenever the subject undergoes a + change in state. The subject is responsible for administering its + list of registered observers. If multiple subjects are of interest + to an observer, the observer must register separately for all of + them. + + + + +Hartke Expires July 3, 2015 [Page 3] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Observer Subject + | | + | Registration | + +------------------->| + | | + | Notification | + |<-------------------+ + | | + | Notification | + |<-------------------+ + | | + | Notification | + |<-------------------+ + | | + + Figure 1: The Observer Design Pattern + + The observer design pattern is realized in CoAP as follows: + + Subject: In the context of CoAP, the subject is a resource in the + namespace of a CoAP server. The state of the resource can change + over time, ranging from infrequent updates to continuous state + transformations. + + Observer: An observer is a CoAP client that is interested in having + a current representation of the resource at any given time. + + Registration: A client registers its interest in a resource by + initiating an extended GET request to the server. In addition to + returning a representation of the target resource, this request + causes the server to add the client to the list of observers of + the resource. + + Notification: Whenever the state of a resource changes, the server + notifies each client in the list of observers of the resource. + Each notification is an additional CoAP response sent by the + server in reply to the single extended GET request, and includes a + complete, updated representation of the new resource state. + + Figure 2 below shows an example of a CoAP client registering its + interest in a resource and receiving three notifications: the first + with the current state upon registration, and then two upon changes + to the resource state. Both the registration request and the + notifications are identified as such by the presence of the Observe + Option defined in this document. In notifications, the Observe + Option additionally provides a sequence number for reordering + detection. All notifications carry the token specified by the + client, so the client can easily correlate them to the request. + + + +Hartke Expires July 3, 2015 [Page 4] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Client Server + | | + | GET /temperature | + | Token: 0x4a | Registration + | Observe: 0 | + +------------------->| + | | + | 2.05 Content | + | Token: 0x4a | Notification of + | Observe: 12 | the current state + | Payload: 22.9 Cel | + |<-------------------+ + | | + | 2.05 Content | + | Token: 0x4a | Notification upon + | Observe: 44 | a state change + | Payload: 22.8 Cel | + |<-------------------+ + | | + | 2.05 Content | + | Token: 0x4a | Notification upon + | Observe: 60 | a state change + | Payload: 23.1 Cel | + |<-------------------+ + | | + + Figure 2: Observing a Resource in CoAP + + A client remains on the list of observers as long as the server can + determine the client's continued interest in the resource. The + server may send a notification in a confirmable CoAP message to + request an acknowledgement from the client. When the client + deregisters, rejects a notification, or the transmission of a + notification times out after several transmission attempts, the + client is considered no longer interested in the resource and is + removed by the server from the list of observers. + +1.3. Consistency Model + + While a client is in the list of observers of a resource, the goal of + the protocol is to keep the resource state observed by the client as + closely in sync with the actual state at the server as possible. + + It cannot be avoided that the client and the server become out of + sync at times: First, there is always some latency between the change + of the resource state and the receipt of the notification. Second, + CoAP messages with notifications can get lost, which will cause the + client to assume an old state until it receives a new notification. + + + +Hartke Expires July 3, 2015 [Page 5] + +Internet-Draft Observing Resources in CoAP December 2014 + + + And third, the server may erroneously come to the conclusion that the + client is no longer interested in the resource, which will cause the + server to stop sending notifications and the client to assume an old + state until it eventually registers its interest again. + + The protocol addresses this issue as follows: + + o It follows a best-effort approach for sending the current + representation to the client after a state change: Clients should + see the new state after a state change as soon as possible, and + they should see as many states as possible. This is limited by + congestion control, however, so a client cannot rely on observing + every single state that a resource might go through. + + o It labels notifications with a maximum duration up to which it is + acceptable for the observed state and the actual state to be out + of sync. When the age of the notification received reaches this + limit, the client cannot use the enclosed representation until it + receives a new notification. + + o It is designed on the principle of eventual consistency: The + protocol guarantees that, if the resource does not undergo a new + change in state, eventually all registered observers will have a + current representation of the latest resource state. + +1.4. Observable Resources + + A CoAP server is the authority for determining under what conditions + resources change their state and thus when observers are notified of + new resource states. The protocol does not offer explicit means for + setting up triggers or thresholds; it is up to the server to expose + observable resources that change their state in a way that is useful + in the application context. + + For example, a CoAP server with an attached temperature sensor could + expose one or more of the following resources: + + o , which changes its state every few + seconds to a current reading of the temperature sensor; + + o , which changes its state to + "COLD" whenever the temperature reading drops below a certain pre- + configured threshold, and to "WARM" whenever the reading exceeds a + second, slightly higher threshold; + + o , which changes its + state based on the client-specified parameter value: every few + seconds to the current temperature reading if the temperature + + + +Hartke Expires July 3, 2015 [Page 6] + +Internet-Draft Observing Resources in CoAP December 2014 + + + exceeds the threshold, or to "OK" when the reading drops below; + + o , which accepts expressions of arbitrary complexity + and changes its state accordingly. + + Thus, by designing CoAP resources that change their state on certain + conditions, it is possible to update the client only when these + conditions occur instead of supplying it continuously with raw sensor + data. By parameterizing resources, this is not limited to conditions + defined by the server, but can be extended to arbitrarily complex + queries specified by the client. The application designer therefore + can choose exactly the right level of complexity for the application + envisioned and devices involved, and is not constrained to a "one + size fits all" mechanism built into the protocol. + +1.5. Requirements Notation + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in RFC 2119 [RFC2119]. + +2. The Observe Option + + The Observe Option has the following properties. Its meaning depends + on whether it is included in a GET request or in a response. + + +-----+---+---+---+---+---------+--------+--------+---------+ + | No. | C | U | N | R | Name | Format | Length | Default | + +-----+---+---+---+---+---------+--------+--------+---------+ + | 6 | | x | - | | Observe | uint | 0-3 B | (none) | + +-----+---+---+---+---+---------+--------+--------+---------+ + + C=Critical, U=Unsafe, N=No-Cache-Key, R=Repeatable + + Table 1: The Observe Option + + When included in a GET request, the Observe Option extends the GET + method so it does not only retrieve a current representation of the + target resource, but also requests the server to add or remove an + entry in the list of observers of the resource, depending on the + option value. The list entry consists of the client endpoint and the + token specified by the client in the request. Possible values are: + + 0 (register) adds the entry to the list, if not present; + + 1 (deregister) removes the entry from the list, if present. + + + + +Hartke Expires July 3, 2015 [Page 7] + +Internet-Draft Observing Resources in CoAP December 2014 + + + The Observe Option is not critical for processing the request. If + the server is unwilling or unable to add a new entry to the list of + observers, then the request falls back to a normal GET request, and + the response does not include the Observe Option. + + The Observe Option is not part of the cache-key: a cacheable response + obtained with an Observe Option in the request can be used to satisfy + a request without an Observe Option, and vice versa. When a stored + response with an Observe Option is used to satisfy a normal GET + request, the option MUST be removed before the response is returned. + + When included in a response, the Observe Option identifies the + message as a notification. This implies that a matching entry exists + in the list of observers and that the server will notify the client + of changes to the resource state. The option value is a sequence + number for reordering detection (see Section 3.4 and Section 4.4). + + The value of the Observe Option is encoded as an unsigned integer in + network byte order using a variable number of bytes ('uint' option + format); see Section 3.2 of RFC 7252 [RFC7252]. + +3. Client-side Requirements + +3.1. Request + + A client registers its interest in a resource by issuing a GET + request with an Observe Option set to 0 (register). If the server + returns a 2.xx response that includes an Observe Option as well, the + server has successfully added an entry with the client endpoint and + request token to the list of observers of the target resource and the + client will be notified of changes to the resource state. + + Like a fresh response can be used to satisfy a request without + contacting the server, the stream of updates resulting from one + observation request can be used to satisfy another (observation or + normal GET) request if the target resource is the same. A client + MUST aggregate such requests and MUST NOT register more than once for + the same target resource. The target resource is identified by all + options in the request that are part of the cache-key. This + includes, for example, the full request URI and the Accept Option. + +3.2. Notifications + + Notifications are additional responses sent by the server in reply to + the single extended GET request that created the registration. Each + notification includes the token specified by the client in the + request. The only difference between a notification and a normal + response is the presence of the Observe Option. + + + +Hartke Expires July 3, 2015 [Page 8] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Notifications typically have a 2.05 (Content) response code. They + include an Observe Option with a sequence number for reordering + detection (see Section 3.4), and a payload in the same Content-Format + as the initial response. If the client included one or more ETag + Options in the GET request (see Section 3.3), notifications can have + a 2.03 (Valid) response code rather than a 2.05 (Content) response + code. Such notifications include an Observe Option with a sequence + number but no payload. + + In the event that the resource changes in a way that would cause a + normal GET request at that time to return a non-2.xx response (for + example, when the resource is deleted), the server sends a + notification with an appropriate response code (such as 4.04 Not + Found) and removes the client's entry from the list of observers of + the resource. Non-2.xx responses do not include an Observe Option. + +3.3. Caching + + As notifications are just additional responses to a GET request, + notifications partake in caching as defined in Section 5.6 of RFC + 7252 [RFC7252]. Both the freshness model and the validation model + are supported. + +3.3.1. Freshness + + A client MAY store a notification like a response in its cache and + use a stored notification that is fresh without contacting the + server. Like a response, a notification is considered fresh while + its age is not greater than the value indicated by the Max-Age Option + (and no newer notification/response has been received). + + The server will do its best to keep the resource state observed by + the client as closely in sync with the actual state as possible. + However, a client cannot rely on observing every single state that a + resource might go through. For example, if the network is congested + or the state changes more frequently than the network can handle, the + server can skip notifications for any number of intermediate states. + + The server uses the Max-Age Option to indicate an age up to which it + is acceptable that the observed state and the actual state are + inconsistent. If the age of the latest notification becomes greater + than its indicated Max-Age, then the client MUST NOT assume that the + enclosed representation reflects the actual resource state. + + To make sure it has a current representation and/or to re-register + its interest in a resource, a client MAY issue a new GET request with + the same token as the original at any time. All options MUST be + identical to those in the original request, except for the set of + + + +Hartke Expires July 3, 2015 [Page 9] + +Internet-Draft Observing Resources in CoAP December 2014 + + + ETag Options. It is RECOMMENDED that the client does not issue the + request while it still has a fresh notification/response for the + resource in its cache. Additionally, the client SHOULD at least wait + for a random amount of time between 5 and 15 seconds after Max-Age + expired to reduce collisions with other clients. + +3.3.2. Validation + + When a client has one or more notifications stored in its cache for a + resource, it can use the ETag Option in the GET request to give the + server an opportunity to select a stored notification to be used. + + The client MAY include an ETag Option for each stored response that + is applicable in the GET request. Whenever the observed resource + changes to a representation identified by one of the ETag Options, + the server can select a stored response by sending a 2.03 (Valid) + notification with an appropriate ETag Option instead of a 2.05 + (Content) notification. + + A client implementation needs to keep all candidate responses in its + cache until it is no longer interested in the target resource or it + re-registers with a new set of entity-tags. + +3.4. Reordering + + Messages with notifications can arrive in a different order than they + were sent. Since the goal is to keep the observed state as closely + in sync with the actual state as possible, a client MUST consider the + notification that was sent most recently as the freshest, regardless + of the order of arrival. + + To provide an order among notifications for the client, the server + sets the value of the Observe Option in each notification to the 24 + least-significant bits of a strictly increasing sequence number. An + incoming notification was sent more recently than the freshest + notification so far when one of the following conditions is met: + + (V1 < V2 and V2 - V1 < 2^23) or + (V1 > V2 and V1 - V2 > 2^23) or + (T2 > T1 + 128 seconds) + + where V1 is the value of the Observe Option in the freshest + notification so far, V2 the value of the Observe Option in the + incoming notification, T1 a client-local timestamp for the freshest + notification so far, and T2 a client-local timestamp for the incoming + notification. + + + + + +Hartke Expires July 3, 2015 [Page 10] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Design Note: The first two conditions verify that V1 is less than V2 + in 24-bit serial number arithmetic [RFC1982]. The third condition + ensures that, if the server is generating serial numbers based on + a local clock, the time elapsed between the two incoming messages + is not so large that the difference between V1 and V2 has become + larger than the largest integer that it is meaningful to add to a + 24-bit serial number; in other words, after 128 seconds have + elapsed without any notification, a client does not need to check + the sequence numbers to assume that an incoming notification was + sent more recently than the freshest notification it has received + so far. + + The duration of 128 seconds was chosen as a nice round number + greater than MAX_LATENCY (Section 4.8.2 of RFC 7252 [RFC7252]). + +3.5. Transmission + + A notification can be confirmable or non-confirmable, i.e., it can be + sent in a confirmable or a non-confirmable message. The message type + used for a notification is independent of the type used for the + request and of any previous notification. + + If a client does not recognize the token in a confirmable + notification, it MUST NOT acknowledge the message and SHOULD reject + it with a Reset message; otherwise, the client MUST acknowledge the + message as usual. In the case of a non-confirmable notification, + rejecting the message with a Reset message is OPTIONAL. + + An acknowledgement message signals to the server that the client is + alive and interested in receiving further notifications; if the + server does not receive an acknowledgement in reply to a confirmable + notification, it will assume that the client is no longer interested + and will eventually remove the associated entry from the list of + observers. + +3.6. Cancellation + + A client that is no longer interested in receiving notifications for + a resource can simply "forget" the observation. When the server then + sends the next notification, the client will not recognize the token + in the message and thus will return a Reset message. This causes the + server to remove the associated entry from the list of observers. + The entries in lists of observers are effectively "garbage collected" + by the server. + + + + + + + +Hartke Expires July 3, 2015 [Page 11] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Implementation Note: Due to potential message loss, the Reset + message may not reach the server. The client may therefore have + to reject multiple notifications, each with one Reset message, + until the server finally removes the associated entry from the + list of observers and stops sending notifications. + + In some circumstances, it may be desirable to cancel an observation + and release the resources allocated by the server to it more eagerly. + In this case, a client MAY explicitly deregister by issuing a GET + request which has the Token field set to the token of the observation + to be cancelled and includes an Observe Option with the value set to + 1 (deregister). All other options MUST be identical to those in the + registration request, except for the set of ETag Options. When the + server receives such a request, it will remove any matching entry + from the list of observers and process the GET request as usual. + +4. Server-side Requirements + +4.1. Request + + A GET request with an Observe Option set to 0 (register) requests the + server not only to return a current representation of the target + resource, but also to add the client to the list of observers of that + resource. Upon success, the server returns a current representation + of the resource and MUST keep this representation updated (as + described in Section 1.3) as long as the client is on the list of + observers. + + The entry in the list of observers is keyed by the client endpoint + and the token specified by the client in the request. If an entry + with a matching endpoint/token pair is already present in the list + (which, for example, happens when the client wishes to reinforce its + interest in a resource), the server MUST NOT add a new entry but MUST + replace or update the existing one. + + A server that is unable or unwilling to add a new entry to the list + of observers of a resource MAY silently ignore the registration + request and process the GET request as usual. The resulting response + MUST NOT include an Observe Option, the absence of which signals to + the client that it will not be notified of changes to the resource + and, e.g., needs to poll the resource for its state instead. + + If the Observe Option in a GET request is set to 1 (deregister), then + the server MUST remove any existing entry with a matching endpoint/ + token pair from the list of observers and process the GET request as + usual. The resulting response MUST NOT include an Observe Option. + + + + + +Hartke Expires July 3, 2015 [Page 12] + +Internet-Draft Observing Resources in CoAP December 2014 + + +4.2. Notifications + + A client is notified of changes to the resource state by additional + responses sent by the server in reply to the GET request. Each such + notification response (including the initial response) MUST echo the + token specified by the client in the GET request. If there are + multiple entries in the list of observers, the order in which the + clients are notified is not defined; the server is free to use any + method to determine the order. + + A notification SHOULD have a 2.05 (Content) or 2.03 (Valid) response + code. However, in the event that the state of a resource changes in + a way that would cause a normal GET request at that time to return a + non-2.xx response (for example, when the resource is deleted), the + server SHOULD notify the client by sending a notification with an + appropriate response code (such as 4.04 Not Found) and subsequently + MUST remove the associated entry from the list of observers of the + resource. + + The Content-Format specified in a 2.xx notification MUST be the same + as the one used in the initial response to the GET request. If the + server is unable to continue sending notifications in this format, it + SHOULD send a notification with a 4.06 (Not Acceptable) response code + and subsequently MUST remove the associated entry from the list of + observers of the resource. + + A 2.xx notification MUST include an Observe Option with a sequence + number as specified in Section 4.4 below; a non-2.xx notification + MUST NOT include an Observe Option. + +4.3. Caching + + As notifications are just additional responses sent by the server in + reply to a GET request, they are subject to caching as defined in + Section 5.6 of RFC 7252 [RFC7252]. + +4.3.1. Freshness + + After returning the initial response, the server MUST keep the + resource state that is observed by the client as closely in sync with + the actual resource state as possible. + + Since becoming out of sync at times cannot be avoided, the server + MUST indicate for each representation an age up to which it is + acceptable that the observed state and the actual state are + inconsistent. This age is application-dependent and MUST be + specified in notifications using the Max-Age Option. + + + + +Hartke Expires July 3, 2015 [Page 13] + +Internet-Draft Observing Resources in CoAP December 2014 + + + When the resource does not change and the client has a current + representation, the server does not need to send a notification. + However, if the client does not receive a notification, the client + cannot tell if the observed state and the actual state are still in + sync. Thus, when the age of the latest notification becomes greater + than its indicated Max-Age, the client no longer has a usable + representation of the resource state. The server MAY wish to prevent + that by sending a new notification with the unchanged representation + and a new Max-Age just before the Max-Age indicated earlier expires. + +4.3.2. Validation + + A client can include a set of entity-tags in its request using the + ETag Option. When a observed resource changes its state and the + origin server is about to send a 2.05 (Content) notification, then, + whenever that notification has an entity-tag in the set of entity- + tags specified by the client, the server MAY send a 2.03 (Valid) + response with an appropriate ETag Option instead. + +4.4. Reordering + + Because messages can get reordered, the client needs a way to + determine if a notification arrived later than a newer notification. + For this purpose, the server MUST set the value of the Observe Option + of each notification it sends to the 24 least-significant bits of a + strictly increasing sequence number. The sequence number MAY start + at any value and MUST NOT increase so fast that it increases by more + than 2^23 within less than 256 seconds. + + The sequence number selected for a notification MUST be greater than + that of any preceding notification sent to the same client with the + same token for the same resource. The value of the Observe Option + MUST be current at the time of transmission; if a notification is + retransmitted, the server MUST update the value of the option to the + sequence number that is current at that time before retransmission. + + Implementation Note: A simple implementation that satisfies the + requirements is to obtain a timestamp from a local clock. The + sequence number then is the timestamp in ticks, where 1 tick = + (256 seconds)/(2^23) = 30.52 microseconds. It is not necessary + that the clock reflects the current time/date. + + Another valid implementation is to store a 24-bit unsigned integer + variable per resource and increment this variable each time the + resource undergoes a change of state (provided that the resource + changes its state less than 2^23 times in the first 256 seconds + after every state change). This removes the need to update the + value of the Observe Option on retransmission when the resource + + + +Hartke Expires July 3, 2015 [Page 14] + +Internet-Draft Observing Resources in CoAP December 2014 + + + state did not change. + + Design Note: The choice of a 24-bit option value and a time span of + 256 seconds theoretically allows for a notification rate of up to + 65536 notifications per second. Constrained nodes often have + rather imprecise clocks, though, and inaccuracies of the client + and server side may cancel out or add in effect. Therefore, the + maximum notification rate is reduced to 32768 notifications per + second. This is still well beyond the highest known design + objective of around 1 kHz (most CoAP applications will be several + orders of magnitude below that), but allows total clock + inaccuracies of up to -50/+100 %. + +4.5. Transmission + + A notification can be sent in a confirmable or a non-confirmable + message. The message type used is typically application-dependent + and may be determined by the server for each notification + individually. + + For example, for resources that change in a somewhat predictable or + regular fashion, notifications can be sent in non-confirmable + messages; for resources that change infrequently, notifications can + be sent in confirmable messages. The server can combine these two + approaches depending on the frequency of state changes and the + importance of individual notifications. + + A server MAY choose to skip sending a notification if it knows that + it will send another notification soon, for example, when the state + of a resource is changing frequently. It also MAY choose to send + more than one notification for the same resource state. However, + above all, the server MUST ensure that a client in the list of + observers of a resource eventually observes the latest state if the + resource does not undergo a new change in state. + + For example, when state changes occur in bursts, the server can skip + some notifications, send the notifications in non-confirmable + messages, and make sure that the client observes the latest state + change by repeating the last notification in a confirmable message + when the burst is over. + + The client's acknowledgement of a confirmable notification signals + that the client is interested in receiving further notifications. If + a client rejects a confirmable or non-confirmable notification with a + Reset message, or if the last attempt to retransmit a confirmable + notification times out, then the client is considered no longer + interested and the server MUST remove the associated entry from the + list of observers. + + + +Hartke Expires July 3, 2015 [Page 15] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Implementation Note: To properly process a Reset message that + rejects a non-confirmable notification, a server needs to remember + the message IDs of the non-confirmable notifications it sends. + This may be challenging for a server with constrained resources. + However, since Reset messages are transmitted unreliably, the + client must be prepared that its Reset messages aren't received by + the server. A server thus can always pretend that a Reset message + rejecting a non-confirmable notification was lost. If a server + does this, it could accelerate cancellation by sending the + following notifications to that client in confirmable messages. + + A server that transmits notifications mostly in non-confirmable + messages MUST send a notification in a confirmable message instead of + a non-confirmable message at least every 24 hours. This prevents a + client that went away or is no longer interested from remaining in + the list of observers indefinitely. + +4.5.1. Congestion Control + + Basic congestion control for CoAP is provided by the exponential + back-off mechanism in Section 4.2 of RFC 7252 [RFC7252] and the + limitations in Section 4.7 of RFC 7252 [RFC7252]. However, CoAP + places the responsibility of congestion control for simple request/ + response interactions only on the clients: rate limiting request + transmission implicitly controls the transmission of the responses. + When a single request yields a potentially infinite number of + notifications, additional responsibility needs to be placed on the + server. + + In order not to cause congestion, servers MUST strictly limit the + number of simultaneous outstanding notifications/responses that they + transmit to a given client to NSTART (1 by default; see Section 4.7 + of RFC 7252 [RFC7252]). An outstanding notification/response is + either a confirmable message for which an acknowledgement has not yet + been received and whose last retransmission attempt has not yet timed + out, or a non-confirmable message for which the waiting time that + results from the following rate limiting rules has not yet elapsed. + + The server SHOULD NOT send more than one non-confirmable notification + per round-trip time (RTT) to a client on average. If the server + cannot maintain an RTT estimate for a client, it SHOULD NOT send more + than one non-confirmable notification every 3 seconds, and SHOULD use + an even less aggressive rate when possible (see also Section 3.1.2 of + RFC 5405 [RFC5405]). + + Further congestion control optimizations and considerations are + expected in the future with advanced CoAP congestion control + mechanisms. + + + +Hartke Expires July 3, 2015 [Page 16] + +Internet-Draft Observing Resources in CoAP December 2014 + + +4.5.2. Advanced Transmission + + The state of an observed resource may change while the number of the + number of simultaneous outstanding notifications/responses to a + client on the list of observers is greater than or equal to NSTART. + In this case, the server cannot notify the client of the new resource + state immediately but has to wait for an outstanding notification/ + response to complete first. + + If there exists an outstanding notification/response that the server + transmits to the client and that pertains to the changed resource, + then it is desirable for the server to stop working towards getting + the representation of the old resource state to the client, and to + start transmitting the current representation to the client instead, + so the resource state observed by the client stays closer in sync + with the actual state at the server. + + For this purpose, the server MAY optimize the transmission process by + aborting the transmission of the old notification (but not before the + current transmission attempt completed) and starting a new + transmission for the new notification (but with the retransmission + timer and counter of the aborted transmission retained). + + In more detail, a server MAY supersede an outstanding transmission + that pertains to an observation as follows: + + 1. Wait for the current (re-)transmission attempt to be + acknowledged, rejected or to time out (confirmable transmission); + or wait for the waiting time to elapse or the transmission to be + rejected (non-confirmable transmission). + + 2. If the transmission is rejected or it was the last attempt to + retransmit a notification, remove the associated entry from the + list of observers of the observed resource. + + 3. If the entry is still in the list of observers, start to transmit + a new notification with a representation of the current resource + state. Should the resource have changed its state more than once + in the meantime, the notifications for the intermediate states + are silently skipped. + + 4. The new notification is transmitted with a new Message ID and the + following transmission parameters: If the previous + (re-)transmission attempt timed out, retain its transmission + parameters, increment the retransmission counter and double the + timeout; otherwise, initialize the transmission parameters as + usual (see Section 4.2 of RFC 7252 [RFC7252]). + + + + +Hartke Expires July 3, 2015 [Page 17] + +Internet-Draft Observing Resources in CoAP December 2014 + + + It is possible that the server later receives an acknowledgement for + a confirmable notification that it superseded this way. Even though + this does not signal consistency, it is valuable in that it signals + the client's further interest in the resource. The server therefore + should avoid inadvertently removing the associated entry from the + list of observers. + +5. Intermediaries + + A client may be interested in a resource in the namespace of a server + that is reached through a chain of one or more CoAP intermediaries. + In this case, the client registers its interest with the first + intermediary towards the server, acting as if it was communicating + with the server itself, as specified in Section 3. It is the task of + this intermediary to provide the client with a current representation + of the target resource and to keep the representation updated upon + changes to the resource state, as specified in Section 4. + + To perform this task, the intermediary SHOULD make use of the + protocol specified in this document, taking the role of the client + and registering its own interest in the target resource with the next + hop towards the server. If the response returned by the next hop + doesn't include an Observe Option, the intermediary MAY resort to + polling the next hop or MAY itself return a response without an + Observe Option. + + The communication between each pair of hops is independent; each hop + in the server role MUST determine individually how many notifications + to send, of which message type, and so on. Each hop MUST generate + its own values for the Observe Option in notifications, and MUST set + the value of the Max-Age Option according to the age of the local + current representation. + + If two or more clients have registered their interest in a resource + with an intermediary, the intermediary MUST register itself only once + with the next hop and fan out the notifications it receives to all + registered clients. This relieves the next hop from sending the same + notifications multiple times and thus enables scalability. + + An intermediary is not required to act on behalf of a client to + observe a resource; an intermediary MAY observe a resource, for + example, just to keep its own cache up to date. + + See Appendix A.2 for examples. + + + + + + + +Hartke Expires July 3, 2015 [Page 18] + +Internet-Draft Observing Resources in CoAP December 2014 + + +6. Web Linking + + A web link [RFC5988] to a resource accessible over CoAP (for example, + in a link-format document [RFC6690]) MAY include the target attribute + "obs". + + The "obs" attribute, when present, is a hint indicating that the + destination of a link is useful for observation and thus, for + example, should have a suitable graphical representation in a user + interface. Note that this is only a hint; it is not a promise that + the Observe Option can actually be used to perform the observation. + A client may need to resort to polling the resource if the Observe + Option is not returned in the response to the GET request. + + A value MUST NOT be given for the "obs" attribute; any present value + MUST be ignored by parsers. The "obs" attribute MUST NOT appear more + than once in a given link-value; occurrences after the first MUST be + ignored by parsers. + +7. Security Considerations + + The security considerations in Section 11 of the CoAP specification + [RFC7252] apply. + + Observing resources can dramatically increase the negative effects of + amplification attacks. That is, not only can notifications messages + be much larger than the request message, but the nature of the + protocol can cause a significant number of notifications to be + generated. Without client authentication, a server therefore MUST + strictly limit the number of notifications that it sends between + receiving acknowledgements that confirm the actual interest of the + client in the data; i.e., any notifications sent in non-confirmable + messages MUST be interspersed with confirmable messages. (An + attacker may still spoof the acknowledgements if the confirmable + messages are sufficiently predictable.) + + The protocol follows a best-effort approach for keeping the state + observed by a client and the actual resource state at a server in + sync. This may have the client and the server become out of sync at + times. Depending on the sensitivity of the observed resource, + operating on an old state might be a security threat. The client + therefore must be careful not to use a representation after its Max- + Age expires, and the server must set the Max-Age Option to a sensible + value. + + As with any protocol that creates state, attackers may attempt to + exhaust the resources that the server has available for maintaining + the list of observers for each resource. Servers may want to apply + + + +Hartke Expires July 3, 2015 [Page 19] + +Internet-Draft Observing Resources in CoAP December 2014 + + + access controls to this creation of state. As degraded behavior, the + server can always fall back to processing the request as a normal GET + request (without an Observe Option) if it is unwilling or unable to + add a client to the list of observers of a resource, including if + system resources are exhausted or nearing exhaustion. + + Intermediaries must be careful to ensure that notifications cannot be + employed to create a loop. A simple way to break any loops is to + employ caches for forwarding notifications in intermediaries. + + Resources can be observed over DTLS-secured CoAP using any of the + security modes described in Section 9 of RFC 7252. The use of DTLS + is indicated by the "coaps" URI scheme. All notifications resulting + from a GET request with an Observe Option MUST be returned within the + same epoch of the same connection as the request. + +8. IANA Considerations + + The following entry is added to the CoAP Option Numbers registry: + + +--------+---------+-----------+ + | Number | Name | Reference | + +--------+---------+-----------+ + | 6 | Observe | [RFCXXXX] | + +--------+---------+-----------+ + + [Note to RFC Editor: Please replace XXXX with the RFC number of this + specification.] + +9. Acknowledgements + + Carsten Bormann was an original author of this draft and is + acknowledged for significant contribution to this document. + + Thanks to Daniele Alessandrelli, Jari Arkko, Peter A. Bigot, Angelo + P. Castellani, Gilbert Clark, Esko Dijk, Thomas Fossati, Brian Frank, + Bert Greevenbosch, Jeroen Hoebeke, Cullen Jennings, Matthias + Kovatsch, Barry Leiba, Salvatore Loreto, Charles Palmer, Akbar + Rahman, Zach Shelby, and Floris Van den Abeele for helpful comments + and discussions that have shaped the document. + + This work was supported in part by Klaus Tschira Foundation, Intel, + Cisco, and Nokia. + +10. References + + + + + + +Hartke Expires July 3, 2015 [Page 20] + +Internet-Draft Observing Resources in CoAP December 2014 + + +10.1. Normative References + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC5988] Nottingham, M., "Web Linking", RFC 5988, October 2010. + + [RFC7252] Shelby, Z., Hartke, K., and C. Bormann, "The Constrained + Application Protocol (CoAP)", RFC 7252, June 2014. + +10.2. Informative References + + [GOF] Gamma, E., Helm, R., Johnson, R., and J. Vlissides, + "Design Patterns: Elements of Reusable Object-Oriented + Software", Addison-Wesley, Reading, MA, USA, + November 1994. + + [REST] Fielding, R., "Architectural Styles and the Design of + Network-based Software Architectures", Ph.D. Dissertation, + University of California, Irvine, 2000, . + + [RFC1982] Elz, R. and R. Bush, "Serial Number Arithmetic", RFC 1982, + August 1996. + + [RFC5405] Eggert, L. and G. Fairhurst, "Unicast UDP Usage Guidelines + for Application Designers", BCP 145, RFC 5405, + November 2008. + + [RFC5989] Roach, A., "A SIP Event Package for Subscribing to Changes + to an HTTP Resource", RFC 5989, October 2010. + + [RFC6202] Loreto, S., Saint-Andre, P., Salsano, S., and G. Wilkins, + "Known Issues and Best Practices for the Use of Long + Polling and Streaming in Bidirectional HTTP", RFC 6202, + April 2011. + + [RFC6690] Shelby, Z., "Constrained RESTful Environments (CoRE) Link + Format", RFC 6690, August 2012. + + [RFC7228] Bormann, C., Ersue, M., and A. Keranen, "Terminology for + Constrained-Node Networks", RFC 7228, May 2014. + + [RFC7230] Fielding, R. and J. Reschke, "Hypertext Transfer Protocol + (HTTP/1.1): Message Syntax and Routing", RFC 7230, + June 2014. + + + + +Hartke Expires July 3, 2015 [Page 21] + +Internet-Draft Observing Resources in CoAP December 2014 + + +Appendix A. Examples + +A.1. Client/Server Examples + + Observed CLIENT SERVER Actual + t State | | State + ____________ | | ____________ + 1 | | + 2 unknown | | 18.5 Cel + 3 +----->| Header: GET 0x41011633 + 4 | GET | Token: 0x4a + 5 | | Uri-Path: temperature + 6 | | Observe: 0 (register) + 7 | | + 8 | | + 9 ____________ |<-----+ Header: 2.05 0x61451633 + 10 | 2.05 | Token: 0x4a + 11 18.5 Cel | | Observe: 9 + 12 | | Max-Age: 15 + 13 | | Payload: "18.5 Cel" + 14 | | + 15 | | ____________ + 16 ____________ |<-----+ Header: 2.05 0x51457b50 + 17 | 2.05 | 19.2 Cel Token: 0x4a + 18 19.2 Cel | | Observe: 16 + 29 | | Max-Age: 15 + 20 | | Payload: "19.2 Cel" + 21 | | + + Figure 3: A client registers and receives one notification of the + current state and one of a new state upon a state change + + + + + + + + + + + + + + + + + + + + +Hartke Expires July 3, 2015 [Page 22] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Observed CLIENT SERVER Actual + t State | | State + ____________ | | ____________ + 22 | | + 23 19.2 Cel | | 19.2 Cel + 24 | | ____________ + 25 | X----+ Header: 2.05 0x51457b51 + 26 | 2.05 | 19.7 Cel Token: 0x4a + 27 | | Observe: 25 + 28 | | Max-Age: 15 + 29 | | Payload: "19.7 Cel" + 30 | | + 31 ____________ | | + 32 | | + 33 19.2 Cel | | + 34 (stale) | | + 35 | | + 36 | | + 37 | | + 38 +----->| Header: GET 0x41011634 + 39 | GET | Token: 0xb2 + 40 | | Uri-Path: temperature + 41 | | Observe: 0 (register) + 42 | | + 43 | | + 44 ____________ |<-----+ Header: 2.05 0x61451634 + 45 | 2.05 | Token: 0xb2 + 46 19.7 Cel | | Observe: 44 + 47 | | Max-Age: 15 + 48 | | ETag: 0x78797a7a79 + 49 | | Payload: "19.7 Cel" + 50 | | + + Figure 4: The client re-registers after Max-Age ends + + + + + + + + + + + + + + + + + +Hartke Expires July 3, 2015 [Page 23] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Observed CLIENT SERVER Actual + t State | | State + ____________ | | ____________ + 51 | | + 52 19.7 Cel | | 19.7 Cel + 53 | | + 54 | | ____________ + 55 | crash + 56 | + 57 | + 58 | + 59 ____________ | + 60 | + 61 19.7 Cel | + 62 (stale) | + 63 | reboot____________ + 64 | | + 65 | | 20.0 Cel + 66 | | + 67 +----->| Header: GET 0x41011635 + 68 | GET | Token: 0xf9 + 69 | | Uri-Path: temperature + 70 | | Observe: 0 (register) + 71 | | ETag: 0x78797a7a79 + 72 | | + 73 | | + 74 ____________ |<-----+ Header: 2.05 0x61451635 + 75 | 2.05 | Token: 0xf9 + 76 20.0 Cel | | Observe: 74 + 77 | | Max-Age: 15 + 78 | | Payload: "20.0 Cel" + 79 | | + 80 | | ____________ + 81 ____________ |<-----+ Header: 2.03 0x5143aa0c + 82 | 2.03 | 19.7 Cel Token: 0xf9 + 83 19.7 Cel | | Observe: 81 + 84 | | ETag: 0x78797a7a79 + 85 | | Max-Age: 15 + 86 | | + + Figure 5: The client re-registers and gives the server the + opportunity to select a stored response + + + + + + + + + +Hartke Expires July 3, 2015 [Page 24] + +Internet-Draft Observing Resources in CoAP December 2014 + + + Observed CLIENT SERVER Actual + t State | | State + ____________ | | ____________ + 87 | | + 88 19.7 Cel | | 19.7 Cel + 89 | | + 90 | | ____________ + 91 ____________ |<-----+ Header: 2.05 0x4145aa0f + 92 | 2.05 | 19.3 Cel Token: 0xf9 + 93 19.3 Cel | | Observe: 91 + 94 | | Max-Age: 15 + 95 | | Payload: "19.3 Cel" + 96 | | + 97 | | + 98 +- - ->| Header: 0x7000aa0f + 99 | | + 100 | | + 101 | | + 102 | | ____________ + 103 | | + 104 | | 19.0 Cel + 105 | | + 106 ____________ | | + 107 | | + 108 19.3 Cel | | + 109 (stale) | | + 110 | | + + Figure 6: The client rejects a notification and thereby cancels the + observation + + + + + + + + + + + + + + + + + + + + + +Hartke Expires July 3, 2015 [Page 25] + +Internet-Draft Observing Resources in CoAP December 2014 + + +A.2. Proxy Examples + + CLIENT PROXY SERVER + | | | + | +----->| Header: GET 0x41015fb8 + | | GET | Token: 0x1a + | | | Uri-Host: sensor.example + | | | Uri-Path: status + | | | Observe: 0 (register) + | | | + | |<-----+ Header: 2.05 0x61455fb8 + | | 2.05 | Token: 0x1a + | | | Observe: 42 + | | | Max-Age: 60 + | | | Payload: "ready" + | | | + +----->| | Header: GET 0x41011633 + | GET | | Token: 0x9a + | | | Proxy-Uri: coap://sensor.example/status + | | | + |<-----+ | Header: 2.05 0x61451633 + | 2.05 | | Token: 0x9a + | | | Max-Age: 53 + | | | Payload: "ready" + | | | + | |<-----+ Header: 2.05 0x514505fc0 + | | 2.05 | Token: 0x1a + | | | Observe: 135 + | | | Max-Age: 60 + | | | Payload: "busy" + | | | + +----->| | Header: GET 0x41011634 + | GET | | Token: 0x9b + | | | Proxy-Uri: coap://sensor.example/status + | | | + |<-----+ | Header: 2.05 0x61451634 + | 2.05 | | Token: 0x9b + | | | Max-Age: 49 + | | | Payload: "busy" + | | | + + Figure 7: A proxy observes a resource to keep its cache up to date + + + + + + + + + +Hartke Expires July 3, 2015 [Page 26] + +Internet-Draft Observing Resources in CoAP December 2014 + + + CLIENT PROXY SERVER + | | | + +----->| | Header: GET 0x41011635 + | GET | | Token: 0x6a + | | | Proxy-Uri: coap://sensor.example/status + | | | Observe: 0 (register) + | | | + |<- - -+ | Header: 0x60001635 + | | | + | +----->| Header: GET 0x4101af90 + | | GET | Token: 0xaa + | | | Uri-Host: sensor.example + | | | Uri-Path: status + | | | Observe: 0 (register) + | | | + | |<-----+ Header: 2.05 0x6145af90 + | | 2.05 | Token: 0xaa + | | | Observe: 67 + | | | Max-Age: 60 + | | | Payload: "ready" + | | | + |<-----+ | Header: 2.05 0x4145af94 + | 2.05 | | Token: 0x6a + | | | Observe: 17346 + | | | Max-Age: 60 + | | | Payload: "ready" + | | | + +- - ->| | Header: 0x6000af94 + | | | + | |<-----+ Header: 2.05 0x51455a20 + | | 2.05 | Token: 0xaa + | | | Observe: 157 + | | | Max-Age: 60 + | | | Payload: "busy" + | | | + |<-----+ | Header: 2.05 0x5145af9b + | 2.05 | | Token: 0x6a + | | | Observe: 17436 + | | | Max-Age: 60 + | | | Payload: "busy" + | | | + + Figure 8: A client observes a resource through a proxy + + + + + + + + +Hartke Expires July 3, 2015 [Page 27] + +Internet-Draft Observing Resources in CoAP December 2014 + + +Appendix B. Changelog + + [Note to RFC Editor: Please remove this section before publication.] + + Changes from ietf-15 to ietf-16: + + o Clarified several points based on AD, GenART, IESG, and Secdir + reviews. + + Changes from ietf-14 to ietf-15: + + o Clarified several points based on AD, GenART, IESG, and Secdir + reviews. + + Changes from ietf-13 to ietf-14: + + o Updated references. + + Changes from ietf-12 to ietf-13: + + o Extended the Observe Option in requests to not only add but also + remove an entry in the list of observers, depending on the option + value. + + Note: The value of the Observe Option in a registration request + may now be any sequence of bytes that encodes the unsigned + integer 0, i.e., 0x'', 0x'00', 0x'00 00' or 0x'00 00 00'. + + o Removed the 7.31 Code for cancellation. + + Changes from ietf-11 to ietf-12: + + o Introduced the 7.31 Code to request the cancellation of a pending + request. + + o Made the algorithm for superseding an outstanding transmission + OPTIONAL. + + o Clarified that the entry in the list of observers is removed if + the client fails to acknowledge a confirmable notification before + the last retransmission attempt times out (#350). + + o Simplified the text on cancellation (#352) and the handling of + Reset messages (#353). + + Changes from ietf-10 to ietf-11: + + + + + +Hartke Expires July 3, 2015 [Page 28] + +Internet-Draft Observing Resources in CoAP December 2014 + + + o Pointed out that client and server clocks may differ in their + realization of the SI second, and added robustness to the existing + reordering scheme by reducing the maximum notification rate to + 32768 notifications per second (#341). + + Changes from ietf-09 to ietf-10: + + o Required consistent sequence numbers across requests (#333). + + o Clarified that a server needs to update the entry in the list of + observers instead of adding a new entry if the endpoint/token pair + is already present. + + o Allowed that a client uses a token that is currently in use to + ensure that it's still in the list of observers. This is possible + because sequence numbers are now consistent across requests and + servers won't add a new entry for the same token. + + o Improved text on the transmission of non-confirmable notifications + to match Section 3.1.2 of RFC 5405 more closely. + + o Updated examples to use UCUM units. + + o Moved Appendix B into the introduction. + + Changes from ietf-08 to ietf-09: + + o Removed the side effects of requests on existing observations. + This includes removing that + + * the client can use a GET request to cancel an observation; + + * the server updates the entry in the list of observers instead + of adding a new entry if the client is already present (#258, + #281). + + o Clarified that a resource (and hence an observation relationship) + is identified by the request options that are part of the Cache- + Key (#258). + + o Clarified that a non-2.xx notification MUST NOT include an Observe + Option. + + o Moved block-wise transfer of notifications to [I-D.ietf-core- + block]. + + Changes from ietf-07 to ietf-08: + + + + +Hartke Expires July 3, 2015 [Page 29] + +Internet-Draft Observing Resources in CoAP December 2014 + + + o Expanded text on transmitting a notification while a previous + transmission is pending (#242). + + o Changed reordering detection to use a fixed time span of 128 + seconds instead of EXCHANGE_LIFETIME (#276). + + o Removed the use of the freshness model to determine if the client + is still on the list of observers. This includes removing that + + * the client assumes that it has been removed from the list of + observers when Max-Age ends; + + * the server sets the Max-Age Option of a notification to a value + that indicates when the server will send the next notification; + + * the server uses a number of retransmit attempts such that + removing a client from the list of observers before Max-Age + ends is avoided (#235); + + * the server may remove the client from all lists of observers + when the transmission of a confirmable notification ultimately + times out. + + o Changed that an unrecognized critical option in a request must + actually have no effect on the state of any observation + relationship to any resource, as the option could lead to a + different target resource. + + o Clarified that client implementations must be prepared to receive + each notification equally as a confirmable or a non-confirmable + message, regardless of the message type of the request and of any + previous notification. + + o Added a requirement for sending a confirmable notification at + least every 24 hours before continuing with non-confirmable + notifications (#221). + + o Added congestion control considerations from [I-D.bormann-core- + congestion-control-02]. + + o Recommended that the client waits for a randomized time after the + freshness of the latest notification expired before re- + registering. This prevents that multiple clients observing a + resource perform a GET request at the same time when the need to + re-register arises. + + o Changed reordering detection from 'MAY' to 'SHOULD', as the goal + of the protocol (to keep the observed state as closely in sync + + + +Hartke Expires July 3, 2015 [Page 30] + +Internet-Draft Observing Resources in CoAP December 2014 + + + with the actual state as possible) is not optional. + + o Fixed the length of the Observe Option (3 bytes) in the table in + Section 2. + + o Replaced the 'x' in the No-Cache-Key column in the table in + Section 2 with a '-', as the Observe Option doesn't have the No- + Cache-Key flag set, even though it is not part of the cache key. + + o Updated examples. + + Changes from ietf-06 to ietf-07: + + o Moved to 24-bit sequence numbers to allow for up to 15000 + notifications per second per client and resource (#217). + + o Re-numbered option number to use Unsafe/Safe and Cache-Key + compliant numbers (#241). + + o Clarified how to react to a Reset message that is sent in reply to + a non-confirmable notification (#225). + + o Clarified the semantics of the "obs" link target attribute (#236). + + Changes from ietf-05 to ietf-06: + + o Improved abstract and introduction to say that the protocol is + about best effort and eventual consistency (#219). + + o Clarified that the value of the Observe Option in a request must + have zero length. + + o Added requirement that the sequence number must be updated each + time a server retransmits a notification. + + o Clarified that a server must remove a client from the list of + observers when it receives a GET request with an unrecognized + critical option. + + o Updated the text to use the endpoint concept from [I-D.ietf-core- + coap] (#224). + + o Improved the reordering text (#223). + + Changes from ietf-04 to ietf-05: + + o Recommended that a client does not re-register while a new + notification from the server is still likely to arrive. This is + + + +Hartke Expires July 3, 2015 [Page 31] + +Internet-Draft Observing Resources in CoAP December 2014 + + + to avoid that the request of the client and the last notification + after max-age cross over each other (#174). + + o Relaxed requirements when sending a Reset message in reply to non- + confirmable notifications. + + o Added an implementation note about careless GET requests (#184). + + o Updated examples. + + Changes from ietf-03 to ietf-04: + + o Removed the "Max-OFE" Option. + + o Allowed a Reset message in reply to non-confirmable notifications. + + o Added a section on cancellation. + + o Updated examples. + + Changes from ietf-02 to ietf-03: + + o Separated client-side and server-side requirements. + + o Fixed uncertainty if client is still on the list of observers by + introducing a liveliness model based on Max-Age and a new option + called "Max-OFE" (#174). + + o Simplified the text on message reordering (#129). + + o Clarified requirements for intermediaries. + + o Clarified the combination of blockwise transfers with + notifications (#172). + + o Updated examples to show how the state observed by the client + becomes eventually consistent with the actual state on the server. + + o Added examples for parameterization of observable resource. + + Changes from ietf-01 to ietf-02: + + o Removed the requirement of periodic refreshing (#126). + + o The new "Observe" Option replaces the "Lifetime" Option. + + o Introduced a new mechanism to detect message reordering. + + + + +Hartke Expires July 3, 2015 [Page 32] + +Internet-Draft Observing Resources in CoAP December 2014 + + + o Changed 2.00 (OK) notifications to 2.05 (Content) notifications. + + Changes from ietf-00 to ietf-01: + + o Changed terminology from "subscriptions" to "observation + relationships" (#33). + + o Changed the name of the option to "Lifetime". + + o Clarified establishment of observation relationships. + + o Clarified that an observation is only identified by the URI of the + observed resource and the identity of the client (#66). + + o Clarified rules for establishing observation relationships (#68). + + o Clarified conditions under which an observation relationship is + terminated. + + o Added explanation on how clients can terminate an observation + relationship before the lifetime ends (#34). + + o Clarified that the overriding objective for notifications is + eventual consistency of the actual and the observed state (#67). + + o Specified how a server needs to deal with clients not + acknowledging confirmable messages carrying notifications (#69). + + o Added a mechanism to detect message reordering (#35). + + o Added an explanation of how notifications can be cached, + supporting both the freshness and the validation model (#39, #64). + + o Clarified that non-GET requests do not affect observation + relationships, and that GET requests without "Lifetime" Option + affecting relationships is by design (#65). + + o Described interaction with blockwise transfers (#36). + + o Added Resource Discovery section (#99). + + o Added IANA Considerations. + + o Added Security Considerations (#40). + + o Added examples (#38). + + + + + +Hartke Expires July 3, 2015 [Page 33] + +Internet-Draft Observing Resources in CoAP December 2014 + + +Author's Address + + Klaus Hartke + Universitaet Bremen TZI + Postfach 330440 + Bremen D-28359 + Germany + + Phone: +49-421-218-63905 + EMail: hartke@tzi.org + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Hartke Expires July 3, 2015 [Page 34] + diff --git a/rfc/rfc6690.txt b/rfc/rfc6690.txt new file mode 100644 index 0000000..37209df --- /dev/null +++ b/rfc/rfc6690.txt @@ -0,0 +1,1235 @@ + + + + + + +Internet Engineering Task Force (IETF) Z. Shelby +Request for Comments: 6690 Sensinode +Category: Standards Track August 2012 +ISSN: 2070-1721 + + + Constrained RESTful Environments (CoRE) Link Format + +Abstract + + This specification defines Web Linking using a link format for use by + constrained web servers to describe hosted resources, their + attributes, and other relationships between links. Based on the HTTP + Link Header field defined in RFC 5988, the Constrained RESTful + Environments (CoRE) Link Format is carried as a payload and is + assigned an Internet media type. "RESTful" refers to the + Representational State Transfer (REST) architecture. A well-known + URI is defined as a default entry point for requesting the links + hosted by a server. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc6690. + +Copyright Notice + + Copyright (c) 2012 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + + +Shelby Standards Track [Page 1] + +RFC 6690 CoRE Link Format August 2012 + + +Table of Contents + + 1. Introduction ....................................................3 + 1.1. Web Linking in CoRE ........................................3 + 1.2. Use Cases ..................................................4 + 1.2.1. Discovery ...........................................4 + 1.2.2. Resource Collections ................................5 + 1.2.3. Resource Directory ..................................5 + 1.3. Terminology ................................................6 + 2. Link Format .....................................................6 + 2.1. Target and Context URIs ....................................8 + 2.2. Link Relations .............................................8 + 2.3. Use of Anchors .............................................9 + 3. CoRE Link Attributes ............................................9 + 3.1. Resource Type 'rt' Attribute ...............................9 + 3.2. Interface Description 'if' Attribute ......................10 + 3.3. Maximum Size Estimate 'sz' Attribute ......................10 + 4. Well-Known Interface ...........................................10 + 4.1. Query Filtering ...........................................12 + 5. Examples .......................................................13 + 6. Security Considerations ........................................15 + 7. IANA Considerations ............................................16 + 7.1. Well-Known 'core' URI .....................................16 + 7.2. New 'hosts' Relation Type .................................16 + 7.3. New 'link-format' Internet Media Type .....................17 + 7.4. Constrained RESTful Environments (CoRE) Parameters + Registry ..................................................18 + 8. Acknowledgments ................................................19 + 9. References .....................................................20 + 9.1. Normative References ......................................20 + 9.2. Informative References ....................................20 + + + + + + + + + + + + + + + + + + + + +Shelby Standards Track [Page 2] + +RFC 6690 CoRE Link Format August 2012 + + +1. Introduction + + The Constrained RESTful Environments (CoRE) realizes the + Representational State Transfer (REST) architecture [REST] in a + suitable form for the most constrained nodes (e.g., 8-bit + microcontrollers with limited memory) and networks (e.g., IPv6 over + Low-Power Wireless Personal Area Networks (6LoWPANs) [RFC4919]). + CoRE is aimed at Machine-to-Machine (M2M) applications such as smart + energy and building automation. + + The discovery of resources hosted by a constrained server is very + important in machine-to-machine applications where there are no + humans in the loop and static interfaces result in fragility. The + discovery of resources provided by an HTTP [RFC2616] web server is + typically called "Web Discovery" and the description of relations + between resources is called "Web Linking" [RFC5988]. In the present + specification, we refer to the discovery of resources hosted by a + constrained web server, their attributes, and other resource + relations as CoRE Resource Discovery. + + The main function of such a discovery mechanism is to provide + Universal Resource Identifiers (URIs, called links) for the resources + hosted by the server, complemented by attributes about those + resources and possible further link relations. In CoRE, this + collection of links is carried as a resource of its own (as opposed + to HTTP headers delivered with a specific resource). This document + specifies a link format for use in CoRE Resource Discovery by + extending the HTTP Link Header format [RFC5988] to describe these + link descriptions. The CoRE Link Format is carried as a payload and + is assigned an Internet media type. A well-known relative URI + "/.well-known/core" is defined as a default entry point for + requesting the list of links about resources hosted by a server and + thus performing CoRE Resource Discovery. This specification is + applicable for use with Constrained Application Protocol (CoAP) + [COAP], HTTP, or any other suitable web transfer protocol. The link + format can also be saved in file format. + +1.1. Web Linking in CoRE + + Technically, the CoRE Link Format is a serialization of a typed link + as specified in [RFC5988], used to describe relationships between + resources, so-called "Web Linking". In this specification, Web + Linking is extended with specific constrained M2M attributes; links + are carried as a message payload rather than in an HTTP Link Header + field, and a default interface is defined to discover resources + hosted by a server. This specification also defines a new relation + + + + + +Shelby Standards Track [Page 3] + +RFC 6690 CoRE Link Format August 2012 + + + type "hosts" (from the verb "to host"), which indicates that the + resource is hosted by the server from which the link document was + requested. + + In HTTP, the Link Header can be used to carry link information about + a resource along with an HTTP response. This works well for the + typical use case for a web server and browser, where further + information about a particular resource is useful after accessing it. + In CoRE, the main use case for Web Linking is the discovery of which + resources a server hosts in the first place. Although some resources + may have further links associated with them, this is expected to be + an exception. For that reason, the CoRE Link Format serialization is + carried as a resource representation of a well-known URI. The CoRE + Link Format does reuse the format of the HTTP Link Header + serialization defined in [RFC5988]. + +1.2. Use Cases + + Typical use cases for Web Linking on today's web include, e.g., + describing the author of a web page or describing relations between + web pages (next chapter, previous chapter, etc.). Web Linking can + also be applied to M2M applications, where typed links are used to + assist a machine client in finding and understanding how to use + resources on a server. In this section a few use cases are described + for how the CoRE Link Format could be used in M2M applications. For + further technical examples, see Section 5. As there is a large range + of M2M applications, these use cases are purposely generic. This + specification assumes that different deployments or application + domains will define the appropriate REST Interface Descriptions along + with Resource Types to make discovery meaningful. + +1.2.1. Discovery + + In M2M applications, for example, home or building automation, there + is a need for local clients and servers to find and interact with + each other without human intervention. The CoRE Link Format can be + used by servers in such environments to enable Resource Discovery of + the resources hosted by the server. + + Resource Discovery can be performed either unicast or multicast. + When a server's IP address is already known, either a priori or + resolved via the Domain Name System (DNS) [RFC1034][RFC1035], unicast + discovery is performed in order to locate the entry point to the + resource of interest. In this specification, this is performed using + a GET to "/.well-known/core" on the server, which returns a payload + in the CoRE Link Format. A client would then match the appropriate + Resource Type, Interface Description, and possible media type + + + + +Shelby Standards Track [Page 4] + +RFC 6690 CoRE Link Format August 2012 + + + [RFC2045] for its application. These attributes may also be included + in the query string in order to filter the number of links returned + in a response. + + Multicast Resource Discovery is useful when a client needs to locate + a resource within a limited scope, and that scope supports IP + multicast. A GET request to the appropriate multicast address is + made for "/.well-known/core". In order to limit the number and size + of responses, a query string is recommended with the known + attributes. Typically, a resource would be discovered based on its + Resource Type and/or Interface Description, along with possible + application-specific attributes. + +1.2.2. Resource Collections + + RESTful designs of M2M interfaces often make use of collections of + resources. For example, an index of temperature sensors on a data + collection node or a list of alarms on a home security controller. + The CoRE Link Format can be used to make it possible to find the + entry point to a collection and traverse its members. The entry + point of a collection would always be included in "/.well-known/core" + to enable its discovery. The members of the collection can be + defined either through the Interface Description of the resource + along with a parameter resource for the size of the collection or by + using the link format to describe each resource in the collection. + These links could be located under "/.well-known/core" or hosted, for + example, in the root resource of the collection. + +1.2.3. Resource Directory + + In many deployment scenarios, for example, constrained networks with + sleeping servers or large M2M deployments with bandwidth limited + access networks, it makes sense to deploy resource directory entities + that store links to resources stored on other servers. Think of this + as a limited search engine for constrained M2M resources. + + The CoRE Link Format can be used by a server to register resources + with a resource directory or to allow a resource directory to poll + for resources. Resource registration can be achieved by having each + server POST their resources to "/.well-known/core" on the resource + directory. This, in turn, adds links to the resource directory under + an appropriate resource. These links can then be discovered by any + client by making a request to a resource directory lookup interface. + + + + + + + + +Shelby Standards Track [Page 5] + +RFC 6690 CoRE Link Format August 2012 + + +1.3. Terminology + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + specification are to be interpreted as described in [RFC2119]. + + This specification makes use of the Augmented Backus-Naur Form (ABNF) + [RFC5234] notation, including the core rules defined in Appendix B of + that document. + + This specification requires readers to be familiar with all the terms + and concepts that are discussed in [RFC5988] and [RFC6454]. In + addition, this specification makes use of the following terminology: + + Web Linking + A framework for indicating the relationships between web + resources. + + Link + Also called "typed links" in [RFC5988]. A link is a typed + connection between two resources identified by URI and is made up + of a context URI, a link relation type, a target URI, and optional + target attributes. + + Link Format + A particular serialization of typed links. + + CoRE Link Format + A particular serialization of typed links based on the HTTP Link + Header field serialization defined in Section 5 of [RFC5988] but + carried as a resource representation with a media type. + + Attribute + Properly called "Target Attribute" in [RFC5988]. A key/value pair + that describes the link or its target. + + CoRE Resource Discovery + When a client discovers the list of resources hosted by a server, + their attributes, and other link relations by accessing + "/.well-known/core". + +2. Link Format + + The CoRE Link Format extends the HTTP Link Header field specified in + [RFC5988]. The format does not require special XML or binary + parsing, is fairly compact, and is extensible -- all important + characteristics for CoRE. It should be noted that this link format + is just one serialization of typed links defined in [RFC5988]; others + + + +Shelby Standards Track [Page 6] + +RFC 6690 CoRE Link Format August 2012 + + + include HTML links, Atom feed links [RFC4287], or HTTP Link Header + fields. It is expected that resources discovered in the CoRE Link + Format may also be made available in alternative formats on the + greater Internet. The CoRE Link Format is only expected to be + supported in constrained networks and M2M systems. + + Section 5 of [RFC5988] did not require an Internet media type for the + defined link format, as it was defined to be carried in an HTTP + header. This specification thus defines the Internet media type + 'application/link-format' for the CoRE Link Format (see Section 7.3). + Whereas the HTTP Link Header field depends on [RFC2616] for its + encoding, the CoRE Link Format is encoded as UTF-8 [RFC3629]. A + decoder of the format is not expected to validate UTF-8 encoding (but + is not prohibited from doing so) and doesn't need to perform any + UTF-8 normalization. UTF-8 data can be compared bitwise, which + allows values to contain UTF-8 data without any added complexity for + constrained nodes. + + The CoRE Link Format is equivalent to the [RFC5988] link format; + however, the ABNF in the present specification is repeated with + improvements to be compliant with [RFC5234] and includes new link + parameters. The link parameter "href" is reserved for use as a query + parameter for filtering in this specification (see Section 4.1) and + MUST NOT be defined as a link parameter. As in [RFC5988], multiple + link descriptions are separated by commas. Note that commas can also + occur in quoted strings and URIs but do not end a description. In + order to convert an HTTP Link Header field to this link format, first + the "Link:" HTTP header is removed, any linear whitespace (LWS) is + removed, the header value is converted to UTF-8, and any percent- + encodings are decoded. + + Link = link-value-list + link-value-list = [ link-value *[ "," link-value ]] + link-value = "<" URI-Reference ">" *( ";" link-param ) + link-param = ( ( "rel" "=" relation-types ) + / ( "anchor" "=" DQUOTE URI-Reference DQUOTE ) + / ( "rev" "=" relation-types ) + / ( "hreflang" "=" Language-Tag ) + / ( "media" "=" ( MediaDesc + / ( DQUOTE MediaDesc DQUOTE ) ) ) + / ( "title" "=" quoted-string ) + / ( "title*" "=" ext-value ) + / ( "type" "=" ( media-type / quoted-mt ) ) + / ( "rt" "=" relation-types ) + / ( "if" "=" relation-types ) + / ( "sz" "=" cardinal ) + / ( link-extension ) ) + link-extension = ( parmname [ "=" ( ptoken / quoted-string ) ] ) + + + +Shelby Standards Track [Page 7] + +RFC 6690 CoRE Link Format August 2012 + + + / ( ext-name-star "=" ext-value ) + ext-name-star = parmname "*" ; reserved for RFC-2231-profiled + ; extensions. Whitespace NOT + ; allowed in between. + ptoken = 1*ptokenchar + ptokenchar = "!" / "#" / "$" / "%" / "&" / "'" / "(" + / ")" / "*" / "+" / "-" / "." / "/" / DIGIT + / ":" / "<" / "=" / ">" / "?" / "@" / ALPHA + / "[" / "]" / "^" / "_" / "`" / "{" / "|" + / "}" / "~" + media-type = type-name "/" subtype-name + quoted-mt = DQUOTE media-type DQUOTE + relation-types = relation-type + / DQUOTE relation-type *( 1*SP relation-type ) DQUOTE + relation-type = reg-rel-type / ext-rel-type + reg-rel-type = LOALPHA *( LOALPHA / DIGIT / "." / "-" ) + ext-rel-type = URI + cardinal = "0" / ( %x31-39 *DIGIT ) + LOALPHA = %x61-7A ; a-z + quoted-string = + URI = + URI-Reference = + type-name = + subtype-name = + MediaDesc = + Language-Tag = + ext-value = + parmname = + +2.1. Target and Context URIs + + Each link conveys one target URI as a URI-reference inside angle + brackets ("<>"). The context URI of a link (also called the base URI + in [RFC3986]) is determined by the following rules in this + specification: + + (a) The context URI is set to the anchor parameter, when specified. + + (b) Origin of the target URI, when specified. + + (c) Origin of the link format resource's base URI. + +2.2. Link Relations + + Since links in the CoRE Link Format are typically used to describe + resources hosted by a server, the new relation type "hosts" is + assumed in the absence of the relation parameter (see Section 7.2). + The "hosts" relation type (from the verb "to host") indicates that + + + +Shelby Standards Track [Page 8] + +RFC 6690 CoRE Link Format August 2012 + + + the target URI is a resource hosted by the server (i.e., server hosts + resource) indicated by the context URI. The target URI MUST be a + relative URI of the context URI for this relation type. + + To express other relations, links can make use of any registered + relation by including the relation parameter. The context of a + relation can be defined using the anchor parameter. In this way, + relations between resources hosted on a server or between hosted + resources and external resources can be expressed. + +2.3. Use of Anchors + + As per Section 5.2 of [RFC5988], a link description MAY include an + "anchor" parameter, in which case the context is the URI included in + that attribute. This is used to describe a relationship between two + resources. A consuming implementation can, however, choose to ignore + such links. It is not expected that all implementations will be able + to derive useful information from explicitly anchored links. + +3. CoRE Link Attributes + + The following CoRE-specific target attributes are defined in addition + to those already defined in [RFC5988]. These attributes describe + information useful in accessing the target link of the relation and, + in some cases, can use the syntactical form of a URI. Such a URI MAY + be dereferenced (for instance, to obtain a description of the link + relation), but that is not part of the protocol and MUST NOT be done + automatically on link evaluation. When the values of attributes are + compared, they MUST be compared as strings. + +3.1. Resource Type 'rt' Attribute + + The Resource Type 'rt' attribute is an opaque string used to assign + an application-specific semantic type to a resource. One can think + of this as a noun describing the resource. In the case of a + temperature resource, this could be, e.g., an application-specific + semantic type like "outdoor-temperature" or a URI referencing a + specific concept in an ontology like + "http://sweet.jpl.nasa.gov/2.0/phys.owl#Temperature". Multiple + Resource Types MAY be included in the value of this parameter, each + separated by a space, similar to the relation attribute. The + registry for Resource Type values is defined in Section 7.4. + + The Resource Type attribute is not meant to be used to assign a + human-readable name to a resource. The "title" attribute defined in + [RFC5988] is meant for that purpose. The Resource Type attribute + MUST NOT appear more than once in a link. + + + + +Shelby Standards Track [Page 9] + +RFC 6690 CoRE Link Format August 2012 + + +3.2. Interface Description 'if' Attribute + + The Interface Description 'if' attribute is an opaque string used to + provide a name or URI indicating a specific interface definition used + to interact with the target resource. One can think of this as + describing verbs usable on a resource. The Interface Description + attribute is meant to describe the generic REST interface to interact + with a resource or a set of resources. It is expected that an + Interface Description will be reused by different Resource Types. + For example, the Resource Types "outdoor-temperature", "dew-point", + and "rel-humidity" could all be accessible using the Interface + Description "http://www.example.org/myapp.wadl#sensor". Multiple + Interface Descriptions MAY be included in the value of this + parameter, each separated by a space, similar to the relation + attribute. The registry for Interface Description values is defined + in Section 7.4. + + The Interface Description could be, for example, the URI of a Web + Application Description Language (WADL) [WADL] definition of the + target resource "http://www.example.org/myapp.wadl#sensor", a URN + indicating the type of interface to the resource "urn:myapp:sensor", + or an application-specific name "sensor". The Interface Description + attribute MUST NOT appear more than once in a link. + +3.3. Maximum Size Estimate 'sz' Attribute + + The maximum size estimate attribute 'sz' gives an indication of the + maximum size of the resource representation returned by performing a + GET on the target URI. For links to CoAP resources, this attribute + is not expected to be included for small resources that can + comfortably be carried in a single Maximum Transmission Unit (MTU) + but SHOULD be included for resources larger than that. The maximum + size estimate attribute MUST NOT appear more than once in a link. + + Note that there is no defined upper limit to the value of the 'sz' + attributes. Implementations MUST be prepared to accept large values. + One implementation strategy is to convert any value larger than a + reasonable size limit for this implementation to a special value + "Big", which in further processing would indicate that a size value + was given that was so big that it cannot be processed by this + implementation. + +4. Well-Known Interface + + Resource discovery in CoRE is accomplished through the use of a well- + known resource URI that returns a list of links about resources + hosted by that server and other link relations. Well-known resources + + + + +Shelby Standards Track [Page 10] + +RFC 6690 CoRE Link Format August 2012 + + + have a path component that begins with "/.well-known/" as specified + in [RFC5785]. This specification defines a new well-known resource + for CoRE Resource Discovery: "/.well-known/core". + + A server implementing this specification MUST support this resource + on the default port appropriate for the protocol for the purpose of + resource discovery. It is, however, up to the application which + links are included and how they are organized. The resource + "/.well-known/core" is meant to be used to return links to the entry + points of resource interfaces on a server. More sophisticated link + organization can be achieved by including links to CoRE Link Format + resources located elsewhere on the server, for example, to achieve an + index. In the absence of any links, a zero-length payload is + returned. The resource representation of this resource MUST be the + CoRE Link Format described in Section 2. + + The CoRE resource discovery interface supports the following + interactions: + + o Performing a GET on "/.well-known/core" to the default port + returns a set of links available from the server (if any) in the + CoRE Link Format. These links might describe resources hosted on + that server or on other servers or express other kinds of link + relations as described in Section 2. + + o Filtering may be performed on any of the link format attributes + using a query string as specified in Section 4.1. For example, + [GET /.well-known/core?rt=temperature-c] would request resources + with the Resource Type temperature-c. A server is not, however, + required to support filtering. + + o More capable servers such as proxies could support a resource + directory by requesting the resource descriptions of other end- + points or allowing servers to POST requests to "/.well-known/ + core". The details of such resource directory functionality is, + however, out of the scope of this specification and is expected to + be specified separately. + + + + + + + + + + + + + + +Shelby Standards Track [Page 11] + +RFC 6690 CoRE Link Format August 2012 + + +4.1. Query Filtering + + A server implementing this specification MAY recognize the query part + of a resource discovery URI as a filter on the resources to be + returned. The path and query components together should conform to + the following level-4 URI Template [RFC6570]: + + /.well-known/core{?search*} + + where the variable "search" is a 1-element list that has a single + name/value pair, where + + o name is either "href", a link-param name defined in this + specification, or any other link-extension name, and + + o value is either a Complete Value String that does not end in an + "*" (%2A), or a Prefix Value String followed by an "*" (%2A). + + The search name "href" refers to the URI-reference between the "<" + and ">" characters of a link. Both Value Strings match a target + attribute only if it exists. Value Strings are percent-decoded + ([RFC3986], Section 2.1) before matching; similarly, any target + attributes notated as quoted-string are interpreted as defined in + Section 2.2 of [RFC2616]. After these steps, a Complete Value String + matches a target attribute if it is bitwise identical. A Prefix + Value String matches a target attribute if it is a bitwise prefix of + the target attribute (where any string is a prefix of itself). Empty + Prefix Value Strings are allowed; by the definition above, they match + any target attribute that does exist. Note that relation-type target + attributes can contain multiple values, and each value MUST be + treated as a separate target attribute when matching. + + It is not expected that very constrained nodes support filtering. + Implementations not supporting filtering MUST simply ignore the query + string and return the whole resource for unicast requests. + + When using a transfer protocol like the Constrained Application + Protocol (CoAP) that supports multicast requests, special care needs + to be taken. A multicast request with a query string SHOULD NOT be + responded to if filtering is not supported or if the filter does not + match (to avoid a needless response storm). The exception is in + cases where the IP stack interface is not able to indicate that the + destination address was multicast. + + + + + + + + +Shelby Standards Track [Page 12] + +RFC 6690 CoRE Link Format August 2012 + + + The following are examples of valid query URIs: + + o ?href=/foo matches a link-value that is anchored at /foo + + o ?href=/foo* matches a link-value that is anchored at a URI that + starts with /foo + + o ?foo=bar matches a link-value that has a target attribute named + foo with the exact value bar + + o ?foo=bar* matches a link-value that has a target attribute named + foo, the value of which starts with bar, e.g., bar or barley + + o ?foo=* matches a link-value that has a target attribute named foo + +5. Examples + + A few examples of typical link descriptions in this format follows. + Multiple resource descriptions in a representation are separated by + commas. Linefeeds are also included in these examples for + readability. Although the following examples use CoAP response + codes, the examples are applicable to HTTP as well (the corresponding + response code would be 200 OK). + + This example includes links to two different sensors sharing the same + Interface Description. Note that the default relation type for this + link format is "hosts" in links with no rel= target attribute. Thus, + the links in this example tell that the Origin server from which + /.well-known/core was requested (the context) hosts the resources + /sensors/temp and /sensors/light (each a target). + + REQ: GET /.well-known/core + + RES: 2.05 Content + ;if="sensor", + ;if="sensor" + + Without the linefeeds inserted here for readability, the format + actually looks as follows. + + ;if="sensor",;if="sensor" + + This example arranges link descriptions hierarchically, with the + entry point including a link to a sub-resource containing links about + the sensors. + + + + + + +Shelby Standards Track [Page 13] + +RFC 6690 CoRE Link Format August 2012 + + + REQ: GET /.well-known/core + + RES: 2.05 Content + ;ct=40 + + REQ: GET /sensors + + RES: 2.05 Content + ;rt="temperature-c";if="sensor", + ;rt="light-lux";if="sensor" + + An example query filter may look like: + + REQ: GET /.well-known/core?rt=light-lux + + RES: 2.05 Content + ;rt="light-lux";if="sensor" + + Note that relation-type attributes like 'rt', 'if', and 'rel' can + have multiple values separated by spaces. A query filter parameter + can match any one of those values, as in this example: + + REQ: GET /.well-known/core?rt=light-lux + + RES: 2.05 Content + ;rt="light-lux core.sen-light";if="sensor" + + This example shows the use of an "anchor" attribute to relate the + temperature sensor resource to an external description and to an + alternative URI. + + REQ: GET /.well-known/core + + RES: 2.05 Content + ;ct=40;title="Sensor Index", + ;rt="temperature-c";if="sensor", + ;rt="light-lux";if="sensor", + ;anchor="/sensors/temp" + ;rel="describedby", + ;anchor="/sensors/temp";rel="alternate" + + + + + + + + + + + +Shelby Standards Track [Page 14] + +RFC 6690 CoRE Link Format August 2012 + + + If a client is interested in finding relations about a particular + resource, it can perform a query on the anchor parameter: + + REQ: GET /.well-known/core?anchor=/sensors/temp + + RES: 2.05 Content + ;anchor="/sensors/temp" + ;rel="describedby", + ;anchor="/sensors/temp";rel="alternate" + + The following example shows a large firmware resource with a size + attribute. The consumer of this link would use the 'sz' attribute to + determine if the resource representation is too large and if block + transfer would be required to request it. In this case, a client + with only a 64 KiB flash might only support a 16-bit integer for + storing the 'sz' attribute. Thus, a special flag or value should be + used to indicate "Big" (larger than 64 KiB). + + REQ: GET /.well-known/core?rt=firmware + + RES: 2.05 Content + ;rt="firmware";sz=262144 + +6. Security Considerations + + This specification has the same security considerations as described + in Section 7 of [RFC5988]. The "/.well-known/core" resource MAY be + protected, e.g., using Datagram Transport Layer Security (DTLS) when + hosted on a CoAP server as per [COAP], Section 9.1. + + Some servers might provide resource discovery services to a mix of + clients that are trusted to different levels. For example, a + lighting control system might allow any client to read state + variables, but only certain clients to write state (turn lights on or + off). Servers that have authentication and authorization features + SHOULD support authentication features of the underlying transport + protocols (HTTP or DTLS/TLS) and allow servers to return different + lists of links based on a client's identity and authorization. While + such servers might not return all links to all requesters, not + providing the link does not, by itself, control access to the + relevant resource -- a bad actor could know or guess the right URIs. + Servers can also lie about the resources available. If it is + important for a client to only get information from a known source, + then that source needs to be authenticated. + + + + + + + +Shelby Standards Track [Page 15] + +RFC 6690 CoRE Link Format August 2012 + + + Multicast requests using CoAP for the well-known link-format + resources could be used to perform denial of service on a constrained + network. A multicast request SHOULD only be accepted if the request + is sufficiently authenticated and secured using, e.g., IPsec or an + appropriate object security mechanism. + + CoRE Link Format parsers should be aware that a link description may + be cyclical, i.e., contain a link to itself. These cyclical links + could be direct or indirect (i.e., through referenced link + resources). Care should be taken when parsing link descriptions and + accessing cyclical links. + +7. IANA Considerations + +7.1. Well-Known 'core' URI + + This memo registers the 'core' well-known URI in the Well-Known URIs + registry as defined by [RFC5785]. + + URI suffix: core + + Change controller: IETF + + Specification document(s): RFC 6690 + + Related information: None + +7.2. New 'hosts' Relation Type + + This memo registers the new "hosts" Web Linking relation type as per + [RFC5988]. + + Relation Name: hosts + + Description: Refers to a resource hosted by the server indicated by + the link context. + + Reference: RFC 6690 + + Notes: This relation is used in CoRE where links are retrieved as a + "/.well-known/core" resource representation and is the default + relation type in the CoRE Link Format. + + Application Data: None + + + + + + + +Shelby Standards Track [Page 16] + +RFC 6690 CoRE Link Format August 2012 + + +7.3. New 'link-format' Internet Media Type + + This memo registers the a new Internet media type for the CoRE Link + Format, 'application/link-format'. + + Type name: application + + Subtype name: link-format + + Required parameters: None + + Optional parameters: None + + Encoding considerations: Binary data (UTF-8) + + Security considerations: + + Multicast requests using CoAP for the well-known link-format + resources could be used to perform denial of service on a constrained + network. A multicast request SHOULD only be accepted if the request + is sufficiently authenticated and secured using, e.g., IPsec or an + appropriate object security mechanism. + + CoRE Link Format parsers should be aware that a link description may + be cyclical, i.e., contain a link to itself. These cyclical links + could be direct or indirect (i.e., through referenced link + resources). Care should be taken when parsing link descriptions and + accessing cyclical links. + + Interoperability considerations: None + + Published specification: RFC 6690 + + Applications that use this media type: CoAP server and client + implementations for resource discovery and HTTP applications that use + the link-format as a payload. + + Additional information: + + Magic number(s): + + File extension(s): *.wlnk + + Macintosh file type code(s): + + Intended usage: COMMON + + Restrictions on usage: None + + + +Shelby Standards Track [Page 17] + +RFC 6690 CoRE Link Format August 2012 + + + Author: CoRE WG + + Change controller: IETF + +7.4. Constrained RESTful Environments (CoRE) Parameters Registry + + This specification establishes a new Constrained RESTful Environments + (CoRE) Parameters registry, which contains two new sub-registries of + Link Target Attribute values (defined in [RFC5988]), one for Resource + Type (rt=) Link Target Attribute values and the other for Interface + Description (if=) Link Target Attribute values. No initial entries + are defined by this specification for either sub-registry. + + For both sub-registries, values starting with the characters "core" + are registered using the IETF Review registration policy [RFC5226]. + All other values are registered using the Specification Required + policy, which requires review by a designated expert appointed by the + IESG or their delegate. + + The designated expert will enforce the following requirements: + + o Registration values MUST be related to the intended purpose of + these attributes as described in Section 3. + + o Registered values MUST conform to the ABNF reg-rel-type definition + of Section 2, meaning that the value starts with a lowercase + alphabetic character, followed by a sequence of lowercase + alphabetic, numeric, ".", or "-" characters, and contains no white + space. + + o It is recommended that the period "." character be used for + dividing name segments and that the dash "-" character be used for + making a segment more readable. Example Interface Description + values might be "core.batch" and "core.link-batch". + + o URIs are reserved for free use as extension values for these + attributes and MUST NOT be registered. + + Registration requests consist of the completed registration template + below, with the reference pointing to the required specification. To + allow for the allocation of values prior to publication, the + designated expert may approve registration once they are satisfied + that a specification will be published. + + Note that Link Target Attribute Values can be registered by third + parties if the Designated Expert determines that an unregistered Link + Target Attribute Value is widely deployed and not likely to be + registered in a timely manner. + + + +Shelby Standards Track [Page 18] + +RFC 6690 CoRE Link Format August 2012 + + + The registration template for both sub-registries is: + + o Attribute Value: + + o Description: + + o Reference: + + o Notes: [optional] + + Registration requests should be sent to the core-parameters@ietf.org + mailing list, marked clearly in the subject line (e.g., "NEW RESOURCE + TYPE - example" to register an "example" relation type or "NEW + INTERFACE DESCRIPTION - example" to register an "example" Interface + Description). + + Within at most 14 days of the request, the Designated Expert(s) will + either approve or deny the registration request, communicating this + decision to the review list and IANA. Denials should include an + explanation and, if applicable, suggestions as to how to make the + request successful. + + Decisions (or lack thereof) made by the Designated Expert can be + first appealed to Application Area Directors (contactable using the + app-ads@tools.ietf.org email address or directly by looking up their + email addresses on http://www.iesg.org/ website) and, if the + appellant is not satisfied with the response, to the full IESG (using + the iesg@ietf.org mailing list). + +8. Acknowledgments + + Special thanks to Peter Bigot, who has made a considerable number of + reviews and text contributions that greatly improved the document. + In particular, Peter is responsible for early improvements to the + ABNF descriptions and the idea for a new 'hosts' relation type. + + Thanks to Mark Nottingham and Eran Hammer-Lahav for the discussions + and ideas that led to this document, and to Carsten Bormann, Martin + Thomson, Alexey Melnikov, Julian Reschke, Joel Halpern, Richard + Barnes, Barry Leiba, and Peter Saint-Andre for extensive comments and + contributions that improved the text. + + Thanks to Michael Stuber, Richard Kelsey, Cullen Jennings, Guido + Moritz, Peter Van Der Stok, Adriano Pezzuto, Lisa Dussealt, Alexey + Melnikov, Gilbert Clark, Salvatore Loreto, Petri Mutka, Szymon Sasin, + Robert Quattlebaum, Robert Cragie, Angelo Castellani, Tom Herbst, Ed + Beroset, Gilman Tolle, Robby Simpson, Colin O'Flynn, and David Ryan + for helpful comments and discussions that have shaped the document. + + + +Shelby Standards Track [Page 19] + +RFC 6690 CoRE Link Format August 2012 + + +9. References + +9.1. Normative References + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [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, June 1999. + + [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, November 2003. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, January 2005. + + [RFC4288] Freed, N. and J. Klensin, "Media Type Specifications and + Registration Procedures", BCP 13, RFC 4288, December 2005. + + [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an + IANA Considerations Section in RFCs", BCP 26, RFC 5226, + May 2008. + + [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, January 2008. + + [RFC5646] Phillips, A. and M. Davis, "Tags for Identifying + Languages", BCP 47, RFC 5646, September 2009. + + [RFC5987] Reschke, J., "Character Set and Language Encoding for + Hypertext Transfer Protocol (HTTP) Header Field + Parameters", RFC 5987, August 2010. + + [RFC5988] Nottingham, M., "Web Linking", RFC 5988, October 2010. + + [RFC6570] Gregorio, J., Fielding, R., Hadley, M., Nottingham, M., + and D. Orchard, "URI Template", RFC 6570, March 2012. + +9.2. Informative References + + [COAP] Shelby, Z., Hartke, K., Bormann, C., and B. Frank, + "Constrained Application Protocol (CoAP)", Work in + Progress, July 2012. + + + + + + +Shelby Standards Track [Page 20] + +RFC 6690 CoRE Link Format August 2012 + + + [REST] Fielding, R., "Architectural Styles and the Design of + Network-based Software Architectures", 2000, + . + + [RFC1034] Mockapetris, P., "Domain names - concepts and facilities", + STD 13, RFC 1034, November 1987. + + [RFC1035] Mockapetris, P., "Domain names - implementation and + specification", STD 13, RFC 1035, November 1987. + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message + Bodies", RFC 2045, November 1996. + + [RFC2231] Freed, N. and K. Moore, "MIME Parameter Value and Encoded + Word Extensions: Character Sets, Languages, and + Continuations", RFC 2231, November 1997. + + [RFC4287] Nottingham, M., Ed. and R. Sayre, Ed., "The Atom + Syndication Format", RFC 4287, December 2005. + + [RFC4919] Kushalnagar, N., Montenegro, G., and C. Schumacher, "IPv6 + over Low-Power Wireless Personal Area Networks (6LoWPANs): + Overview, Assumptions, Problem Statement, and Goals", + RFC 4919, August 2007. + + [RFC5785] Nottingham, M. and E. Hammer-Lahav, "Defining Well-Known + Uniform Resource Identifiers (URIs)", RFC 5785, + April 2010. + + [RFC6454] Barth, A., "The Web Origin Concept", RFC 6454, + December 2011. + + [W3C.HTML.4.01] + Raggett, D., Le Hors, A., and I. Jacobs, "HTML 4.01 + Specification", World Wide Web Consortium + Recommendation REC-html401-19991224, December 1999, + . + + [WADL] Hadley, M., "Web Application Description Language (WADL)", + 2009, . + + + + + + + + +Shelby Standards Track [Page 21] + +RFC 6690 CoRE Link Format August 2012 + + +Author's Address + + Zach Shelby + Sensinode + Kidekuja 2 + Vuokatti 88600 + Finland + + Phone: +358407796297 + EMail: zach@sensinode.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Shelby Standards Track [Page 22] + diff --git a/rfc/rfc7252.txt b/rfc/rfc7252.txt new file mode 100644 index 0000000..7ba5d03 --- /dev/null +++ b/rfc/rfc7252.txt @@ -0,0 +1,6275 @@ + + + + + + +Internet Engineering Task Force (IETF) Z. Shelby +Request for Comments: 7252 ARM +Category: Standards Track K. Hartke +ISSN: 2070-1721 C. Bormann + Universitaet Bremen TZI + June 2014 + + + The Constrained Application Protocol (CoAP) + +Abstract + + The Constrained Application Protocol (CoAP) is a specialized web + transfer protocol for use with constrained nodes and constrained + (e.g., low-power, lossy) networks. The nodes often have 8-bit + microcontrollers with small amounts of ROM and RAM, while constrained + networks such as IPv6 over Low-Power Wireless Personal Area Networks + (6LoWPANs) often have high packet error rates and a typical + throughput of 10s of kbit/s. The protocol is designed for machine- + to-machine (M2M) applications such as smart energy and building + automation. + + CoAP provides a request/response interaction model between + application endpoints, supports built-in discovery of services and + resources, and includes key concepts of the Web such as URIs and + Internet media types. CoAP is designed to easily interface with HTTP + for integration with the Web while meeting specialized requirements + such as multicast support, very low overhead, and simplicity for + constrained environments. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc7252. + + + + + + + + +Shelby, et al. Standards Track [Page 1] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +Copyright Notice + + Copyright (c) 2014 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 5 + 1.1. Features . . . . . . . . . . . . . . . . . . . . . . . . 5 + 1.2. Terminology . . . . . . . . . . . . . . . . . . . . . . . 6 + 2. Constrained Application Protocol . . . . . . . . . . . . . . 10 + 2.1. Messaging Model . . . . . . . . . . . . . . . . . . . . . 11 + 2.2. Request/Response Model . . . . . . . . . . . . . . . . . 12 + 2.3. Intermediaries and Caching . . . . . . . . . . . . . . . 15 + 2.4. Resource Discovery . . . . . . . . . . . . . . . . . . . 15 + 3. Message Format . . . . . . . . . . . . . . . . . . . . . . . 15 + 3.1. Option Format . . . . . . . . . . . . . . . . . . . . . . 17 + 3.2. Option Value Formats . . . . . . . . . . . . . . . . . . 19 + 4. Message Transmission . . . . . . . . . . . . . . . . . . . . 20 + 4.1. Messages and Endpoints . . . . . . . . . . . . . . . . . 20 + 4.2. Messages Transmitted Reliably . . . . . . . . . . . . . . 21 + 4.3. Messages Transmitted without Reliability . . . . . . . . 23 + 4.4. Message Correlation . . . . . . . . . . . . . . . . . . . 24 + 4.5. Message Deduplication . . . . . . . . . . . . . . . . . . 24 + 4.6. Message Size . . . . . . . . . . . . . . . . . . . . . . 25 + 4.7. Congestion Control . . . . . . . . . . . . . . . . . . . 26 + 4.8. Transmission Parameters . . . . . . . . . . . . . . . . . 27 + 4.8.1. Changing the Parameters . . . . . . . . . . . . . . . 27 + 4.8.2. Time Values Derived from Transmission Parameters . . 28 + 5. Request/Response Semantics . . . . . . . . . . . . . . . . . 31 + 5.1. Requests . . . . . . . . . . . . . . . . . . . . . . . . 31 + 5.2. Responses . . . . . . . . . . . . . . . . . . . . . . . . 31 + 5.2.1. Piggybacked . . . . . . . . . . . . . . . . . . . . . 33 + 5.2.2. Separate . . . . . . . . . . . . . . . . . . . . . . 33 + 5.2.3. Non-confirmable . . . . . . . . . . . . . . . . . . . 34 + 5.3. Request/Response Matching . . . . . . . . . . . . . . . . 34 + 5.3.1. Token . . . . . . . . . . . . . . . . . . . . . . . . 34 + 5.3.2. Request/Response Matching Rules . . . . . . . . . . . 35 + + + +Shelby, et al. Standards Track [Page 2] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + 5.4. Options . . . . . . . . . . . . . . . . . . . . . . . . . 36 + 5.4.1. Critical/Elective . . . . . . . . . . . . . . . . . . 37 + 5.4.2. Proxy Unsafe or Safe-to-Forward and NoCacheKey . . . 38 + 5.4.3. Length . . . . . . . . . . . . . . . . . . . . . . . 38 + 5.4.4. Default Values . . . . . . . . . . . . . . . . . . . 38 + 5.4.5. Repeatable Options . . . . . . . . . . . . . . . . . 39 + 5.4.6. Option Numbers . . . . . . . . . . . . . . . . . . . 39 + 5.5. Payloads and Representations . . . . . . . . . . . . . . 40 + 5.5.1. Representation . . . . . . . . . . . . . . . . . . . 40 + 5.5.2. Diagnostic Payload . . . . . . . . . . . . . . . . . 41 + 5.5.3. Selected Representation . . . . . . . . . . . . . . . 41 + 5.5.4. Content Negotiation . . . . . . . . . . . . . . . . . 41 + 5.6. Caching . . . . . . . . . . . . . . . . . . . . . . . . . 42 + 5.6.1. Freshness Model . . . . . . . . . . . . . . . . . . . 43 + 5.6.2. Validation Model . . . . . . . . . . . . . . . . . . 43 + 5.7. Proxying . . . . . . . . . . . . . . . . . . . . . . . . 44 + 5.7.1. Proxy Operation . . . . . . . . . . . . . . . . . . . 44 + 5.7.2. Forward-Proxies . . . . . . . . . . . . . . . . . . . 46 + 5.7.3. Reverse-Proxies . . . . . . . . . . . . . . . . . . . 46 + 5.8. Method Definitions . . . . . . . . . . . . . . . . . . . 47 + 5.8.1. GET . . . . . . . . . . . . . . . . . . . . . . . . . 47 + 5.8.2. POST . . . . . . . . . . . . . . . . . . . . . . . . 47 + 5.8.3. PUT . . . . . . . . . . . . . . . . . . . . . . . . . 48 + 5.8.4. DELETE . . . . . . . . . . . . . . . . . . . . . . . 48 + 5.9. Response Code Definitions . . . . . . . . . . . . . . . . 48 + 5.9.1. Success 2.xx . . . . . . . . . . . . . . . . . . . . 48 + 5.9.2. Client Error 4.xx . . . . . . . . . . . . . . . . . . 50 + 5.9.3. Server Error 5.xx . . . . . . . . . . . . . . . . . . 51 + 5.10. Option Definitions . . . . . . . . . . . . . . . . . . . 52 + 5.10.1. Uri-Host, Uri-Port, Uri-Path, and Uri-Query . . . . 53 + 5.10.2. Proxy-Uri and Proxy-Scheme . . . . . . . . . . . . . 54 + 5.10.3. Content-Format . . . . . . . . . . . . . . . . . . . 55 + 5.10.4. Accept . . . . . . . . . . . . . . . . . . . . . . . 55 + 5.10.5. Max-Age . . . . . . . . . . . . . . . . . . . . . . 55 + 5.10.6. ETag . . . . . . . . . . . . . . . . . . . . . . . . 56 + 5.10.7. Location-Path and Location-Query . . . . . . . . . . 57 + 5.10.8. Conditional Request Options . . . . . . . . . . . . 57 + 5.10.9. Size1 Option . . . . . . . . . . . . . . . . . . . . 59 + 6. CoAP URIs . . . . . . . . . . . . . . . . . . . . . . . . . . 59 + 6.1. coap URI Scheme . . . . . . . . . . . . . . . . . . . . . 59 + 6.2. coaps URI Scheme . . . . . . . . . . . . . . . . . . . . 60 + 6.3. Normalization and Comparison Rules . . . . . . . . . . . 61 + 6.4. Decomposing URIs into Options . . . . . . . . . . . . . . 61 + 6.5. Composing URIs from Options . . . . . . . . . . . . . . . 62 + 7. Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . 64 + 7.1. Service Discovery . . . . . . . . . . . . . . . . . . . . 64 + 7.2. Resource Discovery . . . . . . . . . . . . . . . . . . . 64 + 7.2.1. 'ct' Attribute . . . . . . . . . . . . . . . . . . . 64 + + + +Shelby, et al. Standards Track [Page 3] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + 8. Multicast CoAP . . . . . . . . . . . . . . . . . . . . . . . 65 + 8.1. Messaging Layer . . . . . . . . . . . . . . . . . . . . . 65 + 8.2. Request/Response Layer . . . . . . . . . . . . . . . . . 66 + 8.2.1. Caching . . . . . . . . . . . . . . . . . . . . . . . 67 + 8.2.2. Proxying . . . . . . . . . . . . . . . . . . . . . . 67 + 9. Securing CoAP . . . . . . . . . . . . . . . . . . . . . . . . 68 + 9.1. DTLS-Secured CoAP . . . . . . . . . . . . . . . . . . . . 69 + 9.1.1. Messaging Layer . . . . . . . . . . . . . . . . . . . 70 + 9.1.2. Request/Response Layer . . . . . . . . . . . . . . . 71 + 9.1.3. Endpoint Identity . . . . . . . . . . . . . . . . . . 71 + 10. Cross-Protocol Proxying between CoAP and HTTP . . . . . . . . 74 + 10.1. CoAP-HTTP Proxying . . . . . . . . . . . . . . . . . . . 75 + 10.1.1. GET . . . . . . . . . . . . . . . . . . . . . . . . 76 + 10.1.2. PUT . . . . . . . . . . . . . . . . . . . . . . . . 77 + 10.1.3. DELETE . . . . . . . . . . . . . . . . . . . . . . . 77 + 10.1.4. POST . . . . . . . . . . . . . . . . . . . . . . . . 77 + 10.2. HTTP-CoAP Proxying . . . . . . . . . . . . . . . . . . . 77 + 10.2.1. OPTIONS and TRACE . . . . . . . . . . . . . . . . . 78 + 10.2.2. GET . . . . . . . . . . . . . . . . . . . . . . . . 78 + 10.2.3. HEAD . . . . . . . . . . . . . . . . . . . . . . . . 79 + 10.2.4. POST . . . . . . . . . . . . . . . . . . . . . . . . 79 + 10.2.5. PUT . . . . . . . . . . . . . . . . . . . . . . . . 79 + 10.2.6. DELETE . . . . . . . . . . . . . . . . . . . . . . . 80 + 10.2.7. CONNECT . . . . . . . . . . . . . . . . . . . . . . 80 + 11. Security Considerations . . . . . . . . . . . . . . . . . . . 80 + 11.1. Parsing the Protocol and Processing URIs . . . . . . . . 80 + 11.2. Proxying and Caching . . . . . . . . . . . . . . . . . . 81 + 11.3. Risk of Amplification . . . . . . . . . . . . . . . . . 81 + 11.4. IP Address Spoofing Attacks . . . . . . . . . . . . . . 83 + 11.5. Cross-Protocol Attacks . . . . . . . . . . . . . . . . . 84 + 11.6. Constrained-Node Considerations . . . . . . . . . . . . 86 + 12. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 86 + 12.1. CoAP Code Registries . . . . . . . . . . . . . . . . . . 86 + 12.1.1. Method Codes . . . . . . . . . . . . . . . . . . . . 87 + 12.1.2. Response Codes . . . . . . . . . . . . . . . . . . . 88 + 12.2. CoAP Option Numbers Registry . . . . . . . . . . . . . . 89 + 12.3. CoAP Content-Formats Registry . . . . . . . . . . . . . 91 + 12.4. URI Scheme Registration . . . . . . . . . . . . . . . . 93 + 12.5. Secure URI Scheme Registration . . . . . . . . . . . . . 94 + 12.6. Service Name and Port Number Registration . . . . . . . 95 + 12.7. Secure Service Name and Port Number Registration . . . . 96 + 12.8. Multicast Address Registration . . . . . . . . . . . . . 97 + 13. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 97 + 14. References . . . . . . . . . . . . . . . . . . . . . . . . . 98 + 14.1. Normative References . . . . . . . . . . . . . . . . . . 98 + 14.2. Informative References . . . . . . . . . . . . . . . . . 100 + Appendix A. Examples . . . . . . . . . . . . . . . . . . . . . . 104 + Appendix B. URI Examples . . . . . . . . . . . . . . . . . . . . 110 + + + +Shelby, et al. Standards Track [Page 4] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +1. Introduction + + The use of web services (web APIs) on the Internet has become + ubiquitous in most applications and depends on the fundamental + Representational State Transfer [REST] architecture of the Web. + + The work on Constrained RESTful Environments (CoRE) aims at realizing + the REST architecture in a suitable form for the most constrained + nodes (e.g., 8-bit microcontrollers with limited RAM and ROM) and + networks (e.g., 6LoWPAN, [RFC4944]). Constrained networks such as + 6LoWPAN support the fragmentation of IPv6 packets into small link- + layer frames; however, this causes significant reduction in packet + delivery probability. One design goal of CoAP has been to keep + message overhead small, thus limiting the need for fragmentation. + + One of the main goals of CoAP is to design a generic web protocol for + the special requirements of this constrained environment, especially + considering energy, building automation, and other machine-to-machine + (M2M) applications. The goal of CoAP is not to blindly compress HTTP + [RFC2616], but rather to realize a subset of REST common with HTTP + but optimized for M2M applications. Although CoAP could be used for + refashioning simple HTTP interfaces into a more compact protocol, + more importantly it also offers features for M2M such as built-in + discovery, multicast support, and asynchronous message exchanges. + + This document specifies the Constrained Application Protocol (CoAP), + which easily translates to HTTP for integration with the existing Web + while meeting specialized requirements such as multicast support, + very low overhead, and simplicity for constrained environments and + M2M applications. + +1.1. Features + + CoAP has the following main features: + + o Web protocol fulfilling M2M requirements in constrained + environments + + o UDP [RFC0768] binding with optional reliability supporting unicast + and multicast requests. + + o Asynchronous message exchanges. + + o Low header overhead and parsing complexity. + + o URI and Content-type support. + + o Simple proxy and caching capabilities. + + + +Shelby, et al. Standards Track [Page 5] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o A stateless HTTP mapping, allowing proxies to be built providing + access to CoAP resources via HTTP in a uniform way or for HTTP + simple interfaces to be realized alternatively over CoAP. + + o Security binding to Datagram Transport Layer Security (DTLS) + [RFC6347]. + +1.2. Terminology + + The key words "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 + [RFC2119] when they appear in ALL CAPS. These words may also appear + in this document in lowercase, absent their normative meanings. + + This specification requires readers to be familiar with all the terms + and concepts that are discussed in [RFC2616], including "resource", + "representation", "cache", and "fresh". (Having been completed + before the updated set of HTTP RFCs, RFC 7230 to RFC 7235, became + available, this specification specifically references the predecessor + version -- RFC 2616.) In addition, this specification defines the + following terminology: + + Endpoint + An entity participating in the CoAP protocol. Colloquially, an + endpoint lives on a "Node", although "Host" would be more + consistent with Internet standards usage, and is further + identified by transport-layer multiplexing information that can + include a UDP port number and a security association + (Section 4.1). + + Sender + The originating endpoint of a message. When the aspect of + identification of the specific sender is in focus, also "source + endpoint". + + Recipient + The destination endpoint of a message. When the aspect of + identification of the specific recipient is in focus, also + "destination endpoint". + + Client + The originating endpoint of a request; the destination endpoint of + a response. + + Server + The destination endpoint of a request; the originating endpoint of + a response. + + + +Shelby, et al. Standards Track [Page 6] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Origin Server + The server on which a given resource resides or is to be created. + + Intermediary + A CoAP endpoint that acts both as a server and as a client towards + an origin server (possibly via further intermediaries). A common + form of an intermediary is a proxy; several classes of such + proxies are discussed in this specification. + + Proxy + An intermediary that mainly is concerned with forwarding requests + and relaying back responses, possibly performing caching, + namespace translation, or protocol translation in the process. As + opposed to intermediaries in the general sense, proxies generally + do not implement specific application semantics. Based on the + position in the overall structure of the request forwarding, there + are two common forms of proxy: forward-proxy and reverse-proxy. + In some cases, a single endpoint might act as an origin server, + forward-proxy, or reverse-proxy, switching behavior based on the + nature of each request. + + Forward-Proxy + An endpoint selected by a client, usually via local configuration + rules, to perform requests on behalf of the client, doing any + necessary translations. Some translations are minimal, such as + for proxy requests for "coap" URIs, whereas other requests might + require translation to and from entirely different application- + layer protocols. + + Reverse-Proxy + An endpoint that stands in for one or more other server(s) and + satisfies requests on behalf of these, doing any necessary + translations. Unlike a forward-proxy, the client may not be aware + that it is communicating with a reverse-proxy; a reverse-proxy + receives requests as if it were the origin server for the target + resource. + + CoAP-to-CoAP Proxy + A proxy that maps from a CoAP request to a CoAP request, i.e., + uses the CoAP protocol both on the server and the client side. + Contrast to cross-proxy. + + Cross-Proxy + A cross-protocol proxy, or "cross-proxy" for short, is a proxy + that translates between different protocols, such as a CoAP-to- + HTTP proxy or an HTTP-to-CoAP proxy. While this specification + makes very specific demands of CoAP-to-CoAP proxies, there is more + variation possible in cross-proxies. + + + +Shelby, et al. Standards Track [Page 7] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Confirmable Message + Some messages require an acknowledgement. These messages are + called "Confirmable". When no packets are lost, each Confirmable + message elicits exactly one return message of type Acknowledgement + or type Reset. + + Non-confirmable Message + Some other messages do not require an acknowledgement. This is + particularly true for messages that are repeated regularly for + application requirements, such as repeated readings from a sensor. + + Acknowledgement Message + An Acknowledgement message acknowledges that a specific + Confirmable message arrived. By itself, an Acknowledgement + message does not indicate success or failure of any request + encapsulated in the Confirmable message, but the Acknowledgement + message may also carry a Piggybacked Response (see below). + + Reset Message + A Reset message indicates that a specific message (Confirmable or + Non-confirmable) was received, but some context is missing to + properly process it. This condition is usually caused when the + receiving node has rebooted and has forgotten some state that + would be required to interpret the message. Provoking a Reset + message (e.g., by sending an Empty Confirmable message) is also + useful as an inexpensive check of the liveness of an endpoint + ("CoAP ping"). + + Piggybacked Response + A piggybacked Response is included right in a CoAP Acknowledgement + (ACK) message that is sent to acknowledge receipt of the Request + for this Response (Section 5.2.1). + + Separate Response + When a Confirmable message carrying a request is acknowledged with + an Empty message (e.g., because the server doesn't have the answer + right away), a Separate Response is sent in a separate message + exchange (Section 5.2.2). + + Empty Message + A message with a Code of 0.00; neither a request nor a response. + An Empty message only contains the 4-byte header. + + + + + + + + + +Shelby, et al. Standards Track [Page 8] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Critical Option + An option that would need to be understood by the endpoint + ultimately receiving the message in order to properly process the + message (Section 5.4.1). Note that the implementation of critical + options is, as the name "Option" implies, generally optional: + unsupported critical options lead to an error response or summary + rejection of the message. + + Elective Option + An option that is intended to be ignored by an endpoint that does + not understand it. Processing the message even without + understanding the option is acceptable (Section 5.4.1). + + Unsafe Option + An option that would need to be understood by a proxy receiving + the message in order to safely forward the message + (Section 5.4.2). Not every critical option is an unsafe option. + + Safe-to-Forward Option + An option that is intended to be safe for forwarding by a proxy + that does not understand it. Forwarding the message even without + understanding the option is acceptable (Section 5.4.2). + + Resource Discovery + The process where a CoAP client queries a server for its list of + hosted resources (i.e., links as defined in Section 7). + + Content-Format + The combination of an Internet media type, potentially with + specific parameters given, and a content-coding (which is often + the identity content-coding), identified by a numeric identifier + defined by the "CoAP Content-Formats" registry. When the focus is + less on the numeric identifier than on the combination of these + characteristics of a resource representation, this is also called + "representation format". + + Additional terminology for constrained nodes and constrained-node + networks can be found in [RFC7228]. + + In this specification, the term "byte" is used in its now customary + sense as a synonym for "octet". + + All multi-byte integers in this protocol are interpreted in network + byte order. + + Where arithmetic is used, this specification uses the notation + familiar from the programming language C, except that the operator + "**" stands for exponentiation. + + + +Shelby, et al. Standards Track [Page 9] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +2. Constrained Application Protocol + + The interaction model of CoAP is similar to the client/server model + of HTTP. However, machine-to-machine interactions typically result + in a CoAP implementation acting in both client and server roles. A + CoAP request is equivalent to that of HTTP and is sent by a client to + request an action (using a Method Code) on a resource (identified by + a URI) on a server. The server then sends a response with a Response + Code; this response may include a resource representation. + + Unlike HTTP, CoAP deals with these interchanges asynchronously over a + datagram-oriented transport such as UDP. This is done logically + using a layer of messages that supports optional reliability (with + exponential back-off). CoAP defines four types of messages: + Confirmable, Non-confirmable, Acknowledgement, Reset. Method Codes + and Response Codes included in some of these messages make them carry + requests or responses. The basic exchanges of the four types of + messages are somewhat orthogonal to the request/response + interactions; requests can be carried in Confirmable and Non- + confirmable messages, and responses can be carried in these as well + as piggybacked in Acknowledgement messages. + + One could think of CoAP logically as using a two-layer approach, a + CoAP messaging layer used to deal with UDP and the asynchronous + nature of the interactions, and the request/response interactions + using Method and Response Codes (see Figure 1). CoAP is however a + single protocol, with messaging and request/response as just features + of the CoAP header. + + +----------------------+ + | Application | + +----------------------+ + +----------------------+ \ + | Requests/Responses | | + |----------------------| | CoAP + | Messages | | + +----------------------+ / + +----------------------+ + | UDP | + +----------------------+ + + Figure 1: Abstract Layering of CoAP + + + + + + + + + +Shelby, et al. Standards Track [Page 10] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +2.1. Messaging Model + + The CoAP messaging model is based on the exchange of messages over + UDP between endpoints. + + CoAP uses a short fixed-length binary header (4 bytes) that may be + followed by compact binary options and a payload. This message + format is shared by requests and responses. The CoAP message format + is specified in Section 3. Each message contains a Message ID used + to detect duplicates and for optional reliability. (The Message ID + is compact; its 16-bit size enables up to about 250 messages per + second from one endpoint to another with default protocol + parameters.) + + Reliability is provided by marking a message as Confirmable (CON). A + Confirmable message is retransmitted using a default timeout and + exponential back-off between retransmissions, until the recipient + sends an Acknowledgement message (ACK) with the same Message ID (in + this example, 0x7d34) from the corresponding endpoint; see Figure 2. + When a recipient is not at all able to process a Confirmable message + (i.e., not even able to provide a suitable error response), it + replies with a Reset message (RST) instead of an Acknowledgement + (ACK). + + Client Server + | | + | CON [0x7d34] | + +----------------->| + | | + | ACK [0x7d34] | + |<-----------------+ + | | + + Figure 2: Reliable Message Transmission + + A message that does not require reliable transmission (for example, + each single measurement out of a stream of sensor data) can be sent + as a Non-confirmable message (NON). These are not acknowledged, but + still have a Message ID for duplicate detection (in this example, + 0x01a0); see Figure 3. When a recipient is not able to process a + Non-confirmable message, it may reply with a Reset message (RST). + + + + + + + + + + +Shelby, et al. Standards Track [Page 11] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Client Server + | | + | NON [0x01a0] | + +----------------->| + | | + + Figure 3: Unreliable Message Transmission + + See Section 4 for details of CoAP messages. + + As CoAP runs over UDP, it also supports the use of multicast IP + destination addresses, enabling multicast CoAP requests. Section 8 + discusses the proper use of CoAP messages with multicast addresses + and precautions for avoiding response congestion. + + Several security modes are defined for CoAP in Section 9 ranging from + no security to certificate-based security. This document specifies a + binding to DTLS for securing the protocol; the use of IPsec with CoAP + is discussed in [IPsec-CoAP]. + +2.2. Request/Response Model + + CoAP request and response semantics are carried in CoAP messages, + which include either a Method Code or Response Code, respectively. + Optional (or default) request and response information, such as the + URI and payload media type are carried as CoAP options. A Token is + used to match responses to requests independently from the underlying + messages (Section 5.3). (Note that the Token is a concept separate + from the Message ID.) + + A request is carried in a Confirmable (CON) or Non-confirmable (NON) + message, and, if immediately available, the response to a request + carried in a Confirmable message is carried in the resulting + Acknowledgement (ACK) message. This is called a piggybacked + response, detailed in Section 5.2.1. (There is no need for + separately acknowledging a piggybacked response, as the client will + retransmit the request if the Acknowledgement message carrying the + piggybacked response is lost.) Two examples for a basic GET request + with piggybacked response are shown in Figure 4, one successful, one + resulting in a 4.04 (Not Found) response. + + + + + + + + + + + +Shelby, et al. Standards Track [Page 12] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Client Server Client Server + | | | | + | CON [0xbc90] | | CON [0xbc91] | + | GET /temperature | | GET /temperature | + | (Token 0x71) | | (Token 0x72) | + +----------------->| +----------------->| + | | | | + | ACK [0xbc90] | | ACK [0xbc91] | + | 2.05 Content | | 4.04 Not Found | + | (Token 0x71) | | (Token 0x72) | + | "22.5 C" | | "Not found" | + |<-----------------+ |<-----------------+ + | | | | + + Figure 4: Two GET Requests with Piggybacked Responses + + If the server is not able to respond immediately to a request carried + in a Confirmable message, it simply responds with an Empty + Acknowledgement message so that the client can stop retransmitting + the request. When the response is ready, the server sends it in a + new Confirmable message (which then in turn needs to be acknowledged + by the client). This is called a "separate response", as illustrated + in Figure 5 and described in more detail in Section 5.2.2. + + Client Server + | | + | CON [0x7a10] | + | GET /temperature | + | (Token 0x73) | + +----------------->| + | | + | ACK [0x7a10] | + |<-----------------+ + | | + ... Time Passes ... + | | + | CON [0x23bb] | + | 2.05 Content | + | (Token 0x73) | + | "22.5 C" | + |<-----------------+ + | | + | ACK [0x23bb] | + +----------------->| + | | + + Figure 5: A GET Request with a Separate Response + + + + +Shelby, et al. Standards Track [Page 13] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + If a request is sent in a Non-confirmable message, then the response + is sent using a new Non-confirmable message, although the server may + instead send a Confirmable message. This type of exchange is + illustrated in Figure 6. + + Client Server + | | + | NON [0x7a11] | + | GET /temperature | + | (Token 0x74) | + +----------------->| + | | + | NON [0x23bc] | + | 2.05 Content | + | (Token 0x74) | + | "22.5 C" | + |<-----------------+ + | | + + Figure 6: A Request and a Response Carried in Non-confirmable + Messages + + CoAP makes use of GET, PUT, POST, and DELETE methods in a similar + manner to HTTP, with the semantics specified in Section 5.8. (Note + that the detailed semantics of CoAP methods are "almost, but not + entirely unlike" [HHGTTG] those of HTTP methods: intuition taken from + HTTP experience generally does apply well, but there are enough + differences that make it worthwhile to actually read the present + specification.) + + Methods beyond the basic four can be added to CoAP in separate + specifications. New methods do not necessarily have to use requests + and responses in pairs. Even for existing methods, a single request + may yield multiple responses, e.g., for a multicast request + (Section 8) or with the Observe option [OBSERVE]. + + URI support in a server is simplified as the client already parses + the URI and splits it into host, port, path, and query components, + making use of default values for efficiency. Response Codes relate + to a small subset of HTTP status codes with a few CoAP-specific codes + added, as defined in Section 5.9. + + + + + + + + + + +Shelby, et al. Standards Track [Page 14] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +2.3. Intermediaries and Caching + + The protocol supports the caching of responses in order to + efficiently fulfill requests. Simple caching is enabled using + freshness and validity information carried with CoAP responses. A + cache could be located in an endpoint or an intermediary. Caching + functionality is specified in Section 5.6. + + Proxying is useful in constrained networks for several reasons, + including to limit network traffic, to improve performance, to access + resources of sleeping devices, and for security reasons. The + proxying of requests on behalf of another CoAP endpoint is supported + in the protocol. When using a proxy, the URI of the resource to + request is included in the request, while the destination IP address + is set to the address of the proxy. See Section 5.7 for more + information on proxy functionality. + + As CoAP was designed according to the REST architecture [REST], and + thus exhibits functionality similar to that of the HTTP protocol, it + is quite straightforward to map from CoAP to HTTP and from HTTP to + CoAP. Such a mapping may be used to realize an HTTP REST interface + using CoAP or to convert between HTTP and CoAP. This conversion can + be carried out by a cross-protocol proxy ("cross-proxy"), which + converts the Method or Response Code, media type, and options to the + corresponding HTTP feature. Section 10 provides more detail about + HTTP mapping. + +2.4. Resource Discovery + + Resource discovery is important for machine-to-machine interactions + and is supported using the CoRE Link Format [RFC6690] as discussed in + Section 7. + +3. Message Format + + CoAP is based on the exchange of compact messages that, by default, + are transported over UDP (i.e., each CoAP message occupies the data + section of one UDP datagram). CoAP may also be used over Datagram + Transport Layer Security (DTLS) (see Section 9.1). It could also be + used over other transports such as SMS, TCP, or SCTP, the + specification of which is out of this document's scope. (UDP-lite + [RFC3828] and UDP zero checksum [RFC6936] are not supported by CoAP.) + + CoAP messages are encoded in a simple binary format. The message + format starts with a fixed-size 4-byte header. This is followed by a + variable-length Token value, which can be between 0 and 8 bytes long. + + + + + +Shelby, et al. Standards Track [Page 15] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Following the Token value comes a sequence of zero or more CoAP + Options in Type-Length-Value (TLV) format, optionally followed by a + payload that takes up the rest of the datagram. + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |Ver| T | TKL | Code | Message ID | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Token (if any, TKL bytes) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Options (if any) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |1 1 1 1 1 1 1 1| Payload (if any) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Figure 7: Message Format + + The fields in the header are defined as follows: + + Version (Ver): 2-bit unsigned integer. Indicates the CoAP version + number. Implementations of this specification MUST set this field + to 1 (01 binary). Other values are reserved for future versions. + Messages with unknown version numbers MUST be silently ignored. + + Type (T): 2-bit unsigned integer. Indicates if this message is of + type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or + Reset (3). The semantics of these message types are defined in + Section 4. + + Token Length (TKL): 4-bit unsigned integer. Indicates the length of + the variable-length Token field (0-8 bytes). Lengths 9-15 are + reserved, MUST NOT be sent, and MUST be processed as a message + format error. + + Code: 8-bit unsigned integer, split into a 3-bit class (most + significant bits) and a 5-bit detail (least significant bits), + documented as "c.dd" where "c" is a digit from 0 to 7 for the + 3-bit subfield and "dd" are two digits from 00 to 31 for the 5-bit + subfield. The class can indicate a request (0), a success + response (2), a client error response (4), or a server error + response (5). (All other class values are reserved.) As a + special case, Code 0.00 indicates an Empty message. In case of a + request, the Code field indicates the Request Method; in case of a + response, a Response Code. Possible values are maintained in the + CoAP Code Registries (Section 12.1). The semantics of requests + and responses are defined in Section 5. + + + + +Shelby, et al. Standards Track [Page 16] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Message ID: 16-bit unsigned integer in network byte order. Used to + detect message duplication and to match messages of type + Acknowledgement/Reset to messages of type Confirmable/Non- + confirmable. The rules for generating a Message ID and matching + messages are defined in Section 4. + + The header is followed by the Token value, which may be 0 to 8 bytes, + as given by the Token Length field. The Token value is used to + correlate requests and responses. The rules for generating a Token + and correlating requests and responses are defined in Section 5.3.1. + + Header and Token are followed by zero or more Options (Section 3.1). + An Option can be followed by the end of the message, by another + Option, or by the Payload Marker and the payload. + + Following the header, token, and options, if any, comes the optional + payload. If present and of non-zero length, it is prefixed by a + fixed, one-byte Payload Marker (0xFF), which indicates the end of + options and the start of the payload. The payload data extends from + after the marker to the end of the UDP datagram, i.e., the Payload + Length is calculated from the datagram size. The absence of the + Payload Marker denotes a zero-length payload. The presence of a + marker followed by a zero-length payload MUST be processed as a + message format error. + + Implementation Note: The byte value 0xFF may also occur within an + option length or value, so simple byte-wise scanning for 0xFF is + not a viable technique for finding the payload marker. The byte + 0xFF has the meaning of a payload marker only where the beginning + of another option could occur. + +3.1. Option Format + + CoAP defines a number of options that can be included in a message. + Each option instance in a message specifies the Option Number of the + defined CoAP option, the length of the Option Value, and the Option + Value itself. + + Instead of specifying the Option Number directly, the instances MUST + appear in order of their Option Numbers and a delta encoding is used + between them: the Option Number for each instance is calculated as + the sum of its delta and the Option Number of the preceding instance + in the message. For the first instance in a message, a preceding + option instance with Option Number zero is assumed. Multiple + instances of the same option can be included by using a delta of + zero. + + + + + +Shelby, et al. Standards Track [Page 17] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Option Numbers are maintained in the "CoAP Option Numbers" registry + (Section 12.2). See Section 5.4 for the semantics of the options + defined in this document. + + 0 1 2 3 4 5 6 7 + +---------------+---------------+ + | | | + | Option Delta | Option Length | 1 byte + | | | + +---------------+---------------+ + \ \ + / Option Delta / 0-2 bytes + \ (extended) \ + +-------------------------------+ + \ \ + / Option Length / 0-2 bytes + \ (extended) \ + +-------------------------------+ + \ \ + / / + \ \ + / Option Value / 0 or more bytes + \ \ + / / + \ \ + +-------------------------------+ + + Figure 8: Option Format + + The fields in an option are defined as follows: + + Option Delta: 4-bit unsigned integer. A value between 0 and 12 + indicates the Option Delta. Three values are reserved for special + constructs: + + 13: An 8-bit unsigned integer follows the initial byte and + indicates the Option Delta minus 13. + + 14: A 16-bit unsigned integer in network byte order follows the + initial byte and indicates the Option Delta minus 269. + + 15: Reserved for the Payload Marker. If the field is set to this + value but the entire byte is not the payload marker, this MUST + be processed as a message format error. + + + + + + + +Shelby, et al. Standards Track [Page 18] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The resulting Option Delta is used as the difference between the + Option Number of this option and that of the previous option (or + zero for the first option). In other words, the Option Number is + calculated by simply summing the Option Delta values of this and + all previous options before it. + + Option Length: 4-bit unsigned integer. A value between 0 and 12 + indicates the length of the Option Value, in bytes. Three values + are reserved for special constructs: + + 13: An 8-bit unsigned integer precedes the Option Value and + indicates the Option Length minus 13. + + 14: A 16-bit unsigned integer in network byte order precedes the + Option Value and indicates the Option Length minus 269. + + 15: Reserved for future use. If the field is set to this value, + it MUST be processed as a message format error. + + Value: A sequence of exactly Option Length bytes. The length and + format of the Option Value depend on the respective option, which + MAY define variable-length values. See Section 3.2 for the + formats used in this document; options defined in other documents + MAY make use of other option value formats. + +3.2. Option Value Formats + + The options defined in this document make use of the following option + value formats. + + empty: A zero-length sequence of bytes. + + opaque: An opaque sequence of bytes. + + uint: A non-negative integer that is represented in network byte + order using the number of bytes given by the Option Length + field. + + An option definition may specify a range of permissible + numbers of bytes; if it has a choice, a sender SHOULD + represent the integer with as few bytes as possible, i.e., + without leading zero bytes. For example, the number 0 is + represented with an empty option value (a zero-length + sequence of bytes) and the number 1 by a single byte with + the numerical value of 1 (bit combination 00000001 in most + significant bit first notation). A recipient MUST be + prepared to process values with leading zero bytes. + + + + +Shelby, et al. Standards Track [Page 19] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Implementation Note: The exceptional behavior permitted + for the sender is intended for highly constrained, + templated implementations (e.g., hardware + implementations) that use fixed-size options in the + templates. + + string: A Unicode string that is encoded using UTF-8 [RFC3629] in + Net-Unicode form [RFC5198]. + + Note that here, and in all other places where UTF-8 + encoding is used in the CoAP protocol, the intention is + that the encoded strings can be directly used and compared + as opaque byte strings by CoAP protocol implementations. + There is no expectation and no need to perform + normalization within a CoAP implementation (except where + Unicode strings that are not known to be normalized are + imported from sources outside the CoAP protocol). Note + also that ASCII strings (that do not make use of special + control characters) are always valid UTF-8 Net-Unicode + strings. + +4. Message Transmission + + CoAP messages are exchanged asynchronously between CoAP endpoints. + They are used to transport CoAP requests and responses, the semantics + of which are defined in Section 5. + + As CoAP is bound to unreliable transports such as UDP, CoAP messages + may arrive out of order, appear duplicated, or go missing without + notice. For this reason, CoAP implements a lightweight reliability + mechanism, without trying to re-create the full feature set of a + transport like TCP. It has the following features: + + o Simple stop-and-wait retransmission reliability with exponential + back-off for Confirmable messages. + + o Duplicate detection for both Confirmable and Non-confirmable + messages. + +4.1. Messages and Endpoints + + A CoAP endpoint is the source or destination of a CoAP message. The + specific definition of an endpoint depends on the transport being + used for CoAP. For the transports defined in this specification, the + endpoint is identified depending on the security mode used (see + Section 9): With no security, the endpoint is solely identified by an + IP address and a UDP port number. With other security modes, the + endpoint is identified as defined by the security mode. + + + +Shelby, et al. Standards Track [Page 20] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + There are different types of messages. The type of a message is + specified by the Type field of the CoAP Header. + + Separate from the message type, a message may carry a request, a + response, or be Empty. This is signaled by the Request/Response Code + field in the CoAP Header and is relevant to the request/response + model. Possible values for the field are maintained in the CoAP Code + Registries (Section 12.1). + + An Empty message has the Code field set to 0.00. The Token Length + field MUST be set to 0 and bytes of data MUST NOT be present after + the Message ID field. If there are any bytes, they MUST be processed + as a message format error. + +4.2. Messages Transmitted Reliably + + The reliable transmission of a message is initiated by marking the + message as Confirmable in the CoAP header. A Confirmable message + always carries either a request or response, unless it is used only + to elicit a Reset message, in which case it is Empty. A recipient + MUST either (a) acknowledge a Confirmable message with an + Acknowledgement message or (b) reject the message if the recipient + lacks context to process the message properly, including situations + where the message is Empty, uses a code with a reserved class (1, 6, + or 7), or has a message format error. Rejecting a Confirmable + message is effected by sending a matching Reset message and otherwise + ignoring it. The Acknowledgement message MUST echo the Message ID of + the Confirmable message and MUST carry a response or be Empty (see + Sections 5.2.1 and 5.2.2). The Reset message MUST echo the Message + ID of the Confirmable message and MUST be Empty. Rejecting an + Acknowledgement or Reset message (including the case where the + Acknowledgement carries a request or a code with a reserved class, or + the Reset message is not Empty) is effected by silently ignoring it. + More generally, recipients of Acknowledgement and Reset messages MUST + NOT respond with either Acknowledgement or Reset messages. + + The sender retransmits the Confirmable message at exponentially + increasing intervals, until it receives an acknowledgement (or Reset + message) or runs out of attempts. + + Retransmission is controlled by two things that a CoAP endpoint MUST + keep track of for each Confirmable message it sends while waiting for + an acknowledgement (or reset): a timeout and a retransmission + counter. For a new Confirmable message, the initial timeout is set + to a random duration (often not an integral number of seconds) + between ACK_TIMEOUT and (ACK_TIMEOUT * ACK_RANDOM_FACTOR) (see + Section 4.8), and the retransmission counter is set to 0. When the + timeout is triggered and the retransmission counter is less than + + + +Shelby, et al. Standards Track [Page 21] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + MAX_RETRANSMIT, the message is retransmitted, the retransmission + counter is incremented, and the timeout is doubled. If the + retransmission counter reaches MAX_RETRANSMIT on a timeout, or if the + endpoint receives a Reset message, then the attempt to transmit the + message is canceled and the application process informed of failure. + On the other hand, if the endpoint receives an acknowledgement in + time, transmission is considered successful. + + This specification makes no strong requirements on the accuracy of + the clocks used to implement the above binary exponential back-off + algorithm. In particular, an endpoint may be late for a specific + retransmission due to its sleep schedule and may catch up on the next + one. However, the minimum spacing before another retransmission is + ACK_TIMEOUT, and the entire sequence of (re-)transmissions MUST stay + in the envelope of MAX_TRANSMIT_SPAN (see Section 4.8.2), even if + that means a sender may miss an opportunity to transmit. + + A CoAP endpoint that sent a Confirmable message MAY give up in + attempting to obtain an ACK even before the MAX_RETRANSMIT counter + value is reached. For example, the application has canceled the + request as it no longer needs a response, or there is some other + indication that the CON message did arrive. In particular, a CoAP + request message may have elicited a separate response, in which case + it is clear to the requester that only the ACK was lost and a + retransmission of the request would serve no purpose. However, a + responder MUST NOT in turn rely on this cross-layer behavior from a + requester, i.e., it MUST retain the state to create the ACK for the + request, if needed, even if a Confirmable response was already + acknowledged by the requester. + + Another reason for giving up retransmission MAY be the receipt of + ICMP errors. If it is desired to take account of ICMP errors, to + mitigate potential spoofing attacks, implementations SHOULD take care + to check the information about the original datagram in the ICMP + message, including port numbers and CoAP header information such as + message type and code, Message ID, and Token; if this is not possible + due to limitations of the UDP service API, ICMP errors SHOULD be + ignored. Packet Too Big errors [RFC4443] ("fragmentation needed and + DF set" for IPv4 [RFC0792]) cannot properly occur and SHOULD be + ignored if the implementation note in Section 4.6 is followed; + otherwise, they SHOULD feed into a path MTU discovery algorithm + [RFC4821]. Source Quench and Time Exceeded ICMP messages SHOULD be + ignored. Host, network, port, or protocol unreachable errors or + parameter problem errors MAY, after appropriate vetting, be used to + inform the application of a failure in sending. + + + + + + +Shelby, et al. Standards Track [Page 22] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +4.3. Messages Transmitted without Reliability + + Some messages do not require an acknowledgement. This is + particularly true for messages that are repeated regularly for + application requirements, such as repeated readings from a sensor + where eventual success is sufficient. + + As a more lightweight alternative, a message can be transmitted less + reliably by marking the message as Non-confirmable. A Non- + confirmable message always carries either a request or response and + MUST NOT be Empty. A Non-confirmable message MUST NOT be + acknowledged by the recipient. A recipient MUST reject the message + if it lacks context to process the message properly, including the + case where the message is Empty, uses a code with a reserved class + (1, 6, or 7), or has a message format error. Rejecting a Non- + confirmable message MAY involve sending a matching Reset message, and + apart from the Reset message the rejected message MUST be silently + ignored. + + At the CoAP level, there is no way for the sender to detect if a Non- + confirmable message was received or not. A sender MAY choose to + transmit multiple copies of a Non-confirmable message within + MAX_TRANSMIT_SPAN (limited by the provisions of Section 4.7, in + particular, by PROBING_RATE if no response is received), or the + network may duplicate the message in transit. To enable the receiver + to act only once on the message, Non-confirmable messages specify a + Message ID as well. (This Message ID is drawn from the same number + space as the Message IDs for Confirmable messages.) + + Summarizing Sections 4.2 and 4.3, the four message types can be used + as in Table 1. "*" means that the combination is not used in normal + operation but only to elicit a Reset message ("CoAP ping"). + + +----------+-----+-----+-----+-----+ + | | CON | NON | ACK | RST | + +----------+-----+-----+-----+-----+ + | Request | X | X | - | - | + | Response | X | X | X | - | + | Empty | * | - | X | X | + +----------+-----+-----+-----+-----+ + + Table 1: Usage of Message Types + + + + + + + + + +Shelby, et al. Standards Track [Page 23] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +4.4. Message Correlation + + An Acknowledgement or Reset message is related to a Confirmable + message or Non-confirmable message by means of a Message ID along + with additional address information of the corresponding endpoint. + The Message ID is a 16-bit unsigned integer that is generated by the + sender of a Confirmable or Non-confirmable message and included in + the CoAP header. The Message ID MUST be echoed in the + Acknowledgement or Reset message by the recipient. + + The same Message ID MUST NOT be reused (in communicating with the + same endpoint) within the EXCHANGE_LIFETIME (Section 4.8.2). + + Implementation Note: Several implementation strategies can be + employed for generating Message IDs. In the simplest case, a CoAP + endpoint generates Message IDs by keeping a single Message ID + variable, which is changed each time a new Confirmable or Non- + confirmable message is sent, regardless of the destination address + or port. Endpoints dealing with large numbers of transactions + could keep multiple Message ID variables, for example, per prefix + or destination address. (Note that some receiving endpoints may + not be able to distinguish unicast and multicast packets addressed + to it, so endpoints generating Message IDs need to make sure these + do not overlap.) It is strongly recommended that the initial + value of the variable (e.g., on startup) be randomized, in order + to make successful off-path attacks on the protocol less likely. + + For an Acknowledgement or Reset message to match a Confirmable or + Non-confirmable message, the Message ID and source endpoint of the + Acknowledgement or Reset message MUST match the Message ID and + destination endpoint of the Confirmable or Non-confirmable message. + +4.5. Message Deduplication + + A recipient might receive the same Confirmable message (as indicated + by the Message ID and source endpoint) multiple times within the + EXCHANGE_LIFETIME (Section 4.8.2), for example, when its + Acknowledgement went missing or didn't reach the original sender + before the first timeout. The recipient SHOULD acknowledge each + duplicate copy of a Confirmable message using the same + Acknowledgement or Reset message but SHOULD process any request or + response in the message only once. This rule MAY be relaxed in case + the Confirmable message transports a request that is idempotent (see + Section 5.1) or can be handled in an idempotent fashion. Examples + for relaxed message deduplication: + + + + + + +Shelby, et al. Standards Track [Page 24] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o A server might relax the requirement to answer all retransmissions + of an idempotent request with the same response (Section 4.2), so + that it does not have to maintain state for Message IDs. For + example, an implementation might want to process duplicate + transmissions of a GET, PUT, or DELETE request as separate + requests if the effort incurred by duplicate processing is less + expensive than keeping track of previous responses would be. + + o A constrained server might even want to relax this requirement for + certain non-idempotent requests if the application semantics make + this trade-off favorable. For example, if the result of a POST + request is just the creation of some short-lived state at the + server, it may be less expensive to incur this effort multiple + times for a request than keeping track of whether a previous + transmission of the same request already was processed. + + A recipient might receive the same Non-confirmable message (as + indicated by the Message ID and source endpoint) multiple times + within NON_LIFETIME (Section 4.8.2). As a general rule that MAY be + relaxed based on the specific semantics of a message, the recipient + SHOULD silently ignore any duplicated Non-confirmable message and + SHOULD process any request or response in the message only once. + +4.6. Message Size + + While specific link layers make it beneficial to keep CoAP messages + small enough to fit into their link-layer packets (see Section 1), + this is a matter of implementation quality. The CoAP specification + itself provides only an upper bound to the message size. Messages + larger than an IP packet result in undesirable packet fragmentation. + A CoAP message, appropriately encapsulated, SHOULD fit within a + single IP packet (i.e., avoid IP fragmentation) and (by fitting into + one UDP payload) obviously needs to fit within a single IP datagram. + If the Path MTU is not known for a destination, an IP MTU of 1280 + bytes SHOULD be assumed; if nothing is known about the size of the + headers, good upper bounds are 1152 bytes for the message size and + 1024 bytes for the payload size. + + Implementation Note: CoAP's choice of message size parameters works + well with IPv6 and with most of today's IPv4 paths. (However, + with IPv4, it is harder to absolutely ensure that there is no IP + fragmentation. If IPv4 support on unusual networks is a + consideration, implementations may want to limit themselves to + more conservative IPv4 datagram sizes such as 576 bytes; per + [RFC0791], the absolute minimum value of the IP MTU for IPv4 is as + low as 68 bytes, which would leave only 40 bytes minus security + overhead for a UDP payload. Implementations extremely focused on + this problem set might also set the IPv4 DF bit and perform some + + + +Shelby, et al. Standards Track [Page 25] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + form of path MTU discovery [RFC4821]; this should generally be + unnecessary in realistic use cases for CoAP, however.) A more + important kind of fragmentation in many constrained networks is + that on the adaptation layer (e.g., 6LoWPAN L2 packets are limited + to 127 bytes including various overheads); this may motivate + implementations to be frugal in their packet sizes and to move to + block-wise transfers [BLOCK] when approaching three-digit message + sizes. + + Message sizes are also of considerable importance to + implementations on constrained nodes. Many implementations will + need to allocate a buffer for incoming messages. If an + implementation is too constrained to allow for allocating the + above-mentioned upper bound, it could apply the following + implementation strategy for messages not using DTLS security: + Implementations receiving a datagram into a buffer that is too + small are usually able to determine if the trailing portion of a + datagram was discarded and to retrieve the initial portion. So, + at least the CoAP header and options, if not all of the payload, + are likely to fit within the buffer. A server can thus fully + interpret a request and return a 4.13 (Request Entity Too Large; + see Section 5.9.2.9) Response Code if the payload was truncated. + A client sending an idempotent request and receiving a response + larger than would fit in the buffer can repeat the request with a + suitable value for the Block Option [BLOCK]. + +4.7. Congestion Control + + Basic congestion control for CoAP is provided by the exponential + back-off mechanism in Section 4.2. + + In order not to cause congestion, clients (including proxies) MUST + strictly limit the number of simultaneous outstanding interactions + that they maintain to a given server (including proxies) to NSTART. + An outstanding interaction is either a CON for which an ACK has not + yet been received but is still expected (message layer) or a request + for which neither a response nor an Acknowledgment message has yet + been received but is still expected (which may both occur at the same + time, counting as one outstanding interaction). The default value of + NSTART for this specification is 1. + + Further congestion control optimizations and considerations are + expected in the future, may for example provide automatic + initialization of the CoAP transmission parameters defined in + Section 4.8, and thus may allow a value for NSTART greater than one. + + After EXCHANGE_LIFETIME, a client stops expecting a response to a + Confirmable request for which no acknowledgment message was received. + + + +Shelby, et al. Standards Track [Page 26] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The specific algorithm by which a client stops to "expect" a response + to a Confirmable request that was acknowledged, or to a Non- + confirmable request, is not defined. Unless this is modified by + additional congestion control optimizations, it MUST be chosen in + such a way that an endpoint does not exceed an average data rate of + PROBING_RATE in sending to another endpoint that does not respond. + + Note: CoAP places the onus of congestion control mostly on the + clients. However, clients may malfunction or actually be + attackers, e.g., to perform amplification attacks (Section 11.3). + To limit the damage (to the network and to its own energy + resources), a server SHOULD implement some rate limiting for its + response transmission based on reasonable assumptions about + application requirements. This is most helpful if the rate limit + can be made effective for the misbehaving endpoints, only. + +4.8. Transmission Parameters + + Message transmission is controlled by the following parameters: + + +-------------------+---------------+ + | name | default value | + +-------------------+---------------+ + | ACK_TIMEOUT | 2 seconds | + | ACK_RANDOM_FACTOR | 1.5 | + | MAX_RETRANSMIT | 4 | + | NSTART | 1 | + | DEFAULT_LEISURE | 5 seconds | + | PROBING_RATE | 1 byte/second | + +-------------------+---------------+ + + Table 2: CoAP Protocol Parameters + +4.8.1. Changing the Parameters + + The values for ACK_TIMEOUT, ACK_RANDOM_FACTOR, MAX_RETRANSMIT, + NSTART, DEFAULT_LEISURE (Section 8.2), and PROBING_RATE may be + configured to values specific to the application environment + (including dynamically adjusted values); however, the configuration + method is out of scope of this document. It is RECOMMENDED that an + application environment use consistent values for these parameters; + the specific effects of operating with inconsistent values in an + application environment are outside the scope of the present + specification. + + The transmission parameters have been chosen to achieve a behavior in + the presence of congestion that is safe in the Internet. If a + configuration desires to use different values, the onus is on the + + + +Shelby, et al. Standards Track [Page 27] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + configuration to ensure these congestion control properties are not + violated. In particular, a decrease of ACK_TIMEOUT below 1 second + would violate the guidelines of [RFC5405]. ([RTO-CONSIDER] provides + some additional background.) CoAP was designed to enable + implementations that do not maintain round-trip-time (RTT) + measurements. However, where it is desired to decrease the + ACK_TIMEOUT significantly or increase NSTART, this can only be done + safely when maintaining such measurements. Configurations MUST NOT + decrease ACK_TIMEOUT or increase NSTART without using mechanisms that + ensure congestion control safety, either defined in the configuration + or in future standards documents. + + ACK_RANDOM_FACTOR MUST NOT be decreased below 1.0, and it SHOULD have + a value that is sufficiently different from 1.0 to provide some + protection from synchronization effects. + + MAX_RETRANSMIT can be freely adjusted, but a value that is too small + will reduce the probability that a Confirmable message is actually + received, while a larger value than given here will require further + adjustments in the time values (see Section 4.8.2). + + If the choice of transmission parameters leads to an increase of + derived time values (see Section 4.8.2), the configuration mechanism + MUST ensure the adjusted value is also available to all the endpoints + with which these adjusted values are to be used to communicate. + +4.8.2. Time Values Derived from Transmission Parameters + + The combination of ACK_TIMEOUT, ACK_RANDOM_FACTOR, and MAX_RETRANSMIT + influences the timing of retransmissions, which in turn influences + how long certain information items need to be kept by an + implementation. To be able to unambiguously reference these derived + time values, we give them names as follows: + + o MAX_TRANSMIT_SPAN is the maximum time from the first transmission + of a Confirmable message to its last retransmission. For the + default transmission parameters, the value is (2+4+8+16)*1.5 = 45 + seconds, or more generally: + + ACK_TIMEOUT * ((2 ** MAX_RETRANSMIT) - 1) * ACK_RANDOM_FACTOR + + + + + + + + + + + +Shelby, et al. Standards Track [Page 28] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o MAX_TRANSMIT_WAIT is the maximum time from the first transmission + of a Confirmable message to the time when the sender gives up on + receiving an acknowledgement or reset. For the default + transmission parameters, the value is (2+4+8+16+32)*1.5 = 93 + seconds, or more generally: + + ACK_TIMEOUT * ((2 ** (MAX_RETRANSMIT + 1)) - 1) * + ACK_RANDOM_FACTOR + + In addition, some assumptions need to be made on the characteristics + of the network and the nodes. + + o MAX_LATENCY is the maximum time a datagram is expected to take + from the start of its transmission to the completion of its + reception. This constant is related to the MSL (Maximum Segment + Lifetime) of [RFC0793], which is "arbitrarily defined to be 2 + minutes" ([RFC0793] glossary, page 81). Note that this is not + necessarily smaller than MAX_TRANSMIT_WAIT, as MAX_LATENCY is not + intended to describe a situation when the protocol works well, but + the worst-case situation against which the protocol has to guard. + We, also arbitrarily, define MAX_LATENCY to be 100 seconds. Apart + from being reasonably realistic for the bulk of configurations as + well as close to the historic choice for TCP, this value also + allows Message ID lifetime timers to be represented in 8 bits + (when measured in seconds). In these calculations, there is no + assumption that the direction of the transmission is irrelevant + (i.e., that the network is symmetric); there is just the + assumption that the same value can reasonably be used as a maximum + value for both directions. If that is not the case, the following + calculations become only slightly more complex. + + o PROCESSING_DELAY is the time a node takes to turn around a + Confirmable message into an acknowledgement. We assume the node + will attempt to send an ACK before having the sender time out, so + as a conservative assumption we set it equal to ACK_TIMEOUT. + + o MAX_RTT is the maximum round-trip time, or: + + (2 * MAX_LATENCY) + PROCESSING_DELAY + + From these values, we can derive the following values relevant to the + protocol operation: + + o EXCHANGE_LIFETIME is the time from starting to send a Confirmable + message to the time when an acknowledgement is no longer expected, + i.e., message-layer information about the message exchange can be + purged. EXCHANGE_LIFETIME includes a MAX_TRANSMIT_SPAN, a + MAX_LATENCY forward, PROCESSING_DELAY, and a MAX_LATENCY for the + + + +Shelby, et al. Standards Track [Page 29] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + way back. Note that there is no need to consider + MAX_TRANSMIT_WAIT if the configuration is chosen such that the + last waiting period (ACK_TIMEOUT * (2 ** MAX_RETRANSMIT) or the + difference between MAX_TRANSMIT_SPAN and MAX_TRANSMIT_WAIT) is + less than MAX_LATENCY -- which is a likely choice, as MAX_LATENCY + is a worst-case value unlikely to be met in the real world. In + this case, EXCHANGE_LIFETIME simplifies to: + + MAX_TRANSMIT_SPAN + (2 * MAX_LATENCY) + PROCESSING_DELAY + + or 247 seconds with the default transmission parameters. + + o NON_LIFETIME is the time from sending a Non-confirmable message to + the time its Message ID can be safely reused. If multiple + transmission of a NON message is not used, its value is + MAX_LATENCY, or 100 seconds. However, a CoAP sender might send a + NON message multiple times, in particular for multicast + applications. While the period of reuse is not bounded by the + specification, an expectation of reliable detection of duplication + at the receiver is on the timescales of MAX_TRANSMIT_SPAN. + Therefore, for this purpose, it is safer to use the value: + + MAX_TRANSMIT_SPAN + MAX_LATENCY + + or 145 seconds with the default transmission parameters; however, + an implementation that just wants to use a single timeout value + for retiring Message IDs can safely use the larger value for + EXCHANGE_LIFETIME. + + Table 3 lists the derived parameters introduced in this subsection + with their default values. + + +-------------------+---------------+ + | name | default value | + +-------------------+---------------+ + | MAX_TRANSMIT_SPAN | 45 s | + | MAX_TRANSMIT_WAIT | 93 s | + | MAX_LATENCY | 100 s | + | PROCESSING_DELAY | 2 s | + | MAX_RTT | 202 s | + | EXCHANGE_LIFETIME | 247 s | + | NON_LIFETIME | 145 s | + +-------------------+---------------+ + + Table 3: Derived Protocol Parameters + + + + + + +Shelby, et al. Standards Track [Page 30] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5. Request/Response Semantics + + CoAP operates under a similar request/response model as HTTP: a CoAP + endpoint in the role of a "client" sends one or more CoAP requests to + a "server", which services the requests by sending CoAP responses. + Unlike HTTP, requests and responses are not sent over a previously + established connection but are exchanged asynchronously over CoAP + messages. + +5.1. Requests + + A CoAP request consists of the method to be applied to the resource, + the identifier of the resource, a payload and Internet media type (if + any), and optional metadata about the request. + + CoAP supports the basic methods of GET, POST, PUT, and DELETE, which + are easily mapped to HTTP. They have the same properties of safe + (only retrieval) and idempotent (you can invoke it multiple times + with the same effects) as HTTP (see Section 9.1 of [RFC2616]). The + GET method is safe; therefore, it MUST NOT take any other action on a + resource other than retrieval. The GET, PUT, and DELETE methods MUST + be performed in such a way that they are idempotent. POST is not + idempotent, because its effect is determined by the origin server and + dependent on the target resource; it usually results in a new + resource being created or the target resource being updated. + + A request is initiated by setting the Code field in the CoAP header + of a Confirmable or a Non-confirmable message to a Method Code and + including request information. + + The methods used in requests are described in detail in Section 5.8. + +5.2. Responses + + After receiving and interpreting a request, a server responds with a + CoAP response that is matched to the request by means of a client- + generated token (Section 5.3); note that this is different from the + Message ID that matches a Confirmable message to its Acknowledgement. + + A response is identified by the Code field in the CoAP header being + set to a Response Code. Similar to the HTTP Status Code, the CoAP + Response Code indicates the result of the attempt to understand and + satisfy the request. These codes are fully defined in Section 5.9. + The Response Code numbers to be set in the Code field of the CoAP + header are maintained in the CoAP Response Code Registry + (Section 12.1.2). + + + + + +Shelby, et al. Standards Track [Page 31] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + 0 + 0 1 2 3 4 5 6 7 + +-+-+-+-+-+-+-+-+ + |class| detail | + +-+-+-+-+-+-+-+-+ + + Figure 9: Structure of a Response Code + + The upper three bits of the 8-bit Response Code number define the + class of response. The lower five bits do not have any + categorization role; they give additional detail to the overall class + (Figure 9). + + As a human-readable notation for specifications and protocol + diagnostics, CoAP code numbers including the Response Code are + documented in the format "c.dd", where "c" is the class in decimal, + and "dd" is the detail as a two-digit decimal. For example, + "Forbidden" is written as 4.03 -- indicating an 8-bit code value of + hexadecimal 0x83 (4*0x20+3) or decimal 131 (4*32+3). + + There are 3 classes of Response Codes: + + 2 - Success: The request was successfully received, understood, and + accepted. + + 4 - Client Error: The request contains bad syntax or cannot be + fulfilled. + + 5 - Server Error: The server failed to fulfill an apparently valid + request. + + The Response Codes are designed to be extensible: Response Codes in + the Client Error or Server Error class that are unrecognized by an + endpoint are treated as being equivalent to the generic Response Code + of that class (4.00 and 5.00, respectively). However, there is no + generic Response Code indicating success, so a Response Code in the + Success class that is unrecognized by an endpoint can only be used to + determine that the request was successful without any further + details. + + The possible Response Codes are described in detail in Section 5.9. + + Responses can be sent in multiple ways, which are defined in the + following subsections. + + + + + + + +Shelby, et al. Standards Track [Page 32] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.2.1. Piggybacked + + In the most basic case, the response is carried directly in the + Acknowledgement message that acknowledges the request (which requires + that the request was carried in a Confirmable message). This is + called a "Piggybacked Response". + + The response is returned in the Acknowledgement message, independent + of whether the response indicates success or failure. In effect, the + response is piggybacked on the Acknowledgement message, and no + separate message is required to return the response. + + Implementation Note: The protocol leaves the decision whether to + piggyback a response or not (i.e., send a separate response) to + the server. The client MUST be prepared to receive either. On + the quality-of-implementation level, there is a strong expectation + that servers will implement code to piggyback whenever possible -- + saving resources in the network and both at the client and at the + server. + +5.2.2. Separate + + It may not be possible to return a piggybacked response in all cases. + For example, a server might need longer to obtain the representation + of the resource requested than it can wait to send back the + Acknowledgement message, without risking the client repeatedly + retransmitting the request message (see also the discussion of + PROCESSING_DELAY in Section 4.8.2). The response to a request + carried in a Non-confirmable message is always sent separately (as + there is no Acknowledgement message). + + One way to implement this in a server is to initiate the attempt to + obtain the resource representation and, while that is in progress, + time out an acknowledgement timer. A server may also immediately + send an acknowledgement if it knows in advance that there will be no + piggybacked response. In both cases, the acknowledgement effectively + is a promise that the request will be acted upon later. + + When the server finally has obtained the resource representation, it + sends the response. When it is desired that this message is not + lost, it is sent as a Confirmable message from the server to the + client and answered by the client with an Acknowledgement, echoing + the new Message ID chosen by the server. (It may also be sent as a + Non-confirmable message; see Section 5.2.3.) + + When the server chooses to use a separate response, it sends the + Acknowledgement to the Confirmable request as an Empty message. Once + the server sends back an Empty Acknowledgement, it MUST NOT send back + + + +Shelby, et al. Standards Track [Page 33] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + the response in another Acknowledgement, even if the client + retransmits another identical request. If a retransmitted request is + received (perhaps because the original Acknowledgement was delayed), + another Empty Acknowledgement is sent, and any response MUST be sent + as a separate response. + + If the server then sends a Confirmable response, the client's + Acknowledgement to that response MUST also be an Empty message (one + that carries neither a request nor a response). The server MUST stop + retransmitting its response on any matching Acknowledgement (silently + ignoring any Response Code or payload) or Reset message. + + Implementation Notes: Note that, as the underlying datagram + transport may not be sequence-preserving, the Confirmable message + carrying the response may actually arrive before or after the + Acknowledgement message for the request; for the purposes of + terminating the retransmission sequence, this also serves as an + acknowledgement. Note also that, while the CoAP protocol itself + does not make any specific demands here, there is an expectation + that the response will come within a time frame that is reasonable + from an application point of view. As there is no underlying + transport protocol that could be instructed to run a keep-alive + mechanism, the requester may want to set up a timeout that is + unrelated to CoAP's retransmission timers in case the server is + destroyed or otherwise unable to send the response. + +5.2.3. Non-confirmable + + If the request message is Non-confirmable, then the response SHOULD + be returned in a Non-confirmable message as well. However, an + endpoint MUST be prepared to receive a Non-confirmable response + (preceded or followed by an Empty Acknowledgement message) in reply + to a Confirmable request, or a Confirmable response in reply to a + Non-confirmable request. + +5.3. Request/Response Matching + + Regardless of how a response is sent, it is matched to the request by + means of a token that is included by the client in the request, along + with additional address information of the corresponding endpoint. + +5.3.1. Token + + The Token is used to match a response with a request. The token + value is a sequence of 0 to 8 bytes. (Note that every message + carries a token, even if it is of zero length.) Every request + carries a client-generated token that the server MUST echo (without + modification) in any resulting response. + + + +Shelby, et al. Standards Track [Page 34] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + A token is intended for use as a client-local identifier for + differentiating between concurrent requests (see Section 5.3); it + could have been called a "request ID". + + The client SHOULD generate tokens in such a way that tokens currently + in use for a given source/destination endpoint pair are unique. + (Note that a client implementation can use the same token for any + request if it uses a different endpoint each time, e.g., a different + source port number.) An empty token value is appropriate e.g., when + no other tokens are in use to a destination, or when requests are + made serially per destination and receive piggybacked responses. + There are, however, multiple possible implementation strategies to + fulfill this. + + A client sending a request without using Transport Layer Security + (Section 9) SHOULD use a nontrivial, randomized token to guard + against spoofing of responses (Section 11.4). This protective use of + tokens is the reason they are allowed to be up to 8 bytes in size. + The actual size of the random component to be used for the Token + depends on the security requirements of the client and the level of + threat posed by spoofing of responses. A client that is connected to + the general Internet SHOULD use at least 32 bits of randomness, + keeping in mind that not being directly connected to the Internet is + not necessarily sufficient protection against spoofing. (Note that + the Message ID adds little in protection as it is usually + sequentially assigned, i.e., guessable, and can be circumvented by + spoofing a separate response.) Clients that want to optimize the + Token length may further want to detect the level of ongoing attacks + (e.g., by tallying recent Token mismatches in incoming messages) and + adjust the Token length upwards appropriately. [RFC4086] discusses + randomness requirements for security. + + An endpoint receiving a token it did not generate MUST treat the + token as opaque and make no assumptions about its content or + structure. + +5.3.2. Request/Response Matching Rules + + The exact rules for matching a response to a request are as follows: + + 1. The source endpoint of the response MUST be the same as the + destination endpoint of the original request. + + 2. In a piggybacked response, the Message ID of the Confirmable + request and the Acknowledgement MUST match, and the tokens of the + response and original request MUST match. In a separate + response, just the tokens of the response and original request + MUST match. + + + +Shelby, et al. Standards Track [Page 35] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In case a message carrying a response is unexpected (the client is + not waiting for a response from the identified endpoint, at the + endpoint addressed, and/or with the given token), the response is + rejected (Sections 4.2 and 4.3). + + Implementation Note: A client that receives a response in a CON + message may want to clean up the message state right after sending + the ACK. If that ACK is lost and the server retransmits the CON, + the client may no longer have any state to which to correlate this + response, making the retransmission an unexpected message; the + client will likely send a Reset message so it does not receive any + more retransmissions. This behavior is normal and not an + indication of an error. (Clients that are not aggressively + optimized in their state memory usage will still have message + state that will identify the second CON as a retransmission. + Clients that actually expect more messages from the server + [OBSERVE] will have to keep state in any case.) + +5.4. Options + + Both requests and responses may include a list of one or more + options. For example, the URI in a request is transported in several + options, and metadata that would be carried in an HTTP header in HTTP + is supplied as options as well. + + CoAP defines a single set of options that are used in both requests + and responses: + + o Content-Format + + o ETag + + o Location-Path + + o Location-Query + + o Max-Age + + o Proxy-Uri + + o Proxy-Scheme + + o Uri-Host + + o Uri-Path + + o Uri-Port + + + + +Shelby, et al. Standards Track [Page 36] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o Uri-Query + + o Accept + + o If-Match + + o If-None-Match + + o Size1 + + The semantics of these options along with their properties are + defined in detail in Section 5.10. + + Not all options are defined for use with all methods and Response + Codes. The possible options for methods and Response Codes are + defined in Sections 5.8 and 5.9, respectively. In case an option is + not defined for a Method or Response Code, it MUST NOT be included by + a sender and MUST be treated like an unrecognized option by a + recipient. + +5.4.1. Critical/Elective + + Options fall into one of two classes: "critical" or "elective". The + difference between these is how an option unrecognized by an endpoint + is handled: + + o Upon reception, unrecognized options of class "elective" MUST be + silently ignored. + + o Unrecognized options of class "critical" that occur in a + Confirmable request MUST cause the return of a 4.02 (Bad Option) + response. This response SHOULD include a diagnostic payload + describing the unrecognized option(s) (see Section 5.5.2). + + o Unrecognized options of class "critical" that occur in a + Confirmable response, or piggybacked in an Acknowledgement, MUST + cause the response to be rejected (Section 4.2). + + o Unrecognized options of class "critical" that occur in a Non- + confirmable message MUST cause the message to be rejected + (Section 4.3). + + Note that, whether critical or elective, an option is never + "mandatory" (it is always optional): these rules are defined in order + to enable implementations to stop processing options they do not + understand or implement. + + + + + +Shelby, et al. Standards Track [Page 37] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Critical/elective rules apply to non-proxying endpoints. A proxy + processes options based on Unsafe/Safe-to-Forward classes as defined + in Section 5.7. + +5.4.2. Proxy Unsafe or Safe-to-Forward and NoCacheKey + + In addition to an option being marked as critical or elective, + options are also classified based on how a proxy is to deal with the + option if it does not recognize it. For this purpose, an option can + either be considered Unsafe to forward (UnSafe is set) or Safe-to- + Forward (UnSafe is clear). + + In addition, for an option that is marked Safe-to-Forward, the option + number indicates whether or not it is intended to be part of the + Cache-Key (Section 5.6) in a request. If some of the NoCacheKey bits + are 0, it is; if all NoCacheKey bits are 1, it is not (see + Section 5.4.6). + + Note: The Cache-Key indication is relevant only for proxies that do + not implement the given option as a request option and instead + rely on the Unsafe/Safe-to-Forward indication only. For example, + for ETag, actually using the request option as a part of the + Cache-Key is grossly inefficient, but it is the best thing one can + do if ETag is not implemented by a proxy, as the response is going + to differ based on the presence of the request option. A more + useful proxy that does implement the ETag request option is not + using ETag as a part of the Cache-Key. + + NoCacheKey is indicated in three bits so that only one out of + eight codepoints is qualified as NoCacheKey, leaving seven out of + eight codepoints for what appears to be the more likely case. + + Proxy behavior with regard to these classes is defined in + Section 5.7. + +5.4.3. Length + + Option values are defined to have a specific length, often in the + form of an upper and lower bound. If the length of an option value + in a request is outside the defined range, that option MUST be + treated like an unrecognized option (see Section 5.4.1). + +5.4.4. Default Values + + Options may be defined to have a default value. If the value of an + option is intended to be this default value, the option SHOULD NOT be + included in the message. If the option is not present, the default + value MUST be assumed. + + + +Shelby, et al. Standards Track [Page 38] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Where a critical option has a default value, this is chosen in such a + way that the absence of the option in a message can be processed + properly both by implementations unaware of the critical option and + by implementations that interpret this absence as the presence of the + default value for the option. + +5.4.5. Repeatable Options + + The definition of some options specifies that those options are + repeatable. An option that is repeatable MAY be included one or more + times in a message. An option that is not repeatable MUST NOT be + included more than once in a message. + + If a message includes an option with more occurrences than the option + is defined for, each supernumerary option occurrence that appears + subsequently in the message MUST be treated like an unrecognized + option (see Section 5.4.1). + +5.4.6. Option Numbers + + An Option is identified by an option number, which also provides some + additional semantics information, e.g., odd numbers indicate a + critical option, while even numbers indicate an elective option. + Note that this is not just a convention, it is a feature of the + protocol: Whether an option is elective or critical is entirely + determined by whether its option number is even or odd. + + More generally speaking, an Option number is constructed with a bit + mask to indicate if an option is Critical or Elective, Unsafe or + Safe-to-Forward, and, in the case of Safe-to-Forward, to provide a + Cache-Key indication as shown by the following figure. In the + following text, the bit mask is expressed as a single byte that is + applied to the least significant byte of the option number in + unsigned integer representation. When bit 7 (the least significant + bit) is 1, an option is Critical (and likewise Elective when 0). + When bit 6 is 1, an option is Unsafe (and likewise Safe-to-Forward + when 0). When bit 6 is 0, i.e., the option is not Unsafe, it is not + a Cache-Key (NoCacheKey) if and only if bits 3-5 are all set to 1; + all other bit combinations mean that it indeed is a Cache-Key. These + classes of options are explained in the next sections. + + 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ + | | NoCacheKey| U | C | + +---+---+---+---+---+---+---+---+ + + Figure 10: Option Number Mask (Least Significant Byte) + + + + +Shelby, et al. Standards Track [Page 39] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + An endpoint may use an equivalent of the C code in Figure 11 to + derive the characteristics of an option number "onum". + + Critical = (onum & 1); + UnSafe = (onum & 2); + NoCacheKey = ((onum & 0x1e) == 0x1c); + + Figure 11: Determining Characteristics from an Option Number + + The option numbers for the options defined in this document are + listed in the "CoAP Option Numbers" registry (Section 12.2). + +5.5. Payloads and Representations + + Both requests and responses may include a payload, depending on the + Method or Response Code, respectively. If a Method or Response Code + is not defined to have a payload, then a sender MUST NOT include one, + and a recipient MUST ignore it. + +5.5.1. Representation + + The payload of requests or of responses indicating success is + typically a representation of a resource ("resource representation") + or the result of the requested action ("action result"). Its format + is specified by the Internet media type and content coding given by + the Content-Format Option. In the absence of this option, no default + value is assumed, and the format will need to be inferred by the + application (e.g., from the application context). Payload "sniffing" + SHOULD only be attempted if no content type is given. + + Implementation Note: On a quality-of-implementation level, there is + a strong expectation that a Content-Format indication will be + provided with resource representations whenever possible. This is + not a "SHOULD" level requirement solely because it is not a + protocol requirement, and it also would be difficult to outline + exactly in what cases this expectation can be violated. + + For responses indicating a client or server error, the payload is + considered a representation of the result of the requested action + only if a Content-Format Option is given. In the absence of this + option, the payload is a Diagnostic Payload (Section 5.5.2). + + + + + + + + + + +Shelby, et al. Standards Track [Page 40] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.5.2. Diagnostic Payload + + If no Content-Format option is given, the payload of responses + indicating a client or server error is a brief human-readable + diagnostic message, explaining the error situation. This diagnostic + message MUST be encoded using UTF-8 [RFC3629], more specifically + using Net-Unicode form [RFC5198]. + + The message is similar to the Reason-Phrase on an HTTP status line. + It is not intended for end users but for software engineers that + during debugging need to interpret it in the context of the present, + English-language specification; therefore, no mechanism for language + tagging is needed or provided. In contrast to what is usual in HTTP, + the payload SHOULD be empty if there is no additional information + beyond the Response Code. + +5.5.3. Selected Representation + + Not all responses carry a payload that provides a representation of + the resource addressed by the request. It is, however, sometimes + useful to be able to refer to such a representation in relation to a + response, independent of whether it actually was enclosed. + + We use the term "selected representation" to refer to the current + representation of a target resource that would have been selected in + a successful response if the corresponding request had used the + method GET and excluded any conditional request options + (Section 5.10.8). + + Certain response options provide metadata about the selected + representation, which might differ from the representation included + in the message for responses to some state-changing methods. Of the + response options defined in this specification, only the ETag + response option (Section 5.10.6) is defined as metadata about the + selected representation. + +5.5.4. Content Negotiation + + A server may be able to supply a representation for a resource in one + of multiple representation formats. Without further information from + the client, it will provide the representation in the format it + prefers. + + By using the Accept Option (Section 5.10.4) in a request, the client + can indicate which content-format it prefers to receive. + + + + + + +Shelby, et al. Standards Track [Page 41] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.6. Caching + + CoAP endpoints MAY cache responses in order to reduce the response + time and network bandwidth consumption on future, equivalent + requests. + + The goal of caching in CoAP is to reuse a prior response message to + satisfy a current request. In some cases, a stored response can be + reused without the need for a network request, reducing latency and + network round-trips; a "freshness" mechanism is used for this purpose + (see Section 5.6.1). Even when a new request is required, it is + often possible to reuse the payload of a prior response to satisfy + the request, thereby reducing network bandwidth usage; a "validation" + mechanism is used for this purpose (see Section 5.6.2). + + Unlike HTTP, the cacheability of CoAP responses does not depend on + the request method, but it depends on the Response Code. The + cacheability of each Response Code is defined along the Response Code + definitions in Section 5.9. Response Codes that indicate success and + are unrecognized by an endpoint MUST NOT be cached. + + For a presented request, a CoAP endpoint MUST NOT use a stored + response, unless: + + o the presented request method and that used to obtain the stored + response match, + + o all options match between those in the presented request and those + of the request used to obtain the stored response (which includes + the request URI), except that there is no need for a match of any + request options marked as NoCacheKey (Section 5.4) or recognized + by the Cache and fully interpreted with respect to its specified + cache behavior (such as the ETag request option described in + Section 5.10.6; see also Section 5.4.2), and + + o the stored response is either fresh or successfully validated as + defined below. + + The set of request options that is used for matching the cache entry + is also collectively referred to as the "Cache-Key". For URI schemes + other than coap and coaps, matching of those options that constitute + the request URI may be performed under rules specific to the URI + scheme. + + + + + + + + +Shelby, et al. Standards Track [Page 42] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.6.1. Freshness Model + + When a response is "fresh" in the cache, it can be used to satisfy + subsequent requests without contacting the origin server, thereby + improving efficiency. + + The mechanism for determining freshness is for an origin server to + provide an explicit expiration time in the future, using the Max-Age + Option (see Section 5.10.5). The Max-Age Option indicates that the + response is to be considered not fresh after its age is greater than + the specified number of seconds. + + The Max-Age Option defaults to a value of 60. Thus, if it is not + present in a cacheable response, then the response is considered not + fresh after its age is greater than 60 seconds. If an origin server + wishes to prevent caching, it MUST explicitly include a Max-Age + Option with a value of zero seconds. + + If a client has a fresh stored response and makes a new request + matching the request for that stored response, the new response + invalidates the old response. + +5.6.2. Validation Model + + When an endpoint has one or more stored responses for a GET request, + but cannot use any of them (e.g., because they are not fresh), it can + use the ETag Option (Section 5.10.6) in the GET request to give the + origin server an opportunity both to select a stored response to be + used, and to update its freshness. This process is known as + "validating" or "revalidating" the stored response. + + When sending such a request, the endpoint SHOULD add an ETag Option + specifying the entity-tag of each stored response that is applicable. + + A 2.03 (Valid) response indicates the stored response identified by + the entity-tag given in the response's ETag Option can be reused + after updating it as described in Section 5.9.1.3. + + Any other Response Code indicates that none of the stored responses + nominated in the request is suitable. Instead, the response SHOULD + be used to satisfy the request and MAY replace the stored response. + + + + + + + + + + +Shelby, et al. Standards Track [Page 43] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.7. Proxying + + A proxy is a CoAP endpoint that can be tasked by CoAP clients to + perform requests on their behalf. This may be useful, for example, + when the request could otherwise not be made, or to service the + response from a cache in order to reduce response time and network + bandwidth or energy consumption. + + In an overall architecture for a Constrained RESTful Environment, + proxies can serve quite different purposes. Proxies can be + explicitly selected by clients, a role that we term "forward-proxy". + Proxies can also be inserted to stand in for origin servers, a role + that we term "reverse-proxy". Orthogonal to this distinction, a + proxy can map from a CoAP request to a CoAP request (CoAP-to-CoAP + proxy) or translate from or to a different protocol ("cross-proxy"). + Full definitions of these terms are provided in Section 1.2. + + Notes: The terminology in this specification has been selected to be + culturally compatible with the terminology used in the wider web + application environments, without necessarily matching it in every + detail (which may not even be relevant to Constrained RESTful + Environments). Not too much semantics should be ascribed to the + components of the terms (such as "forward", "reverse", or + "cross"). + + HTTP proxies, besides acting as HTTP proxies, often offer a + transport-protocol proxying function ("CONNECT") to enable end-to- + end transport layer security through the proxy. No such function + is defined for CoAP-to-CoAP proxies in this specification, as + forwarding of UDP packets is unlikely to be of much value in + Constrained RESTful Environments. See also Section 10.2.7 for the + cross-proxy case. + + When a client uses a proxy to make a request that will use a secure + URI scheme (e.g., "coaps" or "https"), the request towards the proxy + SHOULD be sent using DTLS except where equivalent lower-layer + security is used for the leg between the client and the proxy. + +5.7.1. Proxy Operation + + A proxy generally needs a way to determine potential request + parameters for a request it places to a destination, based on the + request it received from its client. This way is fully specified for + a forward-proxy but may depend on the specific configuration for a + reverse-proxy. In particular, the client of a reverse-proxy + generally does not indicate a locator for the destination, + + + + + +Shelby, et al. Standards Track [Page 44] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + necessitating some form of namespace translation in the reverse- + proxy. However, some aspects of the operation of proxies are common + to all its forms. + + If a proxy does not employ a cache, then it simply forwards the + translated request to the determined destination. Otherwise, if it + does employ a cache but does not have a stored response that matches + the translated request and is considered fresh, then it needs to + refresh its cache according to Section 5.6. For options in the + request that the proxy recognizes, it knows whether the option is + intended to act as part of the key used in looking up the cached + value or not. For example, since requests for different Uri-Path + values address different resources, Uri-Path values are always part + of the Cache-Key, while, e.g., Token values are never part of the + Cache-Key. For options that the proxy does not recognize but that + are marked Safe-to-Forward in the option number, the option also + indicates whether it is to be included in the Cache-Key (NoCacheKey + is not all set) or not (NoCacheKey is all set). (Options that are + unrecognized and marked Unsafe lead to 4.02 Bad Option.) + + If the request to the destination times out, then a 5.04 (Gateway + Timeout) response MUST be returned. If the request to the + destination returns a response that cannot be processed by the proxy + (e.g, due to unrecognized critical options or message format errors), + then a 5.02 (Bad Gateway) response MUST be returned. Otherwise, the + proxy returns the response to the client. + + If a response is generated out of a cache, the generated (or implied) + Max-Age Option MUST NOT extend the max-age originally set by the + server, considering the time the resource representation spent in the + cache. For example, the Max-Age Option could be adjusted by the + proxy for each response using the formula: + + proxy-max-age = original-max-age - cache-age + + For example, if a request is made to a proxied resource that was + refreshed 20 seconds ago and had an original Max-Age of 60 seconds, + then that resource's proxied max-age is now 40 seconds. Considering + potential network delays on the way from the origin server, a proxy + should be conservative in the max-age values offered. + + All options present in a proxy request MUST be processed at the + proxy. Unsafe options in a request that are not recognized by the + proxy MUST lead to a 4.02 (Bad Option) response being returned by the + proxy. A CoAP-to-CoAP proxy MUST forward to the origin server all + Safe-to-Forward options that it does not recognize. Similarly, + + + + + +Shelby, et al. Standards Track [Page 45] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Unsafe options in a response that are not recognized by the CoAP-to- + CoAP proxy server MUST lead to a 5.02 (Bad Gateway) response. Again, + Safe-to-Forward options that are not recognized MUST be forwarded. + + Additional considerations for cross-protocol proxying between CoAP + and HTTP are discussed in Section 10. + +5.7.2. Forward-Proxies + + CoAP distinguishes between requests made (as if) to an origin server + and requests made through a forward-proxy. CoAP requests to a + forward-proxy are made as normal Confirmable or Non-confirmable + requests to the forward-proxy endpoint, but they specify the request + URI in a different way: The request URI in a proxy request is + specified as a string in the Proxy-Uri Option (see Section 5.10.2), + while the request URI in a request to an origin server is split into + the Uri-Host, Uri-Port, Uri-Path, and Uri-Query Options (see + Section 5.10.1). Alternatively, the URI in a proxy request can be + assembled from a Proxy-Scheme option and the split options mentioned. + + When a proxy request is made to an endpoint and the endpoint is + unwilling or unable to act as proxy for the request URI, it MUST + return a 5.05 (Proxying Not Supported) response. If the authority + (host and port) is recognized as identifying the proxy endpoint + itself (see Section 5.10.2), then the request MUST be treated as a + local (non-proxied) request. + + Unless a proxy is configured to forward the proxy request to another + proxy, it MUST translate the request as follows: the scheme of the + request URI defines the outgoing protocol and its details (e.g., CoAP + is used over UDP for the "coap" scheme and over DTLS for the "coaps" + scheme.) For a CoAP-to-CoAP proxy, the origin server's IP address + and port are determined by the authority component of the request + URI, and the request URI is decoded and split into the Uri-Host, Uri- + Port, Uri-Path and Uri-Query Options. This consumes the Proxy-Uri or + Proxy-Scheme option, which is therefore not forwarded to the origin + server. + +5.7.3. Reverse-Proxies + + Reverse-proxies do not make use of the Proxy-Uri or Proxy-Scheme + options but need to determine the destination (next hop) of a request + from information in the request and information in their + configuration. For example, a reverse-proxy might offer various + resources as if they were its own resources, after having learned of + their existence through resource discovery. The reverse-proxy is + free to build a namespace for the URIs that identify these resources. + A reverse-proxy may also build a namespace that gives the client more + + + +Shelby, et al. Standards Track [Page 46] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + control over where the request goes, e.g., by embedding host + identifiers and port numbers into the URI path of the resources + offered. + + In processing the response, a reverse-proxy has to be careful that + ETag option values from different sources are not mixed up on one + resource offered to its clients. In many cases, the ETag can be + forwarded unchanged. If the mapping from a resource offered by the + reverse-proxy to resources offered by its various origin servers is + not unique, the reverse-proxy may need to generate a new ETag, making + sure the semantics of this option are properly preserved. + +5.8. Method Definitions + + In this section, each method is defined along with its behavior. A + request with an unrecognized or unsupported Method Code MUST generate + a 4.05 (Method Not Allowed) piggybacked response. + +5.8.1. GET + + The GET method retrieves a representation for the information that + currently corresponds to the resource identified by the request URI. + If the request includes an Accept Option, that indicates the + preferred content-format of a response. If the request includes an + ETag Option, the GET method requests that ETag be validated and that + the representation be transferred only if validation failed. Upon + success, a 2.05 (Content) or 2.03 (Valid) Response Code SHOULD be + present in the response. + + The GET method is safe and idempotent. + +5.8.2. POST + + The POST method requests that the representation enclosed in the + request be processed. The actual function performed by the POST + method is determined by the origin server and dependent on the target + resource. It usually results in a new resource being created or the + target resource being updated. + + If a resource has been created on the server, the response returned + by the server SHOULD have a 2.01 (Created) Response Code and SHOULD + include the URI of the new resource in a sequence of one or more + Location-Path and/or Location-Query Options (Section 5.10.7). If the + POST succeeds but does not result in a new resource being created on + the server, the response SHOULD have a 2.04 (Changed) Response Code. + If the POST succeeds and results in the target resource being + deleted, the response SHOULD have a 2.02 (Deleted) Response Code. + POST is neither safe nor idempotent. + + + +Shelby, et al. Standards Track [Page 47] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.8.3. PUT + + The PUT method requests that the resource identified by the request + URI be updated or created with the enclosed representation. The + representation format is specified by the media type and content + coding given in the Content-Format Option, if provided. + + If a resource exists at the request URI, the enclosed representation + SHOULD be considered a modified version of that resource, and a 2.04 + (Changed) Response Code SHOULD be returned. If no resource exists, + then the server MAY create a new resource with that URI, resulting in + a 2.01 (Created) Response Code. If the resource could not be created + or modified, then an appropriate error Response Code SHOULD be sent. + + Further restrictions to a PUT can be made by including the If-Match + (see Section 5.10.8.1) or If-None-Match (see Section 5.10.8.2) + options in the request. + + PUT is not safe but is idempotent. + +5.8.4. DELETE + + The DELETE method requests that the resource identified by the + request URI be deleted. A 2.02 (Deleted) Response Code SHOULD be + used on success or in case the resource did not exist before the + request. + + DELETE is not safe but is idempotent. + +5.9. Response Code Definitions + + Each Response Code is described below, including any options required + in the response. Where appropriate, some of the codes will be + specified in regards to related Response Codes in HTTP [RFC2616]; + this does not mean that any such relationship modifies the HTTP + mapping specified in Section 10. + +5.9.1. Success 2.xx + + This class of Response Code indicates that the clients request was + successfully received, understood, and accepted. + +5.9.1.1. 2.01 Created + + Like HTTP 201 "Created", but only used in response to POST and PUT + requests. The payload returned with the response, if any, is a + representation of the action result. + + + + +Shelby, et al. Standards Track [Page 48] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + If the response includes one or more Location-Path and/or Location- + Query Options, the values of these options specify the location at + which the resource was created. Otherwise, the resource was created + at the request URI. A cache receiving this response MUST mark any + stored response for the created resource as not fresh. + + This response is not cacheable. + +5.9.1.2. 2.02 Deleted + + This Response Code is like HTTP 204 "No Content" but only used in + response to requests that cause the resource to cease being + available, such as DELETE and, in certain circumstances, POST. The + payload returned with the response, if any, is a representation of + the action result. + + This response is not cacheable. However, a cache MUST mark any + stored response for the deleted resource as not fresh. + +5.9.1.3. 2.03 Valid + + This Response Code is related to HTTP 304 "Not Modified" but only + used to indicate that the response identified by the entity-tag + identified by the included ETag Option is valid. Accordingly, the + response MUST include an ETag Option and MUST NOT include a payload. + + When a cache that recognizes and processes the ETag response option + receives a 2.03 (Valid) response, it MUST update the stored response + with the value of the Max-Age Option included in the response + (explicitly, or implicitly as a default value; see also + Section 5.6.2). For each type of Safe-to-Forward option present in + the response, the (possibly empty) set of options of this type that + are present in the stored response MUST be replaced with the set of + options of this type in the response received. (Unsafe options may + trigger similar option-specific processing as defined by the option.) + +5.9.1.4. 2.04 Changed + + This Response Code is like HTTP 204 "No Content" but only used in + response to POST and PUT requests. The payload returned with the + response, if any, is a representation of the action result. + + This response is not cacheable. However, a cache MUST mark any + stored response for the changed resource as not fresh. + + + + + + + +Shelby, et al. Standards Track [Page 49] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.9.1.5. 2.05 Content + + This Response Code is like HTTP 200 "OK" but only used in response to + GET requests. + + The payload returned with the response is a representation of the + target resource. + + This response is cacheable: Caches can use the Max-Age Option to + determine freshness (see Section 5.6.1) and (if present) the ETag + Option for validation (see Section 5.6.2). + +5.9.2. Client Error 4.xx + + This class of Response Code is intended for cases in which the client + seems to have erred. These Response Codes are applicable to any + request method. + + The server SHOULD include a diagnostic payload under the conditions + detailed in Section 5.5.2. + + Responses of this class are cacheable: Caches can use the Max-Age + Option to determine freshness (see Section 5.6.1). They cannot be + validated. + +5.9.2.1. 4.00 Bad Request + + This Response Code is Like HTTP 400 "Bad Request". + +5.9.2.2. 4.01 Unauthorized + + The client is not authorized to perform the requested action. The + client SHOULD NOT repeat the request without first improving its + authentication status to the server. Which specific mechanism can be + used for this is outside this document's scope; see also Section 9. + +5.9.2.3. 4.02 Bad Option + + The request could not be understood by the server due to one or more + unrecognized or malformed options. The client SHOULD NOT repeat the + request without modification. + +5.9.2.4. 4.03 Forbidden + + This Response Code is like HTTP 403 "Forbidden". + + + + + + +Shelby, et al. Standards Track [Page 50] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.9.2.5. 4.04 Not Found + + This Response Code is like HTTP 404 "Not Found". + +5.9.2.6. 4.05 Method Not Allowed + + This Response Code is like HTTP 405 "Method Not Allowed" but with no + parallel to the "Allow" header field. + +5.9.2.7. 4.06 Not Acceptable + + This Response Code is like HTTP 406 "Not Acceptable", but with no + response entity. + +5.9.2.8. 4.12 Precondition Failed + + This Response Code is like HTTP 412 "Precondition Failed". + +5.9.2.9. 4.13 Request Entity Too Large + + This Response Code is like HTTP 413 "Request Entity Too Large". + + The response SHOULD include a Size1 Option (Section 5.10.9) to + indicate the maximum size of request entity the server is able and + willing to handle, unless the server is not in a position to make + this information available. + +5.9.2.10. 4.15 Unsupported Content-Format + + This Response Code is like HTTP 415 "Unsupported Media Type". + +5.9.3. Server Error 5.xx + + This class of Response Code indicates cases in which the server is + aware that it has erred or is incapable of performing the request. + These Response Codes are applicable to any request method. + + The server SHOULD include a diagnostic payload under the conditions + detailed in Section 5.5.2. + + Responses of this class are cacheable: Caches can use the Max-Age + Option to determine freshness (see Section 5.6.1). They cannot be + validated. + +5.9.3.1. 5.00 Internal Server Error + + This Response Code is like HTTP 500 "Internal Server Error". + + + + +Shelby, et al. Standards Track [Page 51] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.9.3.2. 5.01 Not Implemented + + This Response Code is like HTTP 501 "Not Implemented". + +5.9.3.3. 5.02 Bad Gateway + + This Response Code is like HTTP 502 "Bad Gateway". + +5.9.3.4. 5.03 Service Unavailable + + This Response Code is like HTTP 503 "Service Unavailable" but uses + the Max-Age Option in place of the "Retry-After" header field to + indicate the number of seconds after which to retry. + +5.9.3.5. 5.04 Gateway Timeout + + This Response Code is like HTTP 504 "Gateway Timeout". + +5.9.3.6. 5.05 Proxying Not Supported + + The server is unable or unwilling to act as a forward-proxy for the + URI specified in the Proxy-Uri Option or using Proxy-Scheme (see + Section 5.10.2). + +5.10. Option Definitions + + The individual CoAP options are summarized in Table 4 and explained + in the subsections of this section. + + In this table, the C, U, and N columns indicate the properties + Critical, UnSafe, and NoCacheKey, respectively. Since NoCacheKey + only has a meaning for options that are Safe-to-Forward (not marked + Unsafe), the column is filled with a dash for UnSafe options. + + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 52] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + +-----+---+---+---+---+----------------+--------+--------+----------+ + | No. | C | U | N | R | Name | Format | Length | Default | + +-----+---+---+---+---+----------------+--------+--------+----------+ + | 1 | x | | | x | If-Match | opaque | 0-8 | (none) | + | 3 | x | x | - | | Uri-Host | string | 1-255 | (see | + | | | | | | | | | below) | + | 4 | | | | x | ETag | opaque | 1-8 | (none) | + | 5 | x | | | | If-None-Match | empty | 0 | (none) | + | 7 | x | x | - | | Uri-Port | uint | 0-2 | (see | + | | | | | | | | | below) | + | 8 | | | | x | Location-Path | string | 0-255 | (none) | + | 11 | x | x | - | x | Uri-Path | string | 0-255 | (none) | + | 12 | | | | | Content-Format | uint | 0-2 | (none) | + | 14 | | x | - | | Max-Age | uint | 0-4 | 60 | + | 15 | x | x | - | x | Uri-Query | string | 0-255 | (none) | + | 17 | x | | | | Accept | uint | 0-2 | (none) | + | 20 | | | | x | Location-Query | string | 0-255 | (none) | + | 35 | x | x | - | | Proxy-Uri | string | 1-1034 | (none) | + | 39 | x | x | - | | Proxy-Scheme | string | 1-255 | (none) | + | 60 | | | x | | Size1 | uint | 0-4 | (none) | + +-----+---+---+---+---+----------------+--------+--------+----------+ + + C=Critical, U=Unsafe, N=NoCacheKey, R=Repeatable + + Table 4: Options + +5.10.1. Uri-Host, Uri-Port, Uri-Path, and Uri-Query + + The Uri-Host, Uri-Port, Uri-Path, and Uri-Query Options are used to + specify the target resource of a request to a CoAP origin server. + The options encode the different components of the request URI in a + way that no percent-encoding is visible in the option values and that + the full URI can be reconstructed at any involved endpoint. The + syntax of CoAP URIs is defined in Section 6. + + The steps for parsing URIs into options is defined in Section 6.4. + These steps result in zero or more Uri-Host, Uri-Port, Uri-Path, and + Uri-Query Options being included in a request, where each option + holds the following values: + + o the Uri-Host Option specifies the Internet host of the resource + being requested, + + o the Uri-Port Option specifies the transport-layer port number of + the resource, + + o each Uri-Path Option specifies one segment of the absolute path to + the resource, and + + + +Shelby, et al. Standards Track [Page 53] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o each Uri-Query Option specifies one argument parameterizing the + resource. + + Note: Fragments ([RFC3986], Section 3.5) are not part of the request + URI and thus will not be transmitted in a CoAP request. + + The default value of the Uri-Host Option is the IP literal + representing the destination IP address of the request message. + Likewise, the default value of the Uri-Port Option is the destination + UDP port. The default values for the Uri-Host and Uri-Port Options + are sufficient for requests to most servers. Explicit Uri-Host and + Uri-Port Options are typically used when an endpoint hosts multiple + virtual servers. + + The Uri-Path and Uri-Query Option can contain any character sequence. + No percent-encoding is performed. The value of a Uri-Path Option + MUST NOT be "." or ".." (as the request URI must be resolved before + parsing it into options). + + The steps for constructing the request URI from the options are + defined in Section 6.5. Note that an implementation does not + necessarily have to construct the URI; it can simply look up the + target resource by examining the individual options. + + Examples can be found in Appendix B. + +5.10.2. Proxy-Uri and Proxy-Scheme + + The Proxy-Uri Option is used to make a request to a forward-proxy + (see Section 5.7). The forward-proxy is requested to forward the + request or service it from a valid cache and return the response. + + The option value is an absolute-URI ([RFC3986], Section 4.3). + + Note that the forward-proxy MAY forward the request on to another + proxy or directly to the server specified by the absolute-URI. In + order to avoid request loops, a proxy MUST be able to recognize all + of its server names, including any aliases, local variations, and the + numeric IP addresses. + + An endpoint receiving a request with a Proxy-Uri Option that is + unable or unwilling to act as a forward-proxy for the request MUST + cause the return of a 5.05 (Proxying Not Supported) response. + + The Proxy-Uri Option MUST take precedence over any of the Uri-Host, + Uri-Port, Uri-Path or Uri-Query options (each of which MUST NOT be + included in a request containing the Proxy-Uri Option). + + + + +Shelby, et al. Standards Track [Page 54] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + As a special case to simplify many proxy clients, the absolute-URI + can be constructed from the Uri-* options. When a Proxy-Scheme + Option is present, the absolute-URI is constructed as follows: a CoAP + URI is constructed from the Uri-* options as defined in Section 6.5. + In the resulting URI, the initial scheme up to, but not including, + the following colon is then replaced by the content of the Proxy- + Scheme Option. Note that this case is only applicable if the + components of the desired URI other than the scheme component + actually can be expressed using Uri-* options; for example, to + represent a URI with a userinfo component in the authority, only + Proxy-Uri can be used. + +5.10.3. Content-Format + + The Content-Format Option indicates the representation format of the + message payload. The representation format is given as a numeric + Content-Format identifier that is defined in the "CoAP Content- + Formats" registry (Section 12.3). In the absence of the option, no + default value is assumed, i.e., the representation format of any + representation message payload is indeterminate (Section 5.5). + +5.10.4. Accept + + The CoAP Accept option can be used to indicate which Content-Format + is acceptable to the client. The representation format is given as a + numeric Content-Format identifier that is defined in the "CoAP + Content-Formats" registry (Section 12.3). If no Accept option is + given, the client does not express a preference (thus no default + value is assumed). The client prefers the representation returned by + the server to be in the Content-Format indicated. The server returns + the preferred Content-Format if available. If the preferred Content- + Format cannot be returned, then a 4.06 "Not Acceptable" MUST be sent + as a response, unless another error code takes precedence for this + response. + +5.10.5. Max-Age + + The Max-Age Option indicates the maximum time a response may be + cached before it is considered not fresh (see Section 5.6.1). + + The option value is an integer number of seconds between 0 and + 2**32-1 inclusive (about 136.1 years). A default value of 60 seconds + is assumed in the absence of the option in a response. + + The value is intended to be current at the time of transmission. + Servers that provide resources with strict tolerances on the value of + Max-Age SHOULD update the value before each retransmission. (See + also Section 5.7.1.) + + + +Shelby, et al. Standards Track [Page 55] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.10.6. ETag + + An entity-tag is intended for use as a resource-local identifier for + differentiating between representations of the same resource that + vary over time. It is generated by the server providing the + resource, which may generate it in any number of ways including a + version, checksum, hash, or time. An endpoint receiving an entity- + tag MUST treat it as opaque and make no assumptions about its content + or structure. (Endpoints that generate an entity-tag are encouraged + to use the most compact representation possible, in particular in + regards to clients and intermediaries that may want to store multiple + ETag values.) + +5.10.6.1. ETag as a Response Option + + The ETag Option in a response provides the current value (i.e., after + the request was processed) of the entity-tag for the "tagged + representation". If no Location-* options are present, the tagged + representation is the selected representation (Section 5.5.3) of the + target resource. If one or more Location-* options are present and + thus a location URI is indicated (Section 5.10.7), the tagged + representation is the representation that would be retrieved by a GET + request to the location URI. + + An ETag response option can be included with any response for which + there is a tagged representation (e.g., it would not be meaningful in + a 4.04 or 4.00 response). The ETag Option MUST NOT occur more than + once in a response. + + There is no default value for the ETag Option; if it is not present + in a response, the server makes no statement about the entity-tag for + the tagged representation. + +5.10.6.2. ETag as a Request Option + + In a GET request, an endpoint that has one or more representations + previously obtained from the resource, and has obtained ETag response + options with these, can specify an instance of the ETag Option for + one or more of these stored responses. + + A server can issue a 2.03 Valid response (Section 5.9.1.3) in place + of a 2.05 Content response if one of the ETags given is the entity- + tag for the current representation, i.e., is valid; the 2.03 Valid + response then echoes this specific ETag in a response option. + + In effect, a client can determine if any of the stored + representations is current (see Section 5.6.2) without needing to + transfer them again. + + + +Shelby, et al. Standards Track [Page 56] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The ETag Option MAY occur zero, one, or multiple times in a request. + +5.10.7. Location-Path and Location-Query + + The Location-Path and Location-Query Options together indicate a + relative URI that consists either of an absolute path, a query + string, or both. A combination of these options is included in a + 2.01 (Created) response to indicate the location of the resource + created as the result of a POST request (see Section 5.8.2). The + location is resolved relative to the request URI. + + If a response with one or more Location-Path and/or Location-Query + Options passes through a cache that interprets these options and the + implied URI identifies one or more currently stored responses, those + entries MUST be marked as not fresh. + + Each Location-Path Option specifies one segment of the absolute path + to the resource, and each Location-Query Option specifies one + argument parameterizing the resource. The Location-Path and + Location-Query Option can contain any character sequence. No + percent-encoding is performed. The value of a Location-Path Option + MUST NOT be "." or "..". + + The steps for constructing the location URI from the options are + analogous to Section 6.5, except that the first five steps are + skipped and the result is a relative URI-reference, which is then + interpreted relative to the request URI. Note that the relative URI- + reference constructed this way always includes an absolute path + (e.g., leaving out Location-Path but supplying Location-Query means + the path component in the URI is "/"). + + The options that are used to compute the relative URI-reference are + collectively called Location-* options. Beyond Location-Path and + Location-Query, more Location-* options may be defined in the future + and have been reserved option numbers 128, 132, 136, and 140. If any + of these reserved option numbers occurs in addition to Location-Path + and/or Location-Query and are not supported, then a 4.02 (Bad Option) + error MUST be returned. + +5.10.8. Conditional Request Options + + Conditional request options enable a client to ask the server to + perform the request only if certain conditions specified by the + option are fulfilled. + + + + + + + +Shelby, et al. Standards Track [Page 57] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + For each of these options, if the condition given is not fulfilled, + then the server MUST NOT perform the requested method. Instead, the + server MUST respond with the 4.12 (Precondition Failed) Response + Code. + + If the condition is fulfilled, the server performs the request method + as if the conditional request options were not present. + + If the request would, without the conditional request options, result + in anything other than a 2.xx or 4.12 Response Code, then any + conditional request options MAY be ignored. + +5.10.8.1. If-Match + + The If-Match Option MAY be used to make a request conditional on the + current existence or value of an ETag for one or more representations + of the target resource. If-Match is generally useful for resource + update requests, such as PUT requests, as a means for protecting + against accidental overwrites when multiple clients are acting in + parallel on the same resource (i.e., the "lost update" problem). + + The value of an If-Match option is either an ETag or the empty + string. An If-Match option with an ETag matches a representation + with that exact ETag. An If-Match option with an empty value matches + any existing representation (i.e., it places the precondition on the + existence of any current representation for the target resource). + + The If-Match Option can occur multiple times. If any of the options + match, then the condition is fulfilled. + + If there is one or more If-Match Options, but none of the options + match, then the condition is not fulfilled. + +5.10.8.2. If-None-Match + + The If-None-Match Option MAY be used to make a request conditional on + the nonexistence of the target resource. If-None-Match is useful for + resource creation requests, such as PUT requests, as a means for + protecting against accidental overwrites when multiple clients are + acting in parallel on the same resource. The If-None-Match Option + carries no value. + + If the target resource does exist, then the condition is not + fulfilled. + + (It is not very useful to combine If-Match and If-None-Match options + in one request, because the condition will then never be fulfilled.) + + + + +Shelby, et al. Standards Track [Page 58] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +5.10.9. Size1 Option + + The Size1 option provides size information about the resource + representation in a request. The option value is an integer number + of bytes. Its main use is with block-wise transfers [BLOCK]. In the + present specification, it is used in 4.13 responses (Section 5.9.2.9) + to indicate the maximum size of request entity that the server is + able and willing to handle. + +6. CoAP URIs + + CoAP uses the "coap" and "coaps" URI schemes for identifying CoAP + resources and providing a means of locating the resource. Resources + are organized hierarchically and governed by a potential CoAP origin + server listening for CoAP requests ("coap") or DTLS-secured CoAP + requests ("coaps") on a given UDP port. The CoAP server is + identified via the generic syntax's authority component, which + includes a host component and optional UDP port number. The + remainder of the URI is considered to be identifying a resource that + can be operated on by the methods defined by the CoAP protocol. The + "coap" and "coaps" URI schemes can thus be compared to the "http" and + "https" URI schemes, respectively. + + The syntax of the "coap" and "coaps" URI schemes is specified in this + section in Augmented Backus-Naur Form (ABNF) [RFC5234]. The + definitions of "host", "port", "path-abempty", "query", "segment", + "IP-literal", "IPv4address", and "reg-name" are adopted from + [RFC3986]. + + Implementation Note: Unfortunately, over time, the URI format has + acquired significant complexity. Implementers are encouraged to + examine [RFC3986] closely. For example, the ABNF for IPv6 + addresses is more complicated than maybe expected. Also, + implementers should take care to perform the processing of + percent-decoding or percent-encoding exactly once on the way from + a URI to its decoded components or back. Percent-encoding is + crucial for data transparency but may lead to unusual results such + as a slash character in a path component. + +6.1. coap URI Scheme + + coap-URI = "coap:" "//" host [ ":" port ] path-abempty [ "?" query ] + + If the host component is provided as an IP-literal or IPv4address, + then the CoAP server can be reached at that IP address. If host is a + registered name, then that name is considered an indirect identifier + and the endpoint might use a name resolution service, such as DNS, to + find the address of that host. The host MUST NOT be empty; if a URI + + + +Shelby, et al. Standards Track [Page 59] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + is received with a missing authority or an empty host, then it MUST + be considered invalid. The port subcomponent indicates the UDP port + at which the CoAP server is located. If it is empty or not given, + then the default port 5683 is assumed. + + The path identifies a resource within the scope of the host and port. + It consists of a sequence of path segments separated by a slash + character (U+002F SOLIDUS "/"). + + The query serves to further parameterize the resource. It consists + of a sequence of arguments separated by an ampersand character + (U+0026 AMPERSAND "&"). An argument is often in the form of a + "key=value" pair. + + The "coap" URI scheme supports the path prefix "/.well-known/" + defined by [RFC5785] for "well-known locations" in the namespace of a + host. This enables discovery of policy or other information about a + host ("site-wide metadata"), such as hosted resources (see + Section 7). + + Application designers are encouraged to make use of short but + descriptive URIs. As the environments that CoAP is used in are + usually constrained for bandwidth and energy, the trade-off between + these two qualities should lean towards the shortness, without + ignoring descriptiveness. + +6.2. coaps URI Scheme + + coaps-URI = "coaps:" "//" host [ ":" port ] path-abempty + [ "?" query ] + + All of the requirements listed above for the "coap" scheme are also + requirements for the "coaps" scheme, except that a default UDP port + of 5684 is assumed if the port subcomponent is empty or not given, + and the UDP datagrams MUST be secured through the use of DTLS as + described in Section 9.1. + + Considerations for caching of responses to "coaps" identified + requests are discussed in Section 11.2. + + Resources made available via the "coaps" scheme have no shared + identity with the "coap" scheme even if their resource identifiers + indicate the same authority (the same host listening to the same UDP + port). They are distinct namespaces and are considered to be + distinct origin servers. + + + + + + +Shelby, et al. Standards Track [Page 60] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +6.3. Normalization and Comparison Rules + + Since the "coap" and "coaps" schemes conform to the URI generic + syntax, such URIs are normalized and compared according to the + algorithm defined in [RFC3986], Section 6, using the defaults + described above for each scheme. + + If the port is equal to the default port for a scheme, the normal + form is to elide the port subcomponent. Likewise, an empty path + component is equivalent to an absolute path of "/", so the normal + form is to provide a path of "/" instead. The scheme and host are + case insensitive and normally provided in lowercase; IP-literals are + in recommended form [RFC5952]; all other components are compared in a + case-sensitive manner. Characters other than those in the "reserved" + set are equivalent to their percent-encoded bytes (see [RFC3986], + Section 2.1): the normal form is to not encode them. + + For example, the following three URIs are equivalent and cause the + same options and option values to appear in the CoAP messages: + + coap://example.com:5683/~sensors/temp.xml + coap://EXAMPLE.com/%7Esensors/temp.xml + coap://EXAMPLE.com:/%7esensors/temp.xml + +6.4. Decomposing URIs into Options + + The steps to parse a request's options from a string |url| are as + follows. These steps either result in zero or more of the Uri-Host, + Uri-Port, Uri-Path, and Uri-Query Options being included in the + request or they fail. + + 1. If the |url| string is not an absolute URI ([RFC3986]), then fail + this algorithm. + + 2. Resolve the |url| string using the process of reference + resolution defined by [RFC3986]. At this stage, the URL is in + ASCII encoding [RFC0020], even though the decoded components will + be interpreted in UTF-8 [RFC3629] after steps 5, 8, and 9. + + NOTE: It doesn't matter what it is resolved relative to, since we + already know it is an absolute URL at this point. + + 3. If |url| does not have a component whose value, when + converted to ASCII lowercase, is "coap" or "coaps", then fail + this algorithm. + + 4. If |url| has a component, then fail this algorithm. + + + + +Shelby, et al. Standards Track [Page 61] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + 5. If the component of |url| does not represent the request's + destination IP address as an IP-literal or IPv4address, include a + Uri-Host Option and let that option's value be the value of the + component of |url|, converted to ASCII lowercase, and then + convert all percent-encodings ("%" followed by two hexadecimal + digits) to the corresponding characters. + + NOTE: In the usual case where the request's destination IP + address is derived from the host part, this ensures that a Uri- + Host Option is only used for a component of the form reg- + name. + + 6. If |url| has a component, then let |port| be that + component's value interpreted as a decimal integer; otherwise, + let |port| be the default port for the scheme. + + 7. If |port| does not equal the request's destination UDP port, + include a Uri-Port Option and let that option's value be |port|. + + 8. If the value of the component of |url| is empty or + consists of a single slash character (U+002F SOLIDUS "/"), then + move to the next step. + + Otherwise, for each segment in the component, include a + Uri-Path Option and let that option's value be the segment (not + including the delimiting slash characters) after converting each + percent-encoding ("%" followed by two hexadecimal digits) to the + corresponding byte. + + 9. If |url| has a component, then, for each argument in the + component, include a Uri-Query Option and let that + option's value be the argument (not including the question mark + and the delimiting ampersand characters) after converting each + percent-encoding to the corresponding byte. + + Note that these rules completely resolve any percent-encoding. + +6.5. Composing URIs from Options + + The steps to construct a URI from a request's options are as follows. + These steps either result in a URI or they fail. In these steps, + percent-encoding a character means replacing each of its + (UTF-8-encoded) bytes by a "%" character followed by two hexadecimal + digits representing the byte, where the digits A-F are in uppercase + (as defined in Section 2.1 of [RFC3986]; to reduce variability, the + hexadecimal notation for percent-encoding in CoAP URIs MUST use + uppercase letters). The definitions of "unreserved" and "sub-delims" + are adopted from [RFC3986]. + + + +Shelby, et al. Standards Track [Page 62] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + 1. If the request is secured using DTLS, let |url| be the string + "coaps://". Otherwise, let |url| be the string "coap://". + + 2. If the request includes a Uri-Host Option, let |host| be that + option's value, where any non-ASCII characters are replaced by + their corresponding percent-encoding. If |host| is not a valid + reg-name or IP-literal or IPv4address, fail the algorithm. If + the request does not include a Uri-Host Option, let |host| be + the IP-literal (making use of the conventions of [RFC5952]) or + IPv4address representing the request's destination IP address. + + 3. Append |host| to |url|. + + 4. If the request includes a Uri-Port Option, let |port| be that + option's value. Otherwise, let |port| be the request's + destination UDP port. + + 5. If |port| is not the default port for the scheme, then append a + single U+003A COLON character (:) followed by the decimal + representation of |port| to |url|. + + 6. Let |resource name| be the empty string. For each Uri-Path + Option in the request, append a single character U+002F SOLIDUS + (/) followed by the option's value to |resource name|, after + converting any character that is not either in the "unreserved" + set, in the "sub-delims" set, a U+003A COLON (:) character, or a + U+0040 COMMERCIAL AT (@) character to its percent-encoded form. + + 7. If |resource name| is the empty string, set it to a single + character U+002F SOLIDUS (/). + + 8. For each Uri-Query Option in the request, append a single + character U+003F QUESTION MARK (?) (first option) or U+0026 + AMPERSAND (&) (subsequent options) followed by the option's + value to |resource name|, after converting any character that is + not either in the "unreserved" set, in the "sub-delims" set + (except U+0026 AMPERSAND (&)), a U+003A COLON (:), a U+0040 + COMMERCIAL AT (@), a U+002F SOLIDUS (/), or a U+003F QUESTION + MARK (?) character to its percent-encoded form. + + 9. Append |resource name| to |url|. + + 10. Return |url|. + + Note that these steps have been designed to lead to a URI in normal + form (see Section 6.3). + + + + + +Shelby, et al. Standards Track [Page 63] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +7. Discovery + +7.1. Service Discovery + + As a part of discovering the services offered by a CoAP server, a + client has to learn about the endpoint used by a server. + + A server is discovered by a client (knowing or) learning a URI that + references a resource in the namespace of the server. Alternatively, + clients can use multicast CoAP (see Section 8) and the "All CoAP + Nodes" multicast address to find CoAP servers. + + Unless the port subcomponent in a "coap" or "coaps" URI indicates the + UDP port at which the CoAP server is located, the server is assumed + to be reachable at the default port. + + The CoAP default port number 5683 MUST be supported by a server that + offers resources for resource discovery (see Section 7.2 below) and + SHOULD be supported for providing access to other resources. The + default port number 5684 for DTLS-secured CoAP MAY be supported by a + server for resource discovery and for providing access to other + resources. In addition, other endpoints may be hosted at other + ports, e.g., in the dynamic port space. + + Implementation Note: When a CoAP server is hosted by a 6LoWPAN node, + header compression efficiency is improved when it also supports a + port number in the 61616-61631 compressed UDP port space defined + in [RFC4944] and [RFC6282]. (Note that, as its UDP port differs + from the default port, it is a different endpoint from the server + at the default port.) + +7.2. Resource Discovery + + The discovery of resources offered by a CoAP endpoint is extremely + important in machine-to-machine applications where there are no + humans in the loop and static interfaces result in fragility. To + maximize interoperability in a CoRE environment, a CoAP endpoint + SHOULD support the CoRE Link Format of discoverable resources as + described in [RFC6690], except where fully manual configuration is + desired. It is up to the server which resources are made + discoverable (if any). + +7.2.1. 'ct' Attribute + + This section defines a new Web Linking [RFC5988] attribute for use + with [RFC6690]. The Content-Format code "ct" attribute provides a + hint about the Content-Formats this resource returns. Note that this + is only a hint, and it does not override the Content-Format Option of + + + +Shelby, et al. Standards Track [Page 64] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + a CoAP response obtained by actually requesting the representation of + the resource. The value is in the CoAP identifier code format as a + decimal ASCII integer and MUST be in the range of 0-65535 (16-bit + unsigned integer). For example, "application/xml" would be indicated + as "ct=41". If no Content-Format code attribute is present, then + nothing about the type can be assumed. The Content-Format code + attribute MAY include a space-separated sequence of Content-Format + codes, indicating that multiple content-formats are available. The + syntax of the attribute value is summarized in the production "ct- + value" in Figure 12, where "cardinal", "SP", and "DQUOTE" are defined + as in [RFC6690]. + + ct-value = cardinal + / DQUOTE cardinal *( 1*SP cardinal ) DQUOTE + + Figure 12 + +8. Multicast CoAP + + CoAP supports making requests to an IP multicast group. This is + defined by a series of deltas to unicast CoAP. A more general + discussion of group communication with CoAP is in [GROUPCOMM]. + + CoAP endpoints that offer services that they want other endpoints to + be able to find using multicast service discovery join one or more of + the appropriate all-CoAP-node multicast addresses (Section 12.8) and + listen on the default CoAP port. Note that an endpoint might receive + multicast requests on other multicast addresses, including the all- + nodes IPv6 address (or via broadcast on IPv4); an endpoint MUST + therefore be prepared to receive such messages but MAY ignore them if + multicast service discovery is not desired. + +8.1. Messaging Layer + + A multicast request is characterized by being transported in a CoAP + message that is addressed to an IP multicast address instead of a + CoAP endpoint. Such multicast requests MUST be Non-confirmable. + + A server SHOULD be aware that a request arrived via multicast, e.g., + by making use of modern APIs such as IPV6_RECVPKTINFO [RFC3542], if + available. + + To avoid an implosion of error responses, when a server is aware that + a request arrived via multicast, it MUST NOT return a Reset message + in reply to a Non-confirmable message. If it is not aware, it MAY + return a Reset message in reply to a Non-confirmable message as + usual. Because such a Reset message will look identical to one for a + + + + +Shelby, et al. Standards Track [Page 65] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + unicast message from the sender, the sender MUST avoid using a + Message ID that is also still active from this endpoint with any + unicast endpoint that might receive the multicast message. + + At the time of writing, multicast messages can only be carried in UDP + not in DTLS. This means that the security modes defined for CoAP in + this document are not applicable to multicast. + +8.2. Request/Response Layer + + When a server is aware that a request arrived via multicast, the + server MAY always ignore the request, in particular if it doesn't + have anything useful to respond (e.g., if it only has an empty + payload or an error response). The decision for this may depend on + the application. (For example, in query filtering as described in + [RFC6690], a server should not respond to a multicast request if the + filter does not match. More examples are in [GROUPCOMM].) + + If a server does decide to respond to a multicast request, it should + not respond immediately. Instead, it should pick a duration for the + period of time during which it intends to respond. For the purposes + of this exposition, we call the length of this period the Leisure. + The specific value of this Leisure may depend on the application or + MAY be derived as described below. The server SHOULD then pick a + random point of time within the chosen leisure period to send back + the unicast response to the multicast request. If further responses + need to be sent based on the same multicast address membership, a new + leisure period starts at the earliest after the previous one + finishes. + + To compute a value for Leisure, the server should have a group size + estimate G, a target data transfer rate R (which both should be + chosen conservatively), and an estimated response size S; a rough + lower bound for Leisure can then be computed as + + lb_Leisure = S * G / R + + For example, for a multicast request with link-local scope on a 2.4 + GHz IEEE 802.15.4 (6LoWPAN) network, G could be (relatively + conservatively) set to 100, S to 100 bytes, and the target rate to 8 + kbit/s = 1 kB/s. The resulting lower bound for the Leisure is 10 + seconds. + + If a CoAP endpoint does not have suitable data to compute a value for + Leisure, it MAY resort to DEFAULT_LEISURE. + + + + + + +Shelby, et al. Standards Track [Page 66] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + When matching a response to a multicast request, only the token MUST + match; the source endpoint of the response does not need to (and will + not) be the same as the destination endpoint of the original request. + + For the purposes of interpreting the Location-* options and any links + embedded in the representation, the request URI (i.e., the base URI + relative to which the response is interpreted) is formed by replacing + the multicast address in the Host component of the original request + URI by the literal IP address of the endpoint actually responding. + +8.2.1. Caching + + When a client makes a multicast request, it always makes a new + request to the multicast group (since there may be new group members + that joined meanwhile or ones that did not get the previous request). + It MAY update a cache with the received responses. Then, it uses + both cached-still-fresh and new responses as the result of the + request. + + A response received in reply to a GET request to a multicast group + MAY be used to satisfy a subsequent request on the related unicast + request URI. The unicast request URI is obtained by replacing the + authority part of the request URI with the transport-layer source + address of the response message. + + A cache MAY revalidate a response by making a GET request on the + related unicast request URI. + + A GET request to a multicast group MUST NOT contain an ETag option. + A mechanism to suppress responses the client already has is left for + further study. + +8.2.2. Proxying + + When a forward-proxy receives a request with a Proxy-Uri or URI + constructed from Proxy-Scheme that indicates a multicast address, the + proxy obtains a set of responses as described above and sends all + responses (both cached-still-fresh and new) back to the original + client. + + This specification does not provide a way to indicate the unicast- + modified request URI (base URI) in responses thus forwarded. + Proxying multicast requests is discussed in more detail in + [GROUPCOMM]; one proposal to address the base URI issue can be found + in Section 3 of [CoAP-MISC]. + + + + + + +Shelby, et al. Standards Track [Page 67] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +9. Securing CoAP + + This section defines the DTLS binding for CoAP. + + During the provisioning phase, a CoAP device is provided with the + security information that it needs, including keying materials and + access control lists. This specification defines provisioning for + the RawPublicKey mode in Section 9.1.3.2.1. At the end of the + provisioning phase, the device will be in one of four security modes + with the following information for the given mode. The NoSec and + RawPublicKey modes are mandatory to implement for this specification. + + NoSec: There is no protocol-level security (DTLS is disabled). + Alternative techniques to provide lower-layer security SHOULD be + used when appropriate. The use of IPsec is discussed in + [IPsec-CoAP]. Certain link layers in use with constrained nodes + also provide link-layer security, which may be appropriate with + proper key management. + + PreSharedKey: DTLS is enabled, there is a list of pre-shared keys + [RFC4279], and each key includes a list of which nodes it can be + used to communicate with as described in Section 9.1.3.1. At the + extreme, there may be one key for each node this CoAP node needs + to communicate with (1:1 node/key ratio). Conversely, if more + than two entities share a specific pre-shared key, this key only + enables the entities to authenticate as a member of that group and + not as a specific peer. + + RawPublicKey: DTLS is enabled and the device has an asymmetric key + pair without a certificate (a raw public key) that is validated + using an out-of-band mechanism [RFC7250] as described in + Section 9.1.3.2. The device also has an identity calculated from + the public key and a list of identities of the nodes it can + communicate with. + + Certificate: DTLS is enabled and the device has an asymmetric key + pair with an X.509 certificate [RFC5280] that binds it to its + subject and is signed by some common trust root as described in + Section 9.1.3.3. The device also has a list of root trust anchors + that can be used for validating a certificate. + + In the "NoSec" mode, the system simply sends the packets over normal + UDP over IP and is indicated by the "coap" scheme and the CoAP + default port. The system is secured only by keeping attackers from + being able to send or receive packets from the network with the CoAP + nodes; see Section 11.5 for an additional complication with this + approach. + + + + +Shelby, et al. Standards Track [Page 68] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The other three security modes are achieved using DTLS and are + indicated by the "coaps" scheme and DTLS-secured CoAP default port. + The result is a security association that can be used to authenticate + (within the limits of the security model) and, based on this + authentication, authorize the communication partner. CoAP itself + does not provide protocol primitives for authentication or + authorization; where this is required, it can either be provided by + communication security (i.e., IPsec or DTLS) or by object security + (within the payload). Devices that require authorization for certain + operations are expected to require one of these two forms of + security. Necessarily, where an intermediary is involved, + communication security only works when that intermediary is part of + the trust relationships. CoAP does not provide a way to forward + different levels of authorization that clients may have with an + intermediary to further intermediaries or origin servers -- it + therefore may be required to perform all authorization at the first + intermediary. + +9.1. DTLS-Secured CoAP + + Just as HTTP is secured using Transport Layer Security (TLS) over + TCP, CoAP is secured using Datagram TLS (DTLS) [RFC6347] over UDP + (see Figure 13). This section defines the CoAP binding to DTLS, + along with the minimal mandatory-to-implement configurations + appropriate for constrained environments. The binding is defined by + a series of deltas to unicast CoAP. In practice, DTLS is TLS with + added features to deal with the unreliable nature of the UDP + transport. + + +----------------------+ + | Application | + +----------------------+ + +----------------------+ + | Requests/Responses | + |----------------------| CoAP + | Messages | + +----------------------+ + +----------------------+ + | DTLS | + +----------------------+ + +----------------------+ + | UDP | + +----------------------+ + + Figure 13: Abstract Layering of DTLS-Secured CoAP + + + + + + +Shelby, et al. Standards Track [Page 69] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In some constrained nodes (limited flash and/or RAM) and networks + (limited bandwidth or high scalability requirements), and depending + on the specific cipher suites in use, all modes of DTLS may not be + applicable. Some DTLS cipher suites can add significant + implementation complexity as well as some initial handshake overhead + needed when setting up the security association. Once the initial + handshake is completed, DTLS adds a limited per-datagram overhead of + approximately 13 bytes, not including any initialization vectors/ + nonces (e.g., 8 bytes with TLS_PSK_WITH_AES_128_CCM_8 [RFC6655]), + integrity check values (e.g., 8 bytes with TLS_PSK_WITH_AES_128_CCM_8 + [RFC6655]), and padding required by the cipher suite. Whether the + use of a given mode of DTLS is applicable for a CoAP-based + application should be carefully weighed considering the specific + cipher suites that may be applicable, whether the session maintenance + makes it compatible with application flows, and whether sufficient + resources are available on the constrained nodes and for the added + network overhead. (For some modes of using DTLS, this specification + identifies a mandatory-to-implement cipher suite. This is an + implementation requirement to maximize interoperability in those + cases where these cipher suites are indeed appropriate. The specific + security policies of an application may determine the actual set of + cipher suites that can be used.) DTLS is not applicable to group + keying (multicast communication); however, it may be a component in a + future group key management protocol. + +9.1.1. Messaging Layer + + The endpoint acting as the CoAP client should also act as the DTLS + client. It should initiate a session to the server on the + appropriate port. When the DTLS handshake has finished, the client + may initiate the first CoAP request. All CoAP messages MUST be sent + as DTLS "application data". + + The following rules are added for matching an Acknowledgement message + or Reset message to a Confirmable message, or a Reset message to a + Non-confirmable message: The DTLS session MUST be the same, and the + epoch MUST be the same. + + A message is the same when it is sent within the same DTLS session + and same epoch and has the same Message ID. + + Note: When a Confirmable message is retransmitted, a new DTLS + sequence_number is used for each attempt, even though the CoAP + Message ID stays the same. So a recipient still has to perform + deduplication as described in Section 4.5. Retransmissions MUST NOT + be performed across epochs. + + + + + +Shelby, et al. Standards Track [Page 70] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + DTLS connections in RawPublicKey and Certificate mode are set up + using mutual authentication so they can remain up and be reused for + future message exchanges in either direction. Devices can close a + DTLS connection when they need to recover resources, but in general + they should keep the connection up for as long as possible. Closing + the DTLS connection after every CoAP message exchange is very + inefficient. + +9.1.2. Request/Response Layer + + The following rules are added for matching a response to a request: + The DTLS session MUST be the same, and the epoch MUST be the same. + + This means the response to a DTLS secured request MUST always be DTLS + secured using the same security session and epoch. Any attempt to + supply a NoSec response to a DTLS request simply does not match the + request and therefore MUST be rejected (unless it does match an + unrelated NoSec request). + +9.1.3. Endpoint Identity + + Devices SHOULD support the Server Name Indication (SNI) to indicate + their authority in the SNI HostName field as defined in Section 3 of + [RFC6066]. This is needed so that when a host that acts as a virtual + server for multiple Authorities receives a new DTLS connection, it + knows which keys to use for the DTLS session. + +9.1.3.1. Pre-Shared Keys + + When forming a connection to a new node, the system selects an + appropriate key based on which nodes it is trying to reach and then + forms a DTLS session using a PSK (Pre-Shared Key) mode of DTLS. + Implementations in these modes MUST support the mandatory-to- + implement cipher suite TLS_PSK_WITH_AES_128_CCM_8 as specified in + [RFC6655]. + + Depending on the commissioning model, applications may need to define + an application profile for identity hints (as required and detailed + in Section 5.2 of [RFC4279]) to enable the use of PSK identity hints. + + The security considerations of Section 7 of [RFC4279] apply. In + particular, applications should carefully weigh whether or not they + need Perfect Forward Secrecy (PFS) and select an appropriate cipher + suite (Section 7.1 of [RFC4279]). The entropy of the PSK must be + sufficient to mitigate against brute-force and (where the PSK is not + chosen randomly but by a human) dictionary attacks (Section 7.2 of + [RFC4279]). The cleartext communication of client identities may + leak data or compromise privacy (Section 7.3 of [RFC4279]). + + + +Shelby, et al. Standards Track [Page 71] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +9.1.3.2. Raw Public Key Certificates + + In this mode, the device has an asymmetric key pair but without an + X.509 certificate (called a raw public key); for example, the + asymmetric key pair is generated by the manufacturer and installed on + the device (see also Section 11.6). A device MAY be configured with + multiple raw public keys. The type and length of the raw public key + depends on the cipher suite used. Implementations in RawPublicKey + mode MUST support the mandatory-to-implement cipher suite + TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 as specified in [RFC7251], + [RFC5246], and [RFC4492]. The key used MUST be ECDSA capable. The + curve secp256r1 MUST be supported [RFC4492]; this curve is equivalent + to the NIST P-256 curve. The hash algorithm is SHA-256. + Implementations MUST use the Supported Elliptic Curves and Supported + Point Formats Extensions [RFC4492]; the uncompressed point format + MUST be supported; [RFC6090] can be used as an implementation method. + Some guidance relevant to the implementation of this cipher suite can + be found in [W3CXMLSEC]. The mechanism for using raw public keys + with TLS is specified in [RFC7250]. + + Implementation Note: Specifically, this means the extensions listed + in Figure 14 with at least the values listed will be present in + the DTLS handshake. + + Extension: elliptic_curves + Type: elliptic_curves (0x000a) + Length: 4 + Elliptic Curves Length: 2 + Elliptic curves (1 curve) + Elliptic curve: secp256r1 (0x0017) + + Extension: ec_point_formats + Type: ec_point_formats (0x000b) + Length: 2 + EC point formats Length: 1 + Elliptic curves point formats (1) + EC point format: uncompressed (0) + + Extension: signature_algorithms + Type: signature_algorithms (0x000d) + Length: 4 + Data (4 bytes): 00 02 04 03 + HashAlgorithm: sha256 (4) + SignatureAlgorithm: ecdsa (3) + + Figure 14: DTLS Extensions Present for + TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 + + + + +Shelby, et al. Standards Track [Page 72] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +9.1.3.2.1. Provisioning + + The RawPublicKey mode was designed to be easily provisioned in M2M + deployments. It is assumed that each device has an appropriate + asymmetric public key pair installed. An identifier is calculated by + the endpoint from the public key as described in Section 2 of + [RFC6920]. All implementations that support checking RawPublicKey + identities MUST support at least the sha-256-120 mode (SHA-256 + truncated to 120 bits). Implementations SHOULD also support longer + length identifiers and MAY support shorter lengths. Note that the + shorter lengths provide less security against attacks, and their use + is NOT RECOMMENDED. + + Depending on how identifiers are given to the system that verifies + them, support for URI, binary, and/or human-speakable format + [RFC6920] needs to be implemented. All implementations SHOULD + support the binary mode, and implementations that have a user + interface SHOULD also support the human-speakable format. + + During provisioning, the identifier of each node is collected, for + example, by reading a barcode on the outside of the device or by + obtaining a pre-compiled list of the identifiers. These identifiers + are then installed in the corresponding endpoint, for example, an M2M + data collection server. The identifier is used for two purposes, to + associate the endpoint with further device information and to perform + access control. During (initial and ongoing) provisioning, an access + control list of identifiers with which the device may start DTLS + sessions SHOULD also be installed and maintained. + +9.1.3.3. X.509 Certificates + + Implementations in Certificate Mode MUST support the mandatory-to- + implement cipher suite TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 as + specified in [RFC7251], [RFC5246], and [RFC4492]. Namely, the + certificate includes a SubjectPublicKeyInfo that indicates an + algorithm of id-ecPublicKey with namedCurves secp256r1 [RFC5480]; the + public key format is uncompressed [RFC5480]; the hash algorithm is + SHA-256; if included, the key usage extension indicates + digitalSignature. Certificates MUST be signed with ECDSA using + secp256r1, and the signature MUST use SHA-256. The key used MUST be + ECDSA capable. The curve secp256r1 MUST be supported [RFC4492]; this + curve is equivalent to the NIST P-256 curve. The hash algorithm is + SHA-256. Implementations MUST use the Supported Elliptic Curves and + Supported Point Formats Extensions [RFC4492]; the uncompressed point + format MUST be supported; [RFC6090] can be used as an implementation + method. + + + + + +Shelby, et al. Standards Track [Page 73] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The subject in the certificate would be built out of a long-term + unique identifier for the device such as the EUI-64 [EUI64]. The + subject could also be based on the Fully Qualified Domain Name (FQDN) + that was used as the Host part of the CoAP URI. However, the + device's IP address should not typically be used as the subject, as + it would change over time. The discovery process used in the system + would build up the mapping between IP addresses of the given devices + and the subject for each device. Some devices could have more than + one subject and would need more than a single certificate. + + When a new connection is formed, the certificate from the remote + device needs to be verified. If the CoAP node has a source of + absolute time, then the node SHOULD check that the validity dates of + the certificate are within range. The certificate MUST be validated + as appropriate for the security requirements, using functionality + equivalent to the algorithm specified in Section 6 of [RFC5280]. If + the certificate contains a SubjectAltName, then the authority of the + request URI MUST match at least one of the authorities of any CoAP + URI found in a field of URI type in the SubjectAltName set. If there + is no SubjectAltName in the certificate, then the authority of the + request URI MUST match the Common Name (CN) found in the certificate + using the matching rules defined in [RFC3280] with the exception that + certificates with wildcards are not allowed. + + CoRE support for certificate status checking requires further study. + As a mapping of the Online Certificate Status Protocol (OCSP) + [RFC6960] onto CoAP is not currently defined and OCSP may also not be + easily applicable in all environments, an alternative approach may be + using the TLS Certificate Status Request extension (Section 8 of + [RFC6066]; also known as "OCSP stapling") or preferably the Multiple + Certificate Status Extension ([RFC6961]), if available. + + If the system has a shared key in addition to the certificate, then a + cipher suite that includes the shared key such as + TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA [RFC5489] SHOULD be used. + +10. Cross-Protocol Proxying between CoAP and HTTP + + CoAP supports a limited subset of HTTP functionality, and thus cross- + protocol proxying to HTTP is straightforward. There might be several + reasons for proxying between CoAP and HTTP, for example, when + designing a web interface for use over either protocol or when + realizing a CoAP-HTTP proxy. Likewise, CoAP could equally be proxied + to other protocols such as XMPP [RFC6120] or SIP [RFC3264]; the + definition of these mechanisms is out of scope for this + specification. + + + + + +Shelby, et al. Standards Track [Page 74] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + There are two possible directions to access a resource via a forward- + proxy: + + CoAP-HTTP Proxying: Enables CoAP clients to access resources on HTTP + servers through an intermediary. This is initiated by including + the Proxy-Uri or Proxy-Scheme Option with an "http" or "https" URI + in a CoAP request to a CoAP-HTTP proxy. + + HTTP-CoAP Proxying: Enables HTTP clients to access resources on CoAP + servers through an intermediary. This is initiated by specifying + a "coap" or "coaps" URI in the Request-Line of an HTTP request to + an HTTP-CoAP proxy. + + Either way, only the request/response model of CoAP is mapped to + HTTP. The underlying model of Confirmable or Non-confirmable + messages, etc., is invisible and MUST have no effect on a proxy + function. The following sections describe the handling of requests + to a forward-proxy. Reverse-proxies are not specified, as the proxy + function is transparent to the client with the proxy acting as if it + were the origin server. However, similar considerations apply to + reverse-proxies as to forward-proxies, and there generally will be an + expectation that reverse-proxies operate in a similar way forward- + proxies would. As an implementation note, HTTP client libraries may + make it hard to operate an HTTP-CoAP forward-proxy by not providing a + way to put a CoAP URI on the HTTP Request-Line; reverse-proxying may + therefore lead to wider applicability of a proxy. A separate + specification may define a convention for URIs operating such an + HTTP-CoAP reverse-proxy [MAPPING]. + +10.1. CoAP-HTTP Proxying + + If a request contains a Proxy-Uri or Proxy-Scheme Option with an + 'http' or 'https' URI [RFC2616], then the receiving CoAP endpoint + (called "the proxy" henceforth) is requested to perform the operation + specified by the request method on the indicated HTTP resource and + return the result to the client. (See also Section 5.7 for how the + request to the proxy is formulated, including security requirements.) + + This section specifies for any CoAP request the CoAP response that + the proxy should return to the client. How the proxy actually + satisfies the request is an implementation detail, although the + typical case is expected to be that the proxy translates and forwards + the request to an HTTP origin server. + + + + + + + + +Shelby, et al. Standards Track [Page 75] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Since HTTP and CoAP share the basic set of request methods, + performing a CoAP request on an HTTP resource is not so different + from performing it on a CoAP resource. The meanings of the + individual CoAP methods when performed on HTTP resources are + explained in the subsections of this section. + + If the proxy is unable or unwilling to service a request with an HTTP + URI, a 5.05 (Proxying Not Supported) response is returned to the + client. If the proxy services the request by interacting with a + third party (such as the HTTP origin server) and is unable to obtain + a result within a reasonable time frame, a 5.04 (Gateway Timeout) + response is returned; if a result can be obtained but is not + understood, a 5.02 (Bad Gateway) response is returned. + +10.1.1. GET + + The GET method requests the proxy to return a representation of the + HTTP resource identified by the request URI. + + Upon success, a 2.05 (Content) Response Code SHOULD be returned. The + payload of the response MUST be a representation of the target HTTP + resource, and the Content-Format Option MUST be set accordingly. The + response MUST indicate a Max-Age value that is no greater than the + remaining time the representation can be considered fresh. If the + HTTP entity has an entity-tag, the proxy SHOULD include an ETag + Option in the response and process ETag Options in requests as + described below. + + A client can influence the processing of a GET request by including + the following option: + + Accept: The request MAY include an Accept Option, identifying the + preferred response content-format. + + ETag: The request MAY include one or more ETag Options, identifying + responses that the client has stored. This requests the proxy to + send a 2.03 (Valid) response whenever it would send a 2.05 + (Content) response with an entity-tag in the requested set + otherwise. Note that CoAP ETags are always strong ETags in the + HTTP sense; CoAP does not have the equivalent of HTTP weak ETags, + and there is no good way to make use of these in a cross-proxy. + + + + + + + + + + +Shelby, et al. Standards Track [Page 76] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +10.1.2. PUT + + The PUT method requests the proxy to update or create the HTTP + resource identified by the request URI with the enclosed + representation. + + If a new resource is created at the request URI, a 2.01 (Created) + response MUST be returned to the client. If an existing resource is + modified, a 2.04 (Changed) response MUST be returned to indicate + successful completion of the request. + +10.1.3. DELETE + + The DELETE method requests the proxy to delete the HTTP resource + identified by the request URI at the HTTP origin server. + + A 2.02 (Deleted) response MUST be returned to the client upon success + or if the resource does not exist at the time of the request. + +10.1.4. POST + + The POST method requests the proxy to have the representation + enclosed in the request be processed by the HTTP origin server. The + actual function performed by the POST method is determined by the + origin server and dependent on the resource identified by the request + URI. + + If the action performed by the POST method does not result in a + resource that can be identified by a URI, a 2.04 (Changed) response + MUST be returned to the client. If a resource has been created on + the origin server, a 2.01 (Created) response MUST be returned. + +10.2. HTTP-CoAP Proxying + + If an HTTP request contains a Request-URI with a "coap" or "coaps" + URI, then the receiving HTTP endpoint (called "the proxy" henceforth) + is requested to perform the operation specified by the request method + on the indicated CoAP resource and return the result to the client. + + This section specifies for any HTTP request the HTTP response that + the proxy should return to the client. Unless otherwise specified, + all the statements made are RECOMMENDED behavior; some highly + constrained implementations may need to resort to shortcuts. How the + proxy actually satisfies the request is an implementation detail, + although the typical case is expected to be that the proxy translates + and forwards the request to a CoAP origin server. The meanings of + the individual HTTP methods when performed on CoAP resources are + explained in the subsections of this section. + + + +Shelby, et al. Standards Track [Page 77] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + If the proxy is unable or unwilling to service a request with a CoAP + URI, a 501 (Not Implemented) response is returned to the client. If + the proxy services the request by interacting with a third party + (such as the CoAP origin server) and is unable to obtain a result + within a reasonable time frame, a 504 (Gateway Timeout) response is + returned; if a result can be obtained but is not understood, a 502 + (Bad Gateway) response is returned. + +10.2.1. OPTIONS and TRACE + + As the OPTIONS and TRACE methods are not supported in CoAP, a 501 + (Not Implemented) error MUST be returned to the client. + +10.2.2. GET + + The GET method requests the proxy to return a representation of the + CoAP resource identified by the Request-URI. + + Upon success, a 200 (OK) response is returned. The payload of the + response MUST be a representation of the target CoAP resource, and + the Content-Type and Content-Encoding header fields MUST be set + accordingly. The response MUST indicate a max-age directive that + indicates a value no greater than the remaining time the + representation can be considered fresh. If the CoAP response has an + ETag option, the proxy should include an ETag header field in the + response. + + A client can influence the processing of a GET request by including + the following options: + + Accept: The most-preferred media type of the HTTP Accept header + field in a request is mapped to a CoAP Accept option. HTTP Accept + media-type ranges, parameters, and extensions are not supported by + the CoAP Accept option. If the proxy cannot send a response that + is acceptable according to the combined Accept field value, then + the proxy sends a 406 (Not Acceptable) response. The proxy MAY + then retry the request with further media types from the HTTP + Accept header field. + + Conditional GETs: Conditional HTTP GET requests that include an "If- + Match" or "If-None-Match" request-header field can be mapped to a + corresponding CoAP request. The "If-Modified-Since" and "If- + Unmodified-Since" request-header fields are not directly supported + by CoAP but are implemented locally by a caching proxy. + + + + + + + +Shelby, et al. Standards Track [Page 78] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +10.2.3. HEAD + + The HEAD method is identical to GET except that the server MUST NOT + return a message-body in the response. + + Although there is no direct equivalent of HTTP's HEAD method in CoAP, + an HTTP-CoAP proxy responds to HEAD requests for CoAP resources, and + the HTTP headers are returned without a message-body. + + Implementation Note: An HTTP-CoAP proxy may want to try using a + block-wise transfer option [BLOCK] to minimize the amount of data + actually transferred, but it needs to be prepared for the case + that the origin server does not support block-wise transfers. + +10.2.4. POST + + The POST method requests the proxy to have the representation + enclosed in the request be processed by the CoAP origin server. The + actual function performed by the POST method is determined by the + origin server and dependent on the resource identified by the request + URI. + + If the action performed by the POST method does not result in a + resource that can be identified by a URI, a 200 (OK) or 204 (No + Content) response MUST be returned to the client. If a resource has + been created on the origin server, a 201 (Created) response MUST be + returned. + + If any of the Location-* Options are present in the CoAP response, a + Location header field constructed from the values of these options is + returned. + +10.2.5. PUT + + The PUT method requests the proxy to update or create the CoAP + resource identified by the Request-URI with the enclosed + representation. + + If a new resource is created at the Request-URI, a 201 (Created) + response is returned to the client. If an existing resource is + modified, either the 200 (OK) or 204 (No Content) Response Codes is + sent to indicate successful completion of the request. + + + + + + + + + +Shelby, et al. Standards Track [Page 79] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +10.2.6. DELETE + + The DELETE method requests the proxy to delete the CoAP resource + identified by the Request-URI at the CoAP origin server. + + A successful response is 200 (OK) if the response includes an entity + describing the status or 204 (No Content) if the action has been + enacted but the response does not include an entity. + +10.2.7. CONNECT + + This method cannot currently be satisfied by an HTTP-CoAP proxy + function, as TLS to DTLS tunneling has not yet been specified. For + now, a 501 (Not Implemented) error is returned to the client. + +11. Security Considerations + + This section analyzes the possible threats to the protocol. It is + meant to inform protocol and application developers about the + security limitations of CoAP as described in this document. As CoAP + realizes a subset of the features in HTTP/1.1, the security + considerations in Section 15 of [RFC2616] are also pertinent to CoAP. + This section concentrates on describing limitations specific to CoAP. + +11.1. Parsing the Protocol and Processing URIs + + A network-facing application can exhibit vulnerabilities in its + processing logic for incoming packets. Complex parsers are well- + known as a likely source of such vulnerabilities, such as the ability + to remotely crash a node, or even remotely execute arbitrary code on + it. CoAP attempts to narrow the opportunities for introducing such + vulnerabilities by reducing parser complexity, by giving the entire + range of encodable values a meaning where possible, and by + aggressively reducing complexity that is often caused by unnecessary + choice between multiple representations that mean the same thing. + Much of the URI processing has been moved to the clients, further + reducing the opportunities for introducing vulnerabilities into the + servers. Even so, the URI processing code in CoAP implementations is + likely to be a large source of remaining vulnerabilities and should + be implemented with special care. CoAP access control + implementations need to ensure they don't introduce vulnerabilities + through discrepancies between the code deriving access control + decisions from a URI and the code finally serving up the resource + addressed by the URI. The most complex parser remaining could be the + one for the CoRE Link Format, although this also has been designed + with a goal of reduced implementation complexity [RFC6690]. (See + also Section 15.2 of [RFC2616].) + + + + +Shelby, et al. Standards Track [Page 80] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +11.2. Proxying and Caching + + As mentioned in Section 15.7 of [RFC2616], proxies are by their very + nature men-in-the-middle, breaking any IPsec or DTLS protection that + a direct CoAP message exchange might have. They are therefore + interesting targets for breaking confidentiality or integrity of CoAP + message exchanges. As noted in [RFC2616], they are also interesting + targets for breaking availability. + + The threat to confidentiality and integrity of request/response data + is amplified where proxies also cache. Note that CoAP does not + define any of the cache-suppressing Cache-Control options that + HTTP/1.1 provides to better protect sensitive data. + + For a caching implementation, any access control considerations that + would apply to making the request that generated the cache entry also + need to be applied to the value in the cache. This is relevant for + clients that implement multiple security domains, as well as for + proxies that may serve multiple clients. Also, a caching proxy MUST + NOT make cached values available to requests that have lesser + transport-security properties than those the proxy would require to + perform request forwarding in the first place. + + Unlike the "coap" scheme, responses to "coaps" identified requests + are never "public" and thus MUST NOT be reused for shared caching, + unless the cache is able to make equivalent access control decisions + to the ones that led to the cached entry. They can, however, be + reused in a private cache if the message is cacheable by default in + CoAP. + + Finally, a proxy that fans out Separate Responses (as opposed to + piggybacked Responses) to multiple original requesters may provide + additional amplification (see Section 11.3). + +11.3. Risk of Amplification + + CoAP servers generally reply to a request packet with a response + packet. This response packet may be significantly larger than the + request packet. An attacker might use CoAP nodes to turn a small + attack packet into a larger attack packet, an approach known as + amplification. There is therefore a danger that CoAP nodes could + become implicated in denial-of-service (DoS) attacks by using the + amplifying properties of the protocol: an attacker that is attempting + to overload a victim but is limited in the amount of traffic it can + generate can use amplification to generate a larger amount of + traffic. + + + + + +Shelby, et al. Standards Track [Page 81] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + This is particularly a problem in nodes that enable NoSec access, are + accessible from an attacker, and can access potential victims (e.g., + on the general Internet), as the UDP protocol provides no way to + verify the source address given in the request packet. An attacker + need only place the IP address of the victim in the source address of + a suitable request packet to generate a larger packet directed at the + victim. + + As a mitigating factor, many constrained networks will only be able + to generate a small amount of traffic, which may make CoAP nodes less + attractive for this attack. However, the limited capacity of the + constrained network makes the network itself a likely victim of an + amplification attack. + + Therefore, large amplification factors SHOULD NOT be provided in the + response if the request is not authenticated. A CoAP server can + reduce the amount of amplification it provides to an attacker by + using slicing/blocking modes of CoAP [BLOCK] and offering large + resource representations only in relatively small slices. For + example, for a 1000-byte resource, a 10-byte request might result in + an 80-byte response (with a 64-byte block) instead of a 1016-byte + response, considerably reducing the amplification provided. + + CoAP also supports the use of multicast IP addresses in requests, an + important requirement for M2M. Multicast CoAP requests may be the + source of accidental or deliberate DoS attacks, especially over + constrained networks. This specification attempts to reduce the + amplification effects of multicast requests by limiting when a + response is returned. To limit the possibility of malicious use, + CoAP servers SHOULD NOT accept multicast requests that can not be + authenticated in some way, cryptographically or by some multicast + boundary limiting the potential sources. If possible, a CoAP server + SHOULD limit the support for multicast requests to the specific + resources where the feature is required. + + On some general-purpose operating systems providing a POSIX-style API + [IEEE1003.1], it is not straightforward to find out whether a packet + received was addressed to a multicast address. While many + implementations will know whether they have joined a multicast group, + this creates a problem for packets addressed to multicast addresses + of the form FF0x::1, which are received by every IPv6 node. + Implementations SHOULD make use of modern APIs such as + IPV6_RECVPKTINFO [RFC3542], if available, to make this determination. + + + + + + + + +Shelby, et al. Standards Track [Page 82] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +11.4. IP Address Spoofing Attacks + + Due to the lack of a handshake in UDP, a rogue endpoint that is free + to read and write messages carried by the constrained network (i.e., + NoSec or PreSharedKey deployments with a nodes/key ratio > 1:1), may + easily attack a single endpoint, a group of endpoints, as well as the + whole network, e.g., by: + + 1. spoofing a Reset message in response to a Confirmable message or + Non-confirmable message, thus making an endpoint "deaf"; or + + 2. spoofing an ACK in response to a CON message, thus potentially + preventing the sender of the CON message from retransmitting, and + drowning out the actual response; or + + 3. spoofing the entire response with forged payload/options (this + has different levels of impact: from single-response disruption, + to much bolder attacks on the supporting infrastructure, e.g., + poisoning proxy caches, or tricking validation/lookup interfaces + in resource directories and, more generally, any component that + stores global network state and uses CoAP as the messaging + facility to handle setting or updating state is a potential + target.); or + + 4. spoofing a multicast request for a target node; this may result + in network congestion/collapse, a DoS attack on the victim, or + forced wake-up from sleeping; or + + 5. spoofing observe messages, etc. + + Response spoofing by off-path attackers can be detected and mitigated + even without transport layer security by choosing a nontrivial, + randomized token in the request (Section 5.3.1). [RFC4086] discusses + randomness requirements for security. + + In principle, other kinds of spoofing can be detected by CoAP only in + case Confirmable message semantics is used, because of unexpected + Acknowledgement or Reset messages coming from the deceived endpoint. + But this imposes keeping track of the used Message IDs, which is not + always possible, and moreover detection becomes available usually + after the damage is already done. This kind of attack can be + prevented using security modes other than NoSec. + + With or without source address spoofing, a client can attempt to + overload a server by sending requests, preferably complex ones, to a + server; address spoofing makes tracing back, and blocking, this + attack harder. Given that the cost of a CON request is small, this + attack can easily be executed. Under this attack, a constrained node + + + +Shelby, et al. Standards Track [Page 83] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + with limited total energy available may exhaust that energy much more + quickly than planned (battery depletion attack). Also, if the client + uses a Confirmable message and the server responds with a Confirmable + separate response to a (possibly spoofed) address that does not + respond, the server will have to allocate buffer and retransmission + logic for each response up to the exhaustion of MAX_TRANSMIT_SPAN, + making it more likely that it runs out of resources for processing + legitimate traffic. The latter problem can be mitigated somewhat by + limiting the rate of responses as discussed in Section 4.7. An + attacker could also spoof the address of a legitimate client; this + might cause the server, if it uses separate responses, to block + legitimate responses to that client because of NSTART=1. All these + attacks can be prevented using a security mode other than NoSec, thus + leaving only attacks on the security protocol. + +11.5. Cross-Protocol Attacks + + The ability to incite a CoAP endpoint to send packets to a fake + source address can be used not only for amplification, but also for + cross-protocol attacks against a victim listening to UDP packets at a + given address (IP address and port). This would occur as follows: + + o The attacker sends a message to a CoAP endpoint with the given + address as the fake source address. + + o The CoAP endpoint replies with a message to the given source + address. + + o The victim at the given address receives a UDP packet that it + interprets according to the rules of a different protocol. + + This may be used to circumvent firewall rules that prevent direct + communication from the attacker to the victim but happen to allow + communication from the CoAP endpoint (which may also host a valid + role in the other protocol) to the victim. + + Also, CoAP endpoints may be the victim of a cross-protocol attack + generated through an endpoint of another UDP-based protocol such as + DNS. In both cases, attacks are possible if the security properties + of the endpoints rely on checking IP addresses (and firewalling off + direct attacks sent from outside using fake IP addresses). In + general, because of their lack of context, UDP-based protocols are + relatively easy targets for cross-protocol attacks. + + Finally, CoAP URIs transported by other means could be used to incite + clients to send messages to endpoints of other protocols. + + + + + +Shelby, et al. Standards Track [Page 84] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + One mitigation against cross-protocol attacks is strict checking of + the syntax of packets received, combined with sufficient difference + in syntax. As an example, it might help if it were difficult to + incite a DNS server to send a DNS response that would pass the checks + of a CoAP endpoint. Unfortunately, the first two bytes of a DNS + reply are an ID that can be chosen by the attacker and that map into + the interesting part of the CoAP header, and the next two bytes are + then interpreted as CoAP's Message ID (i.e., any value is + acceptable). The DNS count words may be interpreted as multiple + instances of a (nonexistent but elective) CoAP option 0, or possibly + as a Token. The echoed query finally may be manufactured by the + attacker to achieve a desired effect on the CoAP endpoint; the + response added by the server (if any) might then just be interpreted + as added payload. + + 1 1 1 1 1 1 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ID | T, TKL, code + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + |QR| Opcode |AA|TC|RD|RA| Z | RCODE | Message ID + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | QDCOUNT | (options 0) + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ANCOUNT | (options 0) + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | NSCOUNT | (options 0) + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ARCOUNT | (options 0) + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + + Figure 15: DNS Header ([RFC1035], Section 4.1.1) vs. CoAP Message + + In general, for any pair of protocols, one of the protocols can very + well have been designed in a way that enables an attacker to cause + the generation of replies that look like messages of the other + protocol. It is often much harder to ensure or prove the absence of + viable attacks than to generate examples that may not yet completely + enable an attack but might be further developed by more creative + minds. Cross-protocol attacks can therefore only be completely + mitigated if endpoints don't authorize actions desired by an attacker + just based on trusting the source IP address of a packet. + Conversely, a NoSec environment that completely relies on a firewall + for CoAP security not only needs to firewall off the CoAP endpoints + but also all other endpoints that might be incited to send UDP + messages to CoAP endpoints using some other UDP-based protocol. + + + + + +Shelby, et al. Standards Track [Page 85] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In addition to the considerations above, the security considerations + for DTLS with respect to cross-protocol attacks apply. For example, + if the same DTLS security association ("connection") is used to carry + data of multiple protocols, DTLS no longer provides protection + against cross-protocol attacks between these protocols. + +11.6. Constrained-Node Considerations + + Implementers on constrained nodes often find themselves without a + good source of entropy [RFC4086]. If that is the case, the node MUST + NOT be used for processes that require good entropy, such as key + generation. Instead, keys should be generated externally and added + to the device during manufacturing or commissioning. + + Due to their low processing power, constrained nodes are particularly + susceptible to timing attacks. Special care must be taken in + implementation of cryptographic primitives. + + Large numbers of constrained nodes will be installed in exposed + environments and will have little resistance to tampering, including + recovery of keying materials. This needs to be considered when + defining the scope of credentials assigned to them. In particular, + assigning a shared key to a group of nodes may make any single + constrained node a target for subverting the entire group. + +12. IANA Considerations + +12.1. CoAP Code Registries + + This document defines two sub-registries for the values of the Code + field in the CoAP header within the "Constrained RESTful Environments + (CoRE) Parameters" registry, hereafter referred to as the "CoRE + Parameters" registry. + + Values in the two sub-registries are eight-bit values notated as + three decimal digits c.dd separated by a period between the first and + the second digit; the first digit c is between 0 and 7 and denotes + the code class; the second and third digits dd denote a decimal + number between 00 and 31 for the detail. + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 86] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + All Code values are assigned by sub-registries according to the + following ranges: + + 0.00 Indicates an Empty message (see Section 4.1). + + 0.01-0.31 Indicates a request. Values in this range are assigned by + the "CoAP Method Codes" sub-registry (see Section 12.1.1). + + 1.00-1.31 Reserved + + 2.00-5.31 Indicates a response. Values in this range are assigned by + the "CoAP Response Codes" sub-registry (see + Section 12.1.2). + + 6.00-7.31 Reserved + +12.1.1. Method Codes + + The name of the sub-registry is "CoAP Method Codes". + + Each entry in the sub-registry must include the Method Code in the + range 0.01-0.31, the name of the method, and a reference to the + method's documentation. + + Initial entries in this sub-registry are as follows: + + +------+--------+-----------+ + | Code | Name | Reference | + +------+--------+-----------+ + | 0.01 | GET | [RFC7252] | + | 0.02 | POST | [RFC7252] | + | 0.03 | PUT | [RFC7252] | + | 0.04 | DELETE | [RFC7252] | + +------+--------+-----------+ + + Table 5: CoAP Method Codes + + All other Method Codes are Unassigned. + + The IANA policy for future additions to this sub-registry is "IETF + Review or IESG Approval" as described in [RFC5226]. + + The documentation of a Method Code should specify the semantics of a + request with that code, including the following properties: + + o The Response Codes the method returns in the success case. + + o Whether the method is idempotent, safe, or both. + + + +Shelby, et al. Standards Track [Page 87] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +12.1.2. Response Codes + + The name of the sub-registry is "CoAP Response Codes". + + Each entry in the sub-registry must include the Response Code in the + range 2.00-5.31, a description of the Response Code, and a reference + to the Response Code's documentation. + + Initial entries in this sub-registry are as follows: + + +------+------------------------------+-----------+ + | Code | Description | Reference | + +------+------------------------------+-----------+ + | 2.01 | Created | [RFC7252] | + | 2.02 | Deleted | [RFC7252] | + | 2.03 | Valid | [RFC7252] | + | 2.04 | Changed | [RFC7252] | + | 2.05 | Content | [RFC7252] | + | 4.00 | Bad Request | [RFC7252] | + | 4.01 | Unauthorized | [RFC7252] | + | 4.02 | Bad Option | [RFC7252] | + | 4.03 | Forbidden | [RFC7252] | + | 4.04 | Not Found | [RFC7252] | + | 4.05 | Method Not Allowed | [RFC7252] | + | 4.06 | Not Acceptable | [RFC7252] | + | 4.12 | Precondition Failed | [RFC7252] | + | 4.13 | Request Entity Too Large | [RFC7252] | + | 4.15 | Unsupported Content-Format | [RFC7252] | + | 5.00 | Internal Server Error | [RFC7252] | + | 5.01 | Not Implemented | [RFC7252] | + | 5.02 | Bad Gateway | [RFC7252] | + | 5.03 | Service Unavailable | [RFC7252] | + | 5.04 | Gateway Timeout | [RFC7252] | + | 5.05 | Proxying Not Supported | [RFC7252] | + +------+------------------------------+-----------+ + + Table 6: CoAP Response Codes + + The Response Codes 3.00-3.31 are Reserved for future use. All other + Response Codes are Unassigned. + + The IANA policy for future additions to this sub-registry is "IETF + Review or IESG Approval" as described in [RFC5226]. + + + + + + + + +Shelby, et al. Standards Track [Page 88] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + The documentation of a Response Code should specify the semantics of + a response with that code, including the following properties: + + o The methods the Response Code applies to. + + o Whether payload is required, optional, or not allowed. + + o The semantics of the payload. For example, the payload of a 2.05 + (Content) response is a representation of the target resource; the + payload in an error response is a human-readable diagnostic + payload. + + o The format of the payload. For example, the format in a 2.05 + (Content) response is indicated by the Content-Format Option; the + format of the payload in an error response is always Net-Unicode + text. + + o Whether the response is cacheable according to the freshness + model. + + o Whether the response is validatable according to the validation + model. + + o Whether the response causes a cache to mark responses stored for + the request URI as not fresh. + +12.2. CoAP Option Numbers Registry + + This document defines a sub-registry for the Option Numbers used in + CoAP options within the "CoRE Parameters" registry. The name of the + sub-registry is "CoAP Option Numbers". + + Each entry in the sub-registry must include the Option Number, the + name of the option, and a reference to the option's documentation. + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 89] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Initial entries in this sub-registry are as follows: + + +--------+------------------+-----------+ + | Number | Name | Reference | + +--------+------------------+-----------+ + | 0 | (Reserved) | [RFC7252] | + | 1 | If-Match | [RFC7252] | + | 3 | Uri-Host | [RFC7252] | + | 4 | ETag | [RFC7252] | + | 5 | If-None-Match | [RFC7252] | + | 7 | Uri-Port | [RFC7252] | + | 8 | Location-Path | [RFC7252] | + | 11 | Uri-Path | [RFC7252] | + | 12 | Content-Format | [RFC7252] | + | 14 | Max-Age | [RFC7252] | + | 15 | Uri-Query | [RFC7252] | + | 17 | Accept | [RFC7252] | + | 20 | Location-Query | [RFC7252] | + | 35 | Proxy-Uri | [RFC7252] | + | 39 | Proxy-Scheme | [RFC7252] | + | 60 | Size1 | [RFC7252] | + | 128 | (Reserved) | [RFC7252] | + | 132 | (Reserved) | [RFC7252] | + | 136 | (Reserved) | [RFC7252] | + | 140 | (Reserved) | [RFC7252] | + +--------+------------------+-----------+ + + Table 7: CoAP Option Numbers + + The IANA policy for future additions to this sub-registry is split + into three tiers as follows. The range of 0..255 is reserved for + options defined by the IETF (IETF Review or IESG Approval). The + range of 256..2047 is reserved for commonly used options with public + specifications (Specification Required). The range of 2048..64999 is + for all other options including private or vendor-specific ones, + which undergo a Designated Expert review to help ensure that the + option semantics are defined correctly. The option numbers between + 65000 and 65535 inclusive are reserved for experiments. They are not + meant for vendor-specific use of any kind and MUST NOT be used in + operational deployments. + + + + + + + + + + + +Shelby, et al. Standards Track [Page 90] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + +-------------+---------------------------------------+ + | Range | Registration Procedures | + +-------------+---------------------------------------+ + | 0-255 | IETF Review or IESG Approval | + | 256-2047 | Specification Required | + | 2048-64999 | Expert Review | + | 65000-65535 | Experimental use (no operational use) | + +-------------+---------------------------------------+ + + Table 8: CoAP Option Numbers: Registration Procedures + + The documentation of an Option Number should specify the semantics of + an option with that number, including the following properties: + + o The meaning of the option in a request. + + o The meaning of the option in a response. + + o Whether the option is critical or elective, as determined by the + Option Number. + + o Whether the option is Safe-to-Forward, and, if yes, whether it is + part of the Cache-Key, as determined by the Option Number (see + Section 5.4.2). + + o The format and length of the option's value. + + o Whether the option must occur at most once or whether it can occur + multiple times. + + o The default value, if any. For a critical option with a default + value, a discussion on how the default value enables processing by + implementations that do not support the critical option + (Section 5.4.4). + +12.3. CoAP Content-Formats Registry + + Internet media types are identified by a string, such as + "application/xml" [RFC2046]. In order to minimize the overhead of + using these media types to indicate the format of payloads, this + document defines a sub-registry for a subset of Internet media types + to be used in CoAP and assigns each, in combination with a content- + coding, a numeric identifier. The name of the sub-registry is "CoAP + Content-Formats", within the "CoRE Parameters" registry. + + + + + + + +Shelby, et al. Standards Track [Page 91] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Each entry in the sub-registry must include the media type registered + with IANA, the numeric identifier in the range 0-65535 to be used for + that media type in CoAP, the content-coding associated with this + identifier, and a reference to a document describing what a payload + with that media type means semantically. + + CoAP does not include a separate way to convey content-encoding + information with a request or response, and for that reason the + content-encoding is also specified for each identifier (if any). If + multiple content-encodings will be used with a media type, then a + separate Content-Format identifier for each is to be registered. + Similarly, other parameters related to an Internet media type, such + as level, can be defined for a CoAP Content-Format entry. + + Initial entries in this sub-registry are as follows: + + +--------------------------+----------+----+------------------------+ + | Media type | Encoding | ID | Reference | + +--------------------------+----------+----+------------------------+ + | text/plain; | - | 0 | [RFC2046] [RFC3676] | + | charset=utf-8 | | | [RFC5147] | + | application/link-format | - | 40 | [RFC6690] | + | application/xml | - | 41 | [RFC3023] | + | application/octet-stream | - | 42 | [RFC2045] [RFC2046] | + | application/exi | - | 47 | [REC-exi-20140211] | + | application/json | - | 50 | [RFC7159] | + +--------------------------+----------+----+------------------------+ + + Table 9: CoAP Content-Formats + + The identifiers between 65000 and 65535 inclusive are reserved for + experiments. They are not meant for vendor-specific use of any kind + and MUST NOT be used in operational deployments. The identifiers + between 256 and 9999 are reserved for future use in IETF + specifications (IETF Review or IESG Approval). All other identifiers + are Unassigned. + + Because the namespace of single-byte identifiers is so small, the + IANA policy for future additions in the range 0-255 inclusive to the + sub-registry is "Expert Review" as described in [RFC5226]. The IANA + policy for additions in the range 10000-64999 inclusive is "First + Come First Served" as described in [RFC5226]. This is summarized in + the following table. + + + + + + + + +Shelby, et al. Standards Track [Page 92] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + +-------------+---------------------------------------+ + | Range | Registration Procedures | + +-------------+---------------------------------------+ + | 0-255 | Expert Review | + | 256-9999 | IETF Review or IESG Approval | + | 10000-64999 | First Come First Served | + | 65000-65535 | Experimental use (no operational use) | + +-------------+---------------------------------------+ + + Table 10: CoAP Content-Formats: Registration Procedures + + In machine-to-machine applications, it is not expected that generic + Internet media types such as text/plain, application/xml or + application/octet-stream are useful for real applications in the long + term. It is recommended that M2M applications making use of CoAP + request new Internet media types from IANA indicating semantic + information about how to create or parse a payload. For example, a + Smart Energy application payload carried as XML might request a more + specific type like application/se+xml or application/se-exi. + +12.4. URI Scheme Registration + + This document contains the request for the registration of the + Uniform Resource Identifier (URI) scheme "coap". The registration + request complies with [RFC4395]. + + URI scheme name. + coap + + Status. + Permanent. + + URI scheme syntax. + Defined in Section 6.1 of [RFC7252]. + + URI scheme semantics. + The "coap" URI scheme provides a way to identify resources that + are potentially accessible over the Constrained Application + Protocol (CoAP). The resources can be located by contacting the + governing CoAP server and operated on by sending CoAP requests to + the server. This scheme can thus be compared to the "http" URI + scheme [RFC2616]. See Section 6 of [RFC7252] for the details of + operation. + + Encoding considerations. + The scheme encoding conforms to the encoding rules established for + URIs in [RFC3986], i.e., internationalized and reserved characters + are expressed using UTF-8-based percent-encoding. + + + +Shelby, et al. Standards Track [Page 93] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Applications/protocols that use this URI scheme name. + The scheme is used by CoAP endpoints to access CoAP resources. + + Interoperability considerations. + None. + + Security considerations. + See Section 11.1 of [RFC7252]. + + Contact. + IETF Chair + + Author/Change controller. + IESG + + References. + [RFC7252] + +12.5. Secure URI Scheme Registration + + This document contains the request for the registration of the + Uniform Resource Identifier (URI) scheme "coaps". The registration + request complies with [RFC4395]. + + URI scheme name. + coaps + + Status. + Permanent. + + URI scheme syntax. + Defined in Section 6.2 of [RFC7252]. + + URI scheme semantics. + The "coaps" URI scheme provides a way to identify resources that + are potentially accessible over the Constrained Application + Protocol (CoAP) using Datagram Transport Layer Security (DTLS) for + transport security. The resources can be located by contacting + the governing CoAP server and operated on by sending CoAP requests + to the server. This scheme can thus be compared to the "https" + URI scheme [RFC2616]. See Section 6 of [RFC7252] for the details + of operation. + + Encoding considerations. + The scheme encoding conforms to the encoding rules established for + URIs in [RFC3986], i.e., internationalized and reserved characters + are expressed using UTF-8-based percent-encoding. + + + + +Shelby, et al. Standards Track [Page 94] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Applications/protocols that use this URI scheme name. + The scheme is used by CoAP endpoints to access CoAP resources + using DTLS. + + Interoperability considerations. + None. + + Security considerations. + See Section 11.1 of [RFC7252]. + + Contact. + IETF Chair + + Author/Change controller. + IESG + + References. + [RFC7252] + +12.6. Service Name and Port Number Registration + + One of the functions of CoAP is resource discovery: a CoAP client can + ask a CoAP server about the resources offered by it (see Section 7). + To enable resource discovery just based on the knowledge of an IP + address, the CoAP port for resource discovery needs to be + standardized. + + IANA has assigned the port number 5683 and the service name "coap", + in accordance with [RFC6335]. + + Besides unicast, CoAP can be used with both multicast and anycast. + + Service Name. + coap + + Transport Protocol. + udp + + Assignee. + IESG + + Contact. + IETF Chair + + Description. + Constrained Application Protocol (CoAP) + + + + + +Shelby, et al. Standards Track [Page 95] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Reference. + [RFC7252] + + Port Number. + 5683 + +12.7. Secure Service Name and Port Number Registration + + CoAP resource discovery may also be provided using the DTLS-secured + CoAP "coaps" scheme. Thus, the CoAP port for secure resource + discovery needs to be standardized. + + IANA has assigned the port number 5684 and the service name "coaps", + in accordance with [RFC6335]. + + Besides unicast, DTLS-secured CoAP can be used with anycast. + + Service Name. + coaps + + Transport Protocol. + udp + + Assignee. + IESG + + Contact. + IETF Chair + + Description. + DTLS-secured CoAP + + Reference. + [RFC7252] + + Port Number. + 5684 + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 96] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +12.8. Multicast Address Registration + + Section 8, "Multicast CoAP", defines the use of multicast. IANA has + assigned the following multicast addresses for use by CoAP nodes: + + IPv4 -- "All CoAP Nodes" address 224.0.1.187, from the "IPv4 + Multicast Address Space Registry". As the address is used for + discovery that may span beyond a single network, it has come from + the Internetwork Control Block (224.0.1.x, RFC 5771). + + IPv6 -- "All CoAP Nodes" address FF0X::FD, from the "IPv6 Multicast + Address Space Registry", in the "Variable Scope Multicast + Addresses" space (RFC 3307). Note that there is a distinct + multicast address for each scope that interested CoAP nodes should + listen to; CoAP needs the Link-Local and Site-Local scopes only. + +13. Acknowledgements + + Brian Frank was a contributor to and coauthor of early versions of + this specification. + + Special thanks to Peter Bigot, Esko Dijk, and Cullen Jennings for + substantial contributions to the ideas and text in the document, + along with countless detailed reviews and discussions. + + Thanks to Floris Van den Abeele, Anthony Baire, Ed Beroset, Berta + Carballido, Angelo P. Castellani, Gilbert Clark, Robert Cragie, + Pierre David, Esko Dijk, Lisa Dusseault, Mehmet Ersue, Thomas + Fossati, Tobias Gondrom, Bert Greevenbosch, Tom Herbst, Jeroen + Hoebeke, Richard Kelsey, Sye Loong Keoh, Ari Keranen, Matthias + Kovatsch, Avi Lior, Stephan Lohse, Salvatore Loreto, Kerry Lynn, + Andrew McGregor, Alexey Melnikov, Guido Moritz, Petri Mutka, Colin + O'Flynn, Charles Palmer, Adriano Pezzuto, Thomas Poetsch, Robert + Quattlebaum, Akbar Rahman, Eric Rescorla, Dan Romascanu, David Ryan, + Peter Saint-Andre, Szymon Sasin, Michael Scharf, Dale Seed, Robby + Simpson, Peter van der Stok, Michael Stuber, Linyi Tian, Gilman + Tolle, Matthieu Vial, Maciej Wasilak, Fan Xianyou, and Alper Yegin + for helpful comments and discussions that have shaped the document. + Special thanks also to the responsible IETF area director at the time + of completion, Barry Leiba, and the IESG reviewers, Adrian Farrel, + Martin Stiemerling, Pete Resnick, Richard Barnes, Sean Turner, + Spencer Dawkins, Stephen Farrell, and Ted Lemon, who contributed in- + depth reviews. + + Some of the text has been borrowed from the working documents of the + IETF HTTPBIS working group. + + + + + +Shelby, et al. Standards Track [Page 97] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +14. References + +14.1. Normative References + + [RFC0768] Postel, J., "User Datagram Protocol", STD 6, RFC 768, + August 1980. + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message + Bodies", RFC 2045, November 1996. + + [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + November 1996. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [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, June 1999. + + [RFC3023] Murata, M., St. Laurent, S., and D. Kohn, "XML Media + Types", RFC 3023, January 2001. + + [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, November 2003. + + [RFC3676] Gellens, R., "The Text/Plain Format and DelSp Parameters", + RFC 3676, February 2004. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, RFC + 3986, January 2005. + + [RFC4279] Eronen, P. and H. Tschofenig, "Pre-Shared Key Ciphersuites + for Transport Layer Security (TLS)", RFC 4279, December + 2005. + + [RFC4395] Hansen, T., Hardie, T., and L. Masinter, "Guidelines and + Registration Procedures for New URI Schemes", BCP 35, RFC + 4395, February 2006. + + [RFC5147] Wilde, E. and M. Duerst, "URI Fragment Identifiers for the + text/plain Media Type", RFC 5147, April 2008. + + [RFC5198] Klensin, J. and M. Padlipsky, "Unicode Format for Network + Interchange", RFC 5198, March 2008. + + + +Shelby, et al. Standards Track [Page 98] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an + IANA Considerations Section in RFCs", BCP 26, RFC 5226, + May 2008. + + [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, January 2008. + + [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security + (TLS) Protocol Version 1.2", RFC 5246, August 2008. + + [RFC5280] Cooper, D., Santesson, S., Farrell, S., Boeyen, S., + Housley, R., and W. Polk, "Internet X.509 Public Key + Infrastructure Certificate and Certificate Revocation List + (CRL) Profile", RFC 5280, May 2008. + + [RFC5480] Turner, S., Brown, D., Yiu, K., Housley, R., and T. Polk, + "Elliptic Curve Cryptography Subject Public Key + Information", RFC 5480, March 2009. + + [RFC5785] Nottingham, M. and E. Hammer-Lahav, "Defining Well-Known + Uniform Resource Identifiers (URIs)", RFC 5785, April + 2010. + + [RFC5952] Kawamura, S. and M. Kawashima, "A Recommendation for IPv6 + Address Text Representation", RFC 5952, August 2010. + + [RFC5988] Nottingham, M., "Web Linking", RFC 5988, October 2010. + + [RFC6066] Eastlake, D., "Transport Layer Security (TLS) Extensions: + Extension Definitions", RFC 6066, January 2011. + + [RFC6347] Rescorla, E. and N. Modadugu, "Datagram Transport Layer + Security Version 1.2", RFC 6347, January 2012. + + [RFC6690] Shelby, Z., "Constrained RESTful Environments (CoRE) Link + Format", RFC 6690, August 2012. + + [RFC6920] Farrell, S., Kutscher, D., Dannewitz, C., Ohlman, B., + Keranen, A., and P. Hallam-Baker, "Naming Things with + Hashes", RFC 6920, April 2013. + + [RFC7250] Wouters, P., Tschofenig, H., Gilmore, J., Weiler, S., and + T. Kivinen, "Using Raw Public Keys in Transport Layer + Security (TLS) and Datagram Transport Layer Security + (DTLS)", RFC 7250, June 2014. + + + + + + +Shelby, et al. Standards Track [Page 99] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + [RFC7251] McGrew, D., Bailey, D., Campagna, M., and R. Dugal, "AES- + CCM Elliptic Curve Cryptography (ECC) Cipher Suites for + Transport Layer Security (TLS)", RFC 7251, June 2014. + +14.2. Informative References + + [BLOCK] Bormann, C. and Z. Shelby, "Blockwise transfers in CoAP", + Work in Progress, October 2013. + + [CoAP-MISC] + Bormann, C. and K. Hartke, "Miscellaneous additions to + CoAP", Work in Progress, December 2013. + + [EUI64] IEEE Standards Association, "Guidelines for 64-bit Global + Identifier (EUI-64 (TM))", Registration Authority + Tutorials, April 2010, . + + [GROUPCOMM] + Rahman, A. and E. Dijk, "Group Communication for CoAP", + Work in Progress, December 2013. + + [HHGTTG] Adams, D., "The Hitchhiker's Guide to the Galaxy", Pan + Books ISBN 3320258648, 1979. + + [IEEE1003.1] + IEEE and The Open Group, "Portable Operating System + Interface (POSIX)", The Open Group Base Specifications + Issue 7, IEEE 1003.1, 2013 Edition, + . + + [IPsec-CoAP] + Bormann, C., "Using CoAP with IPsec", Work in Progress, + December 2012. + + [MAPPING] Castellani, A., Loreto, S., Rahman, A., Fossati, T., and + E. Dijk, "Guidelines for HTTP-CoAP Mapping + Implementations", Work in Progress, February 2014. + + [OBSERVE] Hartke, K., "Observing Resources in CoAP", Work in + Progress, April 2014. + + [REC-exi-20140211] + Schneider, J., Kamiya, T., Peintner, D., and R. Kyusakov, + "Efficient XML Interchange (EXI) Format 1.0 (Second + Edition)", W3C Recommendation REC-exi-20140211, February + 2014, . + + + + +Shelby, et al. Standards Track [Page 100] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + [REST] Fielding, R., "Architectural Styles and the Design of + Network-based Software Architectures", Ph.D. Dissertation, + University of California, Irvine, 2000, + . + + [RFC0020] Cerf, V., "ASCII format for network interchange", RFC 20, + October 1969. + + [RFC0791] Postel, J., "Internet Protocol", STD 5, RFC 791, September + 1981. + + [RFC0792] Postel, J., "Internet Control Message Protocol", STD 5, + RFC 792, September 1981. + + [RFC0793] Postel, J., "Transmission Control Protocol", STD 7, RFC + 793, September 1981. + + [RFC1035] Mockapetris, P., "Domain names - implementation and + specification", STD 13, RFC 1035, November 1987. + + [RFC3264] Rosenberg, J. and H. Schulzrinne, "An Offer/Answer Model + with Session Description Protocol (SDP)", RFC 3264, June + 2002. + + [RFC3280] Housley, R., Polk, W., Ford, W., and D. Solo, "Internet + X.509 Public Key Infrastructure Certificate and + Certificate Revocation List (CRL) Profile", RFC 3280, + April 2002. + + [RFC3542] Stevens, W., Thomas, M., Nordmark, E., and T. Jinmei, + "Advanced Sockets Application Program Interface (API) for + IPv6", RFC 3542, May 2003. + + [RFC3828] Larzon, L-A., Degermark, M., Pink, S., Jonsson, L-E., and + G. Fairhurst, "The Lightweight User Datagram Protocol + (UDP-Lite)", RFC 3828, July 2004. + + [RFC4086] Eastlake, D., Schiller, J., and S. Crocker, "Randomness + Requirements for Security", BCP 106, RFC 4086, June 2005. + + [RFC4443] Conta, A., Deering, S., and M. Gupta, "Internet Control + Message Protocol (ICMPv6) for the Internet Protocol + Version 6 (IPv6) Specification", RFC 4443, March 2006. + + [RFC4492] Blake-Wilson, S., Bolyard, N., Gupta, V., Hawk, C., and B. + Moeller, "Elliptic Curve Cryptography (ECC) Cipher Suites + for Transport Layer Security (TLS)", RFC 4492, May 2006. + + + +Shelby, et al. Standards Track [Page 101] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + [RFC4821] Mathis, M. and J. Heffner, "Packetization Layer Path MTU + Discovery", RFC 4821, March 2007. + + [RFC4944] Montenegro, G., Kushalnagar, N., Hui, J., and D. Culler, + "Transmission of IPv6 Packets over IEEE 802.15.4 + Networks", RFC 4944, September 2007. + + [RFC5405] Eggert, L. and G. Fairhurst, "Unicast UDP Usage Guidelines + for Application Designers", BCP 145, RFC 5405, November + 2008. + + [RFC5489] Badra, M. and I. Hajjeh, "ECDHE_PSK Cipher Suites for + Transport Layer Security (TLS)", RFC 5489, March 2009. + + [RFC6090] McGrew, D., Igoe, K., and M. Salter, "Fundamental Elliptic + Curve Cryptography Algorithms", RFC 6090, February 2011. + + [RFC6120] Saint-Andre, P., "Extensible Messaging and Presence + Protocol (XMPP): Core", RFC 6120, March 2011. + + [RFC6282] Hui, J. and P. Thubert, "Compression Format for IPv6 + Datagrams over IEEE 802.15.4-Based Networks", RFC 6282, + September 2011. + + [RFC6335] Cotton, M., Eggert, L., Touch, J., Westerlund, M., and S. + Cheshire, "Internet Assigned Numbers Authority (IANA) + Procedures for the Management of the Service Name and + Transport Protocol Port Number Registry", BCP 165, RFC + 6335, August 2011. + + [RFC6655] McGrew, D. and D. Bailey, "AES-CCM Cipher Suites for + Transport Layer Security (TLS)", RFC 6655, July 2012. + + [RFC6936] Fairhurst, G. and M. Westerlund, "Applicability Statement + for the Use of IPv6 UDP Datagrams with Zero Checksums", + RFC 6936, April 2013. + + [RFC6960] Santesson, S., Myers, M., Ankney, R., Malpani, A., + Galperin, S., and C. Adams, "X.509 Internet Public Key + Infrastructure Online Certificate Status Protocol - OCSP", + RFC 6960, June 2013. + + [RFC6961] Pettersen, Y., "The Transport Layer Security (TLS) + Multiple Certificate Status Request Extension", RFC 6961, + June 2013. + + [RFC7159] Bray, T., "The JavaScript Object Notation (JSON) Data + Interchange Format", RFC 7159, March 2014. + + + +Shelby, et al. Standards Track [Page 102] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + [RFC7228] Bormann, C., Ersue, M., and A. Keranen, "Terminology for + Constrained-Node Networks", RFC 7228, May 2014. + + [RTO-CONSIDER] + Allman, M., "Retransmission Timeout Considerations", Work + in Progress, May 2012. + + [W3CXMLSEC] + Wenning, R., "Report of the XML Security PAG", W3C XML + Security PAG, October 2012, + . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 103] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + +Appendix A. Examples + + This section gives a number of short examples with message flows for + GET requests. These examples demonstrate the basic operation, the + operation in the presence of retransmissions, and multicast. + + Figure 16 shows a basic GET request causing a piggybacked response: + The client sends a Confirmable GET request for the resource + coap://server/temperature to the server with a Message ID of 0x7d34. + The request includes one Uri-Path Option (Delta 0 + 11 = 11, Length + 11, Value "temperature"); the Token is left empty. This request is a + total of 16 bytes long. A 2.05 (Content) response is returned in the + Acknowledgement message that acknowledges the Confirmable request, + echoing both the Message ID 0x7d34 and the empty Token value. The + response includes a Payload of "22.3 C" and is 11 bytes long. + + Client Server + | | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d34) + | GET | Uri-Path: "temperature" + | | + | | + |<-----+ Header: 2.05 Content (T=ACK, Code=2.05, MID=0x7d34) + | 2.05 | Payload: "22.3 C" + | | + + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 1 | 0 | 0 | GET=1 | MID=0x7d34 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 11 | 11 | "temperature" (11 B) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 1 | 2 | 0 | 2.05=69 | MID=0x7d34 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |1 1 1 1 1 1 1 1| "22.3 C" (6 B) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Figure 16: Confirmable Request; Piggybacked Response + + + + + + +Shelby, et al. Standards Track [Page 104] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Figure 17 shows a similar example, but with the inclusion of an non- + empty Token (Value 0x20) in the request and the response, increasing + the sizes to 17 and 12 bytes, respectively. + + Client Server + | | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d35) + | GET | Token: 0x20 + | | Uri-Path: "temperature" + | | + | | + |<-----+ Header: 2.05 Content (T=ACK, Code=2.05, MID=0x7d35) + | 2.05 | Token: 0x20 + | | Payload: "22.3 C" + | | + + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 1 | 0 | 1 | GET=1 | MID=0x7d35 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 0x20 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 11 | 11 | "temperature" (11 B) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 1 | 2 | 1 | 2.05=69 | MID=0x7d35 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | 0x20 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |1 1 1 1 1 1 1 1| "22.3 C" (6 B) ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Figure 17: Confirmable Request; Piggybacked Response + + + + + + + + + + + +Shelby, et al. Standards Track [Page 105] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In Figure 18, the Confirmable GET request is lost. After ACK_TIMEOUT + seconds, the client retransmits the request, resulting in a + piggybacked response as in the previous example. + + Client Server + | | + | | + +----X | Header: GET (T=CON, Code=0.01, MID=0x7d36) + | GET | Token: 0x31 + | | Uri-Path: "temperature" + TIMEOUT | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d36) + | GET | Token: 0x31 + | | Uri-Path: "temperature" + | | + | | + |<-----+ Header: 2.05 Content (T=ACK, Code=2.05, MID=0x7d36) + | 2.05 | Token: 0x31 + | | Payload: "22.3 C" + | | + + Figure 18: Confirmable Request (Retransmitted); Piggybacked Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 106] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In Figure 19, the first Acknowledgement message from the server to + the client is lost. After ACK_TIMEOUT seconds, the client + retransmits the request. + + Client Server + | | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d37) + | GET | Token: 0x42 + | | Uri-Path: "temperature" + | | + | | + | X----+ Header: 2.05 Content (T=ACK, Code=2.05, MID=0x7d37) + | 2.05 | Token: 0x42 + | | Payload: "22.3 C" + TIMEOUT | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d37) + | GET | Token: 0x42 + | | Uri-Path: "temperature" + | | + | | + |<-----+ Header: 2.05 Content (T=ACK, Code=2.05, MID=0x7d37) + | 2.05 | Token: 0x42 + | | Payload: "22.3 C" + | | + + Figure 19: Confirmable Request; Piggybacked Response (Retransmitted) + + + + + + + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 107] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In Figure 20, the server acknowledges the Confirmable request and + sends a 2.05 (Content) response separately in a Confirmable message. + Note that the Acknowledgement message and the Confirmable response do + not necessarily arrive in the same order as they were sent. The + client acknowledges the Confirmable response. + + Client Server + | | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d38) + | GET | Token: 0x53 + | | Uri-Path: "temperature" + | | + | | + |<- - -+ Header: (T=ACK, Code=0.00, MID=0x7d38) + | | + | | + |<-----+ Header: 2.05 Content (T=CON, Code=2.05, MID=0xad7b) + | 2.05 | Token: 0x53 + | | Payload: "22.3 C" + | | + | | + +- - ->| Header: (T=ACK, Code=0.00, MID=0xad7b) + | | + + Figure 20: Confirmable Request; Separate Response + + + + + + + + + + + + + + + + + + + + + + + + + +Shelby, et al. Standards Track [Page 108] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Figure 21 shows an example where the client loses its state (e.g., + crashes and is rebooted) right after sending a Confirmable request, + so the separate response arriving some time later comes unexpected. + In this case, the client rejects the Confirmable response with a + Reset message. Note that the unexpected ACK is silently ignored. + + Client Server + | | + | | + +----->| Header: GET (T=CON, Code=0.01, MID=0x7d39) + | GET | Token: 0x64 + | | Uri-Path: "temperature" + CRASH | + | | + |<- - -+ Header: (T=ACK, Code=0.00, MID=0x7d39) + | | + | | + |<-----+ Header: 2.05 Content (T=CON, Code=2.05, MID=0xad7c) + | 2.05 | Token: 0x64 + | | Payload: "22.3 C" + | | + | | + +- - ->| Header: (T=RST, Code=0.00, MID=0xad7c) + | | + + Figure 21: Confirmable Request; Separate Response (Unexpected) + + Figure 22 shows a basic GET request where the request and the + response are Non-confirmable, so both may be lost without notice. + + Client Server + | | + | | + +----->| Header: GET (T=NON, Code=0.01, MID=0x7d40) + | GET | Token: 0x75 + | | Uri-Path: "temperature" + | | + | | + |<-----+ Header: 2.05 Content (T=NON, Code=2.05, MID=0xad7d) + | 2.05 | Token: 0x75 + | | Payload: "22.3 C" + | | + + Figure 22: Non-confirmable Request; Non-confirmable Response + + + + + + + +Shelby, et al. Standards Track [Page 109] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + In Figure 23, the client sends a Non-confirmable GET request to a + multicast address: all nodes in link-local scope. There are 3 + servers on the link: A, B and C. Servers A and B have a matching + resource, therefore they send back a Non-confirmable 2.05 (Content) + response. The response sent by B is lost. C does not have matching + response, therefore it sends a Non-confirmable 4.04 (Not Found) + response. + + Client ff02::1 A B C + | | | | | + | | | | | + +------>| | | | Header: GET (T=NON, Code=0.01, MID=0x7d41) + | GET | | | | Token: 0x86 + | | | | Uri-Path: "temperature" + | | | | + | | | | + |<------------+ | | Header: 2.05 (T=NON, Code=2.05, MID=0x60b1) + | 2.05 | | | Token: 0x86 + | | | | Payload: "22.3 C" + | | | | + | | | | + | X------------+ | Header: 2.05 (T=NON, Code=2.05, MID=0x01a0) + | 2.05 | | | Token: 0x86 + | | | | Payload: "20.9 C" + | | | | + | | | | + |<------------------+ Header: 4.04 (T=NON, Code=4.04, MID=0x952a) + | 4.04 | | | Token: 0x86 + | | | | + + Figure 23: Non-confirmable Request (Multicast); Non-confirmable + Response + +Appendix B. URI Examples + + The following examples demonstrate different sets of Uri options, and + the result after constructing an URI from them. In addition to the + options, Section 6.5 refers to the destination IP address and port, + but not all paths of the algorithm cause the destination IP address + and port to be included in the URI. + + o Input: + + Destination IP Address = [2001:db8::2:1] + Destination UDP Port = 5683 + + + + + + +Shelby, et al. Standards Track [Page 110] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + Output: + + coap://[2001:db8::2:1]/ + + o Input: + + Destination IP Address = [2001:db8::2:1] + Destination UDP Port = 5683 + Uri-Host = "example.net" + + Output: + + coap://example.net/ + + o Input: + + Destination IP Address = [2001:db8::2:1] + Destination UDP Port = 5683 + Uri-Host = "example.net" + Uri-Path = ".well-known" + Uri-Path = "core" + + Output: + + coap://example.net/.well-known/core + + o Input: + + Destination IP Address = [2001:db8::2:1] + Destination UDP Port = 5683 + Uri-Host = "xn--18j4d.example" + Uri-Path = the string composed of the Unicode characters U+3053 + U+3093 U+306b U+3061 U+306f, usually represented in UTF-8 as + E38193E38293E381ABE381A1E381AF hexadecimal + + Output: + + coap://xn--18j4d.example/ + %E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF + + (The line break has been inserted for readability; it is not + part of the URI.) + + + + + + + + + +Shelby, et al. Standards Track [Page 111] + +RFC 7252 The Constrained Application Protocol (CoAP) June 2014 + + + o Input: + + Destination IP Address = 198.51.100.1 + Destination UDP Port = 61616 + Uri-Path = "" + Uri-Path = "/" + Uri-Path = "" + Uri-Path = "" + Uri-Query = "//" + Uri-Query = "?&" + + Output: + + coap://198.51.100.1:61616//%2F//?%2F%2F&?%26 + +Authors' Addresses + + Zach Shelby + ARM + 150 Rose Orchard + San Jose, CA 95134 + USA + + Phone: +1-408-203-9434 + EMail: zach.shelby@arm.com + + + Klaus Hartke + Universitaet Bremen TZI + Postfach 330440 + Bremen D-28359 + Germany + + Phone: +49-421-218-63905 + EMail: hartke@tzi.org + + + Carsten Bormann + Universitaet Bremen TZI + Postfach 330440 + Bremen D-28359 + Germany + + Phone: +49-421-218-63921 + EMail: cabo@tzi.org + + + + + + +Shelby, et al. Standards Track [Page 112] + diff --git a/src/coap_parse.erl b/src/coap_parse.erl new file mode 100644 index 0000000..bb61a28 --- /dev/null +++ b/src/coap_parse.erl @@ -0,0 +1,137 @@ +-module(coap_parse). +-export([parse/1, + get_option_values/2]). + +-include("coaperl.hrl"). + + +-spec parse(<<>>) -> #coap_request{} | #coap_response{} | #coap_empty_message{}. +% @doc: parse a binary coap message +parse(Packet) -> + {coap, Parsed} = parse_raw(Packet), + parse_to_rec(Parsed). + + +% @doc get the named option values from the given response record +get_option_values(#coap_response{options=Options}, OptNum) -> + [ Val || {coap_option, Num, Val} <- Options, Num =:= OptNum ]. + + +% @doc: convert raw message to request, response or empty message records +parse_to_rec({_Type, Code, MID, _Token, Options, Payload}) when Code > 0, Code =< 31 -> + #coap_request{method=coap_unparse:method_name(Code), + path=parse_path(Options), + query=parse_query(Options), + mid=MID, + ct=parse_content_type(Options), + payload=Payload}; +parse_to_rec({_Type, 0, MID , _Token, _Options, <<>>}) -> + #coap_empty_message{mid=MID}; +parse_to_rec({_Type, Code, MID, _Token, Options, Payload}) -> + <> = <>, + #coap_response{mid=MID, + ct=parse_content_type(Options), + options=Options, + class=Class, + detail=Detail, + block2=parse_block2(Options), + payload=Payload}. + + +% @doc: parse path from raw options +parse_path(Options) -> + erlang:iolist_to_binary(lists:reverse(parse_path(Options, []))). + +parse_path([{coap_option, ?COAP_OPTION_URI_PATH, Comp}|T], Acc) -> + parse_path(T, [["/"|Comp]|Acc]); +parse_path([{coap_option, _, _}|T], Acc) -> + parse_path(T, Acc); +parse_path([], Acc) -> + Acc. + + +% @doc: parse query from raw options +parse_query(Options) -> + parse_query(Options, []). + +parse_query([{coap_option, ?COAP_OPTION_URI_QUERY, Opt}|T], Acc) -> + parse_query(T, [Opt|Acc]); +parse_query([{coap_option, _, _}|T], Acc) -> + parse_query(T, Acc); +parse_query([], Acc) -> + Acc. + + + +% @doc: parse content type from raw options +parse_content_type(Options) -> + OptVals = [Value || {coap_option, Format, Value} <- Options, Format =:= ?COAP_OPTION_CONTENT_FORMAT], + case OptVals of + [<>] -> corerl:content_format_type(Val); + _ -> undefined + end. + + +% @doc: parse block2 option from raw options +parse_block2(Options) -> + OptVals = [Value || {coap_option, Format, Value} <- Options, Format =:= ?COAP_OPTION_BLOCK2], + case OptVals of + [Val] -> + NumLen = bit_size(Val)-4, + <> = Val, + {Num, M, 1 bsl (SZX+4)}; + _ -> undefined + end. + + +% @doc: parse raw packet +parse_raw(<>) when Version =:= 1 -> + {Options, Payload} = parse_raw_options(Tail), + {coap, {Type, Code, MID, Token, Options, Payload}}; +parse_raw(_AnythingElse) -> + {bad, "unable to parse packet"}. + +% @doc: parse options in raw packet, don't interpret any option types yet +parse_raw_options(OptionBin) -> + parse_raw_options(OptionBin, 0, []). + +parse_raw_options(<<>>, _LastNum, OptionList) -> + {OptionList, <<>>}; +parse_raw_options(<<16#FF, Payload/bytes>>, _LastNum, OptionList) -> + {OptionList, Payload}; +parse_raw_options(<>, LastNum, OptionList) -> + {Tail1, OptNum} = case BaseOptNum of + X when X < 13 -> + {Tail, BaseOptNum + LastNum}; + X when X =:= 13 -> + <> = Tail, + {NewTail, ExtOptNum + 13 + LastNum}; + X when X =:= 14 -> + <> = Tail, + {NewTail, ExtOptNum + 269 + LastNum} + end, + {OptLen, Tail3} = case BaseOptLen of + Y when Y < 13 -> + {BaseOptLen, Tail1}; + Y when Y =:= 13 -> + <> = Tail1, + {ExtOptLen + 13, Tail2}; + Y when Y =:= 14 -> + <> = Tail1, + {ExtOptLen + 269, Tail2} + end, + <> = Tail3, + parse_raw_options(NextOpt, OptNum, [{coap_option, OptNum, OptVal}|OptionList]). + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +parse_to_rec_test() -> + % Check if parse to the right rec + ?assertEqual(parse_to_rec({egal, 100, 1, egal, [{coap_option, ?COAP_OPTION_CONTENT_FORMAT, <<50:8>>}], payload}), + {coap_response,3,4,1, + <<"application/json">>, + undefined, + [{coap_option,12,<<"2">>}], + payload}). +-endif. diff --git a/src/coap_unparse.erl b/src/coap_unparse.erl new file mode 100644 index 0000000..aaca450 --- /dev/null +++ b/src/coap_unparse.erl @@ -0,0 +1,195 @@ +-module(coap_unparse). +-export([build_request/2, + build_response/3, + build_text_response/4, + method_name/1]). + +-include("coaperl.hrl"). + +coap_scheme_defaults() -> + [{coap, 5683}, + {coaps, 5684}, + {'coap+tcp', 5683}, + {'coaps+tcp', 443} + ]. + + +% RFC7252, Section 3 +types() -> + [{confirmable, 0}, + {nonconfirmable, 1}, + {acknowledgement, 2}, + {reset, 3}]. + +type_code(Type) -> + proplists:get_value(Type, types()). + + +% RFC7252, Section 3 +%% code() -> +%% [{request, 0}, +%% {success, 2}, +%% {clienterror, 4}, +%% {servererror, 5}]. + + + +% RFC7252, Section 12.1.1 +methods() -> + [{get, 1}, + {post, 2}, + {put, 3}, + {delete, 4} + ]. +method_code(Method) -> + proplists:get_value(Method, methods()). +method_name(Number) -> + {Method, Number} = lists:keyfind(Number, 2, methods()), + Method. + + +-spec uri_to_options(string()) -> [{string(), integer(), list()}]. +% convert an URI to the corresponding COAP Options +uri_to_options(Uri) -> + {ok, {_, _, Host, Port, Path, _}} = http_uri:parse(Uri, + [{scheme_defaults, coap_scheme_defaults()}, + {ipv6_host_with_brackets, true}]), + + % Remove brackets from addr if present + Host2 = case Host of + [$[|T] -> [X || X <- T, X =/= $]]; + _ -> Host + end, + {Host2, Port, path_to_options(Path)}. + + +% convert an URI path to the corresponding COAP Options +path_to_options([$/|Path]) -> + lists:reverse(path_to_options(string:tokens(Path, "/"), [])). + +path_to_options([], Options) -> + Options; +path_to_options([H|T], Options) -> + path_to_options(T, [{?COAP_OPTION_URI_PATH, H}|Options]). + + +-spec content_format_to_options(string()) -> [{integer(), integer()}]. +% @doc: convert a content format into a number (12.3) +content_format_to_options(ContentFormat) -> + FormatNum = corerl:content_format_number(ContentFormat), + [{?COAP_OPTION_CONTENT_FORMAT, FormatNum}]. + + +-spec num_bytes(integer()) -> integer(). +num_bytes(Val) when is_integer(Val), Val =< 16#ff -> + 1; +num_bytes(Val) when is_integer(Val), Val =< 16#ffff -> + 2; +num_bytes(Val) when is_integer(Val), Val =< 16#ffffff -> + 3. + + +-spec option_length(integer() | binary() | list()) -> integer(). +option_length(Val) when is_integer(Val) -> + num_bytes(Val); +option_length(Val) when is_binary(Val) -> + byte_size(Val); +option_length(Val) when is_list(Val) -> + string:len(Val). + + +-spec option_format_int(integer()) -> {integer(), integer(), integer()}. +option_format_int(Val) -> + case Val of + X when X < 13 -> + {X, 0, 0}; + X when 13 =< X, X < 269 -> + {13, X-13, 8}; + X when X >= 14 -> + {14, X-269, 16} + end. + + +-spec options_to_bin(list()) -> iolist(). +options_to_bin(Options) -> + % FIXME: sort options by number here + options_to_bin(Options, 0, []). + +options_to_bin([], _, Acc) -> + lists:reverse(Acc); +options_to_bin([{Num, Val}|T], OldNum, Acc) when is_integer(Num)-> + Diff = Num - OldNum, + if Diff < 0 -> erlang:error(badarith); + true -> true + end, + Len = option_length(Val), + + {Delta, ExtDelta, ExtDeltaBits} = option_format_int(Diff), + {Length, ExtLength, ExtLengthBits} = option_format_int(Len), + + NewBin = [[<>, + Val] | Acc], + options_to_bin(T, Num, NewBin). + + +build_request([{url, Url}, {method, Method}], Msgid, Options) -> + {Host, Port, UriOptions} = uri_to_options(Url), + BinOptions = options_to_bin(UriOptions ++ Options), + MethodNumber = method_code(Method), + Type = type_code(confirmable), + {Host, Port, [<<1:2, Type:2, 0:4, 0:3, MethodNumber:5, Msgid:16>>, BinOptions]}. + +build_request(Url, Msgid) -> + build_request([{url, Url}, {method, get}], Msgid, []). + + +build_response(Class, Detail, Msgid) -> + Type = type_code(confirmable), + [<<1:2, Type:2, 0:4, Class:3, Detail:5, Msgid:16>>]. + +build_text_response(Class, Detail, Msgid, Payload) -> + Options = content_format_to_options("text/plain"), + BinOptions = options_to_bin(Options), + Type = type_code(confirmable), + [<<1:2, Type:2, 0:4, Class:3, Detail:5, Msgid:16>>, BinOptions, ?COAP_PAYLOAD_MARKER, Payload]. + + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +option_delta_test() -> + % Check if we encode the option delta correctly + ?assertEqual(options_to_bin([{11, "foo"}]), + [[<<11:4, 3:4>>, "foo"]]), + ?assertEqual(options_to_bin([{15, "foo"}]), + [[<<13:4, 3:4, 2:8>>, "foo"]]), + ?assertEqual(options_to_bin([{275, "foo"}]), + [[<<14:4, 3:4, 6:16>>, "foo"]]). + +option_length_test() -> + % Check if we encode the option value length correctly + ?assertEqual(options_to_bin([{11, "12345678901234"}]), + [[<<11:4, 13:4, 1:8>>, "12345678901234"]]), + % integer represented in one byte + ?assertEqual(options_to_bin([{11, 24}]), + [[<<11:4, 1:4>>, 24]]), + % integer represented in two bytes + ?assertEqual(options_to_bin([{11, 324}]), + [[<<11:4, 2:4>>, 324]]), + % integer represented in three bytes + ?assertEqual(options_to_bin([{11, 70024}]), + [[<<11:4, 3:4>>, 70024]]). + +path_to_options_test() -> + Path = "/.well-known/core", + Ret = path_to_options(Path), + ?assertEqual(Ret, [{11,".well-known"},{11,"core"}]). + +uri_to_options_test() -> + Uri = "coap://[::1]/.well-known/core", + Ret = uri_to_options(Uri), + ?assertEqual(Ret, {"::1", 5683, [{11,".well-known"},{11,"core"}]}). + +-endif. diff --git a/src/coaperl.app.src b/src/coaperl.app.src new file mode 100644 index 0000000..df8c84c --- /dev/null +++ b/src/coaperl.app.src @@ -0,0 +1,11 @@ +{application, coaperl, + [ + {description, ""}, + {vsn, "1"}, + {registered, []}, + {applications, [ + kernel, + stdlib + ]}, + {env, []} + ]}. diff --git a/src/coaperl_sup.erl b/src/coaperl_sup.erl new file mode 100644 index 0000000..b57c918 --- /dev/null +++ b/src/coaperl_sup.erl @@ -0,0 +1,29 @@ +-module(coaperl_sup). + +-behaviour(supervisor). + +%% API +-export([start_link/0]). + +%% Supervisor callbacks +-export([init/1]). + +%% Helper macro for declaring children of supervisor +-define(CHILD(I, Type, Args), {I, {I, start_link, [Args]}, permanent, 5000, Type, [I]}). + +%% =================================================================== +%% API functions +%% =================================================================== + +start_link() -> + supervisor:start_link({local, ?MODULE}, ?MODULE, []). + +%% =================================================================== +%% Supervisor callbacks +%% =================================================================== + +init([]) -> + {ok, { {one_for_one, 5, 10} +% [?CHILD(udp, worker, [])] + } }. + diff --git a/src/corerl.erl b/src/corerl.erl new file mode 100644 index 0000000..6aa4af5 --- /dev/null +++ b/src/corerl.erl @@ -0,0 +1,72 @@ +-module(corerl). +-export([parse/1, + content_format_number/1, + content_format_type/1]). + +-include("corerl.hrl"). + + +content_formats() -> + [{"text/plain;charset=utf-8", 0}, + % shortcut for the above + {"text/plain", 0}, + {"application/link-format", 40}, + {"application/xml", 41}, + {"application/octext-stream", 42}, + {"application/exi", 47}, + {"application/json", 50}]. + +content_format_number(ContentFormat) -> + proplists:get_value(ContentFormat, content_formats()). + +content_format_type(Number) -> + list_to_binary(proplists:get_value(Number, + [{N,F} || {F,N} <- content_formats()] + )). + + +-spec parse(<<>>) -> list(#core_link{}). +% @doc: parse a core message +parse(Data) -> + parse_link_values(binary:split(Data, <<",">>, [global]), []). + + +parse_link_values([LinkValue|T], Acc) -> + Link = parse_link_value(LinkValue), + parse_link_values(T, [Link|Acc]); +parse_link_values([], Acc) -> + Acc. + +parse_link_value(<<$<, Data/binary>>) -> + [Value, Params] = binary:split(Data, <<$>>>), + parse_link_params(binary:split(Params, <<$;>>, [global]), #core_link{uri=Value}). + + +parse_link_params([LinkParam|T], Rec) -> + NewRec = case binary:split(LinkParam, <<$=>>, [global]) of + [<<"title">>, V] -> + Rec#core_link{title=V}; + [<<"ct">>, V] -> + Rec#core_link{ct=content_format_type(binary_to_integer(V))}; + [<<"rt">>, V] -> + Rec#core_link{rt=V}; + [<<"if">>, V] -> + Rec#core_link{'if'=V}; + _ -> Rec + end, + parse_link_params(T, NewRec); +parse_link_params([], Rec) -> + Rec. + + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). + +parse_link_values_test() -> + Data = <<";title=\"General Info\";ct=0,;if=\"clock\";rt=\"Ticks\";title=\"Internal Clock\";ct=0;obs,;ct=50">>, + ?assertEqual(parse(Data), + [{core_link,<<"/async">>,undefined,undefined,undefined,<<"application/json">>,undefined}, + {core_link,<<"/time">>,<<"\"Internal Clock\"">>,undefined,<<"\"Ticks\"">>, <<"text/plain;charset=utf-8">>,<<"\"clock\"">>}, + {core_link,<<"/">>,<<"\"General Info\"">>,undefined,undefined,<<"text/plain;charset=utf-8">>,undefined} + ]). +-endif. diff --git a/test/coap_parse_test.erl b/test/coap_parse_test.erl new file mode 100644 index 0000000..59b8510 --- /dev/null +++ b/test/coap_parse_test.erl @@ -0,0 +1,19 @@ +-module(coap_parse_test). +-include_lib("eunit/include/eunit.hrl"). + +-include("coaperl.hrl"). + +% Test descriptions +parse_test_() -> + [{"Option extration works", + check_get_option_values()} + ]. + +% Tests +check_get_option_values() -> + Ret = coap_parse:get_option_values(#coap_response{options=[{coap_option,11,<<"bar">>}, + {coap_option,11,<<"baz">>}, + {coap_option,12,<<"foo">>}]}, + 11), + [?_assertEqual(Ret, [<<"bar">>, <<"baz">>])]. + diff --git a/test/coap_unparse_test.erl b/test/coap_unparse_test.erl new file mode 100644 index 0000000..777913e --- /dev/null +++ b/test/coap_unparse_test.erl @@ -0,0 +1,31 @@ +-module(coap_unparse_test). +-include_lib("eunit/include/eunit.hrl"). + +% Test descriptions +unparse_test_() -> + [{"Building a get request should result in binary data", + check_build_request()}, + {"Building a response without payload in binary data", + check_build_response()}, + {"Building a response with payload in binary data", + check_build_text_response()} + ]. + +% Tests +check_build_request() -> + Uri = "coap://[::1]/.well-known/core", + Ret = coap_unparse:build_request(Uri, 1), + [?_assertEqual(Ret, {"::1", 5683, + [<<64,1,0,1>>, + [[<<11:4,11:4>>,".well-known"], + [<<0:4,4:4>>,"core"]]]})]. + +check_build_response() -> + Ret = coap_unparse:build_response(4, 4, 1), + [?_assertEqual(Ret, [<<64,4:3, 4:5,0,1>>])]. + +check_build_text_response() -> + Ret = coap_unparse:build_text_response(2, 5, 1, "payload"), + [?_assertEqual(Ret, [<<64,2:3, 5:5,0,1>>, + [[<<12:4,1:4>>,0]], + 255, "payload"])]. -- cgit v1.2.3