Showing preview only (268K chars total). Download the full file or copy to clipboard to get everything.
Repository: zubairhamed/canopus
Branch: master
Commit: e374f5b1a0f3
Files: 55
Total size: 252.9 KB
Directory structure:
gitextract_9p8qk6we/
├── .gitignore
├── .gitmodules
├── Godeps/
│ └── Godeps.json
├── LICENSE
├── README.md
├── bytecontent.go
├── canopus.go
├── client.go
├── conn.go
├── corelink.go
├── coreresource.go
├── coreresource_test.go
├── dtls.go
├── empty.go
├── event.go
├── event_test.go
├── examples/
│ ├── block1/
│ │ ├── client.go
│ │ ├── ietf-block.htm
│ │ └── server.go
│ ├── discovery/
│ │ └── main.go
│ ├── dtls/
│ │ └── simple-psk/
│ │ ├── client.go
│ │ └── server.go
│ ├── observe/
│ │ ├── client.go
│ │ └── server.go
│ ├── proxy/
│ │ ├── coap/
│ │ │ ├── client.go
│ │ │ ├── proxy.go
│ │ │ └── server.go
│ │ └── http/
│ │ ├── client.go
│ │ └── server.go
│ └── simple/
│ ├── client.go
│ └── server.go
├── init.go
├── json.go
├── message.go
├── message_test.go
├── options.go
├── plaintext.go
├── proxy.go
├── request.go
├── request_test.go
├── response.go
├── response_test.go
├── routes.go
├── routes_test.go
├── server.go
├── server_test.go
├── serverconn.go
├── session.go
├── test-coverage.sh
├── types.go
├── utilconn_test.go
├── utildebug.go
├── utils.go
├── utils_test.go
└── xml.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
Godeps/_workspace
Readme
================================================
FILE: .gitmodules
================================================
[submodule "openssl"]
path = openssl
url = https://github.com/openssl/openssl.git
================================================
FILE: Godeps/Godeps.json
================================================
{
"ImportPath": "github.com/zubairhamed/canopus",
"GoVersion": "go1.7",
"Deps": [
{
"ImportPath": "github.com/davecgh/go-spew/spew",
"Rev": "5215b55f46b2b919f50a1df0eaa5886afe4e3b3d"
},
{
"ImportPath": "github.com/pmezard/go-difflib/difflib",
"Rev": "d8ed2627bdf02c080bf22230dbb337003b7aba2d"
},
{
"ImportPath": "github.com/stretchr/testify/assert",
"Comment": "v1.0-80-g67106a5",
"Rev": "67106a5111a06241c8d84952c33214675f51a34a"
}
]
}
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2015, Zubair Hamed
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# Canopus
[](https://godoc.org/github.com/zubairhamed/canopus)
[](https://drone.io/github.com/zubairhamed/canopus/latest)
[](https://coveralls.io/r/zubairhamed/canopus?branch=master)
[](https://goreportcard.com/report/github.com/zubairhamed/canopus)
#### Canopus is a client/server implementation of the [Constrained Application Protocol (CoAP)][RFC7252]
[RFC7252]: http://tools.ietf.org/html/rfc7252
## Updates
#### 25.11.2016
I've added basic dTLS Support based on [Julien Vermillard's][JVERMILLARD] [implementation][NATIVEDTLS]. Thanks Julien! It should now support PSK-based authentication.
I've also gone ahead and refactored the APIs to make it that bit more Go idiomatic.
[JVERMILLARD]: https://github.com/jvermillard
[NATIVEDTLS]: https://github.com/jvermillard/nativedtls
## Building and running
1. git submodule update --init --recursive
2. cd openssl
3. ./config && make
4. You should then be able to run the examples in the /examples folder
#### Simple Example
```go
// Server
// See /examples/simple/server/main.go
server := canopus.NewServer()
server.Get("/hello", func(req canopus.Request) canopus.Response {
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.ListenAndServe(":5683")
// Client
// See /examples/simple/client/main.go
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID()).(*canopus.CoapRequest)
req.SetStringPayload("Hello, canopus")
req.SetRequestURI("/hello")
resp, err := conn.Send(req)
if err != nil {
panic(err.Error())
}
fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
```
#### Observe / Notify
```go
// Server
// See /examples/observe/server/main.go
server := canopus.NewServer()
server.Get("/watch/this", func(req canopus.Request) canopus.Response {
msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), canopus.NewPlainTextPayload("Acknowledged"))
res := canopus.NewResponse(msg, nil)
return res
})
ticker := time.NewTicker(3 * time.Second)
go func() {
for {
select {
case <-ticker.C:
changeVal := strconv.Itoa(rand.Int())
fmt.Println("[SERVER << ] Change of value -->", changeVal)
server.NotifyChange("/watch/this", changeVal, false)
}
}
}()
server.OnObserve(func(resource string, msg canopus.Message) {
fmt.Println("[SERVER << ] Observe Requested for " + resource)
})
server.ListenAndServe(":5683")
// Client
// See /examples/observe/client/main.go
conn, err := canopus.Dial("localhost:5683")
tok, err := conn.ObserveResource("/watch/this")
if err != nil {
panic(err.Error())
}
obsChannel := make(chan canopus.ObserveMessage)
done := make(chan bool)
go conn.Observe(obsChannel)
notifyCount := 0
for {
select {
case obsMsg, _ := <-obsChannel:
if notifyCount == 5 {
fmt.Println("[CLIENT >> ] Canceling observe after 5 notifications..")
go conn.CancelObserveResource("watch/this", tok)
go conn.StopObserve(obsChannel)
return
} else {
notifyCount++
// msg := obsMsg.Msg\
resource := obsMsg.GetResource()
val := obsMsg.GetValue()
fmt.Println("[CLIENT >> ] Got Change Notification for resource and value: ", notifyCount, resource, val)
}
}
}
```
### dTLS with PSK
```go
// Server
// See /examples/dtls/simple-psk/server/main.go
server := canopus.NewServer()
server.Get("/hello", func(req canopus.Request) canopus.Response {
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.HandlePSK(func(id string) []byte {
return []byte("secretPSK")
})
server.ListenAndServeDTLS(":5684")
// Client
// See /examples/dtls/simple-psk/client/main.go
conn, err := canopus.DialDTLS("localhost:5684", "canopus", "secretPSK")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
req.SetStringPayload("Hello, canopus")
req.SetRequestURI("/hello")
resp, err := conn.Send(req)
if err != nil {
panic(err.Error())
}
fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
```
#### CoAP-CoAP Proxy
```go
// Server
// See /examples/proxy/coap/server/main.go
server := canopus.NewServer()
server.Get("/proxycall", func(req canopus.Request) canopus.Response {
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Data from :5685 -- " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.ListenAndServe(":5685")
// Proxy Server
// See /examples/proxy/coap/proxy/main.go
server := canopus.NewServer()
server.ProxyOverCoap(true)
server.Get("/proxycall", func(req canopus.Request) canopus.Response {
canopus.PrintMessage(req.GetMessage())
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.ListenAndServe(":5683")
// Client
// See /examples/proxy/coap/client/main.go
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
req.SetProxyURI("coap://localhost:5685/proxycall")
resp, err := conn.Send(req)
if err != nil {
println("err", err)
}
canopus.PrintMessage(resp.GetMessage())
```
#### CoAP-HTTP Proxy
```go
// Server
// See /examples/proxy/http/server/main.go
server := canopus.NewServer()
server.ProxyOverHttp(true)
server.ListenAndServe(":5683")
// Client
// See /examples/proxy/http/client/main.go
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
req.SetProxyURI("https://httpbin.org/get")
resp, err := conn.Send(req)
if err != nil {
println("err", err)
}
canopus.PrintMessage(resp.GetMessage())
```
================================================
FILE: bytecontent.go
================================================
package canopus
// Represents a message payload containing an array of bytes
func NewBytesPayload(v []byte) MessagePayload {
return &BytesPayload{
content: v,
}
}
type BytesPayload struct {
content []byte
}
func (p *BytesPayload) GetBytes() []byte {
return p.content
}
func (p *BytesPayload) Length() int {
return len(p.content)
}
func (p *BytesPayload) String() string {
return string(p.content)
}
================================================
FILE: canopus.go
================================================
package canopus
import (
"errors"
"math/rand"
"net"
"sync"
"time"
)
// CurrentMessageID stores the current message id used/generated for messages
var CurrentMessageID = 0
var MESSAGEID_MUTEX *sync.Mutex
func init() {
rand.Seed(time.Now().UTC().UnixNano())
CurrentMessageID = rand.Intn(65535)
MESSAGEID_MUTEX = &sync.Mutex{}
}
var GENERATE_ID uint16 = 0
const UDP = "udp"
// Types of Messages
const (
MessageConfirmable = 0
MessageNonConfirmable = 1
MessageAcknowledgment = 2
MessageReset = 3
)
// Fragments/parts of a CoAP Message packet
const (
DataHeader = 0
DataCode = 1
DataMsgIDStart = 2
DataMsgIDEnd = 4
DataTokenStart = 4
)
// OptionCode type represents a valid CoAP Option Code
type OptionCode int
const (
// OptionIfMatch request-header field is used with a method to make it conditional.
// A client that has one or more entities previously obtained from the resource can verify
// that one of those entities is current by including a list of their associated entity tags
// in the If-Match header field.
OptionIfMatch OptionCode = 1
OptionURIHost OptionCode = 3
OptionEtag OptionCode = 4
OptionIfNoneMatch OptionCode = 5
OptionObserve OptionCode = 6
OptionURIPort OptionCode = 7
OptionLocationPath OptionCode = 8
OptionURIPath OptionCode = 11
OptionContentFormat OptionCode = 12
OptionMaxAge OptionCode = 14
OptionURIQuery OptionCode = 15
OptionAccept OptionCode = 17
OptionLocationQuery OptionCode = 20
OptionBlock2 OptionCode = 23
OptionBlock1 OptionCode = 27
OptionSize2 OptionCode = 28
OptionProxyURI OptionCode = 35
OptionProxyScheme OptionCode = 39
OptionSize1 OptionCode = 60
)
// CoapCode defines a valid CoAP Code Type
type CoapCode uint8
const (
Get CoapCode = 1
Post CoapCode = 2
Put CoapCode = 3
Delete CoapCode = 4
// 2.x
CoapCodeEmpty CoapCode = 0
CoapCodeCreated CoapCode = 65 // 2.01
CoapCodeDeleted CoapCode = 66 // 2.02
CoapCodeValid CoapCode = 67 // 2.03
CoapCodeChanged CoapCode = 68 // 2.04
CoapCodeContent CoapCode = 69 // 2.05
CoapCodeContinue CoapCode = 95 // 2.31
// 4.x
CoapCodeBadRequest CoapCode = 128 // 4.00
CoapCodeUnauthorized CoapCode = 129 // 4.01
CoapCodeBadOption CoapCode = 130 // 4.02
CoapCodeForbidden CoapCode = 131 // 4.03
CoapCodeNotFound CoapCode = 132 // 4.04
CoapCodeMethodNotAllowed CoapCode = 133 // 4.05
CoapCodeNotAcceptable CoapCode = 134 // 4.06
CoapCodeRequestEntityIncomplete CoapCode = 136 // 4.08
CoapCodeConflict CoapCode = 137 // 4.09
CoapCodePreconditionFailed CoapCode = 140 // 4.12
CoapCodeRequestEntityTooLarge CoapCode = 141 // 4.13
CoapCodeUnsupportedContentFormat CoapCode = 143 // 4.15
// 5.x
CoapCodeInternalServerError CoapCode = 160 // 5.00
CoapCodeNotImplemented CoapCode = 161 // 5.01
CoapCodeBadGateway CoapCode = 162 // 5.02
CoapCodeServiceUnavailable CoapCode = 163 // 5.03
CoapCodeGatewayTimeout CoapCode = 164 // 5.04
CoapCodeProxyingNotSupported CoapCode = 165 // 5.05
)
const DefaultAckTimeout = 2
const DefaultAckRandomFactor = 1.5
const DefaultMaxRetransmit = 4
const DefaultNStart = 1
const DefaultLeisure = 5
const DefaultProbingRate = 1
const CoapDefaultHost = ""
const CoapDefaultPort = 5683
const CoapsDefaultPort = 5684
const PayloadMarker = 0xff
const MaxPacketSize = 1500
// MessageIDPurgeDuration defines the number of seconds before a MessageID Purge is initiated
const MessageIDPurgeDuration = 60
type RouteHandler func(Request) Response
// Proxy Filter
type ProxyFilter func(Message, net.Addr) bool
type ProxyHandler func(c CoapServer, msg Message, session Session)
type MediaType int
const (
MediaTypeTextPlain MediaType = 0
MediaTypeTextXML MediaType = 1
MediaTypeTextCsv MediaType = 2
MediaTypeTextHTML MediaType = 3
MediaTypeImageGif MediaType = 21
MediaTypeImageJpeg MediaType = 22
MediaTypeImagePng MediaType = 23
MediaTypeImageTiff MediaType = 24
MediaTypeAudioRaw MediaType = 25
MediaTypeVideoRaw MediaType = 26
MediaTypeApplicationLinkFormat MediaType = 40
MediaTypeApplicationXML MediaType = 41
MediaTypeApplicationOctetStream MediaType = 42
MediaTypeApplicationRdfXML MediaType = 43
MediaTypeApplicationSoapXML MediaType = 44
MediaTypeApplicationAtomXML MediaType = 45
MediaTypeApplicationXmppXML MediaType = 46
MediaTypeApplicationExi MediaType = 47
MediaTypeApplicationFastInfoSet MediaType = 48
MediaTypeApplicationSoapFastInfoSet MediaType = 49
MediaTypeApplicationJSON MediaType = 50
MediaTypeApplicationXObitBinary MediaType = 51
MediaTypeTextPlainVndOmaLwm2m MediaType = 1541
MediaTypeTlvVndOmaLwm2m MediaType = 1542
MediaTypeJSONVndOmaLwm2m MediaType = 1543
MediaTypeOpaqueVndOmaLwm2m MediaType = 1544
)
const (
MethodGet = "GET"
MethodPut = "PUT"
MethodPost = "POST"
MethodDelete = "DELETE"
MethodOptions = "OPTIONS"
MethodPatch = "PATCH"
)
type BlockSizeType byte
const (
BlockSize16 BlockSizeType = 0
BlockSize32 BlockSizeType = 1
BlockSize64 BlockSizeType = 2
BlockSize128 BlockSizeType = 3
BlockSize256 BlockSizeType = 4
BlockSize512 BlockSizeType = 5
BlockSize1024 BlockSizeType = 6
)
// Errors
var ErrPacketLengthLessThan4 = errors.New("Packet length less than 4 bytes")
var ErrInvalidCoapVersion = errors.New("Invalid CoAP version. Should be 1.")
var ErrOptionLengthUsesValue15 = errors.New(("Message format error. Option length has reserved value of 15"))
var ErrOptionDeltaUsesValue15 = errors.New(("Message format error. Option delta has reserved value of 15"))
var ErrUnknownMessageType = errors.New("Unknown message type")
var ErrInvalidTokenLength = errors.New("Invalid Token Length ( > 8)")
var ErrUnknownCriticalOption = errors.New("Unknown critical option encountered")
var ErrUnsupportedMethod = errors.New("Unsupported Method")
var ErrNoMatchingRoute = errors.New("No matching route found")
var ErrUnsupportedContentFormat = errors.New("Unsupported Content-Format")
var ErrNoMatchingMethod = errors.New("No matching method")
var ErrNilMessage = errors.New("Message is nil")
var ErrNilConn = errors.New("Connection object is nil")
var ErrNilAddr = errors.New("Address cannot be nil")
var ErrMessageSizeTooLongBlockOptionValNotSet = errors.New("Message is too long, block option or value not set")
// Security Options
const (
SecNoSec = "NoSec"
SecPreSharedKey = "PreSharedKey"
SecRawPublicKey = "RawPublicKey"
SecCertificate = "Certificate"
)
// Interfaces
type CoapServer interface {
ListenAndServe(addr string)
ListenAndServeDTLS(addr string)
Stop()
Get(path string, fn RouteHandler) Route
Delete(path string, fn RouteHandler) Route
Put(path string, fn RouteHandler) Route
Post(path string, fn RouteHandler) Route
Options(path string, fn RouteHandler) Route
Patch(path string, fn RouteHandler) Route
NewRoute(path string, method CoapCode, fn RouteHandler) Route
NotifyChange(resource, value string, confirm bool)
OnNotify(fn FnEventNotify)
OnStart(fn FnEventStart)
OnClose(fn FnEventClose)
OnDiscover(fn FnEventDiscover)
OnError(fn FnEventError)
OnObserve(fn FnEventObserve)
OnObserveCancel(fn FnEventObserveCancel)
OnMessage(fn FnEventMessage)
OnBlockMessage(fn FnEventBlockMessage)
ProxyOverHttp(enabled bool)
ProxyOverCoap(enabled bool)
GetEvents() Events
AllowProxyForwarding(Message, net.Addr) bool
GetRoutes() []Route
ForwardCoap(msg Message, session Session)
ForwardHTTP(msg Message, session Session)
AddObservation(resource, token string, session Session)
HasObservation(resource string, addr net.Addr) bool
RemoveObservation(resource string, addr net.Addr)
HandlePSK(func(id string) []byte)
GetSession(addr string) Session
DeleteSession(ssn Session)
GetCookieSecret() []byte
}
type ServerConnection interface {
ReadFrom(b []byte) (n int, addr net.Addr, err error)
WriteTo(b []byte, addr net.Addr) (n int, err error)
Close() error
LocalAddr() net.Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
}
type Option interface {
Name() string
IsElective() bool
IsCritical() bool
StringValue() string
IntValue() int
GetCode() OptionCode
GetValue() interface{}
}
type Session interface {
GetConnection() ServerConnection
GetAddress() net.Addr
Write([]byte) (int, error)
Read([]byte) (n int, err error)
GetServer() CoapServer
WriteBuffer([]byte) int
}
type Request interface {
GetAttributes() map[string]string
GetAttribute(o string) string
GetAttributeAsInt(o string) int
GetMessage() Message
GetURIQuery(q string) string
SetProxyURI(uri string)
SetMediaType(mt MediaType)
SetPayload([]byte)
SetStringPayload(s string)
SetRequestURI(uri string)
SetConfirmable(con bool)
SetToken(t string)
SetURIQuery(k string, v string)
}
type Response interface {
GetMessage() Message
GetError() error
GetPayload() []byte
GetURIQuery(q string) string
}
type Connection interface {
ObserveResource(resource string) (tok string, err error)
CancelObserveResource(resource string, token string) (err error)
StopObserve(ch chan ObserveMessage)
Observe(ch chan ObserveMessage)
Send(req Request) (resp Response, err error)
Write(b []byte) (n int, err error)
Read(b []byte) (n int, err error)
Close() error
}
// Represents the payload/content of a CoAP Message
type MessagePayload interface {
GetBytes() []byte
Length() int
String() string
}
type Message interface {
GetToken() []byte
GetMessageId() uint16
GetMessageType() uint8
GetAcceptedContent() MediaType
GetCodeString() string
GetCode() CoapCode
GetMethod() uint8
GetTokenLength() uint8
GetTokenString() string
GetOptions(id OptionCode) []Option
GetOption(id OptionCode) Option
GetAllOptions() []Option
GetOptionsAsString(id OptionCode) []string
GetLocationPath() string
GetURIPath() string
GetPayload() MessagePayload
SetToken([]byte)
SetMessageId(uint16)
SetMessageType(uint8)
SetBlock1Option(opt Option)
SetStringPayload(s string)
SetPayload(MessagePayload)
AddOption(code OptionCode, value interface{})
AddOptions(opts []Option)
CloneOptions(cm Message, opts ...OptionCode)
ReplaceOptions(code OptionCode, opts []Option)
RemoveOptions(id OptionCode)
}
type Route interface {
GetMethod() string
GetMediaTypes() []MediaType
GetConfiguredPath() string
Matches(path string) (bool, map[string]string)
AutoAcknowledge() bool
Handle(req Request) Response
}
type FnEventNotify func(string, interface{}, Message)
type FnEventStart func(CoapServer)
type FnEventClose func(CoapServer)
type FnEventDiscover func()
type FnEventError func(error)
type FnEventObserve func(string, Message)
type FnEventObserveCancel func(string, Message)
type FnEventMessage func(Message, bool)
type FnEventBlockMessage func(Message, bool)
type EventCode int
const (
EventStart EventCode = 0
EventClose EventCode = 1
EventDiscover EventCode = 2
EventMessage EventCode = 3
EventError EventCode = 4
EventObserve EventCode = 5
EventObserveCancel EventCode = 6
EventNotify EventCode = 7
)
type ObserveMessage interface {
GetResource() string
GetValue() interface{}
GetMessage() Message
}
type Events interface {
OnNotify(fn FnEventNotify)
OnStart(fn FnEventStart)
OnClose(fn FnEventClose)
OnDiscover(fn FnEventDiscover)
OnError(fn FnEventError)
OnObserve(fn FnEventObserve)
OnObserveCancel(fn FnEventObserveCancel)
OnMessage(fn FnEventMessage)
OnBlockMessage(fn FnEventBlockMessage)
Notify(resource string, value interface{}, msg Message)
Started(server CoapServer)
Closed(server CoapServer)
Discover()
Error(err error)
Observe(resource string, msg Message)
ObserveCancelled(resource string, msg Message)
Message(msg Message, inbound bool)
BlockMessage(msg Message, inbound bool)
}
type BlockMessage interface {
}
================================================
FILE: client.go
================================================
package canopus
import "net"
func Dial(address string) (conn Connection, err error) {
udpConn, err := net.Dial("udp", address)
if err != nil {
return
}
conn = &UDPConnection{
conn: udpConn,
}
return
}
func DialDTLS(address, identity, psk string) (conn Connection, err error) {
udpConn, err := net.Dial("udp", address)
if err != nil {
return
}
conn, err = NewDTLSConnection(udpConn, identity, psk)
if err != nil {
return
}
return
}
func NewObserveMessage(r string, val interface{}, msg Message) ObserveMessage {
return &CoapObserveMessage{
Resource: r,
Value: val,
Msg: msg,
}
}
type CoapObserveMessage struct {
CoapMessage
Resource string
Value interface{}
Msg Message
}
func (m *CoapObserveMessage) GetResource() string {
return m.Resource
}
func (m *CoapObserveMessage) GetValue() interface{} {
return m.Value
}
func (m *CoapObserveMessage) GetMessage() Message {
return m.GetMessage()
}
================================================
FILE: conn.go
================================================
package canopus
import (
"log"
"net"
"sync"
)
func MessageSizeAllowed(req Request) bool {
msg := req.GetMessage()
b, _ := MessageToBytes(msg)
if len(b) > 65536 {
return false
}
return true
}
type UDPConnection struct {
conn net.Conn
}
func (c *UDPConnection) ObserveResource(resource string) (tok string, err error) {
req := NewRequest(MessageConfirmable, Get)
req.SetRequestURI(resource)
req.GetMessage().AddOption(OptionObserve, 0)
resp, err := c.Send(req)
tok = string(resp.GetMessage().GetToken())
return
}
func (c *UDPConnection) CancelObserveResource(resource string, token string) (err error) {
req := NewRequest(MessageConfirmable, Get)
req.SetRequestURI(resource)
req.GetMessage().AddOption(OptionObserve, 1)
_, err = c.Send(req)
return
}
func (c *UDPConnection) StopObserve(ch chan ObserveMessage) {
close(ch)
}
func (c *UDPConnection) Close() error {
return c.conn.Close()
}
func (c *UDPConnection) Observe(ch chan ObserveMessage) {
readBuf := make([]byte, MaxPacketSize)
for {
len, err := c.Read(readBuf)
if err == nil {
msgBuf := make([]byte, len)
copy(msgBuf, readBuf)
msg, err := BytesToMessage(msgBuf)
if msg.GetOption(OptionObserve) != nil {
ch <- NewObserveMessage(msg.GetURIPath(), msg.GetPayload(), msg)
}
if err != nil {
log.Println("Error occured reading UDP", err)
close(ch)
}
} else {
log.Println("Error occured reading UDP", err)
close(ch)
}
}
}
func (c *UDPConnection) Send(req Request) (resp Response, err error) {
msg := req.GetMessage()
opt := msg.GetOption(OptionBlock1)
if opt == nil { // Block1 was not set
if MessageSizeAllowed(req) != true {
return nil, ErrMessageSizeTooLongBlockOptionValNotSet
}
} else { // Block1 was set
// log.Println("Block 1 was set")
}
if opt != nil {
blockOpt := Block1OptionFromOption(opt)
if blockOpt.Value == nil {
if MessageSizeAllowed(req) != true {
err = ErrMessageSizeTooLongBlockOptionValNotSet
return
} else {
// - Block # = one and only block (sz = unspecified), whereas 0 = 16bits
// - MOre bit = 0
}
} else { // BLock transfer request
payload := msg.GetPayload().GetBytes()
payloadLen := uint32(len(payload))
blockSize := blockOpt.BlockSizeLength()
currSeq := uint32(0)
totalBlocks := uint32(payloadLen / blockSize)
completed := false
var wg sync.WaitGroup
wg.Add(1)
for completed == false {
if currSeq <= totalBlocks {
var blockPayloadStart uint32
var blockPayloadEnd uint32
var blockPayload []byte
blockPayloadStart = currSeq * uint32(blockSize)
more := true
if currSeq == totalBlocks {
more = false
blockPayloadEnd = payloadLen
} else {
blockPayloadEnd = blockPayloadStart + uint32(blockSize)
}
blockPayload = payload[blockPayloadStart : blockPayloadEnd+1]
blockOpt = NewBlock1Option(blockOpt.Size(), more, currSeq)
msg.ReplaceOptions(blockOpt.Code, []Option{blockOpt})
modifiedMsg := msg.(*CoapMessage)
modifiedMsg.SetMessageId(GenerateMessageID())
modifiedMsg.SetPayload(NewBytesPayload(blockPayload))
// send message
_, err2 := c.SendMessage(msg)
if err2 != nil {
wg.Done()
return
}
currSeq = currSeq + 1
} else {
completed = true
wg.Done()
}
}
}
}
resp, err = c.SendMessage(msg)
return
}
func (c *UDPConnection) SendMessage(msg Message) (resp Response, err error) {
if msg == nil {
return nil, ErrNilMessage
}
b, err := MessageToBytes(msg)
if err != nil {
return
}
if msg.GetMessageType() == MessageNonConfirmable {
go c.Write(b)
resp = NewResponse(NewEmptyMessage(msg.GetMessageId()), nil)
return
}
_, err = c.Write(b)
if err != nil {
return
}
msgBuf := make([]byte, 1500)
if msg.GetMessageType() == MessageAcknowledgment {
resp = NewResponse(NewEmptyMessage(msg.GetMessageId()), nil)
return
}
n, err := c.Read(msgBuf)
if err != nil {
return
}
respMsg, err := BytesToMessage(msgBuf[:n])
if err != nil {
return
}
resp = NewResponse(respMsg, nil)
if msg.GetMessageType() == MessageConfirmable {
// TODO: Send out message and wait for a confirm. If confirmation not retrieved,
// resend (taking into account timeouts and back-off transmissions
// c.Send(NewRequestFromMessage(msg))
}
return
}
func (c *UDPConnection) Write(b []byte) (int, error) {
return c.conn.Write(b)
}
func (c *UDPConnection) Read(b []byte) (int, error) {
return c.conn.Read(b)
}
================================================
FILE: corelink.go
================================================
package canopus
// Represents a message payload containing core-link format values
type CoreLinkFormatPayload struct {
}
func (p *CoreLinkFormatPayload) GetBytes() []byte {
return make([]byte, 0)
}
func (p *CoreLinkFormatPayload) Length() int {
return 0
}
func (p *CoreLinkFormatPayload) String() string {
return ""
}
================================================
FILE: coreresource.go
================================================
package canopus
// Instantiates a new core-attribute with a given key/value
func NewCoreAttribute(key string, value interface{}) *CoreAttribute {
return &CoreAttribute{
Key: key,
Value: value,
}
}
// Instantiates a new Core Resource Object
func NewCoreResource() *CoreResource {
c := &CoreResource{}
return c
}
================================================
FILE: coreresource_test.go
================================================
package canopus
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCoreResourceParsing(t *testing.T) {
cases1 := []struct {
in string
elemCount int
targets []string
attrCount []int
attributes []map[string]string
}{
{
"</1>,</2>,</3>,</4>,</5/0>,</5/1>,</5/2>,</5/3>",
8,
[]string{"/1", "/2", "/3", "/4", "/5/0", "/5/1", "/5/2", "/5/3"},
[]int{0, 0, 0, 0, 0, 0, 0, 0, 0},
nil,
},
{
"</sensors>;ct=40;title=\"Sensor Index\",</sensors/temp>;rt=\"temperature-c\";if=\"sensor\",</sensors/light>;rt=\"light-lux\";if=\"sensor\",<http://www.example.com/sensors/t123>;anchor=\"/sensors/temp\";rel=\"describedby\",</t>;anchor=\"/sensors/temp\";rel=\"alternate\"",
5,
[]string{"/sensors", "/sensors/temp", "/sensors/light", "http://www.example.com/sensors/t123", "/t"},
[]int{1, 2, 2, 2, 2},
[]map[string]string{
map[string]string{
"ct": "40",
"title": "Sensor Index",
},
map[string]string{
"rt": "temperature-c",
"if": "sensor",
},
map[string]string{
"rt": "light-lux",
"if": "sensor",
},
map[string]string{
"anchor": "/sensors/temp",
"rel": "describedby",
},
map[string]string{
"anchor": "/sensors/temp",
"rel": "alternate",
},
},
},
}
for _, c := range cases1 {
resources := CoreResourcesFromString(c.in)
assert.Equal(t, len(resources), c.elemCount)
for i, o := range resources {
assert.Equal(t, o.Target, c.targets[i])
for _, a := range o.Attributes {
key := a.Key
val := a.Value
assert.Equal(t, c.attributes[i][key], val)
}
}
}
}
================================================
FILE: dtls.go
================================================
package canopus
/*
#cgo LDFLAGS: -L${SRCDIR}/openssl -lssl -lcrypto -ldl
#cgo CFLAGS: -g -Wno-deprecated -Wno-error -I${SRCDIR}/openssl/include -Wno-incompatible-pointer-types -Wno-return-type
#include <stdlib.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <internal/bio.h>
extern int go_session_bio_write(BIO* bio, char* buf, int num);
extern int go_session_bio_read(BIO* bio, char* buf, int num);
extern int go_session_bio_free(BIO* bio);
extern unsigned int go_server_psk_callback(SSL *ssl, char *identity, char *psk, unsigned int max_psk_len);
extern int generate_cookie_callback(SSL* ssl, unsigned char* cookie, unsigned int *cookie_len);
extern int verify_cookie_callback(SSL* ssl, unsigned char* cookie, unsigned int cookie_len);
static long go_session_bio_ctrl(BIO *bp,int cmd,long larg,void *parg) {
return 1;
}
static int write_wrapper(BIO* bio, char* data, int n) {
return go_session_bio_write(bio,data,n);
}
static int go_session_bio_create( BIO *b ) {
BIO_set_init(b,1);
BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_WRITE);
return 1;
}
// a BIO for a client conencted to our server
static BIO_METHOD* go_session_bio_method;
static BIO_METHOD* BIO_go_session() {
return go_session_bio_method;
}
static void set_errno(int e) {
errno = e;
}
static char *getGoData(BIO* bio) {
return BIO_get_data(bio);
}
static unsigned int server_psk_callback(SSL *ssl, char *identity, unsigned char *psk, unsigned int max_psk_len) {
return go_server_psk_callback(ssl,identity,(char*)psk,max_psk_len);
}
static void init_lib() {
setvbuf(stdout, NULL, _IOLBF, 0);
SSL_library_init();
ERR_load_BIO_strings();
SSL_load_error_strings();
}
static int init_session_bio_method() {
go_session_bio_method = BIO_meth_new(BIO_TYPE_SOURCE_SINK,"go session dtls");
BIO_meth_set_write(go_session_bio_method,write_wrapper);
BIO_meth_set_read(go_session_bio_method,go_session_bio_read);
BIO_meth_set_ctrl(go_session_bio_method,go_session_bio_ctrl);
BIO_meth_set_create(go_session_bio_method,go_session_bio_create);
BIO_meth_set_destroy(go_session_bio_method,go_session_bio_free);
}
static void init_server_ctx(SSL_CTX *ctx) {
SSL_CTX_set_min_proto_version(ctx, 0xFEFD); // 1.2
SSL_CTX_set_max_proto_version(ctx, 0xFEFD); // 1.2
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, &generate_cookie_callback);
SSL_CTX_set_cookie_verify_cb(ctx, &verify_cookie_callback);
}
static int get_errno(void) {
return errno;
}
static void setGoData(BIO* bio, char *data) {
BIO_set_data(bio, data);
}
static void set_cookie_option(SSL *ssl) {
SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
}
static void set_psk_callback(SSL *ssl) {
SSL_set_psk_server_callback(ssl, &server_psk_callback);
}
static void setGoSessionId(BIO* bio, unsigned int clientId) {
unsigned int * pId = malloc(sizeof(unsigned int));
*pId = clientId;
BIO_set_data(bio,pId);
}
// Client
extern int go_conn_bio_write(BIO* bio, char* buf, int num);
extern int go_conn_bio_read(BIO* bio, char* buf, int num);
extern int go_conn_bio_free(BIO* bio);
extern unsigned int go_psk_callback(SSL *ssl, char *hint, char *identity, unsigned int max_identity_len, char *psk, unsigned int max_psk_len);
static long go_bio_ctrl(BIO *bp,int cmd,long larg,void *parg) {
//always return operation not supported
//http://www.openssl.org/docs/crypto/BIO_ctrl.html
//printf("go_bio_ctrl %d\n", cmd);
return 1;
}
static int go_bio_create( BIO *b ) {
BIO_set_init(b,1);
//BIO_set_num(b,-1);
//BIO_set_ptr(b,NULL);
BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_WRITE);
return 1;
}
static BIO_METHOD go_bio_method = {
BIO_TYPE_SOURCE_SINK,
"go dtls",
(int (*)(BIO *, const char *, int))go_conn_bio_write,
go_conn_bio_read,
NULL,
NULL,
go_bio_ctrl, // ctrl
go_bio_create, // new
go_conn_bio_free // delete
};
static BIO_METHOD* BIO_go() {
return &go_bio_method;
}
static void set_proto_1_2(SSL_CTX *ctx) {
SSL_CTX_set_min_proto_version(ctx, 0xFEFD); // 1.2
SSL_CTX_set_max_proto_version(ctx, 0xFEFD); // 1.2
}
static unsigned int psk_callback(SSL *ssl, const char *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len) {
return go_psk_callback(ssl,hint,identity,max_identity_len,(char*)psk,max_psk_len);
}
static void init_ctx(SSL_CTX *ctx) {
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_psk_client_callback(ctx,&psk_callback);
}
static void setGoClientId(BIO* bio, unsigned int clientId) {
unsigned int * pId = malloc(sizeof(unsigned int));
*pId = clientId;
BIO_set_data(bio,pId);
}
*/
import "C"
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"io"
"net"
"reflect"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
func init() {
// low level init of OpenSSL
C.init_lib()
// init server BIO
server_bio_method_init()
}
func server_bio_method_init() {
C.init_session_bio_method()
}
func NewServerDtlsContext() (ctx *ServerDtlsContext, err error) {
sslCtx := C.SSL_CTX_new(C.DTLSv1_2_server_method())
if sslCtx == nil {
err = errors.New("error creating SSL context")
return
}
C.init_server_ctx(sslCtx)
ret := int(C.SSL_CTX_set_cipher_list(sslCtx, C.CString("PSK-AES256-CCM8:PSK-AES128-CCM8")))
if ret != 1 {
err = errors.New("impossible to set cipherlist")
}
ctx = &ServerDtlsContext{
sslCtx: sslCtx,
}
return
}
type ServerDtlsContext struct {
sslCtx *C.SSL_CTX
}
//export go_session_bio_read
func go_session_bio_read(bio *C.BIO, buf *C.char, num C.int) C.int {
session := DTLS_SERVER_SESSIONS[*(*int32)(C.BIO_get_data(bio))]
socketData := <-session.rcvd
data := goSliceFromCString(buf, int(num))
if data == nil {
return 0
}
wrote := copy(data, socketData)
return C.int(wrote)
}
//export go_session_bio_write
func go_session_bio_write(bio *C.BIO, buf *C.char, num C.int) C.int {
session := DTLS_SERVER_SESSIONS[*(*int32)(C.BIO_get_data(bio))]
data := goSliceFromCString(buf, int(num))
n, err := session.GetConnection().WriteTo(data, session.GetAddress())
if err != nil && err != io.EOF {
//We expect either a syscall error
//or a netOp error wrapping a syscall error
TESTERR:
switch err.(type) {
case syscall.Errno:
C.set_errno(C.int(err.(syscall.Errno)))
case *net.OpError:
err = err.(*net.OpError).Err
break TESTERR
}
return C.int(-1)
}
return C.int(n)
}
//export go_session_bio_free
func go_session_bio_free(bio *C.BIO) C.int {
// TODO
// some flags magic
if C.int(C.BIO_get_shutdown(bio)) != 0 {
C.BIO_set_data(bio, nil)
C.BIO_set_flags(bio, 0)
C.BIO_set_init(bio, 0)
}
return C.int(1)
}
//export go_server_psk_callback
func go_server_psk_callback(ssl *C.SSL, identity *C.char, psk *C.char, max_psk_len C.uint) C.uint {
bio := C.SSL_get_rbio(ssl)
session := DTLS_SERVER_SESSIONS[*(*int32)(C.BIO_get_data(bio))]
server := session.GetServer().(*DefaultCoapServer)
goPskID := C.GoString(identity)
serverPsk := server.fnPskHandler(goPskID)
if serverPsk == nil {
return 0
}
if len(serverPsk) >= int(max_psk_len) {
return 0
}
targetPsk := goSliceFromCString(psk, int(max_psk_len))
return C.uint(copy(targetPsk, serverPsk))
}
//export generate_cookie_callback
func generate_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len *C.uint) C.int {
bio := C.SSL_get_rbio(ssl)
session := DTLS_SERVER_SESSIONS[*(*int32)(C.BIO_get_data(bio))]
mac := hmac.New(sha256.New, session.GetServer().GetCookieSecret())
mac.Write([]byte(session.GetAddress().String()))
cookieValue := mac.Sum(nil)
if len(cookieValue) >= int(*cookie_len) {
logMsg("Not enough cookie space (should not happen..)")
return 0
}
data := goSliceFromUCString(cookie, int(*cookie_len))
*cookie_len = C.uint(copy(data, cookieValue))
return 1
}
//export verify_cookie_callback
func verify_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len C.uint) C.int {
bio := C.SSL_get_rbio(ssl)
session := DTLS_SERVER_SESSIONS[*(*int32)(C.BIO_get_data(bio))]
mac := hmac.New(sha256.New, session.GetServer().GetCookieSecret())
mac.Write([]byte(session.GetAddress().String()))
cookieValue := mac.Sum(nil)
if len(cookieValue) != int(cookie_len) {
return 0
}
data := goSliceFromUCString(cookie, int(cookie_len))
if bytes.Equal(data, cookieValue) {
return 1
} else {
return 0
}
}
// Provides a zero copy interface for returning a go slice backed by a c array.
func goSliceFromCString(cArray *C.char, size int) (cslice []byte) {
//See http://code.google.com/p/go-wiki/wiki/cgo
//It turns out it's really easy to
//make a string from a *C.char and vise versa.
//not so easy to write to a c array.
sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&cslice)))
sliceHeader.Cap = size
sliceHeader.Len = size
sliceHeader.Data = uintptr(unsafe.Pointer(cArray))
return
}
// Provides a zero copy interface for returning a go slice backed by a c array.
func goSliceFromUCString(cArray *C.uchar, size int) (cslice []byte) {
//See http://code.google.com/p/go-wiki/wiki/cgo
//It turns out it's really easy to
//make a string from a *C.char and vise versa.
//not so easy to write to a c array.
sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&cslice)))
sliceHeader.Cap = size
sliceHeader.Len = size
sliceHeader.Data = uintptr(unsafe.Pointer(cArray))
return
}
func getErrorString(code C.ulong) string {
if code == 0 {
return ""
}
msg := fmt.Sprintf("%s:%s:%s\n",
C.GoString(C.ERR_lib_error_string(code)),
C.GoString(C.ERR_func_error_string(code)),
C.GoString(C.ERR_reason_error_string(code)))
if len(msg) == 4 { //being lazy here, all the strings were empty
return ""
}
//Check for extra line data
var file *C.char
var line C.int
var data *C.char
var flags C.int
if int(C.ERR_get_error_line_data(&file, &line, &data, &flags)) != 0 {
msg += fmt.Sprintf("%s:%s", C.GoString(file), int(line))
if flags&C.ERR_TXT_STRING != 0 {
msg += ":" + C.GoString(data)
}
if flags&C.ERR_TXT_MALLOCED != 0 {
C.CRYPTO_free(unsafe.Pointer(data), C.CString(""), 0)
}
}
return msg
}
func newSslSession(session *DTLSServerSession, ctx *ServerDtlsContext, pskCallback func(id string) []byte) (err error) {
ssl := C.SSL_new(ctx.sslCtx)
id := atomic.AddInt32(&NEXT_SESSION_ID, 1)
if pskCallback != nil {
C.set_psk_callback(ssl)
}
bio := C.BIO_new(C.BIO_go_session())
if bio == nil {
err = errors.New("Error creating session: Bio is nil")
return
}
C.SSL_set_bio(ssl, bio, bio)
session.ssl = ssl
session.bio = bio
DTLS_SERVER_SESSIONS[id] = session
C.setGoSessionId(bio, C.uint(id))
C.set_cookie_option(ssl)
C.SSL_set_accept_state(ssl)
C.DTLSv1_listen
return
}
type DTLSServerSession struct {
UDPServerSession
ssl *C.SSL
bio *C.BIO
}
func (s *DTLSServerSession) GetConnection() ServerConnection {
return s.conn
}
func (s *DTLSServerSession) Write(b []byte) (int, error) {
// TODO test is connected ?
length := len(b)
ret := C.SSL_write(s.ssl, unsafe.Pointer(&b[0]), C.int(length))
if err := s.getError(ret); err != nil {
return 0, err
}
return int(ret), nil
}
func (s *DTLSServerSession) Read(b []byte) (n int, err error) {
// TODO test if closed?
length := len(b)
// s.rcvd <- s.buf
ret := C.SSL_read(s.ssl, unsafe.Pointer(&b[0]), C.int(length))
if err = s.getError(ret); err != nil {
n = 0
return
}
// if there's no error, but a return value of 0
// let's say it's an EOF
if ret == 0 {
n = 0
err = io.EOF
return
}
n = int(ret)
return
}
func (s *DTLSServerSession) getError(ret C.int) error {
err := C.SSL_get_error(s.ssl, ret)
switch err {
case C.SSL_ERROR_NONE:
return nil
case C.SSL_ERROR_ZERO_RETURN:
return io.EOF
case C.SSL_ERROR_SYSCALL:
if int(C.ERR_peek_error()) != 0 {
return syscall.Errno(C.get_errno())
}
default:
msg := ""
for {
errCode := C.ERR_get_error()
if errCode == 0 {
break
}
msg += getErrorString(errCode)
}
C.ERR_clear_error()
return errors.New(msg)
}
return nil
}
// Client DTLS
func NewDTLSConnection(c net.Conn, identity, psk string) (conn Connection, err error) {
sslCtx := C.SSL_CTX_new(C.DTLSv1_2_client_method())
C.set_proto_1_2(sslCtx)
C.init_ctx(sslCtx)
ret := int(C.SSL_CTX_set_cipher_list(sslCtx, C.CString("PSK-AES256-CCM8:PSK-AES128-CCM8")))
if ret != 1 {
err = errors.New("impossible to set cipherlist")
return
}
ssl := C.SSL_new(sslCtx)
// self := DTLSClient{false, 0, C.BIO_new(C.BIO_go()), dtlsCtx.ctx, ssl, conn, nil, nil}
bio := C.BIO_new(C.BIO_go())
conn = &DTLSConnection{
UDPConnection: UDPConnection{
conn: c,
},
sslCtx: sslCtx,
ssl: ssl,
bio: bio,
psk: []byte(psk),
pskId: &identity,
}
C.SSL_set_bio(ssl, bio, bio)
id := atomic.AddInt32(&NEXT_SESSION_ID, 1)
C.setGoClientId(bio, C.uint(id))
DTLS_CLIENT_CONNECTIONS[id] = conn.(*DTLSConnection)
return
}
type DTLSConnection struct {
UDPConnection
closed bool
connected int32 // connection handshake was done, atomic (0 false, 1 true)
sslCtx *C.SSL_CTX
bio *C.BIO
ssl *C.SSL
pskId *string
psk []byte
}
func (c *DTLSConnection) ObserveResource(resource string) (tok string, err error) {
req := NewRequest(MessageConfirmable, Get)
req.SetRequestURI(resource)
req.GetMessage().AddOption(OptionObserve, 0)
resp, err := c.Send(req)
tok = string(resp.GetMessage().GetToken())
return
}
func (c *DTLSConnection) CancelObserveResource(resource string, token string) (err error) {
req := NewRequest(MessageConfirmable, Get)
req.SetRequestURI(resource)
req.GetMessage().AddOption(OptionObserve, 1)
_, err = c.Send(req)
return
}
func (c *DTLSConnection) StopObserve(ch chan ObserveMessage) {
close(ch)
}
func (c *DTLSConnection) Observe(ch chan ObserveMessage) {
readBuf := make([]byte, MaxPacketSize)
for {
len, err := c.Read(readBuf)
if err == nil {
msgBuf := make([]byte, len)
copy(msgBuf, readBuf)
msg, err := BytesToMessage(msgBuf)
if msg.GetOption(OptionObserve) != nil {
ch <- NewObserveMessage(msg.GetURIPath(), msg.GetPayload(), msg)
}
if err != nil {
logMsg("Error occured reading UDP", err)
close(ch)
}
} else {
logMsg("Error occured reading UDP", err)
close(ch)
}
}
}
func (c *DTLSConnection) Send(req Request) (resp Response, err error) {
msg := req.GetMessage()
opt := msg.GetOption(OptionBlock1)
if opt == nil { // Block1 was not set
if MessageSizeAllowed(req) != true {
return nil, ErrMessageSizeTooLongBlockOptionValNotSet
}
} else { // Block1 was set
// fmt.Println("Block 1 was set")
}
if opt != nil {
blockOpt := Block1OptionFromOption(opt)
if blockOpt.Value == nil {
if MessageSizeAllowed(req) != true {
err = ErrMessageSizeTooLongBlockOptionValNotSet
return
} else {
// - Block # = one and only block (sz = unspecified), whereas 0 = 16bits
// - MOre bit = 0
}
} else { // BLock transfer request
payload := msg.GetPayload().GetBytes()
payloadLen := uint32(len(payload))
blockSize := blockOpt.BlockSizeLength()
currSeq := uint32(0)
totalBlocks := uint32(payloadLen / blockSize)
completed := false
var wg sync.WaitGroup
wg.Add(1)
for completed == false {
if currSeq <= totalBlocks {
var blockPayloadStart uint32
var blockPayloadEnd uint32
var blockPayload []byte
blockPayloadStart = currSeq*uint32(blockSize) + (currSeq * 1)
more := true
if currSeq == totalBlocks {
more = false
blockPayloadEnd = payloadLen
} else {
blockPayloadEnd = blockPayloadStart + uint32(blockSize)
}
blockPayload = payload[blockPayloadStart:blockPayloadEnd]
blockOpt = NewBlock1Option(blockOpt.Size(), more, currSeq)
msg.ReplaceOptions(blockOpt.Code, []Option{blockOpt})
modifiedMsg := msg.(*CoapMessage)
modifiedMsg.SetMessageId(GenerateMessageID())
modifiedMsg.SetPayload(NewBytesPayload(blockPayload))
// send message
_, err2 := c.sendMessage(msg)
if err2 != nil {
wg.Done()
return
}
currSeq = currSeq + 1
} else {
completed = true
wg.Done()
}
}
}
}
resp, err = c.sendMessage(msg)
return
}
func (c *DTLSConnection) sendMessage(msg Message) (resp Response, err error) {
if msg == nil {
return nil, ErrNilMessage
}
b, err := MessageToBytes(msg)
if err != nil {
return
}
if msg.GetMessageType() == MessageNonConfirmable {
go c.Write(b)
resp = NewResponse(NewEmptyMessage(msg.GetMessageId()), nil)
return
}
_, err = c.Write(b)
if err != nil {
return
}
msgBuf := make([]byte, 1500)
if msg.GetMessageType() == MessageAcknowledgment {
resp = NewResponse(NewEmptyMessage(msg.GetMessageId()), nil)
return
}
n, err := c.Read(msgBuf)
if err != nil {
return
}
respMsg, err := BytesToMessage(msgBuf[:n])
if err != nil {
return
}
resp = NewResponse(respMsg, nil)
if msg.GetMessageType() == MessageConfirmable {
// TODO: Send out message and wait for a confirm. If confirmation not retrieved,
// resend (taking into account timeouts and back-off transmissions
// c.Send(NewRequestFromMessage(msg))
}
return
}
func (c *DTLSConnection) Write(b []byte) (int, error) {
if atomic.CompareAndSwapInt32(&c.connected, 0, 1) {
if err := c.connect(); err != nil {
return 0, err
}
}
length := len(b)
ret := C.SSL_write(c.ssl, unsafe.Pointer(&b[0]), C.int(length))
if err := c.getError(ret); err != nil {
return 0, err
}
return int(ret), nil
}
func (c *DTLSConnection) Read(b []byte) (int, error) {
if atomic.CompareAndSwapInt32(&c.connected, 0, 1) {
if err := c.connect(); err != nil {
return 0, err
}
}
length := len(b)
ret := C.SSL_read(c.ssl, unsafe.Pointer(&b[0]), C.int(length))
if err := c.getError(ret); err != nil {
return 0, err
}
// if there's no error, but a return value of 0
// let's say it's an EOF
if ret == 0 {
return 0, io.EOF
}
return int(ret), nil
}
func (c *DTLSConnection) Close() error {
if c.closed {
return nil
}
c.closed = true
defer func() {
C.SSL_free(c.ssl)
}()
ret := C.SSL_shutdown(c.ssl)
if int(ret) == 0 {
ret = C.SSL_shutdown(c.ssl)
if int(ret) != 1 {
return c.getError(ret)
}
}
return nil
}
func (c *DTLSConnection) connect() error {
ret := C.SSL_connect(c.ssl)
if err := c.getError(ret); err != nil {
return err
}
return nil
}
func (c *DTLSConnection) getError(ret C.int) error {
err := C.SSL_get_error(c.ssl, ret)
switch err {
case C.SSL_ERROR_NONE:
return nil
case C.SSL_ERROR_ZERO_RETURN:
return io.EOF
case C.SSL_ERROR_SYSCALL:
if int(C.ERR_peek_error()) != 0 {
return syscall.Errno(C.get_errno())
}
default:
msg := ""
for {
errCode := C.ERR_get_error()
if errCode == 0 {
break
}
msg += getErrorString(errCode)
}
C.ERR_clear_error()
return errors.New(msg)
}
return nil
}
//export go_conn_bio_write
func go_conn_bio_write(bio *C.BIO, buf *C.char, num C.int) C.int {
client := DTLS_CLIENT_CONNECTIONS[*(*int32)(C.BIO_get_data(bio))]
data := goSliceFromCString(buf, int(num))
n, err := client.conn.Write(data)
if err != nil && err != io.EOF {
//We expect either a syscall error
//or a netOp error wrapping a syscall error
TESTERR:
switch err.(type) {
case syscall.Errno:
C.set_errno(C.int(err.(syscall.Errno)))
case *net.OpError:
err = err.(*net.OpError).Err
break TESTERR
}
return C.int(-1)
}
return C.int(n)
}
//export go_conn_bio_read
func go_conn_bio_read(bio *C.BIO, buf *C.char, num C.int) C.int {
client := DTLS_CLIENT_CONNECTIONS[*(*int32)(C.BIO_get_data(bio))]
data := goSliceFromCString(buf, int(num))
n, err := client.conn.Read(data)
if err == nil {
return C.int(n)
}
if err == io.EOF || err == io.ErrUnexpectedEOF {
return 0
}
//We expect either a syscall error
//or a netOp error wrapping a syscall error
TESTERR:
switch err.(type) {
case syscall.Errno:
C.set_errno(C.int(err.(syscall.Errno)))
case *net.OpError:
err = err.(*net.OpError).Err
break TESTERR
}
return C.int(-1)
}
//export go_conn_bio_free
func go_conn_bio_free(bio *C.BIO) C.int {
client := DTLS_CLIENT_CONNECTIONS[*(*int32)(C.BIO_get_data(bio))]
client.Close()
if C.int(C.BIO_get_shutdown(bio)) != 0 {
C.BIO_set_data(bio, nil)
C.BIO_set_flags(bio, 0)
C.BIO_set_init(bio, 0)
}
return C.int(1)
}
//export go_psk_callback
func go_psk_callback(ssl *C.SSL, hint *C.char, identity *C.char, max_identity_len C.uint, psk *C.char, max_psk_len C.uint) C.uint {
bio := C.SSL_get_rbio(ssl)
client := DTLS_CLIENT_CONNECTIONS[*(*int32)(C.BIO_get_data(bio))]
if client.pskId == nil || client.psk == nil {
return 0
}
if len(*client.pskId) >= int(max_identity_len) || len(client.psk) >= int(max_psk_len) {
logMsg("PSKID or PSK too large")
return 0
}
targetId := goSliceFromCString(identity, int(max_identity_len))
copy(targetId, *client.pskId)
targetPsk := goSliceFromCString(psk, int(max_psk_len))
return C.uint(copy(targetPsk, client.psk))
}
================================================
FILE: empty.go
================================================
package canopus
func NewEmptyPayload() MessagePayload {
return &EmptyPayload{}
}
// Represents an empty message payload
type EmptyPayload struct {
}
func (p *EmptyPayload) GetBytes() []byte {
return []byte{}
}
func (p *EmptyPayload) Length() int {
return 0
}
func (p *EmptyPayload) String() string {
return ""
}
================================================
FILE: event.go
================================================
package canopus
func NewEvents() *ServerEvents {
return &ServerEvents{
evtFnNotify: []FnEventNotify{},
evtFnStart: []FnEventStart{},
evtFnClose: []FnEventClose{},
evtFnDiscover: []FnEventDiscover{},
evtFnError: []FnEventError{},
evtFnObserve: []FnEventObserve{},
evtFnObserveCancel: []FnEventObserveCancel{},
evtFnMessage: []FnEventMessage{},
evtFnBlockMessage: []FnEventBlockMessage{},
}
}
// This holds the various events which are triggered throughout
// an application's lifetime
type ServerEvents struct {
evtFnNotify []FnEventNotify
evtFnStart []FnEventStart
evtFnClose []FnEventClose
evtFnDiscover []FnEventDiscover
evtFnError []FnEventError
evtFnObserve []FnEventObserve
evtFnObserveCancel []FnEventObserveCancel
evtFnMessage []FnEventMessage
evtFnBlockMessage []FnEventBlockMessage
}
// OnNotify is Fired when an observeed resource is notified
func (ce *ServerEvents) OnNotify(fn FnEventNotify) {
ce.evtFnNotify = append(ce.evtFnNotify, fn)
}
// Fired when the server/client starts up
func (ce *ServerEvents) OnStart(fn FnEventStart) {
ce.evtFnStart = append(ce.evtFnStart, fn)
}
// Fired when the server/client closes
func (ce *ServerEvents) OnClose(fn FnEventClose) {
ce.evtFnClose = append(ce.evtFnClose, fn)
}
// Fired when a discovery request is triggered
func (ce *ServerEvents) OnDiscover(fn FnEventDiscover) {
ce.evtFnDiscover = append(ce.evtFnDiscover, fn)
}
// Catch-all event which is fired when an error occurs
func (ce *ServerEvents) OnError(fn FnEventError) {
ce.evtFnError = append(ce.evtFnError, fn)
}
// Fired when an observe request is triggered for a resource
func (ce *ServerEvents) OnObserve(fn FnEventObserve) {
ce.evtFnObserve = append(ce.evtFnObserve, fn)
}
// Fired when an observe-cancel request is triggered foa r esource
func (ce *ServerEvents) OnObserveCancel(fn FnEventObserveCancel) {
ce.evtFnObserveCancel = append(ce.evtFnObserveCancel, fn)
}
// Fired when a message is received
func (ce *ServerEvents) OnMessage(fn FnEventMessage) {
ce.evtFnMessage = append(ce.evtFnMessage, fn)
}
// Fired when a block messageis received
func (ce *ServerEvents) OnBlockMessage(fn FnEventBlockMessage) {
ce.evtFnBlockMessage = append(ce.evtFnBlockMessage, fn)
}
// Fires the "OnNotify" event
func (ce *ServerEvents) Notify(resource string, value interface{}, msg Message) {
for _, fn := range ce.evtFnNotify {
fn(resource, value, msg)
}
}
// Fires the "OnStarted" event
func (ce *ServerEvents) Started(server CoapServer) {
for _, fn := range ce.evtFnStart {
fn(server)
}
}
// Fires the "OnClosed" event
func (ce *ServerEvents) Closed(server CoapServer) {
for _, fn := range ce.evtFnClose {
fn(server)
}
}
// Fires the "OnDiscover" event
func (ce *ServerEvents) Discover() {
for _, fn := range ce.evtFnDiscover {
fn()
}
}
// Fires the "OnError" event given an error object
func (ce *ServerEvents) Error(err error) {
for _, fn := range ce.evtFnError {
fn(err)
}
}
// Fires the "OnObserve" event for a given resource
func (ce *ServerEvents) Observe(resource string, msg Message) {
for _, fn := range ce.evtFnObserve {
fn(resource, msg)
}
}
// Fires the "OnObserveCancelled" event for a given resource
func (ce *ServerEvents) ObserveCancelled(resource string, msg Message) {
for _, fn := range ce.evtFnObserveCancel {
fn(resource, msg)
}
}
// Fires the "OnMessage" event. The 'inbound' variables determines if the
// message is inbound or outgoing
func (ce *ServerEvents) Message(msg Message, inbound bool) {
for _, fn := range ce.evtFnMessage {
fn(msg, inbound)
}
}
// Fires the "OnBlockMessage" event. The 'inbound' variables determines if the
// message is inbound or outgoing
func (ce *ServerEvents) BlockMessage(msg Message, inbound bool) {
for _, fn := range ce.evtFnBlockMessage {
fn(msg, inbound)
}
}
================================================
FILE: event_test.go
================================================
package canopus
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestEvents(t *testing.T) {
events := NewEvents()
assert.NotNil(t, events)
// OnNotify
evtOnNotifyCalled := false
events.OnNotify(func(string, interface{}, Message) {
evtOnNotifyCalled = true
})
events.Notify("/test", "", nil)
// OnStarted
evtOnStartedCalled := false
events.OnStart(func(CoapServer) {
evtOnStartedCalled = true
})
events.Started(nil)
// OnClosed
evtOnClosedCalled := false
events.OnClose(func(CoapServer) {
evtOnClosedCalled = true
})
events.Closed(nil)
// OnDiscover
evtOnDiscoverCalled := false
events.OnDiscover(func() {
evtOnDiscoverCalled = true
})
events.Discover()
// OnError
evtOnErrorCalled := false
events.OnError(func(error) {
evtOnErrorCalled = true
})
events.Error(errors.New("An error occured"))
// OnObserve
evtOnObserveCalled := false
events.OnObserve(func(string, Message) {
evtOnObserveCalled = true
})
events.Observe("/test", nil)
// OnObserveCancelled
evtOnObserveCancelledCalled := false
events.OnObserveCancel(func(string, Message) {
evtOnObserveCancelledCalled = true
})
events.ObserveCancelled("/test", nil)
// OnMessage
evtOnMessageCalled := false
events.OnMessage(func(Message, bool) {
evtOnMessageCalled = true
})
events.Message(nil, true)
time.Sleep(3000)
assert.True(t, evtOnNotifyCalled)
assert.True(t, evtOnStartedCalled)
assert.True(t, evtOnClosedCalled)
assert.True(t, evtOnDiscoverCalled)
assert.True(t, evtOnErrorCalled)
assert.True(t, evtOnObserveCalled)
assert.True(t, evtOnObserveCancelledCalled)
assert.True(t, evtOnMessageCalled)
}
================================================
FILE: examples/block1/client.go
================================================
package main
import (
"io/ioutil"
"log"
"github.com/zubairhamed/canopus"
)
func main() {
conn, err := canopus.Dial("localhost:5683")
file, err := ioutil.ReadFile("./ietf-block.htm")
if err != nil {
log.Fatal(err)
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Post)
blockOpt := canopus.NewBlock1Option(canopus.BlockSize16, true, 0)
req.GetMessage().SetBlock1Option(blockOpt)
req.SetRequestURI("/blockupload")
req.SetPayload(file)
resp, err := conn.Send(req)
if err != nil {
log.Println(err)
} else {
log.Println("Got Response:")
log.Println(resp.GetMessage().GetPayload().String())
}
}
================================================
FILE: examples/block1/ietf-block.htm
================================================
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://dublincore.org/documents/2008/08/04/dc-html/">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index,follow" />
<meta name="creator" content="rfcmarkup version 1.118" />
<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />
<meta name="DC.Relation.Replaces" content="draft-bormann-core-coap-block" />
<meta name="DC.Identifier" content="urn:ietf:id:ietf-core-block" />
<meta name="DC.Date.Issued" content="2016-04-29" />
<meta name="DC.Creator" content="Shelby, Zach" />
<meta name="DC.Creator" content="Bormann, Carsten" />
<meta name="DC.Description.Abstract" content="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." />
<meta name="DC.Title" content="Block-wise transfers in CoAP" />
<link rel="icon" href="/images/id.png" type="image/png" />
<link rel="shortcut icon" href="/images/id.png" type="image/png" />
<title>draft-ietf-core-block-15 - Block-wise transfers in CoAP</title>
<style type="text/css">
@media only screen
and (min-width: 992px)
and (max-width: 1199px) {
body { font-size: 14pt; }
div.content { width: 96ex; margin: 0 auto; }
}
@media only screen
and (min-width: 768px)
and (max-width: 991px) {
body { font-size: 14pt; }
div.content { width: 96ex; margin: 0 auto; }
}
@media only screen
and (min-width: 480px)
and (max-width: 767px) {
body { font-size: 11pt; }
div.content { width: 96ex; margin: 0 auto; }
}
@media only screen
and (max-width: 479px) {
body { font-size: 8pt; }
div.content { width: 96ex; margin: 0 auto; }
}
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px) {
body { font-size: 9.5pt; }
div.content { width: 96ex; margin: 0 1px; }
}
@media only screen
and (min-device-width: 1200px) {
body { font-size: 10pt; margin: 0 4em; }
div.content { width: 96ex; margin: 0; }
}
h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 {
font-weight: bold;
line-height: 0pt;
display: inline;
white-space: pre;
font-family: monospace;
font-size: 1em;
font-weight: bold;
}
pre {
font-size: 1em;
margin-top: 0px;
margin-bottom: 0px;
}
.pre {
white-space: pre;
font-family: monospace;
}
.header{
font-weight: bold;
}
.newpage {
page-break-before: always;
}
.invisible {
text-decoration: none;
color: white;
}
a.selflink {
color: black;
text-decoration: none;
}
@media print {
body {
font-family: monospace;
font-size: 10.5pt;
}
h1, h2, h3, h4, h5, h6 {
font-size: 1em;
}
a:link, a:visited {
color: inherit;
text-decoration: none;
}
.noprint {
display: none;
}
}
@media screen {
.grey, .grey a:link, .grey a:visited {
color: #777;
}
.docinfo {
background-color: #EEE;
}
.top {
border-top: 7px solid #EEE;
}
.bgwhite { background-color: white; }
.bgred { background-color: #F44; }
.bggrey { background-color: #666; }
.bgbrown { background-color: #840; }
.bgorange { background-color: #FA0; }
.bgyellow { background-color: #EE0; }
.bgmagenta{ background-color: #F4F; }
.bgblue { background-color: #66F; }
.bgcyan { background-color: #4DD; }
.bggreen { background-color: #4F4; }
.legend { font-size: 90%; }
.cplate { font-size: 70%; border: solid grey 1px; }
}
</style>
<!--[if IE]>
<style>
body {
font-size: 13px;
margin: 10px 10px;
}
</style>
<![endif]-->
<script type="text/javascript"><!--
function addHeaderTags() {
var spans = document.getElementsByTagName("span");
for (var i=0; i < spans.length; i++) {
var elem = spans[i];
if (elem) {
var level = elem.getAttribute("class");
if (level == "h1" || level == "h2" || level == "h3" || level == "h4" || level == "h5" || level == "h6") {
elem.innerHTML = "<"+level+">"+elem.innerHTML+"</"+level+">";
}
}
}
}
var legend_html = "Colour legend:<br /> <table> <tr><td>Unknown:</td> <td><span class='cplate bgwhite'> </span></td></tr> <tr><td>Draft:</td> <td><span class='cplate bgred'> </span></td></tr> <tr><td>Informational:</td> <td><span class='cplate bgorange'> </span></td></tr> <tr><td>Experimental:</td> <td><span class='cplate bgyellow'> </span></td></tr> <tr><td>Best Common Practice:</td> <td><span class='cplate bgmagenta'> </span></td></tr> <tr><td>Proposed Standard:</td> <td><span class='cplate bgblue'> </span></td></tr> <tr><td>Draft Standard (old designation):</td> <td><span class='cplate bgcyan'> </span></td></tr> <tr><td>Internet Standard:</td> <td><span class='cplate bggreen'> </span></td></tr> <tr><td>Historic:</td> <td><span class='cplate bggrey'> </span></td></tr> <tr><td>Obsolete:</td> <td><span class='cplate bgbrown'> </span></td></tr> </table>";
function showElem(id) {
var elem = document.getElementById(id);
elem.innerHTML = eval(id+"_html");
elem.style.visibility='visible';
}
function hideElem(id) {
var elem = document.getElementById(id);
elem.style.visibility='hidden';
elem.innerHTML = "";
}
// -->
</script>
</head>
<body onload="addHeaderTags()">
<div class="content">
<div style="height: 13px;">
<div onmouseover="this.style.cursor='pointer';"
onclick="showElem('legend');"
onmouseout="hideElem('legend')"
style="height: 6px; position: absolute;"
class="pre noprint docinfo bgred"
title="Click for colour legend." > </div>
<div id="legend"
class="docinfo noprint pre legend"
style="position:absolute; top: 4px; left: 4ex; visibility:hidden; background-color: white; padding: 4px 9px 5px 7px; border: solid #345 1px; "
onmouseover="showElem('legend');"
onmouseout="hideElem('legend');">
</div>
</div>
<span class="pre noprint docinfo top">[<a href="../html/" title="Document search and retrieval page">Docs</a>] [<a href="https://tools.ietf.org/id/draft-ietf-core-block-15.txt" title="Plaintext version of this document">txt</a>|<a href="/pdf/draft-ietf-core-block-15.txt" title="PDF version of this document">pdf</a>] [<a href='https://datatracker.ietf.org/doc/draft-ietf-core-block' title='IESG Datatracker information for this document'>Tracker</a>] [<a href="../wg/core" title="The working group handling this document">WG</a>] [<a href="mailto:draft-ietf-core-block@tools.ietf.org?subject=draft-ietf-core-block%20" title="Send email to the document authors">Email</a>] [<a href="/rfcdiff?difftype=--hwdiff&url2=draft-ietf-core-block-15.txt" title="Inline diff (wdiff)">Diff1</a>] [<a href="/rfcdiff?url2=draft-ietf-core-block-15.txt" title="Side-by-side diff">Diff2</a>] [<a href="/idnits?url=https://tools.ietf.org/id/draft-ietf-core-block-15.txt" title="Run an idnits check of this document">Nits</a>] </span><br />
<span class="pre noprint docinfo"> </span><br />
<span class="pre noprint docinfo">Versions: (<a href="./draft-bormann-core-coap-block" title="Precursor">draft-bormann-core-coap-block</a>) <a href="./draft-ietf-core-block-00">00</a>
<a href="./draft-ietf-core-block-01">01</a> <a href="./draft-ietf-core-block-02">02</a> <a href="./draft-ietf-core-block-03">03</a> <a href="./draft-ietf-core-block-04">04</a> <a href="./draft-ietf-core-block-05">05</a> <a href="./draft-ietf-core-block-06">06</a> <a href="./draft-ietf-core-block-07">07</a> <a href="./draft-ietf-core-block-08">08</a> <a href="./draft-ietf-core-block-09">09</a> <a href="./draft-ietf-core-block-10">10</a> <a href="./draft-ietf-core-block-11">11</a> <a href="./draft-ietf-core-block-12">12</a>
<a href="./draft-ietf-core-block-13">13</a> <a href="./draft-ietf-core-block-14">14</a> <a href="./draft-ietf-core-block-15">15</a> <a href="./draft-ietf-core-block-16">16</a> <a href="./draft-ietf-core-block-17">17</a> <a href="./draft-ietf-core-block-18">18</a> <a href="./draft-ietf-core-block-19">19</a> <a href="./draft-ietf-core-block-20">20</a> </span><br />
<span class="pre noprint docinfo"> </span><br />
<pre>
CoRE Working Group C. Bormann
Internet-Draft Universitaet Bremen TZI
Intended status: Standards Track Z. Shelby, Ed.
Expires: January 5, 2015 ARM
July 04, 2014
<span class="h1">Blockwise transfers in CoAP</span>
<span class="h1">draft-ietf-core-block-15</span>
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 <a href="./bcp78">BCP 78</a> and <a href="./bcp79">BCP 79</a>.
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 <a href="http://datatracker.ietf.org/drafts/current/">http://datatracker.ietf.org/drafts/current/</a>.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 1]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-2" id="page-2" href="#page-2" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 January 5, 2015.
Copyright Notice
Copyright (c) 2014 IETF Trust and the persons identified as the
document authors. All rights reserved.
This document is subject to <a href="./bcp78">BCP 78</a> and the IETF Trust's Legal
Provisions Relating to IETF Documents
(<a href="http://trustee.ietf.org/license-info">http://trustee.ietf.org/license-info</a>) 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
<a href="#section-1">1</a>. Introduction . . . . . . . . . . . . . . . . . . . . . . . . <a href="#page-3">3</a>
<a href="#section-2">2</a>. Block-wise transfers . . . . . . . . . . . . . . . . . . . . <a href="#page-5">5</a>
<a href="#section-2.1">2.1</a>. The Block2 and Block1 Options . . . . . . . . . . . . . . <a href="#page-5">5</a>
<a href="#section-2.2">2.2</a>. Structure of a Block Option . . . . . . . . . . . . . . . <a href="#page-6">6</a>
<a href="#section-2.3">2.3</a>. Block Options in Requests and Responses . . . . . . . . . <a href="#page-8">8</a>
<a href="#section-2.4">2.4</a>. Using the Block2 Option . . . . . . . . . . . . . . . . . <a href="#page-10">10</a>
<a href="#section-2.5">2.5</a>. Using the Block1 Option . . . . . . . . . . . . . . . . . <a href="#page-11">11</a>
<a href="#section-2.6">2.6</a>. Combining Blockwise Transfers with the Observe Option . . <a href="#page-12">12</a>
<a href="#section-2.7">2.7</a>. Combining Block1 and Block2 . . . . . . . . . . . . . . . <a href="#page-13">13</a>
<a href="#section-2.8">2.8</a>. Combining Block2 with Multicast . . . . . . . . . . . . . <a href="#page-13">13</a>
<a href="#section-2.9">2.9</a>. Response Codes . . . . . . . . . . . . . . . . . . . . . <a href="#page-14">14</a>
<a href="#section-2.9.1">2.9.1</a>. 2.31 Continue . . . . . . . . . . . . . . . . . . . . <a href="#page-14">14</a>
<a href="#section-2.9.2">2.9.2</a>. 4.08 Request Entity Incomplete . . . . . . . . . . . <a href="#page-14">14</a>
<a href="#section-2.9.3">2.9.3</a>. 4.13 Request Entity Too Large . . . . . . . . . . . . <a href="#page-14">14</a>
<a href="#section-3">3</a>. Examples . . . . . . . . . . . . . . . . . . . . . . . . . . <a href="#page-15">15</a>
<a href="#section-3.1">3.1</a>. Block2 Examples . . . . . . . . . . . . . . . . . . . . . <a href="#page-15">15</a>
<a href="#section-3.2">3.2</a>. Block1 Examples . . . . . . . . . . . . . . . . . . . . . <a href="#page-19">19</a>
<a href="#section-3.3">3.3</a>. Combining Block1 and Block2 . . . . . . . . . . . . . . . <a href="#page-20">20</a>
<a href="#section-3.4">3.4</a>. Combining Observe and Block2 . . . . . . . . . . . . . . <a href="#page-22">22</a>
<a href="#section-4">4</a>. The Size2 and Size1 Options . . . . . . . . . . . . . . . . . <a href="#page-25">25</a>
<a href="#section-5">5</a>. HTTP Mapping Considerations . . . . . . . . . . . . . . . . . <a href="#page-26">26</a>
<a href="#section-6">6</a>. IANA Considerations . . . . . . . . . . . . . . . . . . . . . <a href="#page-27">27</a>
<a href="#section-7">7</a>. Security Considerations . . . . . . . . . . . . . . . . . . . <a href="#page-28">28</a>
<a href="#section-7.1">7.1</a>. Mitigating Resource Exhaustion Attacks . . . . . . . . . <a href="#page-29">29</a>
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 2]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-3" id="page-3" href="#page-3" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
<a href="#section-7.2">7.2</a>. Mitigating Amplification Attacks . . . . . . . . . . . . <a href="#page-29">29</a>
<a href="#section-8">8</a>. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . <a href="#page-30">30</a>
<a href="#section-9">9</a>. References . . . . . . . . . . . . . . . . . . . . . . . . . <a href="#page-30">30</a>
<a href="#section-9.1">9.1</a>. Normative References . . . . . . . . . . . . . . . . . . <a href="#page-30">30</a>
<a href="#section-9.2">9.2</a>. Informative References . . . . . . . . . . . . . . . . . <a href="#page-30">30</a>
Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . <a href="#page-31">31</a>
<span class="h2"><a class="selflink" name="section-1" href="#section-1">1</a>. Introduction</span>
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 [<a href="./rfc7228" title=""Terminology for Constrained-Node Networks"">RFC7228</a>])
and networks (such as 6LoWPAN, [<a href="./rfc4944" title=""Transmission of IPv6 Packets over IEEE 802.15.4 Networks"">RFC4944</a>]) [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>]. The CoAP
protocol is intended to provide RESTful [<a href="#ref-REST" title=""Architectural Styles and the Design of Network-based Software Architectures"">REST</a>] services not unlike
HTTP [<a href="./rfc7230" title=""Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing"">RFC7230</a>], 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.
The present specification defines a pair of CoAP options to enable
_block-wise_ access to resource representations. The Block options
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 3]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-4" id="page-4" href="#page-4" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 <a href="./rfc2119">RFC</a>
<a href="./rfc2119">2119</a>, <a href="./bcp14">BCP 14</a> [<a href="./rfc2119" title=""Key words for use in RFCs to Indicate Requirement Levels"">RFC2119</a>] 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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 4]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-5" id="page-5" href="#page-5" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
<span class="h2"><a class="selflink" name="section-2" href="#section-2">2</a>. Block-wise transfers</span>
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 [<a href="./rfc4919" title=""IPv6 over Low-Power Wireless Personal Area Networks (6LoWPANs): Overview, Assumptions, Problem Statement, and Goals"">RFC4919</a>])
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).
<span class="h3"><a class="selflink" name="section-2.1" href="#section-2.1">2.1</a>. The Block2 and Block1 Options</span>
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 5]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-6" id="page-6" href="#page-6" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
+-----+---+---+---+---+--------+--------+--------+---------+
| 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 [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>], 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
[<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>]).
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.
<span class="h3"><a class="selflink" name="section-2.2" href="#section-2.2">2.2</a>. Structure of a Block Option</span>
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 <a href="./rfc7252#section-3.2">Section 3.2 of [RFC7252]</a>). This integer
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 6]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-7" id="page-7" href="#page-7" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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:
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 7]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-8" id="page-8" href="#page-8" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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.)
<span class="h3"><a class="selflink" name="section-2.3" href="#section-2.3">2.3</a>. Block Options in Requests and Responses</span>
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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 8]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-9" id="page-9" href="#page-9" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
* 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
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 9]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-10" id="page-10" href="#page-10" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>],
each of these message exchanges uses their own CoAP Message ID.
<span class="h3"><a class="selflink" name="section-2.4" href="#section-2.4">2.4</a>. Using the Block2 Option</span>
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
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
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 10]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-11" id="page-11" href="#page-11" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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.
<span class="h3"><a class="selflink" name="section-2.5" href="#section-2.5">2.5</a>. Using the Block1 Option</span>
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
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 11]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-12" id="page-12" href="#page-12" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
acknowledgement was lost, this strategy is useful mostly for
idempotent requests.)
In a blockwise 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, <a href="#section-2.9.1">Section 2.9.1</a>). 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, <a href="#section-2.9.2">Section 2.9.2</a>) 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.
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.)
<span class="h3"><a class="selflink" name="section-2.6" href="#section-2.6">2.6</a>. Combining Blockwise Transfers with the Observe Option</span>
The Observe Option provides a way for a client to be notified about
changes over time of a resource [<a href="#ref-I-D.ietf-core-observe">I-D.ietf-core-observe</a>]. 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 blockwise 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
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 12]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-13" id="page-13" href="#page-13" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
renewing the observation relationship. If the server supports
blockwise 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.)
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
(<a href="#section-2.4">Section 2.4</a>).
See <a href="#section-3.4">Section 3.4</a> for examples.
<span class="h3"><a class="selflink" name="section-2.7" href="#section-2.7">2.7</a>. Combining Block1 and Block2</span>
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.
<span class="h3"><a class="selflink" name="section-2.8" href="#section-2.8">2.8</a>. Combining Block2 with Multicast</span>
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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 13]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-14" id="page-14" href="#page-14" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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.
<span class="h3"><a class="selflink" name="section-2.9" href="#section-2.9">2.9</a>. Response Codes</span>
Two response codes are defined by this specification beyond those
already defined in [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>], and another response code is extended
in its meaning.
<span class="h4"><a class="selflink" name="section-2.9.1" href="#section-2.9.1">2.9.1</a>. 2.31 Continue</span>
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.
<span class="h4"><a class="selflink" name="section-2.9.2" href="#section-2.9.2">2.9.2</a>. 4.08 Request Entity Incomplete</span>
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.
<span class="h4"><a class="selflink" name="section-2.9.3" href="#section-2.9.3">2.9.3</a>. 4.13 Request Entity Too Large</span>
In <a href="./rfc7252#section-5.9.2.9">[RFC7252], section 5.9.2.9</a>, the response code 4.13 (Request Entity
Too Large) is defined to be like HTTP 413 "Request Entity Too Large".
[<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>] also recommends that this response SHOULD include a Size1
Option (<a href="#section-4">Section 4</a>) 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 <a href="#section-2.3">Section 2.3</a>) where the response carries a smaller SZX in
its Block1 option is a hint to try that smaller SZX.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 14]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-15" id="page-15" href="#page-15" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
<span class="h2"><a class="selflink" name="section-3" href="#section-3">3</a>. Examples</span>
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.
<span class="h3"><a class="selflink" name="section-3.1" href="#section-3.1">3.1</a>. Block2 Examples</span>
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.
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 blockwise GET
In the second example (Figure 3), the client anticipates the
blockwise transfer (e.g., because of a size indication in the link-
format description [<a href="./rfc6690" title=""Constrained RESTful Environments (CoRE) Link Format"">RFC6690</a>]) 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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 15]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-16" id="page-16" href="#page-16" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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: Blockwise GET with early negotiation
In the third example (Figure 4), the client is surprised by the need
for a blockwise 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
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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 16]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-17" id="page-17" href="#page-17" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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: Blockwise 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).
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 17]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-18" id="page-18" href="#page-18" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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: Blockwise 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: Blockwise GET with late negotiation and lost ACK
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 18]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-19" id="page-19" href="#page-19" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
<span class="h3"><a class="selflink" name="section-3.2" href="#section-3.2">3.2</a>. Block1 Examples</span>
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 blockwise 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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 19]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-20" id="page-20" href="#page-20" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 blockwise PUT
Finally, a server receiving a blockwise 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.04 Changed, 1:0/1/32 |
| |
| CON [MID=1235], PUT, /options, 1:4/1/32 ------> |
| |
| <------ ACK [MID=1235], 2.04 Changed, 1:4/1/32 |
| |
| CON [MID=1236], PUT, /options, 1:5/1/32 ------> |
| |
| <------ ACK [MID=1235], 2.04 Changed, 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 blockwise PUT with negotiation
<span class="h3"><a class="selflink" name="section-3.3" href="#section-3.3">3.3</a>. Combining Block1 and Block2</span>
Block options may be used in both directions of a single exchange.
The following example demonstrates a blockwise POST request,
resulting in a separate blockwise response.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 20]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-21" id="page-21" href="#page-21" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 blockwise POST with blockwise response
This model does provide for early negotiation input to the Block2
blockwise transfer, as shown below.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 21]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-22" id="page-22" href="#page-22" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 blockwise POST with blockwise response, early
negotiation
<span class="h3"><a class="selflink" name="section-3.4" href="#section-3.4">3.4</a>. Combining Observe and Block2</span>
In the following example, the server first sends a direct response
(Observe sequence number 62350) to the initial GET request (the
resulting blockwise 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
| 2.05 | Token: 0xfb
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 22]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-23" id="page-23" href="#page-23" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
| | 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 blockwise response
In the following example, the client also uses early negotiation to
limit the block size to 64 bytes.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 23]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-24" id="page-24" href="#page-24" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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
| | ETag: 6f00f392
| | Payload: [64 bytes]
....
| |
+----->| Header: GET 0x41011638
| GET | Token: 0xfc
| | Uri-Path: status-icon
| | Block2: 4/0/64
| |
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 24]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-25" id="page-25" href="#page-25" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
|<-----+ Header: 2.05 0x61451638
| 2.05 | Token: 0xfc
| | Block2: 4/0/64
| | ETag: 6f00f392
| | Payload: [53 bytes]
Figure 13: Observe sequence with early negotiation
<span class="h2"><a class="selflink" name="section-4" href="#section-4">4</a>. The Size2 and Size1 Options</span>
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 [<a href="./rfc6690" title=""Constrained RESTful Environments (CoRE) Link Format"">RFC6690</a>].
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 [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>] 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").
o in a 4.13 response, to indicate the maximum size that would have
been acceptable [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>], 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).
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 25]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-26" id="page-26" href="#page-26" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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, blockwise 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 blockwise 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.
<span class="h2"><a class="selflink" name="section-5" href="#section-5">5</a>. HTTP Mapping Considerations</span>
In this subsection, we give some brief examples for the influence the
Block options might have on intermediaries that map between CoAP and
HTTP.
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.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 26]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-27" id="page-27" href="#page-27" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
For PUT or POST requests, historically there was more variation in
how HTTP servers might implement ranges; recently, [<a href="./rfc7233" title=""Hypertext Transfer Protocol (HTTP/1.1): Range Requests"">RFC7233</a>] 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.)
<span class="h2"><a class="selflink" name="section-6" href="#section-6">6</a>. IANA Considerations</span>
This draft adds the following option numbers to the CoAP Option
Numbers registry of [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>]:
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 27]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-28" id="page-28" href="#page-28" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
+--------+--------+-----------+
| 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 [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>]:
+------+---------------------------+-----------+
| Code | Description | Reference |
+------+---------------------------+-----------+
| 2.31 | Continue | [RFCXXXX] |
| | | |
| 4.08 | Request Entity Incomplete | [RFCXXXX] |
+------+---------------------------+-----------+
Table 4: CoAP Response Codes
<span class="h2"><a class="selflink" name="section-7" href="#section-7">7</a>. Security Considerations</span>
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.
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
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 28]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-29" id="page-29" href="#page-29" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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.
<span class="h3"><a class="selflink" name="section-7.1" href="#section-7.1">7.1</a>. Mitigating Resource Exhaustion Attacks</span>
Certain blockwise requests may induce the server to create state,
e.g. to create a snapshot for the blockwise 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 blockwise
transfers in an expedient way to minimize the likelihood of running
into such a timeout.
<span class="h3"><a class="selflink" name="section-7.2" href="#section-7.2">7.2</a>. Mitigating Amplification Attacks</span>
[<a name="ref-RFC7252" id="ref-RFC7252">RFC7252</a>] discusses the susceptibility of CoAP end-points for use in
amplification attacks.
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 29]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-30" id="page-30" href="#page-30" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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.
<span class="h2"><a class="selflink" name="section-8" href="#section-8">8</a>. Acknowledgements</span>
Much of the content of this draft is the result of discussions with
the [<a href="./rfc7252" title=""The Constrained Application Protocol (CoAP)"">RFC7252</a>] 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.
<span class="h2"><a class="selflink" name="section-9" href="#section-9">9</a>. References</span>
<span class="h3"><a class="selflink" name="section-9.1" href="#section-9.1">9.1</a>. Normative References</span>
[<a name="ref-I-D.ietf-core-observe" id="ref-I-D.ietf-core-observe">I-D.ietf-core-observe</a>]
Hartke, K., "Observing Resources in CoAP", <a href="./draft-ietf-core-observe-14">draft-ietf-</a>
<a href="./draft-ietf-core-observe-14">core-observe-14</a> (work in progress), June 2014.
[<a name="ref-RFC2119" id="ref-RFC2119">RFC2119</a>] Bradner, S., "Key words for use in RFCs to Indicate
Requirement Levels", <a href="./bcp14">BCP 14</a>, <a href="./rfc2119">RFC 2119</a>, March 1997.
[<a name="ref-RFC7252" id="ref-RFC7252">RFC7252</a>] Shelby, Z., Hartke, K., and C. Bormann, "The Constrained
Application Protocol (CoAP)", <a href="./rfc7252">RFC 7252</a>, June 2014.
<span class="h3"><a class="selflink" name="section-9.2" href="#section-9.2">9.2</a>. Informative References</span>
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 30]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-31" id="page-31" href="#page-31" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
[<a name="ref-REST" id="ref-REST">REST</a>] Fielding, R., "Architectural Styles and the Design of
Network-based Software Architectures", Ph.D. Dissertation,
University of California, Irvine, 2000,
<<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf">http://www.ics.uci.edu/~fielding/pubs/dissertation/</a>
<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf">fielding_dissertation.pdf</a>>.
[<a name="ref-RFC4919" id="ref-RFC4919">RFC4919</a>] Kushalnagar, N., Montenegro, G., and C. Schumacher, "IPv6
over Low-Power Wireless Personal Area Networks (6LoWPANs):
Overview, Assumptions, Problem Statement, and Goals", <a href="./rfc4919">RFC</a>
<a href="./rfc4919">4919</a>, August 2007.
[<a name="ref-RFC4944" id="ref-RFC4944">RFC4944</a>] Montenegro, G., Kushalnagar, N., Hui, J., and D. Culler,
"Transmission of IPv6 Packets over IEEE 802.15.4
Networks", <a href="./rfc4944">RFC 4944</a>, September 2007.
[<a name="ref-RFC6690" id="ref-RFC6690">RFC6690</a>] Shelby, Z., "Constrained RESTful Environments (CoRE) Link
Format", <a href="./rfc6690">RFC 6690</a>, August 2012.
[<a name="ref-RFC7228" id="ref-RFC7228">RFC7228</a>] Bormann, C., Ersue, M., and A. Keranen, "Terminology for
Constrained-Node Networks", <a href="./rfc7228">RFC 7228</a>, May 2014.
[<a name="ref-RFC7230" id="ref-RFC7230">RFC7230</a>] Fielding, R. and J. Reschke, "Hypertext Transfer Protocol
(HTTP/1.1): Message Syntax and Routing", <a href="./rfc7230">RFC 7230</a>, June
2014.
[<a name="ref-RFC7233" id="ref-RFC7233">RFC7233</a>] Fielding, R., Lafon, Y., and J. Reschke, "Hypertext
Transfer Protocol (HTTP/1.1): Range Requests", <a href="./rfc7233">RFC 7233</a>,
June 2014.
Authors' Addresses
Carsten Bormann
Universitaet Bremen TZI
Postfach 330440
Bremen D-28359
Germany
Phone: +49-421-218-63921
Email: cabo@tzi.org
<span class="grey">Bormann & Shelby Expires January 5, 2015 [Page 31]</span></pre>
<hr class='noprint' style='width: 96ex;' align='left'/><!--NewPage--><pre class='newpage'><a name="page-32" id="page-32" href="#page-32" class="invisible"> </a>
<span class="grey">Internet-Draft Blockwise transfers in CoAP July 2014</span>
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 January 5, 2015 [Page 32]
</pre><br />
<span class="noprint"><small><small>Html markup produced by rfcmarkup 1.118, available from
<a href="https://tools.ietf.org/tools/rfcmarkup/">https://tools.ietf.org/tools/rfcmarkup/</a>
</small></small></span>
</div>
</body>
</html>
================================================
FILE: examples/block1/server.go
================================================
package main
import (
"io/ioutil"
"log"
"github.com/zubairhamed/canopus"
)
func main() {
server := canopus.NewServer()
server.Get("/blockinfo", func(req canopus.Request) canopus.Response {
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.Post("/blockupload", func(req canopus.Request) canopus.Response {
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
// Save to file
payload := req.GetMessage().GetPayload().GetBytes()
log.Println("len", len(payload))
err := ioutil.WriteFile("output.html", payload, 0644)
if err != nil {
log.Println(err)
}
return res
})
server.OnBlockMessage(func(msg canopus.Message, inbound bool) {
// log.Println("Incoming Block Message:")
// canopus.PrintMessage(msg)
})
server.ListenAndServe(":5683")
<-make(chan struct{})
}
================================================
FILE: examples/discovery/main.go
================================================
package main
import (
"fmt"
"crypto/rand"
"github.com/zubairhamed/canopus"
)
func main() {
fmt.Println("Starting up")
server := canopus.NewServer()
server.ListenAndServeDTLS(":5682")
fmt.Println("New Request..")
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Post, canopus.GenerateMessageID())
// req.SetStringPayload(BuildModelResourceStringPayload(c.enabledObjects))
req.SetRequestURI("/rd")
req.SetURIQuery("ep", "name")
// session := canopus.NewUDPServerSession("localhost:5684", server.GetConnection(), server)
// DTLS Version
fmt.Println("Initializing SSL")
secret := make([]byte, 32)
if n, err := rand.Read(secret); n != 32 || err != nil {
panic(err)
}
server.(*canopus.DefaultCoapServer).SetCookieSecret(secret)
server.HandlePSK(func(id string) []byte {
return []byte("secretPSK")
})
ctx, err := canopus.NewServerDtlsContext()
if err != nil {
panic(err.Error())
}
session := canopus.NewDTLSServerSession("localhost:5684", server.GetConnection(), server, ctx)
fmt.Println("Sending Message")
resp, err := canopus.SendMessage(req.GetMessage(), session)
fmt.Println("Response", resp, err)
canopus.PrintMessage(resp.GetMessage())
<-make(chan struct{})
}
================================================
FILE: examples/dtls/simple-psk/client.go
================================================
package main
import (
"fmt"
"github.com/zubairhamed/canopus"
)
func main() {
conn, err := canopus.DialDTLS("localhost:5684", "canopus", "secretPSK")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get)
req.SetStringPayload("Hello, canopus")
req.SetRequestURI("/hello")
resp, err := conn.Send(req)
if err != nil {
panic(err.Error())
}
fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
}
================================================
FILE: examples/dtls/simple-psk/server.go
================================================
package main
import (
"fmt"
"github.com/zubairhamed/canopus"
)
func main() {
server := canopus.NewServer()
server.Get("/hello", func(req canopus.Request) canopus.Response {
fmt.Println("Hello Called")
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.HandlePSK(func(id string) []byte {
return []byte("secretPSK")
})
server.ListenAndServeDTLS(":5684")
<-make(chan struct{})
}
================================================
FILE: examples/observe/client.go
================================================
package main
import (
"fmt"
"github.com/zubairhamed/canopus"
)
func main() {
conn, err := canopus.Dial("localhost:5683")
tok, err := conn.ObserveResource("/watch/this")
if err != nil {
panic(err.Error())
}
obsChannel := make(chan canopus.ObserveMessage)
done := make(chan bool)
go conn.Observe(obsChannel)
notifyCount := 0
go func() {
for {
select {
case obsMsg, open := <-obsChannel:
if open {
if notifyCount == 5 {
fmt.Println("[CLIENT >> ] Canceling observe after 5 notifications..")
go conn.CancelObserveResource("watch/this", tok)
go conn.StopObserve(obsChannel)
done <- true
return
} else {
notifyCount++
// msg := obsMsg.Msg\
resource := obsMsg.GetResource()
val := obsMsg.GetValue()
fmt.Println("[CLIENT >> ] Got Change Notification for resource and value: ", notifyCount, resource, val)
}
} else {
done <- true
return
}
}
}
}()
<-done
fmt.Println("Done")
}
================================================
FILE: examples/observe/server.go
================================================
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
"github.com/zubairhamed/canopus"
)
func main() {
server := canopus.NewServer()
server.Get("/watch/this", func(req canopus.Request) canopus.Response {
msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), canopus.NewPlainTextPayload("Acknowledged"))
res := canopus.NewResponse(msg, nil)
return res
})
ticker := time.NewTicker(3 * time.Second)
go func() {
for {
select {
case <-ticker.C:
changeVal := strconv.Itoa(rand.Int())
fmt.Println("[SERVER << ] Change of value -->", changeVal)
server.NotifyChange("/watch/this", changeVal, false)
}
}
}()
server.OnMessage(func(msg canopus.Message, inbound bool) {
canopus.PrintMessage(msg)
})
server.OnObserve(func(resource string, msg canopus.Message) {
fmt.Println("[SERVER << ] Observe Requested for " + resource)
})
server.ListenAndServe(":5683")
<-make(chan struct{})
}
================================================
FILE: examples/proxy/coap/client.go
================================================
package main
import "github.com/zubairhamed/canopus"
func main() {
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
req.SetProxyURI("coap://localhost:5685/proxycall")
canopus.PrintMessage(req.GetMessage())
resp, err := conn.Send(req)
if err != nil {
println("err", err)
}
canopus.PrintMessage(resp.GetMessage())
}
================================================
FILE: examples/proxy/coap/proxy.go
================================================
package main
import "github.com/zubairhamed/canopus"
func main() {
server := canopus.NewServer()
server.ProxyOverCoap(true)
server.Get("/proxycall", func(req canopus.Request) canopus.Response {
canopus.PrintMessage(req.GetMessage())
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.ListenAndServe(":5683")
<-make(chan struct{})
}
================================================
FILE: examples/proxy/coap/server.go
================================================
package main
import "github.com/zubairhamed/canopus"
func main() {
server := canopus.NewServer()
server.Get("/proxycall", func(req canopus.Request) canopus.Response {
canopus.PrintMessage(req.GetMessage())
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Data from :5685 -- " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.ListenAndServe(":5685")
<-make(chan struct{})
}
================================================
FILE: examples/proxy/http/client.go
================================================
package main
import "github.com/zubairhamed/canopus"
func main() {
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get, canopus.GenerateMessageID())
req.SetProxyURI("https://httpbin.org/get")
canopus.PrintMessage(req.GetMessage())
resp, err := conn.Send(req)
if err != nil {
println("err", err)
}
canopus.PrintMessage(resp.GetMessage())
}
================================================
FILE: examples/proxy/http/server.go
================================================
package main
import "github.com/zubairhamed/canopus"
func main() {
server := canopus.NewServer()
server.ProxyOverHttp(true)
server.ListenAndServe(":5683")
<-make(chan struct{})
}
================================================
FILE: examples/simple/client.go
================================================
package main
import (
"fmt"
"github.com/zubairhamed/canopus"
)
func main() {
fmt.Println("Connecting to CoAP Server")
conn, err := canopus.Dial("localhost:5683")
if err != nil {
panic(err.Error())
}
req := canopus.NewRequest(canopus.MessageConfirmable, canopus.Get)
req.SetStringPayload("Hello, canopus")
req.SetRequestURI("/hello")
fmt.Println("Sending request..")
resp, err := conn.Send(req)
if err != nil {
panic(err.Error())
}
fmt.Println("Got Response:" + resp.GetMessage().GetPayload().String())
}
================================================
FILE: examples/simple/server.go
================================================
package main
import (
"log"
"github.com/zubairhamed/canopus"
)
func main() {
server := canopus.NewServer()
server.Get("/hello", func(req canopus.Request) canopus.Response {
log.Println("Hello Called")
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged with response : " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.Post("/hello", func(req canopus.Request) canopus.Response {
log.Println("Hello Called via POST")
msg := canopus.ContentMessage(req.GetMessage().GetMessageId(), canopus.MessageAcknowledgment)
msg.SetStringPayload("Acknowledged: " + req.GetMessage().GetPayload().String())
res := canopus.NewResponse(msg, nil)
return res
})
server.Get("/basic", func(req canopus.Request) canopus.Response {
msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), canopus.NewPlainTextPayload("Acknowledged"))
res := canopus.NewResponse(msg, nil)
return res
})
server.Get("/basic/json", func(req canopus.Request) canopus.Response {
msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), nil)
res := canopus.NewResponse(msg, nil)
return res
})
server.Get("/basic/xml", func(req canopus.Request) canopus.Response {
msg := canopus.NewMessageOfType(canopus.MessageAcknowledgment, req.GetMessage().GetMessageId(), nil)
res := canopus.NewResponse(msg, nil)
return res
})
server.OnMessage(func(msg canopus.Message, inbound bool) {
canopus.PrintMessage(msg)
})
server.ListenAndServe(":5683")
<-make(chan struct{})
}
================================================
FILE: init.go
================================================
package canopus
func init() {
}
================================================
FILE: json.go
================================================
package canopus
import (
"encoding/json"
"log"
)
func NewJSONPayload(obj interface{}) MessagePayload {
return &JSONPayload{
obj: obj,
}
}
// Represents a message payload containing JSON String
type JSONPayload struct {
obj interface{}
}
func (p *JSONPayload) GetBytes() []byte {
o, err := json.MarshalIndent(p.obj, "", " ")
if err != nil {
log.Println(err)
return []byte{}
}
return []byte(string(o))
}
func (p *JSONPayload) Length() int {
return 0
}
func (p *JSONPayload) String() string {
o, _ := json.Marshal(p.obj)
return string(o)
}
================================================
FILE: message.go
================================================
package canopus
import (
"bytes"
"encoding/binary"
"errors"
"log"
"sort"
"strings"
)
// Instantiates a new message object
// messageType (e.g. Confirm/Non-Confirm)
// CoAP code 404 - Not found etc
// Message ID uint16 unique id
func NewMessage(messageType uint8, code CoapCode, messageID uint16) Message {
return &CoapMessage{
MessageType: messageType,
MessageID: messageID,
Code: code,
Token: []byte(GenerateToken(8)),
}
}
// Instantiates an empty message with a given message id
func NewEmptyMessage(id uint16) Message {
msg := NewMessageOfType(MessageAcknowledgment, id, nil)
return msg
}
// Instantiates an empty message of a specific type and message id
func NewMessageOfType(t uint8, id uint16, payload MessagePayload) Message {
return &CoapMessage{
MessageType: t,
MessageID: id,
Payload: payload,
}
}
/*
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) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
// Converts an array of bytes to a Mesasge object.
// An error is returned if a parsing error occurs
func BytesToMessage(data []byte) (Message, error) {
msg := &CoapMessage{}
dataLen := len(data)
if dataLen < 4 {
return msg, ErrPacketLengthLessThan4
}
ver := data[DataHeader] >> 6
if ver != 1 {
return nil, ErrInvalidCoapVersion
}
msg.MessageType = data[DataHeader] >> 4 & 0x03
tokenLength := data[DataHeader] & 0x0f
msg.Code = CoapCode(data[DataCode])
msg.MessageID = binary.BigEndian.Uint16(data[DataMsgIDStart:DataMsgIDEnd])
// Token
if tokenLength > 0 {
msg.Token = make([]byte, tokenLength)
token := data[DataTokenStart : DataTokenStart+tokenLength]
copy(msg.Token, token)
}
/*
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
\ \
/ /
\ \
+-------------------------------+
*/
tmp := data[DataTokenStart+msg.GetTokenLength():]
lastOptionID := uint(0)
for len(tmp) > 0 {
if tmp[0] == PayloadMarker {
tmp = tmp[1:]
break
}
optionDelta := uint(tmp[0] >> 4)
optionLength := uint(tmp[0] & 0x0f)
tmp = tmp[1:]
switch optionDelta {
case 13:
optionDeltaExtended := uint(tmp[0])
optionDelta += optionDeltaExtended
tmp = tmp[1:]
break
case 14:
optionDeltaExtended := uint(decodeInt(tmp[:2]))
optionDelta = uint(optionDeltaExtended + 269)
tmp = tmp[2:]
break
case 15:
return msg, ErrOptionDeltaUsesValue15
}
lastOptionID += optionDelta
switch optionLength {
case 13:
optionLengthExtended := uint(tmp[0])
optionLength += optionLengthExtended
tmp = tmp[1:]
break
case 14:
optionLengthExtended := uint(decodeInt(tmp[:1]))
optionLength += uint(optionLengthExtended - uint(269))
tmp = tmp[2:]
break
case 15:
return msg, ErrOptionLengthUsesValue15
}
optCode := OptionCode(lastOptionID)
if optionLength > 0 {
optionValue := tmp[:optionLength]
switch optCode {
case OptionURIPort, OptionContentFormat, OptionMaxAge, OptionAccept, OptionSize1,
OptionSize2, OptionBlock1, OptionBlock2:
msg.Options = append(msg.Options, NewOption(optCode, decodeInt(optionValue)))
break
case OptionURIHost, OptionEtag, OptionLocationPath, OptionURIPath, OptionURIQuery,
OptionLocationQuery, OptionProxyURI, OptionProxyScheme, OptionObserve:
msg.Options = append(msg.Options, NewOption(optCode, string(optionValue)))
break
default:
if lastOptionID&0x01 == 1 {
log.Println("Unknown Critical Option id ", lastOptionID)
return msg, ErrUnknownCriticalOption
}
log.Println("Warning: Unknown Option id ", optionDelta)
msg.Options = append(msg.Options, NewOption(optCode, optionValue))
break
}
tmp = tmp[optionLength:]
} else {
msg.Options = append(msg.Options, NewOption(optCode, nil))
}
}
msg.Payload = NewBytesPayload(tmp)
err := ValidateMessage(msg)
return msg, err
}
// type to sort the coap options list (which is mandatory) prior to transmission
type SortOptions []Option
func (opts SortOptions) Len() int {
return len(opts)
}
func (opts SortOptions) Swap(i, j int) {
opts[i], opts[j] = opts[j], opts[i]
}
func (opts SortOptions) Less(i, j int) bool {
return opts[i].GetCode() < opts[j].GetCode()
}
// Converts a message object to a byte array. Typically done prior to transmission
func MessageToBytes(msg Message) ([]byte, error) {
messageID := []byte{0, 0}
binary.BigEndian.PutUint16(messageID, msg.GetMessageId())
buf := bytes.Buffer{}
buf.Write([]byte{(1 << 6) | (msg.GetMessageType() << 4) | 0x0f&msg.GetTokenLength()})
buf.Write([]byte{byte(msg.GetCode())})
buf.Write([]byte{messageID[0]})
buf.Write([]byte{messageID[1]})
buf.Write(msg.GetToken())
// Sort Options
sort.Sort(SortOptions(msg.GetAllOptions()))
lastOptionCode := 0
for _, opt := range msg.GetAllOptions() {
optCode := int(opt.GetCode())
optDelta := optCode - lastOptionCode
optDeltaValue, _ := getOptionHeaderValue(optDelta)
byteValue := valueToBytes(opt.GetValue())
valueLength := len(byteValue)
optLength := valueLength
optLengthValue, _ := getOptionHeaderValue(optLength)
buf.Write([]byte{byte(optDeltaValue<<4 | optLengthValue)})
if optDeltaValue == 13 {
buf.Write([]byte{byte(optDelta - 13)})
} else if optDeltaValue == 14 {
tmpBuf := new(bytes.Buffer)
binary.Write(tmpBuf, binary.BigEndian, uint16(optDelta-269))
buf.Write(tmpBuf.Bytes())
}
// TODO: If optDeltaValue == 15, throw error
if optLengthValue == 13 {
buf.Write([]byte{byte(optLength - 13)})
} else if optLengthValue == 14 {
tmpBuf := new(bytes.Buffer)
binary.Write(tmpBuf, binary.BigEndian, uint16(optLength-269))
buf.Write(tmpBuf.Bytes())
}
buf.Write(byteValue)
lastOptionCode = int(optCode)
}
if msg.GetPayload() != nil {
if msg.GetPayload().Length() > 0 {
buf.Write([]byte{PayloadMarker})
}
buf.Write(msg.GetPayload().GetBytes())
}
return buf.Bytes(), nil
}
func getOptionHeaderValue(optValue int) (int, error) {
switch true {
case optValue <= 12:
return optValue, nil
case optValue <= 268:
return 13, nil
case optValue <= 65804:
return 14, nil
}
return 0, errors.New("Invalid Option Delta")
}
// Validates a message object and returns any error upon validation failure
func ValidateMessage(msg Message) error {
if msg.GetMessageType() > 3 {
return ErrUnknownMessageType
}
if msg.GetTokenLength() > 8 {
return ErrInvalidTokenLength
}
// Repeated Unrecognized Options
for _, opt := range msg.GetAllOptions() {
opts := msg.GetOptions(opt.GetCode())
if len(opts) > 1 {
if !IsRepeatableOption(opts[0]) {
if opts[0].GetCode()&0x01 == 1 {
return ErrUnknownCriticalOption
}
}
}
}
return nil
}
func NewBlockMessage() BlockMessage {
return &CoapBlockMessage{
Sequence: 0,
}
}
type CoapBlockMessage struct {
CoapMessage
MessageBuf []byte
Sequence uint32
}
type BySequence []*CoapBlockMessage
func (o BySequence) Len() int {
return len(o)
}
func (o BySequence) Swap(i, j int) {
o[i], o[j] = o[j], o[i]
}
func (o BySequence) Less(i, j int) bool {
return o[i].Sequence < o[j].Sequence
}
// A Message object represents a CoAP payload
type CoapMessage struct {
MessageType uint8
Code CoapCode
MessageID uint16
Payload MessagePayload
Token []byte
Options []Option
}
func (m *CoapMessage) SetMessageType(t uint8) {
m.MessageType = t
}
func (m *CoapMessage) SetToken(t []byte) {
m.Token = t
}
func (m *CoapMessage) SetPayload(p MessagePayload) {
m.Payload = p
}
func (m *CoapMessage) SetMessageId(id uint16) {
m.MessageID = id
}
func (m *CoapMessage) GetToken() []byte {
return m.Token
}
func (m *CoapMessage) GetPayload() MessagePayload {
return m.Payload
}
func (m *CoapMessage) GetMessageType() uint8 {
return m.MessageType
}
func (m *CoapMessage) GetMessageId() uint16 {
return m.MessageID
}
func (m *CoapMessage) GetCode() CoapCode {
return m.Code
}
func (m *CoapMessage) GetAllOptions() []Option {
return m.Options
}
func (m *CoapMessage) GetAcceptedContent() MediaType {
mediaTypeCode := m.GetOption(OptionAccept).IntValue()
return MediaType(mediaTypeCode)
}
func (m *CoapMessage) GetCodeString() string {
codeClass := string(m.Code >> 5)
codeDetail := string(m.Code & 0x1f)
return codeClass + "." + codeDetail
}
func (m *CoapMessage) GetMethod() uint8 {
return (byte(m.Code) & 0x1f)
}
func (m *CoapMessage) GetTokenLength() uint8 {
return uint8(len(m.Token))
}
func (m *CoapMessage) GetTokenString() string {
return string(m.Token[:len(m.Token)])
}
// Returns an array of options given an option code
func (m CoapMessage) GetOptions(id OptionCode) []Option {
var opts []Option
for _, val := range m.Options {
if val.GetCode() == id {
opts = append(opts, val)
}
}
return opts
}
// Returns the first option found for a given option code
func (m CoapMessage) GetOption(id OptionCode) Option {
for _, val := range m.Options {
if val.GetCode() == id {
return val
}
}
return nil
}
// Attempts to return the string value of an Option
func (m CoapMessage) GetOptionsAsString(id OptionCode) []string {
opts := m.GetOptions(id)
var str []string
for _, o := range opts {
if o.GetValue() != nil {
str = append(str, o.GetValue().(string))
}
}
return str
}
// Returns the string value of the Location Path Options by joining and defining a / separator
func (m *CoapMessage) GetLocationPath() string {
opts := m.GetOptionsAsString(OptionLocationPath)
return strings.Join(opts, "/")
}
// Returns the string value of the Uri Path Options by joining and defining a / separator
func (m CoapMessage) GetURIPath() string {
opts := m.GetOptionsAsString(OptionURIPath)
return "/" + strings.Join(opts, "/")
}
// Add an Option to the message. If an option is not repeatable, it will replace
// any existing defined Option of the same type
func (m *CoapMessage) AddOption(code OptionCode, value interface{}) {
opt := NewOption(code, value)
if IsRepeatableOption(opt) {
m.Options = append(m.Options, opt)
} else {
m.RemoveOptions(code)
m.Options = append(m.Options, opt)
}
}
// Add an array of Options to the message. If an option is not repeatable, it will replace
// any existing defined Option of the same type
func (m *CoapMessage) AddOptions(opts []Option) {
for _, opt := range opts {
if IsRepeatableOption(opt) {
m.Options = append(m.Options, opt)
} else {
m.RemoveOptions(opt.GetCode())
m.Options = append(m.Options, opt)
}
}
}
func (c *CoapMessage) SetBlock1Option(opt Option) {
c.AddOption(OptionBlock1, opt.GetValue())
}
// Copies the given list of options from another message to this one
func (m *CoapMessage) CloneOptions(cm Message, opts ...OptionCode) {
for _, opt := range opts {
m.AddOptions(cm.GetOptions(opt))
}
}
// Replace an Option
func (m *CoapMessage) ReplaceOptions(code OptionCode, opts []Option) {
m.RemoveOptions(code)
m.AddOptions(opts)
}
// Removes an Option
func (m *CoapMessage) RemoveOptions(id OptionCode) {
var opts []Option
for _, opt := range m.Options {
if opt.GetCode() != id {
opts = append(opts, opt)
}
}
m.Options = opts
}
// Adds a string payload
func (m *CoapMessage) SetStringPayload(s string) {
m.Payload = NewPlainTextPayload(s)
}
// Determines if a message contains options for proxying (i.e. Proxy-Scheme or Proxy-Uri)
func IsProxyRequest(msg Message) bool {
if msg.GetOption(OptionProxyScheme) != nil || msg.GetOption(OptionProxyURI) != nil {
return true
}
return false
}
func valueToBytes(value interface{}) []byte {
var v uint32
switch i := value.(type) {
case string:
return []byte(i)
case []byte:
return i
case MediaType:
v = uint32(i)
case byte:
v = uint32(i)
case int:
v = uint32(i)
case int32:
v = uint32(i)
case uint:
v = uint32(i)
case uint32:
v = i
default:
break
}
return encodeInt(v)
}
func decodeInt(b []byte) uint32 {
tmp := []byte{0, 0, 0, 0}
copy(tmp[4-len(b):], b)
return binary.BigEndian.Uint32(tmp)
}
func encodeInt(v uint32) []byte {
switch {
case v == 0:
return nil
case v < 256:
return []byte{byte(v)}
case v < 65536:
rv := []byte{0, 0}
binary.BigEndian.PutUint16(rv, uint16(v))
return rv
case v < 16777216:
rv := []byte{0, 0, 0, 0}
binary.BigEndian.PutUint32(rv, uint32(v))
return rv[1:]
default:
rv := []byte{0, 0, 0, 0}
binary.BigEndian.PutUint32(rv, uint32(v))
return rv
}
}
// Determines if a message contains URI targeting a CoAP resource
func IsCoapURI(uri string) bool {
if strings.HasPrefix(uri, "coap") || strings.HasPrefix(uri, "coaps") {
return true
}
return false
}
// Determines if a message contains URI targeting an HTTP resource
func IsHTTPURI(uri string) bool {
if strings.HasPrefix(uri, "http") || strings.HasPrefix(uri, "https") {
return true
}
return false
}
// Gets the string representation of a CoAP Method code (e.g. GET, PUT, DELETE etc)
func MethodString(c CoapCode) string {
switch c {
case Get:
return "GET"
case Delete:
return "DELETE"
case Post:
return "POST"
case Put:
return "PUT"
}
return ""
}
// Response Code Messages
// Creates a Non-Confirmable Empty Message
func EmptyMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeEmpty, messageID)
}
// Creates a Non-Confirmable with CoAP Code 201 - Created
func CreatedMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeCreated, messageID)
}
// // Creates a Non-Confirmable with CoAP Code 202 - Deleted
func DeletedMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeDeleted, messageID)
}
// Creates a Non-Confirmable with CoAP Code 203 - Valid
func ValidMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeValid, messageID)
}
// Creates a Non-Confirmable with CoAP Code 204 - Changed
func ChangedMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeChanged, messageID)
}
// Creates a Non-Confirmable with CoAP Code 205 - Content
func ContentMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeContent, messageID)
}
// Creates a Non-Confirmable with CoAP Code 400 - Bad Request
func BadRequestMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeBadRequest, messageID)
}
func ContinueMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeContinue, messageID)
}
// Creates a Non-Confirmable with CoAP Code 401 - Unauthorized
func UnauthorizedMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeUnauthorized, messageID)
}
// Creates a Non-Confirmable with CoAP Code 402 - Bad Option
func BadOptionMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeBadOption, messageID)
}
// Creates a Non-Confirmable with CoAP Code 403 - Forbidden
func ForbiddenMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeForbidden, messageID)
}
// Creates a Non-Confirmable with CoAP Code 404 - Not Found
func NotFoundMessage(messageID uint16, messageType uint8, token []byte) (m Message) {
m = NewMessage(messageType, CoapCodeNotFound, messageID)
m.SetToken(token)
return
}
// Creates a Non-Confirmable with CoAP Code 405 - Method Not Allowed
func MethodNotAllowedMessage(messageID uint16, messageType uint8) Message {
return NewMessage(messageType, CoapCodeMethodNotAllowed, messageID)
}
// Creates a Non-Confirmable with CoAP Code 406 - Not Accept
gitextract_9p8qk6we/ ├── .gitignore ├── .gitmodules ├── Godeps/ │ └── Godeps.json ├── LICENSE ├── README.md ├── bytecontent.go ├── canopus.go ├── client.go ├── conn.go ├── corelink.go ├── coreresource.go ├── coreresource_test.go ├── dtls.go ├── empty.go ├── event.go ├── event_test.go ├── examples/ │ ├── block1/ │ │ ├── client.go │ │ ├── ietf-block.htm │ │ └── server.go │ ├── discovery/ │ │ └── main.go │ ├── dtls/ │ │ └── simple-psk/ │ │ ├── client.go │ │ └── server.go │ ├── observe/ │ │ ├── client.go │ │ └── server.go │ ├── proxy/ │ │ ├── coap/ │ │ │ ├── client.go │ │ │ ├── proxy.go │ │ │ └── server.go │ │ └── http/ │ │ ├── client.go │ │ └── server.go │ └── simple/ │ ├── client.go │ └── server.go ├── init.go ├── json.go ├── message.go ├── message_test.go ├── options.go ├── plaintext.go ├── proxy.go ├── request.go ├── request_test.go ├── response.go ├── response_test.go ├── routes.go ├── routes_test.go ├── server.go ├── server_test.go ├── serverconn.go ├── session.go ├── test-coverage.sh ├── types.go ├── utilconn_test.go ├── utildebug.go ├── utils.go ├── utils_test.go └── xml.go
SYMBOL INDEX (544 symbols across 48 files)
FILE: bytecontent.go
function NewBytesPayload (line 4) | func NewBytesPayload(v []byte) MessagePayload {
type BytesPayload (line 10) | type BytesPayload struct
method GetBytes (line 14) | func (p *BytesPayload) GetBytes() []byte {
method Length (line 18) | func (p *BytesPayload) Length() int {
method String (line 22) | func (p *BytesPayload) String() string {
FILE: canopus.go
function init (line 15) | func init() {
constant UDP (line 25) | UDP = "udp"
constant MessageConfirmable (line 29) | MessageConfirmable = 0
constant MessageNonConfirmable (line 30) | MessageNonConfirmable = 1
constant MessageAcknowledgment (line 31) | MessageAcknowledgment = 2
constant MessageReset (line 32) | MessageReset = 3
constant DataHeader (line 37) | DataHeader = 0
constant DataCode (line 38) | DataCode = 1
constant DataMsgIDStart (line 39) | DataMsgIDStart = 2
constant DataMsgIDEnd (line 40) | DataMsgIDEnd = 4
constant DataTokenStart (line 41) | DataTokenStart = 4
type OptionCode (line 45) | type OptionCode
constant OptionIfMatch (line 52) | OptionIfMatch OptionCode = 1
constant OptionURIHost (line 54) | OptionURIHost OptionCode = 3
constant OptionEtag (line 55) | OptionEtag OptionCode = 4
constant OptionIfNoneMatch (line 56) | OptionIfNoneMatch OptionCode = 5
constant OptionObserve (line 57) | OptionObserve OptionCode = 6
constant OptionURIPort (line 58) | OptionURIPort OptionCode = 7
constant OptionLocationPath (line 59) | OptionLocationPath OptionCode = 8
constant OptionURIPath (line 60) | OptionURIPath OptionCode = 11
constant OptionContentFormat (line 61) | OptionContentFormat OptionCode = 12
constant OptionMaxAge (line 62) | OptionMaxAge OptionCode = 14
constant OptionURIQuery (line 63) | OptionURIQuery OptionCode = 15
constant OptionAccept (line 64) | OptionAccept OptionCode = 17
constant OptionLocationQuery (line 65) | OptionLocationQuery OptionCode = 20
constant OptionBlock2 (line 66) | OptionBlock2 OptionCode = 23
constant OptionBlock1 (line 67) | OptionBlock1 OptionCode = 27
constant OptionSize2 (line 68) | OptionSize2 OptionCode = 28
constant OptionProxyURI (line 69) | OptionProxyURI OptionCode = 35
constant OptionProxyScheme (line 70) | OptionProxyScheme OptionCode = 39
constant OptionSize1 (line 71) | OptionSize1 OptionCode = 60
type CoapCode (line 75) | type CoapCode
constant Get (line 78) | Get CoapCode = 1
constant Post (line 79) | Post CoapCode = 2
constant Put (line 80) | Put CoapCode = 3
constant Delete (line 81) | Delete CoapCode = 4
constant CoapCodeEmpty (line 84) | CoapCodeEmpty CoapCode = 0
constant CoapCodeCreated (line 85) | CoapCodeCreated CoapCode = 65
constant CoapCodeDeleted (line 86) | CoapCodeDeleted CoapCode = 66
constant CoapCodeValid (line 87) | CoapCodeValid CoapCode = 67
constant CoapCodeChanged (line 88) | CoapCodeChanged CoapCode = 68
constant CoapCodeContent (line 89) | CoapCodeContent CoapCode = 69
constant CoapCodeContinue (line 90) | CoapCodeContinue CoapCode = 95
constant CoapCodeBadRequest (line 93) | CoapCodeBadRequest CoapCode = 128
constant CoapCodeUnauthorized (line 94) | CoapCodeUnauthorized CoapCode = 129
constant CoapCodeBadOption (line 95) | CoapCodeBadOption CoapCode = 130
constant CoapCodeForbidden (line 96) | CoapCodeForbidden CoapCode = 131
constant CoapCodeNotFound (line 97) | CoapCodeNotFound CoapCode = 132
constant CoapCodeMethodNotAllowed (line 98) | CoapCodeMethodNotAllowed CoapCode = 133
constant CoapCodeNotAcceptable (line 99) | CoapCodeNotAcceptable CoapCode = 134
constant CoapCodeRequestEntityIncomplete (line 100) | CoapCodeRequestEntityIncomplete CoapCode = 136
constant CoapCodeConflict (line 101) | CoapCodeConflict CoapCode = 137
constant CoapCodePreconditionFailed (line 102) | CoapCodePreconditionFailed CoapCode = 140
constant CoapCodeRequestEntityTooLarge (line 103) | CoapCodeRequestEntityTooLarge CoapCode = 141
constant CoapCodeUnsupportedContentFormat (line 104) | CoapCodeUnsupportedContentFormat CoapCode = 143
constant CoapCodeInternalServerError (line 107) | CoapCodeInternalServerError CoapCode = 160
constant CoapCodeNotImplemented (line 108) | CoapCodeNotImplemented CoapCode = 161
constant CoapCodeBadGateway (line 109) | CoapCodeBadGateway CoapCode = 162
constant CoapCodeServiceUnavailable (line 110) | CoapCodeServiceUnavailable CoapCode = 163
constant CoapCodeGatewayTimeout (line 111) | CoapCodeGatewayTimeout CoapCode = 164
constant CoapCodeProxyingNotSupported (line 112) | CoapCodeProxyingNotSupported CoapCode = 165
constant DefaultAckTimeout (line 115) | DefaultAckTimeout = 2
constant DefaultAckRandomFactor (line 116) | DefaultAckRandomFactor = 1.5
constant DefaultMaxRetransmit (line 117) | DefaultMaxRetransmit = 4
constant DefaultNStart (line 118) | DefaultNStart = 1
constant DefaultLeisure (line 119) | DefaultLeisure = 5
constant DefaultProbingRate (line 120) | DefaultProbingRate = 1
constant CoapDefaultHost (line 122) | CoapDefaultHost = ""
constant CoapDefaultPort (line 123) | CoapDefaultPort = 5683
constant CoapsDefaultPort (line 124) | CoapsDefaultPort = 5684
constant PayloadMarker (line 126) | PayloadMarker = 0xff
constant MaxPacketSize (line 127) | MaxPacketSize = 1500
constant MessageIDPurgeDuration (line 130) | MessageIDPurgeDuration = 60
type RouteHandler (line 132) | type RouteHandler
type ProxyFilter (line 135) | type ProxyFilter
type ProxyHandler (line 136) | type ProxyHandler
type MediaType (line 138) | type MediaType
constant MediaTypeTextPlain (line 141) | MediaTypeTextPlain MediaType = 0
constant MediaTypeTextXML (line 142) | MediaTypeTextXML MediaType = 1
constant MediaTypeTextCsv (line 143) | MediaTypeTextCsv MediaType = 2
constant MediaTypeTextHTML (line 144) | MediaTypeTextHTML MediaType = 3
constant MediaTypeImageGif (line 145) | MediaTypeImageGif MediaType = 21
constant MediaTypeImageJpeg (line 146) | MediaTypeImageJpeg MediaType = 22
constant MediaTypeImagePng (line 147) | MediaTypeImagePng MediaType = 23
constant MediaTypeImageTiff (line 148) | MediaTypeImageTiff MediaType = 24
constant MediaTypeAudioRaw (line 149) | MediaTypeAudioRaw MediaType = 25
constant MediaTypeVideoRaw (line 150) | MediaTypeVideoRaw MediaType = 26
constant MediaTypeApplicationLinkFormat (line 151) | MediaTypeApplicationLinkFormat MediaType = 40
constant MediaTypeApplicationXML (line 152) | MediaTypeApplicationXML MediaType = 41
constant MediaTypeApplicationOctetStream (line 153) | MediaTypeApplicationOctetStream MediaType = 42
constant MediaTypeApplicationRdfXML (line 154) | MediaTypeApplicationRdfXML MediaType = 43
constant MediaTypeApplicationSoapXML (line 155) | MediaTypeApplicationSoapXML MediaType = 44
constant MediaTypeApplicationAtomXML (line 156) | MediaTypeApplicationAtomXML MediaType = 45
constant MediaTypeApplicationXmppXML (line 157) | MediaTypeApplicationXmppXML MediaType = 46
constant MediaTypeApplicationExi (line 158) | MediaTypeApplicationExi MediaType = 47
constant MediaTypeApplicationFastInfoSet (line 159) | MediaTypeApplicationFastInfoSet MediaType = 48
constant MediaTypeApplicationSoapFastInfoSet (line 160) | MediaTypeApplicationSoapFastInfoSet MediaType = 49
constant MediaTypeApplicationJSON (line 161) | MediaTypeApplicationJSON MediaType = 50
constant MediaTypeApplicationXObitBinary (line 162) | MediaTypeApplicationXObitBinary MediaType = 51
constant MediaTypeTextPlainVndOmaLwm2m (line 163) | MediaTypeTextPlainVndOmaLwm2m MediaType = 1541
constant MediaTypeTlvVndOmaLwm2m (line 164) | MediaTypeTlvVndOmaLwm2m MediaType = 1542
constant MediaTypeJSONVndOmaLwm2m (line 165) | MediaTypeJSONVndOmaLwm2m MediaType = 1543
constant MediaTypeOpaqueVndOmaLwm2m (line 166) | MediaTypeOpaqueVndOmaLwm2m MediaType = 1544
constant MethodGet (line 170) | MethodGet = "GET"
constant MethodPut (line 171) | MethodPut = "PUT"
constant MethodPost (line 172) | MethodPost = "POST"
constant MethodDelete (line 173) | MethodDelete = "DELETE"
constant MethodOptions (line 174) | MethodOptions = "OPTIONS"
constant MethodPatch (line 175) | MethodPatch = "PATCH"
type BlockSizeType (line 178) | type BlockSizeType
constant BlockSize16 (line 181) | BlockSize16 BlockSizeType = 0
constant BlockSize32 (line 182) | BlockSize32 BlockSizeType = 1
constant BlockSize64 (line 183) | BlockSize64 BlockSizeType = 2
constant BlockSize128 (line 184) | BlockSize128 BlockSizeType = 3
constant BlockSize256 (line 185) | BlockSize256 BlockSizeType = 4
constant BlockSize512 (line 186) | BlockSize512 BlockSizeType = 5
constant BlockSize1024 (line 187) | BlockSize1024 BlockSizeType = 6
constant SecNoSec (line 209) | SecNoSec = "NoSec"
constant SecPreSharedKey (line 210) | SecPreSharedKey = "PreSharedKey"
constant SecRawPublicKey (line 211) | SecRawPublicKey = "RawPublicKey"
constant SecCertificate (line 212) | SecCertificate = "Certificate"
type CoapServer (line 216) | type CoapServer interface
type ServerConnection (line 263) | type ServerConnection interface
type Option (line 273) | type Option interface
type Session (line 283) | type Session interface
type Request (line 292) | type Request interface
type Response (line 309) | type Response interface
type Connection (line 316) | type Connection interface
type MessagePayload (line 329) | type MessagePayload interface
type Message (line 335) | type Message interface
type Route (line 367) | type Route interface
type FnEventNotify (line 377) | type FnEventNotify
type FnEventStart (line 378) | type FnEventStart
type FnEventClose (line 379) | type FnEventClose
type FnEventDiscover (line 380) | type FnEventDiscover
type FnEventError (line 381) | type FnEventError
type FnEventObserve (line 382) | type FnEventObserve
type FnEventObserveCancel (line 383) | type FnEventObserveCancel
type FnEventMessage (line 384) | type FnEventMessage
type FnEventBlockMessage (line 385) | type FnEventBlockMessage
type EventCode (line 387) | type EventCode
constant EventStart (line 390) | EventStart EventCode = 0
constant EventClose (line 391) | EventClose EventCode = 1
constant EventDiscover (line 392) | EventDiscover EventCode = 2
constant EventMessage (line 393) | EventMessage EventCode = 3
constant EventError (line 394) | EventError EventCode = 4
constant EventObserve (line 395) | EventObserve EventCode = 5
constant EventObserveCancel (line 396) | EventObserveCancel EventCode = 6
constant EventNotify (line 397) | EventNotify EventCode = 7
type ObserveMessage (line 400) | type ObserveMessage interface
type Events (line 406) | type Events interface
type BlockMessage (line 428) | type BlockMessage interface
FILE: client.go
function Dial (line 5) | func Dial(address string) (conn Connection, err error) {
function DialDTLS (line 18) | func DialDTLS(address, identity, psk string) (conn Connection, err error) {
function NewObserveMessage (line 32) | func NewObserveMessage(r string, val interface{}, msg Message) ObserveMe...
type CoapObserveMessage (line 40) | type CoapObserveMessage struct
method GetResource (line 47) | func (m *CoapObserveMessage) GetResource() string {
method GetValue (line 51) | func (m *CoapObserveMessage) GetValue() interface{} {
method GetMessage (line 55) | func (m *CoapObserveMessage) GetMessage() Message {
FILE: conn.go
function MessageSizeAllowed (line 9) | func MessageSizeAllowed(req Request) bool {
type UDPConnection (line 20) | type UDPConnection struct
method ObserveResource (line 24) | func (c *UDPConnection) ObserveResource(resource string) (tok string, ...
method CancelObserveResource (line 35) | func (c *UDPConnection) CancelObserveResource(resource string, token s...
method StopObserve (line 44) | func (c *UDPConnection) StopObserve(ch chan ObserveMessage) {
method Close (line 48) | func (c *UDPConnection) Close() error {
method Observe (line 52) | func (c *UDPConnection) Observe(ch chan ObserveMessage) {
method Send (line 76) | func (c *UDPConnection) Send(req Request) (resp Response, err error) {
method SendMessage (line 153) | func (c *UDPConnection) SendMessage(msg Message) (resp Response, err e...
method Write (line 200) | func (c *UDPConnection) Write(b []byte) (int, error) {
method Read (line 204) | func (c *UDPConnection) Read(b []byte) (int, error) {
FILE: corelink.go
type CoreLinkFormatPayload (line 4) | type CoreLinkFormatPayload struct
method GetBytes (line 7) | func (p *CoreLinkFormatPayload) GetBytes() []byte {
method Length (line 11) | func (p *CoreLinkFormatPayload) Length() int {
method String (line 15) | func (p *CoreLinkFormatPayload) String() string {
FILE: coreresource.go
function NewCoreAttribute (line 4) | func NewCoreAttribute(key string, value interface{}) *CoreAttribute {
function NewCoreResource (line 12) | func NewCoreResource() *CoreResource {
FILE: coreresource_test.go
function TestCoreResourceParsing (line 9) | func TestCoreResourceParsing(t *testing.T) {
FILE: dtls.go
function init (line 176) | func init() {
function server_bio_method_init (line 184) | func server_bio_method_init() {
function NewServerDtlsContext (line 188) | func NewServerDtlsContext() (ctx *ServerDtlsContext, err error) {
type ServerDtlsContext (line 210) | type ServerDtlsContext struct
function go_session_bio_read (line 215) | func go_session_bio_read(bio *C.BIO, buf *C.char, num C.int) C.int {
function go_session_bio_write (line 229) | func go_session_bio_write(bio *C.BIO, buf *C.char, num C.int) C.int {
function go_session_bio_free (line 251) | func go_session_bio_free(bio *C.BIO) C.int {
function go_server_psk_callback (line 264) | func go_server_psk_callback(ssl *C.SSL, identity *C.char, psk *C.char, m...
function generate_cookie_callback (line 286) | func generate_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len *C...
function verify_cookie_callback (line 307) | func verify_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len C.ui...
function goSliceFromCString (line 329) | func goSliceFromCString(cArray *C.char, size int) (cslice []byte) {
function goSliceFromUCString (line 342) | func goSliceFromUCString(cArray *C.uchar, size int) (cslice []byte) {
function getErrorString (line 354) | func getErrorString(code C.ulong) string {
function newSslSession (line 382) | func newSslSession(session *DTLSServerSession, ctx *ServerDtlsContext, p...
type DTLSServerSession (line 413) | type DTLSServerSession struct
method GetConnection (line 419) | func (s *DTLSServerSession) GetConnection() ServerConnection {
method Write (line 423) | func (s *DTLSServerSession) Write(b []byte) (int, error) {
method Read (line 433) | func (s *DTLSServerSession) Read(b []byte) (n int, err error) {
method getError (line 454) | func (s *DTLSServerSession) getError(ret C.int) error {
function NewDTLSConnection (line 482) | func NewDTLSConnection(c net.Conn, identity, psk string) (conn Connectio...
type DTLSConnection (line 519) | type DTLSConnection struct
method ObserveResource (line 530) | func (c *DTLSConnection) ObserveResource(resource string) (tok string,...
method CancelObserveResource (line 541) | func (c *DTLSConnection) CancelObserveResource(resource string, token ...
method StopObserve (line 550) | func (c *DTLSConnection) StopObserve(ch chan ObserveMessage) {
method Observe (line 554) | func (c *DTLSConnection) Observe(ch chan ObserveMessage) {
method Send (line 578) | func (c *DTLSConnection) Send(req Request) (resp Response, err error) {
method sendMessage (line 657) | func (c *DTLSConnection) sendMessage(msg Message) (resp Response, err ...
method Write (line 706) | func (c *DTLSConnection) Write(b []byte) (int, error) {
method Read (line 721) | func (c *DTLSConnection) Read(b []byte) (int, error) {
method Close (line 743) | func (c *DTLSConnection) Close() error {
method connect (line 762) | func (c *DTLSConnection) connect() error {
method getError (line 770) | func (c *DTLSConnection) getError(ret C.int) error {
function go_conn_bio_write (line 798) | func go_conn_bio_write(bio *C.BIO, buf *C.char, num C.int) C.int {
function go_conn_bio_read (line 819) | func go_conn_bio_read(bio *C.BIO, buf *C.char, num C.int) C.int {
function go_conn_bio_free (line 845) | func go_conn_bio_free(bio *C.BIO) C.int {
function go_psk_callback (line 857) | func go_psk_callback(ssl *C.SSL, hint *C.char, identity *C.char, max_ide...
FILE: empty.go
function NewEmptyPayload (line 3) | func NewEmptyPayload() MessagePayload {
type EmptyPayload (line 8) | type EmptyPayload struct
method GetBytes (line 11) | func (p *EmptyPayload) GetBytes() []byte {
method Length (line 15) | func (p *EmptyPayload) Length() int {
method String (line 19) | func (p *EmptyPayload) String() string {
FILE: event.go
function NewEvents (line 3) | func NewEvents() *ServerEvents {
type ServerEvents (line 19) | type ServerEvents struct
method OnNotify (line 32) | func (ce *ServerEvents) OnNotify(fn FnEventNotify) {
method OnStart (line 37) | func (ce *ServerEvents) OnStart(fn FnEventStart) {
method OnClose (line 42) | func (ce *ServerEvents) OnClose(fn FnEventClose) {
method OnDiscover (line 47) | func (ce *ServerEvents) OnDiscover(fn FnEventDiscover) {
method OnError (line 52) | func (ce *ServerEvents) OnError(fn FnEventError) {
method OnObserve (line 57) | func (ce *ServerEvents) OnObserve(fn FnEventObserve) {
method OnObserveCancel (line 62) | func (ce *ServerEvents) OnObserveCancel(fn FnEventObserveCancel) {
method OnMessage (line 67) | func (ce *ServerEvents) OnMessage(fn FnEventMessage) {
method OnBlockMessage (line 72) | func (ce *ServerEvents) OnBlockMessage(fn FnEventBlockMessage) {
method Notify (line 77) | func (ce *ServerEvents) Notify(resource string, value interface{}, msg...
method Started (line 84) | func (ce *ServerEvents) Started(server CoapServer) {
method Closed (line 91) | func (ce *ServerEvents) Closed(server CoapServer) {
method Discover (line 98) | func (ce *ServerEvents) Discover() {
method Error (line 105) | func (ce *ServerEvents) Error(err error) {
method Observe (line 112) | func (ce *ServerEvents) Observe(resource string, msg Message) {
method ObserveCancelled (line 119) | func (ce *ServerEvents) ObserveCancelled(resource string, msg Message) {
method Message (line 127) | func (ce *ServerEvents) Message(msg Message, inbound bool) {
method BlockMessage (line 135) | func (ce *ServerEvents) BlockMessage(msg Message, inbound bool) {
FILE: event_test.go
function TestEvents (line 11) | func TestEvents(t *testing.T) {
FILE: examples/block1/client.go
function main (line 10) | func main() {
FILE: examples/block1/server.go
function main (line 10) | func main() {
FILE: examples/discovery/main.go
function main (line 11) | func main() {
FILE: examples/dtls/simple-psk/client.go
function main (line 9) | func main() {
FILE: examples/dtls/simple-psk/server.go
function main (line 9) | func main() {
FILE: examples/observe/client.go
function main (line 9) | func main() {
FILE: examples/observe/server.go
function main (line 12) | func main() {
FILE: examples/proxy/coap/client.go
function main (line 5) | func main() {
FILE: examples/proxy/coap/proxy.go
function main (line 5) | func main() {
FILE: examples/proxy/coap/server.go
function main (line 5) | func main() {
FILE: examples/proxy/http/client.go
function main (line 5) | func main() {
FILE: examples/proxy/http/server.go
function main (line 5) | func main() {
FILE: examples/simple/client.go
function main (line 9) | func main() {
FILE: examples/simple/server.go
function main (line 9) | func main() {
FILE: init.go
function init (line 3) | func init() {
FILE: json.go
function NewJSONPayload (line 8) | func NewJSONPayload(obj interface{}) MessagePayload {
type JSONPayload (line 15) | type JSONPayload struct
method GetBytes (line 19) | func (p *JSONPayload) GetBytes() []byte {
method Length (line 31) | func (p *JSONPayload) Length() int {
method String (line 35) | func (p *JSONPayload) String() string {
FILE: message.go
function NewMessage (line 16) | func NewMessage(messageType uint8, code CoapCode, messageID uint16) Mess...
function NewEmptyMessage (line 26) | func NewEmptyMessage(id uint16) Message {
function NewMessageOfType (line 33) | func NewMessageOfType(t uint8, id uint16, payload MessagePayload) Message {
function BytesToMessage (line 57) | func BytesToMessage(data []byte) (Message, error) {
type SortOptions (line 192) | type SortOptions
method Len (line 194) | func (opts SortOptions) Len() int {
method Swap (line 198) | func (opts SortOptions) Swap(i, j int) {
method Less (line 202) | func (opts SortOptions) Less(i, j int) bool {
function MessageToBytes (line 207) | func MessageToBytes(msg Message) ([]byte, error) {
function getOptionHeaderValue (line 265) | func getOptionHeaderValue(optValue int) (int, error) {
function ValidateMessage (line 280) | func ValidateMessage(msg Message) error {
function NewBlockMessage (line 305) | func NewBlockMessage() BlockMessage {
type CoapBlockMessage (line 311) | type CoapBlockMessage struct
type BySequence (line 317) | type BySequence
method Len (line 319) | func (o BySequence) Len() int {
method Swap (line 323) | func (o BySequence) Swap(i, j int) {
method Less (line 327) | func (o BySequence) Less(i, j int) bool {
type CoapMessage (line 332) | type CoapMessage struct
method SetMessageType (line 341) | func (m *CoapMessage) SetMessageType(t uint8) {
method SetToken (line 345) | func (m *CoapMessage) SetToken(t []byte) {
method SetPayload (line 349) | func (m *CoapMessage) SetPayload(p MessagePayload) {
method SetMessageId (line 353) | func (m *CoapMessage) SetMessageId(id uint16) {
method GetToken (line 357) | func (m *CoapMessage) GetToken() []byte {
method GetPayload (line 361) | func (m *CoapMessage) GetPayload() MessagePayload {
method GetMessageType (line 365) | func (m *CoapMessage) GetMessageType() uint8 {
method GetMessageId (line 369) | func (m *CoapMessage) GetMessageId() uint16 {
method GetCode (line 373) | func (m *CoapMessage) GetCode() CoapCode {
method GetAllOptions (line 377) | func (m *CoapMessage) GetAllOptions() []Option {
method GetAcceptedContent (line 381) | func (m *CoapMessage) GetAcceptedContent() MediaType {
method GetCodeString (line 387) | func (m *CoapMessage) GetCodeString() string {
method GetMethod (line 394) | func (m *CoapMessage) GetMethod() uint8 {
method GetTokenLength (line 398) | func (m *CoapMessage) GetTokenLength() uint8 {
method GetTokenString (line 402) | func (m *CoapMessage) GetTokenString() string {
method GetOptions (line 407) | func (m CoapMessage) GetOptions(id OptionCode) []Option {
method GetOption (line 418) | func (m CoapMessage) GetOption(id OptionCode) Option {
method GetOptionsAsString (line 428) | func (m CoapMessage) GetOptionsAsString(id OptionCode) []string {
method GetLocationPath (line 441) | func (m *CoapMessage) GetLocationPath() string {
method GetURIPath (line 448) | func (m CoapMessage) GetURIPath() string {
method AddOption (line 456) | func (m *CoapMessage) AddOption(code OptionCode, value interface{}) {
method AddOptions (line 468) | func (m *CoapMessage) AddOptions(opts []Option) {
method SetBlock1Option (line 479) | func (c *CoapMessage) SetBlock1Option(opt Option) {
method CloneOptions (line 484) | func (m *CoapMessage) CloneOptions(cm Message, opts ...OptionCode) {
method ReplaceOptions (line 491) | func (m *CoapMessage) ReplaceOptions(code OptionCode, opts []Option) {
method RemoveOptions (line 498) | func (m *CoapMessage) RemoveOptions(id OptionCode) {
method SetStringPayload (line 509) | func (m *CoapMessage) SetStringPayload(s string) {
function IsProxyRequest (line 514) | func IsProxyRequest(msg Message) bool {
function valueToBytes (line 521) | func valueToBytes(value interface{}) []byte {
function decodeInt (line 548) | func decodeInt(b []byte) uint32 {
function encodeInt (line 555) | func encodeInt(v uint32) []byte {
function IsCoapURI (line 581) | func IsCoapURI(uri string) bool {
function IsHTTPURI (line 589) | func IsHTTPURI(uri string) bool {
function MethodString (line 598) | func MethodString(c CoapCode) string {
function EmptyMessage (line 617) | func EmptyMessage(messageID uint16, messageType uint8) Message {
function CreatedMessage (line 622) | func CreatedMessage(messageID uint16, messageType uint8) Message {
function DeletedMessage (line 627) | func DeletedMessage(messageID uint16, messageType uint8) Message {
function ValidMessage (line 632) | func ValidMessage(messageID uint16, messageType uint8) Message {
function ChangedMessage (line 637) | func ChangedMessage(messageID uint16, messageType uint8) Message {
function ContentMessage (line 642) | func ContentMessage(messageID uint16, messageType uint8) Message {
function BadRequestMessage (line 647) | func BadRequestMessage(messageID uint16, messageType uint8) Message {
function ContinueMessage (line 651) | func ContinueMessage(messageID uint16, messageType uint8) Message {
function UnauthorizedMessage (line 656) | func UnauthorizedMessage(messageID uint16, messageType uint8) Message {
function BadOptionMessage (line 661) | func BadOptionMessage(messageID uint16, messageType uint8) Message {
function ForbiddenMessage (line 666) | func ForbiddenMessage(messageID uint16, messageType uint8) Message {
function NotFoundMessage (line 671) | func NotFoundMessage(messageID uint16, messageType uint8, token []byte) ...
function MethodNotAllowedMessage (line 679) | func MethodNotAllowedMessage(messageID uint16, messageType uint8) Message {
function NotAcceptableMessage (line 684) | func NotAcceptableMessage(messageID uint16, messageType uint8) Message {
function ConflictMessage (line 689) | func ConflictMessage(messageID uint16, messageType uint8) Message {
function PreconditionFailedMessage (line 694) | func PreconditionFailedMessage(messageID uint16, messageType uint8) Mess...
function RequestEntityTooLargeMessage (line 699) | func RequestEntityTooLargeMessage(messageID uint16, messageType uint8) M...
function UnsupportedContentFormatMessage (line 704) | func UnsupportedContentFormatMessage(messageID uint16, messageType uint8...
function InternalServerErrorMessage (line 709) | func InternalServerErrorMessage(messageID uint16, messageType uint8) Mes...
function NotImplementedMessage (line 714) | func NotImplementedMessage(messageID uint16, messageType uint8) Message {
function BadGatewayMessage (line 719) | func BadGatewayMessage(messageID uint16, messageType uint8) Message {
function ServiceUnavailableMessage (line 724) | func ServiceUnavailableMessage(messageID uint16, messageType uint8) Mess...
function GatewayTimeoutMessage (line 729) | func GatewayTimeoutMessage(messageID uint16, messageType uint8) Message {
function ProxyingNotSupportedMessage (line 734) | func ProxyingNotSupportedMessage(messageID uint16, messageType uint8) Me...
FILE: message_test.go
function TestMessage (line 10) | func TestMessage(t *testing.T) {
function TestInvalidMessage (line 15) | func TestInvalidMessage(t *testing.T) {
function TestMessagValidation (line 24) | func TestMessagValidation(t *testing.T) {
function TestMessageConversion (line 28) | func TestMessageConversion(t *testing.T) {
function TestMessageBadOptions (line 49) | func TestMessageBadOptions(t *testing.T) {
function TestMessageObject (line 60) | func TestMessageObject(t *testing.T) {
function TestOptionConversion (line 76) | func TestOptionConversion(t *testing.T) {
function TestNewMessageHelpers (line 98) | func TestNewMessageHelpers(t *testing.T) {
function NewBasicConfirmableMessage (line 136) | func NewBasicConfirmableMessage() *CoapMessage {
FILE: options.go
type CoapOption (line 9) | type CoapOption struct
method GetValue (line 14) | func (o *CoapOption) GetValue() interface{} {
method GetCode (line 18) | func (o *CoapOption) GetCode() OptionCode {
method Name (line 22) | func (o *CoapOption) Name() string {
method IsElective (line 27) | func (o *CoapOption) IsElective() bool {
method IsCritical (line 35) | func (o *CoapOption) IsCritical() bool {
method StringValue (line 43) | func (o *CoapOption) StringValue() string {
method IntValue (line 47) | func (o *CoapOption) IntValue() int {
function NewOption (line 52) | func NewOption(optionNumber OptionCode, optionValue interface{}) *CoapOp...
function NewPathOptions (line 60) | func NewPathOptions(path string) []Option {
function IsRepeatableOption (line 74) | func IsRepeatableOption(opt Option) bool {
function IsValidOption (line 88) | func IsValidOption(opt Option) bool {
function IsElectiveOption (line 103) | func IsElectiveOption(opt Option) bool {
function IsCriticalOption (line 113) | func IsCriticalOption(opt Option) bool {
function NewBlock1Option (line 117) | func NewBlock1Option(bs BlockSizeType, more bool, seq uint32) *Block1Opt...
function Block1OptionFromOption (line 149) | func Block1OptionFromOption(opt Option) *Block1Option {
type Block1Option (line 158) | type Block1Option struct
method Sequence (line 162) | func (o *Block1Option) Sequence() uint32 {
method Exponent (line 168) | func (o *Block1Option) Exponent() uint32 {
method BlockSizeLength (line 174) | func (o *Block1Option) BlockSizeLength() uint32 {
method Size (line 180) | func (o *Block1Option) Size() BlockSizeType {
method HasMore (line 187) | func (o *Block1Option) HasMore() bool {
FILE: plaintext.go
function NewPlainTextPayload (line 6) | func NewPlainTextPayload(s string) MessagePayload {
type PlainTextPayload (line 13) | type PlainTextPayload struct
method GetBytes (line 17) | func (p *PlainTextPayload) GetBytes() []byte {
method Length (line 21) | func (p *PlainTextPayload) Length() int {
method String (line 25) | func (p *PlainTextPayload) String() string {
FILE: proxy.go
function NullProxyFilter (line 11) | func NullProxyFilter(Message, net.Addr) bool {
function NullProxyHandler (line 16) | func NullProxyHandler(c CoapServer, msg Message, session Session) {
function COAPProxyHandler (line 20) | func COAPProxyHandler(c CoapServer, msg Message, session Session) {
function HTTPProxyHandler (line 52) | func HTTPProxyHandler(c CoapServer, msg Message, session Session) {
function HTTPCOAPProxyHandler (line 102) | func HTTPCOAPProxyHandler(msg *Message, conn *net.UDPConn, addr net.Addr) {
FILE: request.go
function NewRequest (line 9) | func NewRequest(messageType uint8, messageMethod CoapCode) Request {
function NewRequestWithMessageId (line 13) | func NewRequestWithMessageId(messageType uint8, messageMethod CoapCode, ...
function NewConfirmableGetRequest (line 20) | func NewConfirmableGetRequest() Request {
function NewConfirmablePostRequest (line 26) | func NewConfirmablePostRequest() Request {
function NewConfirmablePutRequest (line 32) | func NewConfirmablePutRequest() Request {
function NewConfirmableDeleteRequest (line 38) | func NewConfirmableDeleteRequest() Request {
function NewRequestFromMessage (line 45) | func NewRequestFromMessage(msg Message) Request {
function NewClientRequestFromMessage (line 51) | func NewClientRequestFromMessage(msg Message, attrs map[string]string, s...
type CoapRequest (line 61) | type CoapRequest struct
method SetProxyURI (line 68) | func (c *CoapRequest) SetProxyURI(uri string) {
method SetMediaType (line 72) | func (c *CoapRequest) SetMediaType(mt MediaType) {
method GetSession (line 76) | func (c *CoapRequest) GetSession() Session {
method GetAttributes (line 80) | func (c *CoapRequest) GetAttributes() map[string]string {
method GetAttribute (line 84) | func (c *CoapRequest) GetAttribute(o string) string {
method GetAttributeAsInt (line 88) | func (c *CoapRequest) GetAttributeAsInt(o string) int {
method GetMessage (line 95) | func (c *CoapRequest) GetMessage() Message {
method SetStringPayload (line 99) | func (c *CoapRequest) SetStringPayload(s string) {
method SetPayload (line 103) | func (c *CoapRequest) SetPayload(b []byte) {
method SetRequestURI (line 107) | func (c *CoapRequest) SetRequestURI(uri string) {
method SetConfirmable (line 111) | func (c *CoapRequest) SetConfirmable(con bool) {
method SetToken (line 119) | func (c *CoapRequest) SetToken(t string) {
method GetURIQuery (line 123) | func (c *CoapRequest) GetURIQuery(q string) string {
method SetURIQuery (line 137) | func (c *CoapRequest) SetURIQuery(k string, v string) {
FILE: request_test.go
function TestRequest (line 9) | func TestRequest(t *testing.T) {
FILE: response.go
function NoResponse (line 7) | func NoResponse() Response {
type NilResponse (line 11) | type NilResponse struct
method GetMessage (line 14) | func (c NilResponse) GetMessage() Message {
method GetError (line 18) | func (c NilResponse) GetError() error {
method GetPayload (line 22) | func (c NilResponse) GetPayload() []byte {
method GetURIQuery (line 26) | func (c NilResponse) GetURIQuery(q string) string {
function NewResponse (line 31) | func NewResponse(msg Message, err error) Response {
function NewResponseWithMessage (line 41) | func NewResponseWithMessage(msg Message) Response {
type DefaultResponse (line 49) | type DefaultResponse struct
method GetMessage (line 54) | func (c *DefaultResponse) GetMessage() Message {
method GetError (line 58) | func (c *DefaultResponse) GetError() error {
method GetPayload (line 62) | func (c *DefaultResponse) GetPayload() []byte {
method GetURIQuery (line 66) | func (c *DefaultResponse) GetURIQuery(q string) string {
FILE: response_test.go
function TestResponse (line 9) | func TestResponse(t *testing.T) {
FILE: routes.go
function CreateNewRegExRoute (line 9) | func CreateNewRegExRoute(path string, method string, fn RouteHandler) Ro...
type RegExRoute (line 42) | type RegExRoute struct
method Matches (line 51) | func (r *RegExRoute) Matches(path string) (bool, map[string]string) {
method GetMethod (line 65) | func (r *RegExRoute) GetMethod() string {
method GetMediaTypes (line 69) | func (r *RegExRoute) GetMediaTypes() []MediaType {
method GetConfiguredPath (line 73) | func (r *RegExRoute) GetConfiguredPath() string {
method AutoAcknowledge (line 77) | func (r *RegExRoute) AutoAcknowledge() bool {
method Handle (line 81) | func (r *RegExRoute) Handle(req Request) Response {
function MatchingRoute (line 86) | func MatchingRoute(path string, method string, cf interface{}, routes []...
FILE: routes_test.go
function TestRoutes (line 9) | func TestRoutes(t *testing.T) {
FILE: server.go
type ServerConfiguration (line 17) | type ServerConfiguration struct
function NewServer (line 21) | func NewServer() CoapServer {
function createServer (line 25) | func createServer() CoapServer {
type DefaultCoapServer (line 42) | type DefaultCoapServer struct
method DeleteSession (line 68) | func (s *DefaultCoapServer) DeleteSession(ssn Session) {
method HandlePSK (line 72) | func (s *DefaultCoapServer) HandlePSK(fn func(id string) []byte) {
method handleRequest (line 76) | func (s *DefaultCoapServer) handleRequest(msg Message, session Session) {
method handleReqObserve (line 207) | func (s *DefaultCoapServer) handleReqObserve(req Request, msg Message,...
method handleResponse (line 231) | func (s *DefaultCoapServer) handleResponse(msg Message, session Sessio...
method GetEvents (line 248) | func (s *DefaultCoapServer) GetEvents() Events {
method addDiscoveryRoute (line 252) | func (s *DefaultCoapServer) addDiscoveryRoute() {
method ListenAndServeDTLS (line 291) | func (s *DefaultCoapServer) ListenAndServeDTLS(addr string) {
method ListenAndServe (line 317) | func (s *DefaultCoapServer) ListenAndServe(addr string) {
method createConn (line 332) | func (s *DefaultCoapServer) createConn(addr string) ServerConnection {
method handleIncomingDTLSData (line 352) | func (s *DefaultCoapServer) handleIncomingDTLSData(conn ServerConnecti...
method handleIncomingData (line 403) | func (s *DefaultCoapServer) handleIncomingData(conn ServerConnection) {
method GetSession (line 444) | func (s *DefaultCoapServer) GetSession(addr string) Session {
method Stop (line 448) | func (s *DefaultCoapServer) Stop() {
method updateBlockMessageFragment (line 452) | func (s *DefaultCoapServer) updateBlockMessageFragment(client string, ...
method flushBlockMessagePayload (line 469) | func (s *DefaultCoapServer) flushBlockMessagePayload(origin string) Me...
method handleMessageIDPurge (line 478) | func (s *DefaultCoapServer) handleMessageIDPurge() {
method SetProxyFilter (line 496) | func (s *DefaultCoapServer) SetProxyFilter(fn ProxyFilter) {
method GetCookieSecret (line 500) | func (s *DefaultCoapServer) GetCookieSecret() []byte {
method handleSession (line 504) | func (s *DefaultCoapServer) handleSession(session Session) {
method closeSession (line 521) | func (s *DefaultCoapServer) closeSession(ssn Session) {
method Get (line 525) | func (s *DefaultCoapServer) Get(path string, fn RouteHandler) Route {
method Delete (line 529) | func (s *DefaultCoapServer) Delete(path string, fn RouteHandler) Route {
method Put (line 533) | func (s *DefaultCoapServer) Put(path string, fn RouteHandler) Route {
method Post (line 537) | func (s *DefaultCoapServer) Post(path string, fn RouteHandler) Route {
method Options (line 541) | func (s *DefaultCoapServer) Options(path string, fn RouteHandler) Route {
method Patch (line 545) | func (s *DefaultCoapServer) Patch(path string, fn RouteHandler) Route {
method add (line 549) | func (s *DefaultCoapServer) add(method string, path string, fn RouteHa...
method NewRoute (line 556) | func (s *DefaultCoapServer) NewRoute(path string, method CoapCode, fn ...
method storeNewOutgoingBlockMessage (line 563) | func (s *DefaultCoapServer) storeNewOutgoingBlockMessage(client string...
method NotifyChange (line 569) | func (s *DefaultCoapServer) NotifyChange(resource, value string, confi...
method AddObservation (line 593) | func (s *DefaultCoapServer) AddObservation(resource, token string, ses...
method HasObservation (line 597) | func (s *DefaultCoapServer) HasObservation(resource string, addr net.A...
method RemoveObservation (line 611) | func (s *DefaultCoapServer) RemoveObservation(resource string, addr ne...
method OnNotify (line 625) | func (s *DefaultCoapServer) OnNotify(fn FnEventNotify) {
method OnStart (line 629) | func (s *DefaultCoapServer) OnStart(fn FnEventStart) {
method OnClose (line 633) | func (s *DefaultCoapServer) OnClose(fn FnEventClose) {
method OnDiscover (line 637) | func (s *DefaultCoapServer) OnDiscover(fn FnEventDiscover) {
method OnError (line 641) | func (s *DefaultCoapServer) OnError(fn FnEventError) {
method OnObserve (line 645) | func (s *DefaultCoapServer) OnObserve(fn FnEventObserve) {
method OnObserveCancel (line 649) | func (s *DefaultCoapServer) OnObserveCancel(fn FnEventObserveCancel) {
method OnMessage (line 653) | func (s *DefaultCoapServer) OnMessage(fn FnEventMessage) {
method OnBlockMessage (line 657) | func (s *DefaultCoapServer) OnBlockMessage(fn FnEventBlockMessage) {
method ProxyOverHttp (line 661) | func (s *DefaultCoapServer) ProxyOverHttp(enabled bool) {
method ProxyOverCoap (line 669) | func (s *DefaultCoapServer) ProxyOverCoap(enabled bool) {
method AllowProxyForwarding (line 677) | func (s *DefaultCoapServer) AllowProxyForwarding(msg Message, addr net...
method ForwardCoap (line 681) | func (s *DefaultCoapServer) ForwardCoap(msg Message, session Session) {
method ForwardHTTP (line 685) | func (s *DefaultCoapServer) ForwardHTTP(msg Message, session Session) {
method GetRoutes (line 689) | func (s *DefaultCoapServer) GetRoutes() []Route {
method isDuplicateMessage (line 693) | func (s *DefaultCoapServer) isDuplicateMessage(msg Message) bool {
method updateMessageTS (line 699) | func (s *DefaultCoapServer) updateMessageTS(msg Message) {
method handleReqUnknownCriticalOption (line 703) | func (s *DefaultCoapServer) handleReqUnknownCriticalOption(msg Message...
method handleReqBadRequest (line 710) | func (s *DefaultCoapServer) handleReqBadRequest(msg Message, session S...
method handleReqContinue (line 717) | func (s *DefaultCoapServer) handleReqContinue(msg Message, session Ses...
method handleReqUnsupportedMethodRequest (line 724) | func (s *DefaultCoapServer) handleReqUnsupportedMethodRequest(msg Mess...
method handleReqProxyRequest (line 732) | func (s *DefaultCoapServer) handleReqProxyRequest(msg Message, session...
method handleReqNoMatchingRoute (line 747) | func (s *DefaultCoapServer) handleReqNoMatchingRoute(msg Message, sess...
method handleReqNoMatchingMethod (line 754) | func (s *DefaultCoapServer) handleReqNoMatchingMethod(msg Message, ses...
method handleReqUnsupportedContentFormat (line 761) | func (s *DefaultCoapServer) handleReqUnsupportedContentFormat(msg Mess...
method handleReqDuplicateMessageID (line 769) | func (s *DefaultCoapServer) handleReqDuplicateMessageID(msg Message, s...
method handleRequestAcknowledge (line 776) | func (s *DefaultCoapServer) handleRequestAcknowledge(msg Message, sess...
method handleAcknowledgeObserveRequest (line 782) | func (s *DefaultCoapServer) handleAcknowledgeObserveRequest(msg Messag...
method handleAcknowledgeObserveRequestGetSession (line 786) | func (s *DefaultCoapServer) handleAcknowledgeObserveRequestGetSession(...
function NewResponseChannel (line 790) | func NewResponseChannel() (ch chan *CoapResponseChannel) {
function AddResponseChannel (line 796) | func AddResponseChannel(c CoapServer, msgId uint16, ch chan *CoapRespons...
function DeleteResponseChannel (line 801) | func DeleteResponseChannel(c CoapServer, msgId uint16) {
function GetResponseChannel (line 806) | func GetResponseChannel(c CoapServer, msgId uint16) (ch chan *CoapRespon...
function NewObservation (line 813) | func NewObservation(session Session, token string, resource string) *Obs...
type Observation (line 822) | type Observation struct
function _doSendMessage (line 829) | func _doSendMessage(msg Message, session Session, ch chan *CoapResponseC...
function SendMessage (line 851) | func SendMessage(msg Message, session Session) (Response, error) {
type CoapResponseChannel (line 872) | type CoapResponseChannel struct
FILE: server_test.go
function TestServerInstantiate (line 6) | func TestServerInstantiate(t *testing.T) {
FILE: serverconn.go
type UDPServerConnection (line 8) | type UDPServerConnection struct
method ReadFrom (line 12) | func (uc *UDPServerConnection) ReadFrom(b []byte) (n int, addr net.Add...
method WriteTo (line 16) | func (uc *UDPServerConnection) WriteTo(b []byte, addr net.Addr) (n int...
method Close (line 20) | func (uc *UDPServerConnection) Close() error {
method LocalAddr (line 24) | func (uc *UDPServerConnection) LocalAddr() net.Addr {
method SetDeadline (line 28) | func (uc *UDPServerConnection) SetDeadline(t time.Time) error {
method SetReadDeadline (line 32) | func (uc *UDPServerConnection) SetReadDeadline(t time.Time) error {
method SetWriteDeadline (line 36) | func (uc *UDPServerConnection) SetWriteDeadline(t time.Time) error {
FILE: session.go
type UDPServerSession (line 5) | type UDPServerSession struct
method GetConnection (line 13) | func (s *UDPServerSession) GetConnection() ServerConnection {
method GetAddress (line 17) | func (s *UDPServerSession) GetAddress() net.Addr {
method WriteBuffer (line 21) | func (s *UDPServerSession) WriteBuffer(b []byte) (n int) {
method Write (line 27) | func (s *UDPServerSession) Write(b []byte) (n int, err error) {
method Read (line 33) | func (s *UDPServerSession) Read(b []byte) (n int, err error) {
method GetServer (line 39) | func (s *UDPServerSession) GetServer() CoapServer {
FILE: types.go
type CoreAttributes (line 3) | type CoreAttributes
type CoreResource (line 5) | type CoreResource struct
method AddAttribute (line 16) | func (c *CoreResource) AddAttribute(key string, value interface{}) {
method GetAttribute (line 21) | func (c *CoreResource) GetAttribute(key string) *CoreAttribute {
type CoreAttribute (line 10) | type CoreAttribute struct
FILE: utilconn_test.go
function TestSendMessages (line 5) | func TestSendMessages(t *testing.T) {
FILE: utildebug.go
function PrintOptions (line 4) | func PrintOptions(msg Message) {
function PrintMessage (line 17) | func PrintMessage(msg Message) {
function OptionNumberToString (line 31) | func OptionNumberToString(o OptionCode) string {
FILE: utils.go
function PayloadAsString (line 12) | func PayloadAsString(p MessagePayload) string {
function GenerateMessageID (line 20) | func GenerateMessageID() uint16 {
function GenerateToken (line 35) | func GenerateToken(l int) string {
function CoreResourcesFromString (line 45) | func CoreResourcesFromString(str string) []*CoreResource {
function CoapCodeToString (line 74) | func CoapCodeToString(code CoapCode) string {
function ValidCoapMediaTypeCode (line 160) | func ValidCoapMediaTypeCode(mt MediaType) bool {
function logMsg (line 175) | func logMsg(a ...interface{}) (n int, err error) {
FILE: utils_test.go
function TestGenerateMessageId (line 9) | func TestGenerateMessageId(t *testing.T) {
function TestGenerateToken (line 25) | func TestGenerateToken(t *testing.T) {
function TestCoreResourceUtil (line 35) | func TestCoreResourceUtil(t *testing.T) {
function TestCoapCodeToString (line 81) | func TestCoapCodeToString(t *testing.T) {
function TestRouteMatching (line 120) | func TestRouteMatching(t *testing.T) {
function TestMediaTypeUtils (line 124) | func TestMediaTypeUtils(t *testing.T) {
FILE: xml.go
type XMLPayload (line 4) | type XMLPayload struct
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (278K chars).
[
{
"path": ".gitignore",
"chars": 291,
"preview": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture spe"
},
{
"path": ".gitmodules",
"chars": 84,
"preview": "[submodule \"openssl\"]\n\tpath = openssl\n\turl = https://github.com/openssl/openssl.git\n"
},
{
"path": "Godeps/Godeps.json",
"chars": 474,
"preview": "{\n\t\"ImportPath\": \"github.com/zubairhamed/canopus\",\n\t\"GoVersion\": \"go1.7\",\n\t\"Deps\": [\n\t\t{\n\t\t\t\"ImportPath\": \"github.com/da"
},
{
"path": "LICENSE",
"chars": 11343,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 6793,
"preview": "# Canopus\n\n[](https://godoc.org/github.com/zubairha"
},
{
"path": "bytecontent.go",
"chars": 412,
"preview": "package canopus\n\n// Represents a message payload containing an array of bytes\nfunc NewBytesPayload(v []byte) MessagePayl"
},
{
"path": "canopus.go",
"chars": 12291,
"preview": "package canopus\n\nimport (\n\t\"errors\"\n\t\"math/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\n// CurrentMessageID stores the current messag"
},
{
"path": "client.go",
"chars": 954,
"preview": "package canopus\n\nimport \"net\"\n\nfunc Dial(address string) (conn Connection, err error) {\n\tudpConn, err := net.Dial(\"udp\","
},
{
"path": "conn.go",
"chars": 4519,
"preview": "package canopus\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n)\n\nfunc MessageSizeAllowed(req Request) bool {\n\tmsg := req.GetMessage()\n"
},
{
"path": "corelink.go",
"chars": 325,
"preview": "package canopus\n\n// Represents a message payload containing core-link format values\ntype CoreLinkFormatPayload struct {\n"
},
{
"path": "coreresource.go",
"chars": 324,
"preview": "package canopus\n\n// Instantiates a new core-attribute with a given key/value\nfunc NewCoreAttribute(key string, value int"
},
{
"path": "coreresource_test.go",
"chars": 1647,
"preview": "package canopus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestCoreResourceParsing(t *testing.T"
},
{
"path": "dtls.go",
"chars": 20954,
"preview": "package canopus\n\n/*\n#cgo LDFLAGS: -L${SRCDIR}/openssl -lssl -lcrypto -ldl\n#cgo CFLAGS: -g -Wno-deprecated -Wno-error -I$"
},
{
"path": "empty.go",
"chars": 321,
"preview": "package canopus\n\nfunc NewEmptyPayload() MessagePayload {\n\treturn &EmptyPayload{}\n}\n\n// Represents an empty message paylo"
},
{
"path": "event.go",
"chars": 3923,
"preview": "package canopus\n\nfunc NewEvents() *ServerEvents {\n\treturn &ServerEvents{\n\t\tevtFnNotify: []FnEventNotify{},\n\t\tevtF"
},
{
"path": "event_test.go",
"chars": 1668,
"preview": "package canopus\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestEvents(t *test"
},
{
"path": "examples/block1/client.go",
"chars": 634,
"preview": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tconn, err := canopus.Dia"
},
{
"path": "examples/block1/ietf-block.htm",
"chars": 101482,
"preview": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt"
},
{
"path": "examples/block1/server.go",
"chars": 1153,
"preview": "package main\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tserver := canopus.NewSer"
},
{
"path": "examples/discovery/main.go",
"chars": 1219,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"crypto/rand\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tfmt.Println(\"Starting"
},
{
"path": "examples/dtls/simple-psk/client.go",
"chars": 480,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tconn, err := canopus.DialDTLS(\"localh"
},
{
"path": "examples/dtls/simple-psk/server.go",
"chars": 586,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tserver := canopus.NewServer()\n\n\tserve"
},
{
"path": "examples/observe/client.go",
"chars": 999,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tconn, err := canopus.Dial(\"localhost:"
},
{
"path": "examples/observe/server.go",
"chars": 974,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tserve"
},
{
"path": "examples/proxy/coap/client.go",
"chars": 460,
"preview": "package main\n\nimport \"github.com/zubairhamed/canopus\"\n\nfunc main() {\n\tconn, err := canopus.Dial(\"localhost:5683\")\n\tif er"
},
{
"path": "examples/proxy/coap/proxy.go",
"chars": 533,
"preview": "package main\n\nimport \"github.com/zubairhamed/canopus\"\n\nfunc main() {\n\tserver := canopus.NewServer()\n\tserver.ProxyOverCoa"
},
{
"path": "examples/proxy/coap/server.go",
"chars": 510,
"preview": "package main\n\nimport \"github.com/zubairhamed/canopus\"\n\nfunc main() {\n\tserver := canopus.NewServer()\n\n\tserver.Get(\"/proxy"
},
{
"path": "examples/proxy/http/client.go",
"chars": 452,
"preview": "package main\n\nimport \"github.com/zubairhamed/canopus\"\n\nfunc main() {\n\tconn, err := canopus.Dial(\"localhost:5683\")\n\tif er"
},
{
"path": "examples/proxy/http/server.go",
"chars": 187,
"preview": "package main\n\nimport \"github.com/zubairhamed/canopus\"\n\nfunc main() {\n\tserver := canopus.NewServer()\n\tserver.ProxyOverHtt"
},
{
"path": "examples/simple/client.go",
"chars": 528,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tfmt.Println(\"Connecting to CoAP Serve"
},
{
"path": "examples/simple/server.go",
"chars": 1688,
"preview": "package main\n\nimport (\n\t\"log\"\n\n\t\"github.com/zubairhamed/canopus\"\n)\n\nfunc main() {\n\tserver := canopus.NewServer()\n\n\tserve"
},
{
"path": "init.go",
"chars": 34,
"preview": "package canopus\n\nfunc init() {\n\n}\n"
},
{
"path": "json.go",
"chars": 567,
"preview": "package canopus\n\nimport (\n\t\"encoding/json\"\n\t\"log\"\n)\n\nfunc NewJSONPayload(obj interface{}) MessagePayload {\n\treturn &JSON"
},
{
"path": "message.go",
"chars": 19262,
"preview": "package canopus\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n)\n\n// Instantiates a new messa"
},
{
"path": "message_test.go",
"chars": 5129,
"preview": "package canopus\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestMessage(t *testing.T) {"
},
{
"path": "options.go",
"chars": 3495,
"preview": "package canopus\n\nimport (\n\t\"math\"\n\t\"strings\"\n)\n\n// Represents an Option for a CoAP Message\ntype CoapOption struct {\n\tCod"
},
{
"path": "plaintext.go",
"chars": 523,
"preview": "package canopus\n\nimport \"bytes\"\n\n// Instantiates a new message payload of type string\nfunc NewPlainTextPayload(s string)"
},
{
"path": "proxy.go",
"chars": 2771,
"preview": "package canopus\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nfunc NullProxyFilter(Message, net.Addr) b"
},
{
"path": "request.go",
"chars": 3058,
"preview": "package canopus\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Creates a New Request Instance\nfunc NewRequest(messageType uint8, "
},
{
"path": "request_test.go",
"chars": 674,
"preview": "package canopus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRequest(t *testing.T) {\n\tvar req"
},
{
"path": "response.go",
"chars": 1261,
"preview": "package canopus\n\nimport (\n\t\"strings\"\n)\n\nfunc NoResponse() Response {\n\treturn NilResponse{}\n}\n\ntype NilResponse struct {\n"
},
{
"path": "response_test.go",
"chars": 452,
"preview": "package canopus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResponse(t *testing.T) {\n\tmsg :="
},
{
"path": "routes.go",
"chars": 2594,
"preview": "package canopus\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\n// CreateNewRoute creates a new Route object\nfunc CreateNewRegExRoute(path"
},
{
"path": "routes_test.go",
"chars": 1226,
"preview": "package canopus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRoutes(t *testing.T) {\n\tvar rout"
},
{
"path": "server.go",
"chars": 21803,
"preview": "package canopus\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar DTLS_SERVER_SESSION"
},
{
"path": "server_test.go",
"chars": 4096,
"preview": "package canopus\n\nimport \"testing\"\n\n// TODO Redo this entire test suite\nfunc TestServerInstantiate(t *testing.T) {\n\t//var"
},
{
"path": "serverconn.go",
"chars": 810,
"preview": "package canopus\n\nimport (\n\t\"net\"\n\t\"time\"\n)\n\ntype UDPServerConnection struct {\n\tconn net.PacketConn\n}\n\nfunc (uc *UDPServe"
},
{
"path": "session.go",
"chars": 737,
"preview": "package canopus\n\nimport \"net\"\n\ntype UDPServerSession struct {\n\taddr net.Addr\n\tconn ServerConnection\n\tserver CoapServ"
},
{
"path": "test-coverage.sh",
"chars": 601,
"preview": "#!/bin/bash\n\necho \"mode: set\" > acc.out\nfail=0\n\n# Standard go tooling behavior is to ignore dirs with leading underscors"
},
{
"path": "types.go",
"chars": 595,
"preview": "package canopus\n\ntype CoreAttributes []*CoreAttribute\n\ntype CoreResource struct {\n\tTarget string\n\tAttributes CoreAtt"
},
{
"path": "utilconn_test.go",
"chars": 1039,
"preview": "package canopus\n\nimport \"testing\"\n\nfunc TestSendMessages(t *testing.T) {\n\t//var conn Connection\n\t//var s CoapServer\n\t//_"
},
{
"path": "utildebug.go",
"chars": 1870,
"preview": "package canopus\n\n// PrintOptions pretty prints out a given Message's options\nfunc PrintOptions(msg Message) {\n\topts := m"
},
{
"path": "utils.go",
"chars": 4157,
"preview": "package canopus\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\n// Returns the string value for a Message "
},
{
"path": "utils_test.go",
"chars": 3899,
"preview": "package canopus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGenerateMessageId(t *testing.T) "
},
{
"path": "xml.go",
"chars": 98,
"preview": "package canopus\n\n// Represents a message payload containing XML String\ntype XMLPayload struct {\n}\n"
}
]
About this extraction
This page contains the full source code of the zubairhamed/canopus GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (252.9 KB), approximately 69.9k tokens, and a symbol index with 544 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.