Update examples

This commit is contained in:
Valerii Koval
2023-01-05 12:42:19 +02:00
parent d0835e994c
commit 4a461f5221
541 changed files with 145063 additions and 1 deletions
+6
View File
@@ -18,3 +18,9 @@ board_build.embed_txtfiles =
src/certs/private.pem.key
src/certs/certificate.pem.crt
src/certs/aws-root-ca.pem
# IDF v5 is not supported by ASW-IoT SDK
# https://github.com/espressif/esp-aws-iot/blob/bbaf03d7d1fbf8a3f91dc18489d7bd27d5b9e9df/README.md?plain=1#L21
platform_packages =
framework-espidf @ ~3.40403.0
toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
@@ -0,0 +1,41 @@
if(NOT CONFIG_LWIP_IPV6 AND NOT CMAKE_BUILD_EARLY_EXPANSION)
message(STATUS "IPV6 support is disabled so the coap component will not be built")
# note: the component is still included in the build so it can become visible again in config
# without needing to re-run CMake. However no source or header files are built.
idf_component_register()
return()
endif()
set(include_dirs port/include port/include libcoap/include)
set(srcs
"libcoap/src/block.c"
"libcoap/src/coap_address.c"
"libcoap/src/coap_asn1.c"
"libcoap/src/coap_async.c"
"libcoap/src/coap_cache.c"
"libcoap/src/coap_debug.c"
"libcoap/src/coap_event.c"
"libcoap/src/coap_hashkey.c"
"libcoap/src/coap_io.c"
"libcoap/src/coap_notls.c"
"libcoap/src/coap_option.c"
"libcoap/src/coap_prng.c"
"libcoap/src/coap_session.c"
"libcoap/src/coap_subscribe.c"
"libcoap/src/coap_tcp.c"
"libcoap/src/coap_time.c"
"libcoap/src/encode.c"
"libcoap/src/mem.c"
"libcoap/src/net.c"
"libcoap/src/pdu.c"
"libcoap/src/resource.c"
"libcoap/src/str.c"
"libcoap/src/uri.c"
"libcoap/src/coap_mbedtls.c")
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "${include_dirs}"
REQUIRES lwip mbedtls)
target_compile_options(${COMPONENT_LIB} PRIVATE "-Wno-format")
@@ -0,0 +1,109 @@
menu "CoAP Configuration"
visible if LWIP_IPV6
choice COAP_MBEDTLS_ENCRYPTION_MODE
prompt "CoAP Encryption method"
default COAP_MBEDTLS_PSK
help
If the CoAP information is to be encrypted, the encryption environment
can be set up in one of two ways (default being Pre-Shared key mode)
- Encrypt using defined Pre-Shared Keys (PSK if uri includes coaps://)
- Encrypt using defined Public Key Infrastructure (PKI if uri includes coaps://)
config COAP_MBEDTLS_PSK
bool "Pre-Shared Keys"
config COAP_MBEDTLS_PKI
bool "PKI Certificates"
endchoice #COAP_MBEDTLS_ENCRYPTION_MODE
config COAP_MBEDTLS_DEBUG
bool "Enable CoAP debugging"
default n
help
Enable CoAP debugging functions at compile time for the example code.
If this option is enabled, call coap_set_log_level()
at runtime in order to enable CoAP debug output via the ESP
log mechanism.
Note: The Mbed TLS library logging is controlled by the mbedTLS
configuration, but logging level mbedTLS must be set for CoAP
to log it.
choice COAP_MBEDTLS_DEBUG_LEVEL
bool "Set CoAP debugging level"
depends on COAP_MBEDTLS_DEBUG
default COAP_LOG_WARNING
help
Set CoAP debugging level
config COAP_LOG_EMERG
bool "Emergency"
config COAP_LOG_ALERT
bool "Alert"
config COAP_LOG_CRIT
bool "Critical"
config COAP_LOG_ERROR
bool "Error"
config COAP_LOG_WARNING
bool "Warning"
config COAP_LOG_NOTICE
bool "Notice"
config COAP_LOG_INFO
bool "Info"
config COAP_LOG_DEBUG
bool "Debug"
config COAP_LOG_MBEDTLS
bool "mbedTLS"
endchoice
config COAP_LOG_DEFAULT_LEVEL
int
default 0 if !COAP_MBEDTLS_DEBUG
default 0 if COAP_LOG_EMERG
default 1 if COAP_LOG_ALERT
default 2 if COAP_LOG_CRIT
default 3 if COAP_LOG_ERROR
default 4 if COAP_LOG_WARNING
default 5 if COAP_LOG_NOTICE
default 6 if COAP_LOG_INFO
default 7 if COAP_LOG_DEBUG
default 9 if COAP_LOG_MBEDTLS
config COAP_TCP_SUPPORT
bool "Enable TCP within CoAP"
default y
help
Enable TCP functionality for CoAP. This is required if TLS sessions
are to be used.
If this option is disabled, redundent CoAP TCP code is removed.
config COAP_CLIENT_SUPPORT
bool "Enable Client functionality within CoAP"
default n
help
Enable client functionality (ability to make requests and receive
responses) for CoAP. If the server is going to act as a proxy, then
this needs to be enabled to support the ongoing session going to
the next hop.
If this option is disabled, redundent CoAP client only code is removed.
If both this option and COAP_SERVER_SUPPORT are disabled, then both
are automatically enabled for backwards compatability.
config COAP_SERVER_SUPPORT
bool "Enable Server functionality within CoAP"
default n
help
Enable server functionality (ability to receive requests and send
responses) for CoAP.
If this option is disabled, redundent CoAP server only code is removed.
If both this option and COAP_CLIENT_SUPPORT are disabled, then both
are automatically enabled for backwards compatability.
endmenu
@@ -0,0 +1,85 @@
Copyright (c) 2010--2022, Olaf Bergmann and others
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================
getopt.c
License information for getopt.c. This file is only used on Windows
builds of the executables in the examples folder:
/*
* This file was copied from the following newsgroup posting:
*
* Newsgroups: mod.std.unix
* Subject: public domain AT&T getopt source
* Date: 3 Nov 85 19:34:15 GMT
*
* Here's something you've all been waiting for: the AT&T public domain
* source for getopt(3). It is the code which was given out at the 1985
* UNIFORUM conference in Dallas. I obtained it by electronic mail
* directly from AT&T. The people there assure me that it is indeed
* in the public domain.
*/
========================================================================
uthash
libcoap uses uthash.h and utlist.h from Troy D. Hanson
(https://troydhanson.github.io/uthash/). These files use the revised
BSD license (BSD-1-Clause license) as included in these two source
files.
========================================================================
OpenSSL
Binaries that are linked against OpenSSL include software developed
by the OpenSSL Project for use in the OpenSSL Toolkit.
(http://www.openssl.org/). Please consult the OpenSSL license
(https://www.openssl.org/source/license.html) for licensing terms.
========================================================================
GnuTLS
When compiled with GnuTLS support, this software includes components
that are licensed under the terms of the the GNU Lesser General Public
License, version 2.1
(https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html).
========================================================================
tinyDTLS
When compiled with tinyDTLS support, this software includes components
that are licensed under the terms of the Eclipse Distribution License 1.0
(http://www.eclipse.org/org/documents/edl-v10.php).
========================================================================
Mbed TLS
When compiled with Mbed TLS support, this software includes components
that are licensed under the terms of the Apache 2.0 license
(http://www.apache.org/licenses/LICENSE-2.0).
@@ -0,0 +1,89 @@
# libcoap: A C implementation of the Constrained Application Protocol (RFC 7252)
[![Build Status: main](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/obgm/libcoap/actions?query=branch:main)
[![Build Status: develop](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=develop)](https://github.com/obgm/libcoap/actions?query=branch:develop)
[![Static Analysis](https://scan.coverity.com/projects/10970/badge.svg?flat=1)](https://scan.coverity.com/projects/obgm-libcoap)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/libcoap.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:libcoap)
Copyright (C) 2010—2022 by Olaf Bergmann <bergmann@tzi.org> and others
ABOUT LIBCOAP
=============
libcoap is a C implementation of a lightweight application-protocol
for devices that are constrained their resources such as computing
power, RF range, memory, bandwidth, or network packet sizes. This
protocol, CoAP, is standardized by the IETF as RFC 7252. For further
information related to CoAP, see <http://coap.technology>.
You might want to check out
[libcoap-minimal](https://github.com/obgm/libcoap-minimal) for usage
examples.
DOCUMENTATION
=============
Documentation and further information can be found at
<https://libcoap.net>.
PACKAGE CONTENTS
================
This package contains a protocol parser and basic networking
functions for platforms with support for malloc() and BSD-style
sockets. In addition, there is support for Contiki, LwIP and
Espressif/ESP-IDF hosted environments.
The following RFCs are supported
* RFC7252: The Constrained Application Protocol (CoAP)
* RFC7390: Group Communication for the Constrained Application Protocol (CoAP)
* RFC7641: Observing Resources in the Constrained Application Protocol (CoAP)
* RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)
* RFC7967: Constrained Application Protocol (CoAP) Option for No Server Response
* RFC8132: PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
* RFC8323: CoAP (Constrained Application Protocol) over TCP, TLS, and WebSockets
[No WebSockets support]
* RFC8516: "Too Many Requests" Response Code for the Constrained Application Protocol
* RFC8768: Constrained Application Protocol (CoAP) Hop-Limit Option
* RFC9175: CoAP: Echo, Request-Tag, and Token Processing
There is (D)TLS support for the following libraries
* OpenSSL (Minimum version 1.1.0) [PKI, PSK and PKCS11]
* GnuTLS (Minimum version 3.3.0) [PKI, PSK, RPK(3.6.6+) and PKCS11]
* Mbed TLS (Minimum version 2.7.10) [PKI and PSK]
* TinyDTLS [PSK and RPK] [DTLS Only]
The examples directory contain a CoAP client, CoAP Resource Directory server
and a CoAP server to demonstrate the use of this library.
BUILDING
========
Further information can be found at <https://libcoap.net/install.html>
and [BUILDING](https://raw.githubusercontent.com/obgm/libcoap/develop/BUILDING).
LICENSE INFORMATION
===================
This library is published as open-source software without any warranty
of any kind. Use is permitted under the terms of the simplified BSD
license. It includes public domain software. libcoap binaries may also
include open-source software with their respective licensing terms.
Please refer to
[LICENSE](https://raw.githubusercontent.com/obgm/libcoap/develop/LICENSE)
for further details.
@@ -0,0 +1,5 @@
dependencies:
idf: '>=4.4'
description: Constrained Application Protocol (CoAP) C Library
url: https://github.com/espressif/idf-extra-components/tree/master/coap
version: 4.3.1~1
@@ -0,0 +1,112 @@
---
name: Bug report
about: libcoap crashes, produces incorrect output, or has incorrect behavior
title: ''
labels: ''
assignees: ''
---
----------------------------- Delete Below -----------------------------
INSTRUCTIONS
============
Before submitting a new issue, please follow the checklist and try to find the
answer.
- [ ] I have read the documentation [libcoap Modules Documentation](https://libcoap.net/doc/reference/develop/modules.html)
and the issue is not addressed there.
- [ ] I have read the documentation [libcoap Manual Pages](https://libcoap.net/doc/reference/develop/manpage.html)
and the issue is not addressed there.
- [ ] I have updated my libcoap branch (develop) to the latest version and
checked that the issue is present there.
- [ ] I have searched the [Issue Tracker](https://github.com/obgm/libcoap/issues)
(both open and closed - overwrite `is:issue is:open`) for a similar issue and
not found a similar issue.
- [ ] I have checked the [Wiki](https://github.com/obgm/libcoap/wiki) to see if
the issue is reported there.
- [ ] I have read the HOWTOs provided with the source.
- [ ] I have read the [BUILDING](https://raw.githubusercontent.com/obgm/libcoap/develop/BUILDING)
on how to build from source.
If the issue cannot be solved after checking through the steps above, please
follow these instructions so we can get the needed information to help you in a
quick and effective fashion.
1. Fill in all the fields under **Environment** marked with [ ] by picking the
correct option for you in each case and deleting the others.
2. Describe your problem.
3. Include any debug logs (running the application with verbose logging).
4. Providing as much information as possible under **Other items if possible**
will help us locate and fix the problem.
5. Use [Markdown](https://guides.github.com/features/mastering-markdown/) (see
formatting buttons above) and the Preview tab to check what the issue will look
like.
6. Delete these instructions from the `Delete Below` to the `Delete Above`
marker lines before submitting this issue.
**IMPORTANT: If you do not follow these instructions and provide the necessary
details, it may not be possible to resolve your issue.**
----------------------------- Delete Above -----------------------------
## Environment
- libcoap version (run ``git describe --tags`` to find it):
// v4.3.0-rc3-41-g25fe796
- Build System: [Make|CMake]
- Operating System: [Windows|Linux|macOS|FreeBSD|Cygwin|Solaris|RIOT|Other (which?)]
- Operating System Version: [ ]
- Hosted Environment: [None|Contiki|LwIP|ESP-IDF|Other (which?)]
## Problem Description
// Detailed problem description goes here.
### Expected Behavior
// Describe what you are expecting.
### Actual Behavior
// Describe what you are seeing.
### Steps to reproduce
1. step1
2. ...
### Code to reproduce this issue
```cpp
// the code should be wrapped in the ```cpp tag so that it will be displayed
better.
#include "coap3/coap.h"
void main()
{
}
```
// If your code is longer than 30 lines, upload it as an attachment. Do not
include code that is proprietary or sensitive for your project. Try to reduce
your code as much as possible so that it only demonstrates the issue.
## Debug Logs
```
Debug verbose logs go here.
Please copy the plain text here for us to search the error log. Or attach the
complete logs but leave the main part here if the log is *too* long.
```
## Other items if possible
- [ ] Does what you are trying to do work under any configuration. Detail what
works.
- [ ] Network configuration that is not straightforward. Detail any networking
that may have NAT or firewalls that might affect what is going on.
@@ -0,0 +1,14 @@
blank_issues_enabled: false
contact_links:
- name: General libcoap Information
url: https://libcoap.net/
about: General information about libcoap
- name: General libcoap Documentation
url: https://libcoap.net/documentation.html
about: Documentation information for libcoap
- name: Latest libcoap API Documentation
url: https://libcoap.net/doc/reference/develop/modules.html
about: Latest API information for libcoap
- name: Latest libcoap Manual Pages
url: https://libcoap.net/doc/reference/develop/manpage.html
about: Latest Manual Pages and Examples for libcoap
@@ -0,0 +1,26 @@
---
name: Feature request
about: Suggest an idea for libcoap
title: ''
labels: 'Type: Feature Request'
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. E.g. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
Please give as many details as you can. Include suggestions for useful APIs or interfaces if relevant.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,196 @@
name: Build Tests
on:
push:
branches:
- main
- develop
- release-*
- gh-workflows
pull_request:
branches:
- main
- develop
env:
PLATFORM: posix
TESTS: yes
OPENSSL_INSTALL_PATH: C:\Program Files\OpenSSL-Win64\
jobs:
build-linux:
runs-on: ubuntu-latest
strategy:
matrix:
CC: ["gcc", "clang"]
TLS: ["no", "openssl", "gnutls", "mbedtls"]
steps:
- uses: actions/checkout@v2
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libcunit1-dev libmbedtls-dev libgnutls28-dev libtool libtool-bin exuberant-ctags valgrind
./autogen.sh
- name: configure no-TLS
if: matrix.TLS == 'no'
run: |
mkdir build-${{matrix.TLS}}-${{matrix.CC}}
cd build-${{matrix.TLS}}-${{matrix.CC}}
$GITHUB_WORKSPACE/configure --disable-silent-rules --disable-documentation --enable-examples --enable-tests --disable-dtls CC=${{matrix.CC}}
- name: configure TLS
if: matrix.TLS != 'no'
run: |
mkdir build-${{matrix.TLS}}-${{matrix.CC}}
cd build-${{matrix.TLS}}-${{matrix.CC}}
"$GITHUB_WORKSPACE/configure" --disable-silent-rules --disable-documentation --enable-examples --enable-tests --with-${{matrix.TLS}} CC=${{matrix.CC}}
- name: compile
run: |
cd build-${{matrix.TLS}}-${{matrix.CC}}
make EXTRA_CFLAGS=-Werror && make check EXTRA_CFLAGS=-Werror
- name: test
run: |
cd build-${{matrix.TLS}}-${{matrix.CC}}
libtool --mode=execute valgrind --track-origins=yes --leak-check=yes --show-reachable=yes --error-exitcode=123 --quiet --suppressions=$GITHUB_WORKSPACE/tests/valgrind_suppression tests/testdriver
tinydtls-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libcunit1-dev libtool libtool-bin exuberant-ctags valgrind
./autogen.sh
- name: configure
run: |
$GITHUB_WORKSPACE/configure --disable-silent-rules --disable-documentation --enable-examples --enable-tests --with-tinydtls
- name: compile
run: |
make EXTRA_CFLAGS=-Werror && make check EXTRA_CFLAGS=-Werror
- name: test
run: |
LD_LIBRARY_PATH=ext/tinydtls libtool --mode=execute valgrind --track-origins=yes --leak-check=yes --show-reachable=yes --error-exitcode=123 --quiet --suppressions=$GITHUB_WORKSPACE/tests/valgrind_suppression tests/testdriver
cmake-build:
runs-on: ubuntu-latest
strategy:
matrix:
TLS: ["no", "openssl", "gnutls", "mbedtls", "tinydtls"]
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libcunit1-dev libmbedtls-dev libgnutls28-dev
cmake -E make_directory $GITHUB_WORKSPACE}/build-${{matrix.TLS}}-cmake
- name: configure no-TLS
if: matrix.TLS == 'no'
run: |
cd $GITHUB_WORKSPACE}/build-${{matrix.TLS}}-cmake
cmake $GITHUB_WORKSPACE -DENABLE_EXAMPLES=ON -DENABLE_TESTS=ON -DENABLE_DTLS=OFF -DENABLE_DOCS=OFF
- name: configure TLS
if: matrix.TLS != 'no'
run: |
cd $GITHUB_WORKSPACE}/build-${{matrix.TLS}}-cmake
cmake $GITHUB_WORKSPACE -DENABLE_EXAMPLES=ON -DENABLE_TESTS=ON -DENABLE_DTLS=ON -DENABLE_DOCS=OFF -DDTLS_BACKEND=${{matrix.TLS}}
- name: build
run: |
cd $GITHUB_WORKSPACE}/build-${{matrix.TLS}}-cmake
cmake --build .
other-build:
runs-on: ubuntu-latest
strategy:
matrix:
OS: ["contiki", "lwip"]
steps:
- uses: actions/checkout@v2
- name: setup
run: |
./autogen.sh
- name: configure
run: |
$GITHUB_WORKSPACE/configure --disable-documentation --disable-examples --disable-tests --disable-dtls
- name: compile
run: |
make -C examples/${{matrix.OS}}
ms-build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Add MSBuild to PATH
uses: microsoft/setup-msbuild@v1
- name: Install OpenSSL on Windows (choco)
run: |
choco install openssl
shell: cmd
- name: Build sln
shell: cmd
run: call .\scripts\msbuild.sln.cmd
additional-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libgnutls28-dev libtool libtool-bin exuberant-ctags
./autogen.sh
- name: configure
run: ./configure --disable-tests --disable-documentation
- name: build
run: |
make
make -C tests/oss-fuzz -f Makefile.ci check clean
documentation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libtool libtool-bin exuberant-ctags graphviz doxygen libxml2-utils xsltproc docbook-xml docbook-xsl asciidoc
./autogen.sh
- name: configure
run: ./configure --disable-tests --enable-documentation --prefix $GITHUB_WORKSPACE/test-install
- name: manuals check
run: |
make -C man
- name: manual page examples check
run: |
man/examples-code-check man
- name: doxygen check
run: |
make -C doc
- name: installation check
run: |
make install && ls -lR $GITHUB_WORKSPACE/test-install
distribution:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: setup
run: |
sudo apt-get update && sudo apt-get install -y libcunit1-dev libtool libtool-bin exuberant-ctags graphviz doxygen libxml2-utils xsltproc docbook-xml docbook-xsl asciidoc
./autogen.sh
- name: configure
run: |
mkdir build-dist
cd build-dist
$GITHUB_WORKSPACE/configure --enable-silent-rules --enable-documentation --enable-examples --disable-dtls
- name: build distribution
run: |
cd build-dist
make dist
- name: check distribution build
run: |
cd build-dist
$GITHUB_WORKSPACE/scripts/github_dist.sh
shell: bash
@@ -0,0 +1,116 @@
# .gitignore for libcoap
# autosave files
*~
\#*#
# ignoring autogenerated files and directories by autoreconf
INSTALL
Makefile
Makefile.in
aclocal.m4
ar-lib
autom4te.cache/
coap_config.h
coap_config.h.in
compile
config.*
!config.yml
configure
debian/
depcomp
install-sh
libcoap-*.tar.bz2
libtool
ltmain.sh
m4/libtool.m4
m4/ltoptions.m4
m4/ltsugar.m4
m4/ltversion.m4
m4/lt~obsolete.m4
missing
stamp-h1
# ignoring more files generated by the configure script or the make actions
.libs/
libcoap*.la
libcoap*.pc
src/**/.deps/
src/**/.dirstamp
src/**/.libs/
src/**/*.o
src/**/*.lo
src/*.lo
src/*.o
src/.deps/
src/.dirstamp
src/.libs/
build/
# the doc/ folder
doc/Doxyfile
doc/Makefile.in
doc/docbook-xsl.css
doc/doxyfile.stamp
doc/doxygen_sqlite3.db
doc/DoxygenLayout.xml
doc/upgrade_*.html
doc/html/
doc/man_html/
doc/man_tmp/
# the man/ folder
man/docbook-xsl.css
man/examples-code-check
man/examples-code-check.exe
man/examples-code-check.o
man/Makefile
man/Makefile.in
man/tmp
man/.deps/
man/*.html
man/*.txt
man/*.xml
man/*.3
man/*.5
man/*.7
# the examples/ folder
examples/.deps/
examples/*.o
examples/coap-client
examples/coap-client-*
examples/coap-etsi_iot_01
examples/coap-rd
examples/coap-rd-*
examples/coap-server
examples/coap-server-*
examples/coap-tiny
examples/*.exe
# the include/ folder
include/coap3/coap.h
# the tests/ folder
tests/.deps
tests/oss-fuzz/Makefile.ci
tests/testdriver
tests/*.o
tests/test_common.h
# ctags - Sublime plugin
tags
.tags*
TAGS
# ignore gcov-generated files
**/*.gcda
**/*.gcno
**/*.gcov
# IDE files
CMakeLists.txt.user
/.vs/
/out/
/.vscode/
/_build/
@@ -0,0 +1,4 @@
[submodule "ext/tinydtls"]
path = ext/tinydtls
url = https://github.com/eclipse/tinydtls.git
ignore = dirty
@@ -0,0 +1,70 @@
os:
- linux
language: c
compiler:
- gcc
- clang
services:
- docker
env:
- PLATFORM=posix TESTS=yes TLS=no
- PLATFORM=posix TESTS=yes TLS=gnutls SMALL_STACK=yes
- PLATFORM=posix TESTS=yes TLS=gnutls SMALL_STACK=no
- PLATFORM=posix TESTS=yes TLS=gnutls SMALL_STACK=yes EPOLL=no
- PLATFORM=posix TESTS=yes TLS=gnutls SMALL_STACK=no EPOLL=no
- PLATFORM=posix TESTS=yes TLS=openssl
- PLATFORM=posix TESTS=yes TLS=tinydtls
- PLATFORM=posix TESTS=yes TLS=mbedtls
before_install:
- docker build -t obgm/libcoap:travis-env .
branches:
only:
- main
- develop
- /^release-.*$/
- travis-test
stages:
- test
- other platforms
- dist
jobs:
include:
- stage: other platforms
env: PLATFORM=contiki TLS=no
before_script:
script:
- docker run --privileged -e CC -e PLATFORM -e TLS obgm/libcoap:travis-env /bin/sh -c "scripts/build.sh"
- stage: other platforms
env: PLATFORM=lwip TLS=no
before_script:
script:
- docker run --privileged -e CC -e PLATFORM -e TLS obgm/libcoap:travis-env /bin/sh -c "scripts/build.sh"
- stage: dist
env: PLATFORM=posix TESTS=yes TLS=no DOCS=yes
before_script:
script:
- docker run --privileged -e CC -e PLATFORM -e TESTS -e DOCS -e TLS obgm/libcoap:travis-env /bin/sh -c "scripts/dist.sh"
# Docker disables IPv6 in containers by default, so re-enable it.
before_script:
# `daemon.json` is normally missing, but let's log it in case that changes.
- sudo touch /etc/docker/daemon.json
- sudo cat /etc/docker/daemon.json
- sudo service docker stop
# This needs YAML quoting because of the curly braces.
- 'echo ''{"ipv6": true, "fixed-cidr-v6": "2001:db8:1::/64"}'' | sudo tee /etc/docker/daemon.json'
- sudo service docker start
# Fail early if docker failed on start -- add `- sudo dockerd` to debug.
- sudo docker info
# Paranoia log: what if our config got overwritten?
- sudo cat /etc/docker/daemon.json
script:
- docker run --privileged -e CC -e PLATFORM -e TESTS -e DOCS -e TLS -e EPOLL -e SMALL_STACK obgm/libcoap:travis-env /bin/sh -c "scripts/build.sh"
@@ -0,0 +1,8 @@
Olaf Bergmann
Carsten Schönert
Jon Shallow
Jean-Claude Michelou
Christian Amsüss
For additional contributors, see
https://github.com/obgm/libcoap/graphs/contributors
@@ -0,0 +1,157 @@
For Windows builds - see the Windows Section
Obtaining the Libcoap Source
============================
To get the libcoap library source, you need to do either the following
* Obtain the latest distribution package file from
https://github.com/obgm/libcoap/archive/develop.zip
[There is a stable version at
https://github.com/obgm/libcoap/archive/main.zip]
* Change to the directory that you want to install the libcoap sub-directory
into
* Unpack the distribution package file
* Change into the top level directory of the unpackaged files
or alternatively, clone the libcoap git repository from github
* Change to the directory that you want to install the libcoap sub-directory
into.
* Then clone the latest (develop) version of the code:-
git clone https://github.com/obgm/libcoap.git
* Change into the top level directory of the cloned files
* Optionally, change the branch from develop to the stable main branch:-
git checkout main
Building Libcoap Libraries and Examples
=======================================
Follow the appropriate sections below
TinyDTLS Only
=============
It is possible that you may need to execute the following two commands once to
get the TinyDTLS code into your project, so the TinyDTLS library can be used.
git submodule init
git submodule update
General Building with cmake for linux/windows/macos/android (not for LwIP or Contiki - see below)
================
cmake -E remove_directory build
cmake -E make_directory build
cd build
cmake .. -DENABLE_TESTS=ON
cmake --build .
[sudo] cmake --build . -- install
cd ..
Note: to see possible options (TLS lib, doc, tests, examples etc.):
cmake -LH build
Note: For Windows, this is supported by Visual Studio Code with CMake extension
Note: You must use cmake version >=3.10.
Note: you can use cmake's find package after installation: find_package(libcoap-2 REQUIRED),
and target_link_libraries(myTarget PRIVATE libcoap::coap-2)
Note: Shared Library support is not currently available for Windows.
General Building with autoconf (not for LwIP or Contiki - see below)
================
./autogen.sh
./configure
make
sudo make install
./autogen.sh will fail if there is a required package for buildling libcoap
that is missing. Install the missing package and try ./autogen.sh again.
It is possible that you may need to provide some options to ./configure
to customize your installation.
In particular you may need to define which (D)TLS library to use as well as
disable some building of documentation.
General configure instructions can be found in INSTALL, which is built
by ./autogen.sh
./configure --help
gives the specific options available to libcoap.
Some examples are:-
# No DTLS
./configure --enable-tests --disable-documentation --enable-examples --disable-dtls --enable-shared
# With TinyDTLS
./configure --enable-tests --disable-documentation --enable-examples --with-tinydtls --enable-shared
Note: FreeBSD requires gmake instead of make when building TinyDTLS - i.e.
gmake
sudo gmake install
# With OpenSSL
./configure --with-openssl --enable-tests --enable-shared
# With GnuTLS
./configure --with-gnutls --enable-tests --enable-shared
Note: --disable-documentation disables the building of doxygen and man page
files. If you want to only disable one of them, use --disable-doxygen or
--disable-manpages. Doxygen requires the program doxygen and man pages require
the program a2x to build the appropriate files.
If you need to rebuild the libcoap-*.{map,sym} files to update any exposed
function changes, run
make update-map-file
prior to running 'make'.
LwIP
====
./autogen.sh
./configure --disable-tests --disable-documentation --disable-examples --disable-dtls
cd examples/lwip
make
Executable is ./server. See examples/lwip/README for further information
Contiki
=======
./autogen.sh
./configure --disable-tests --disable-documentation --disable-examples --disable-dtls
cd examples/contiki
make
Executable is ./server.minimal-net. See examples/contiki/README for further
information
Windows
=======
Install OpenSSL (minimum version 1.1.0) including the development libraries if
not already installed.
Within Visual Studio, "Clone or check out code" using the repository
https://github.com/obgm/libcoap.git
You may need to update the SDK version of the libcoap Windows Project files to
match that of the SDK version of the Visual Studio you are using. In Solution
Explorer with the view set to libcoap.sln, right click "Solution 'libcoap'"
and then "Retarget solution".
You may need to edit win32\libcoap.props to update the OpenSSLRootDir and
OpenSSLRootDirDbg variables to point to the top level directory where OpenSSL
is installed so that the include, lib etc. directories are correctly set up.
Note: Make sure that you include a trailing \ in the variable definitions.
Alternatively you can build everything in Visual Studio with CMake.
@@ -0,0 +1,723 @@
# CMakeLists.txt for libcoap
#
# Copyright (C) 2020 Carlos Gomes Martinho <carlos.gomes_martinho@siemens.com>
# Copyright (C) 2020-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
#
# SPDX-License-Identifier: BSD-2-Clause
#
# This file is part of the CoAP library libcoap. Please see README for terms
# of use.
cmake_minimum_required(VERSION 3.10)
project(
libcoap
VERSION 4.3.1
LANGUAGES CXX C)
set(LIBCOAP_API_VERSION 3)
set(COAP_LIBRARY_NAME "coap-${LIBCOAP_API_VERSION}")
option(
BUILD_SHARED_LIBS
"Build shared libs"
OFF)
add_library(${COAP_LIBRARY_NAME})
#
# options to tweak the library
#
option(
ENABLE_DTLS
"Enable building with DTLS support"
ON)
set(DTLS_BACKEND
"default"
CACHE
STRING
"\
Name of the dtls backend, only relevant if `ENABLE_DTLS` is ON which is default. \
Possible values: default, gnutls, openssl, tinydtls and mbedtls. \
If specified then this library will be searched and if found also used. \
If not found then the cmake configuration will stop with an error. \
If not specified, then cmake will try to use the first one found in the following order: \
gnutls, openssl, tinydtls, mbedtls \
")
set_property(
CACHE DTLS_BACKEND
PROPERTY STRINGS
default
openssl
gnutls
tinydtls
mbedtls)
option(
USE_VENDORED_TINYDTLS
"compile with the tinydtls project in the submodule if on, otherwise try to find the compiled lib with find_package"
ON)
option(
ENABLE_CLIENT_MODE
"compile with support for client mode code"
ON)
option(
ENABLE_SERVER_MODE
"compile with support for server mode code"
ON)
option(
WITH_EPOLL
"compile with epoll support"
ON)
option(
ENABLE_SMALL_STACK
"Define if the system has small stack size"
OFF)
option(
ENABLE_TCP
"Enable building with TCP support"
ON)
option(
ENABLE_TESTS
"build also tests"
OFF)
option(
ENABLE_EXAMPLES
"build also examples"
ON)
option(
ENABLE_DOCS
"build also doxygen documentation"
ON)
if(NOT CMAKE_C_STANDARD)
set(CMAKE_C_STANDARD 11)
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
endif()
if(MSVC)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif()
if(APPLE)
add_definitions(-D__APPLE_USE_RFC_3542=1)
endif()
list(APPEND CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR})
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_BINARY_DIR})
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
include(CheckCSourceCompiles)
include(CheckFunctionExists)
include(CheckIncludeFile)
include(CheckSymbolExists)
include(CheckTypeSize)
include(TestBigEndian)
# check for headers
check_include_file(byteswap.h HAVE_BYTESWAP_H)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_include_file(limits.h HAVE_LIMITS_H)
check_include_file(memory.h HAVE_MEMORY_H)
check_include_file(strings.h HAVE_STRINGS_H)
check_include_file(string.h HAVE_STRING_H)
check_include_file(sys/sysctl.h HAVE_SYS_SYSCTL_H)
check_include_file(net/if.h HAVE_NET_IF_H)
check_include_file(netinet/in.h HAVE_NETINET_IN_H)
check_include_file(sys/epoll.h HAVE_EPOLL_H)
check_include_file(sys/timerfd.h HAVE_TIMERFD_H)
check_include_file(arpa/inet.h HAVE_ARPA_INET_H)
check_include_file(stdbool.h HAVE_STDBOOL_H)
check_include_file(netdb.h HAVE_NETDB_H)
check_include_file(pthread.h HAVE_PTHREAD_H)
check_include_file(stdlib.h HAVE_STDINT_H)
check_include_file(stdint.h HAVE_STDLIB_H)
check_include_file(syslog.h HAVE_SYSLOG_H)
check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
check_include_file(sys/socket.h HAVE_SYS_SOCKET_H)
check_include_file(sys/stat.h HAVE_SYS_STAT_H)
check_include_file(sys/time.h HAVE_SYS_TIME_H)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(sys/unistd.h HAVE_SYS_UNISTD_H)
check_include_file(time.h HAVE_TIME_H)
check_include_file(unistd.h HAVE_UNISTD_H)
check_include_file(float.h HAVE_FLOAT_H)
check_include_file(stddef.h HAVE_STDDEF_H)
check_include_file(winsock2.h HAVE_WINSOCK2_H)
check_include_file(ws2tcpip.h HAVE_WS2TCPIP_H)
# check for functions
check_function_exists(malloc HAVE_MALLOC)
check_function_exists(memset HAVE_MEMSET)
check_function_exists(select HAVE_SELECT)
check_function_exists(socket HAVE_SOCKET)
check_function_exists(strcasecmp HAVE_STRCASECMP)
check_function_exists(pthread_mutex_lock HAVE_PTHREAD_MUTEX_LOCK)
check_function_exists(getaddrinfo HAVE_GETADDRINFO)
check_function_exists(strnlen HAVE_STRNLEN)
check_function_exists(strrchr HAVE_STRRCHR)
check_function_exists(getrandom HAVE_GETRANDOM)
check_function_exists(if_nametoindex HAVE_IF_NAMETOINDEX)
# check for symbols
if(WIN32)
set(HAVE_STRUCT_CMSGHDR 1)
else()
check_symbol_exists(
CMSG_FIRSTHDR
sys/socket.h
HAVE_STRUCT_CMSGHDR)
endif()
if(${ENABLE_CLIENT_MODE})
set(COAP_CLIENT_SUPPORT "1")
message(STATUS "compiling with client support")
else()
message(STATUS "compiling without client support")
endif()
if(${ENABLE_SERVER_MODE})
set(COAP_SERVER_SUPPORT "1")
message(STATUS "compiling with server support")
else()
message(STATUS "compiling without server support")
endif()
if(${WITH_EPOLL}
AND ${HAVE_EPOLL_H}
AND ${HAVE_TIMERFD_H})
set(COAP_EPOLL_SUPPORT "1")
message(STATUS "compiling with epoll support")
else()
message(STATUS "compiling without epoll support")
endif()
if(ENABLE_SMALL_STACK)
set(ENABLE_SMALL_STACK "${ENABLE_SMALL_STACK}")
message(STATUS "compiling with small stack support")
endif()
set(WITH_GNUTLS OFF)
set(WITH_OPENSSL OFF)
set(WITH_TINYDTLS OFF)
set(WITH_MBEDTLS OFF)
function(compile_tinydtls)
set(TINYDTLS_SOURCES_DIR ${CMAKE_CURRENT_LIST_DIR}/ext/tinydtls)
set(TINYDTLS_SOURCES_GENERATED ${TINYDTLS_SOURCES_DIR}/dtls_config.h)
message(STATUS "compiling the tinydtls lib")
include(ExternalProject)
externalproject_add(
external_tinydtls
SOURCE_DIR "${TINYDTLS_SOURCES_DIR}"
BUILD_IN_SOURCE 1
DOWNLOAD_COMMAND ""
UPDATE_COMMAND ""
CONFIGURE_COMMAND
${TINYDTLS_SOURCES_DIR}/configure
--disable-manpages
--prefix=${CMAKE_BINARY_DIR}
BUILD_COMMAND make install
INSTALL_COMMAND ""
LOG_DOWNLOAD 1
LOG_CONFIGURE 1)
externalproject_add_step(
external_tinydtls autoreconf
COMMAND autoreconf --force --install
ALWAYS 1
WORKING_DIRECTORY "${TINYDTLS_SOURCES_DIR}"
DEPENDERS configure
DEPENDEES download)
# Let cmake know that it needs to execute the external_tinydtls target to generate those files.
add_custom_command(
OUTPUT ${TINYDTLS_SOURCES_GENERATED}
WORKING_DIRECTORY "${TINYDTLS_SOURCES_DIR}"
COMMAND "make install"
DEPENDS external_tinydtls)
add_dependencies(${COAP_LIBRARY_NAME} external_tinydtls)
if(BUILD_SHARED_LIBS)
set(LIBTINYDTLS_PATH "${CMAKE_CURRENT_BINARY_DIR}/lib/libtinydtls.so")
else()
set(LIBTINYDTLS_PATH "${CMAKE_CURRENT_BINARY_DIR}/lib/libtinydtls.a")
endif()
add_library(
tinydtls
UNKNOWN
IMPORTED)
set_target_properties(
tinydtls
PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
"${CMAKE_CURRENT_BINARY_DIR}/include"
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${LIBTINYDTLS_PATH}")
endfunction()
if(ENABLE_DTLS)
message(STATUS "compiling with DTLS support")
message(STATUS "DTLS_BACKEND: ${DTLS_BACKEND}")
if(DTLS_BACKEND
STREQUAL
"default")
# try to find a crypto lib and use it, use the first one found
# libgnutls (e.g. debian libgnutls28-dev)
find_package(GnuTLS)
if(GnuTLS_FOUND)
set(WITH_GNUTLS ON)
message(STATUS "compiling with gnutls support")
set(HAVE_LIBGNUTLS 1)
else()
# gnutls not found
find_package(OpenSSL)
if(OpenSSL_FOUND)
set(WITH_OPENSSL ON)
message(STATUS "compiling with openssl support")
set(HAVE_OPENSSL 1)
else()
# openssl not found
# libmbedtls (e.g. debian libmbedtls-dev)
find_package(MbedTLS)
if(MbedTLS_FOUND)
set(WITH_MBEDTLS ON)
message(STATUS "compiling with mbedtls support")
set(HAVE_MBEDTLS 1)
else()
# mbedtls not found
if(USE_VENDORED_TINYDTLS)
compile_tinydtls()
else()
find_package(TinyDTLS)
if(TINYDTLS_FOUND)
else()
# no cryto lib found
message(
FATAL_ERROR
"cannot find any cryto lib, either install one or compile without DTLS support"
)
endif()
endif()
set(WITH_TINYDTLS ON)
message(STATUS "compiling with tinydtls support")
set(HAVE_LIBTINYDTLS 1)
endif()
endif()
endif()
else()
# DTLS_BACKEND variable is not empty, so set all to false and set the only right to true
set(WITH_GNUTLS OFF)
set(WITH_TINYDTLS OFF)
set(WITH_MBEDTLS OFF)
set(WITH_OPENSSL OFF)
if(DTLS_BACKEND
STREQUAL
"gnutls")
# libgnutls (e.g. debian libgnutls28-dev)
find_package(GnuTLS REQUIRED)
set(WITH_GNUTLS ON)
message(STATUS "compiling with gnutls support")
set(HAVE_LIBGNUTLS 1)
endif()
if(DTLS_BACKEND
STREQUAL
"openssl")
# libssl (e.g. debian libssl1.0-dev)
find_package(OpenSSL REQUIRED)
set(WITH_OPENSSL ON)
message(STATUS "compiling with openssl support")
set(HAVE_OPENSSL 1)
endif()
if(DTLS_BACKEND
STREQUAL
"mbedtls")
# libmbedtls (e.g. debian libmbedtls-dev)
find_package(MbedTLS REQUIRED)
set(WITH_MBEDTLS ON)
message(STATUS "compiling with mbedtls support")
set(HAVE_MBEDTLS 1)
endif()
if(DTLS_BACKEND
STREQUAL
"tinydtls")
if(USE_VENDORED_TINYDTLS)
compile_tinydtls()
else(USE_VENDORED_TINYDTLS)
find_package(TinyDTLS REQUIRED)
endif(USE_VENDORED_TINYDTLS)
message(STATUS "compiling with tinydtls support")
set(WITH_TINYDTLS ON)
set(HAVE_LIBTINYDTLS 1)
endif()
endif()
endif()
execute_process(COMMAND git describe --tags --dirty --always
RESULT_VARIABLE USING_GIT
OUTPUT_VARIABLE LIBCOAP_PACKAGE_BUILD
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET)
if(NOT ${USING_GIT} EQUAL 0)
set(LIBCOAP_PACKAGE_BUILD ${PROJECT_VERSION})
else()
set(LIBCOAP_PACKAGE_BUILD "${LIBCOAP_PACKAGE_BUILD}")
endif()
set(PACKAGE_URL "https://libcoap.net/")
set(PACKAGE_NAME "${PROJECT_NAME}")
set(PACKAGE_TARNAME "${PROJECT_NAME}")
set(PACKAGE_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(PACKAGE_VERSION "${PROJECT_VERSION}")
set(PACKAGE_BUGREPORT "libcoap-developers@lists.sourceforge.net")
set(LIBCOAP_PACKAGE_VERSION "${PACKAGE_VERSION}")
set(LIBCOAP_PACKAGE_URL "${PACKAGE_URL}")
set(LIBCOAP_PACKAGE_NAME "${PACKAGE_NAME}")
set(LIBCOAP_PACKAGE_STRING "${PACKAGE_STRING}")
set(LIBCOAP_PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}")
message(STATUS "PACKAGE VERSION..................${PACKAGE_VERSION}")
message(STATUS "PACKAGE BUILD....................${LIBCOAP_PACKAGE_BUILD}")
message(STATUS "ENABLE_DTLS:.....................${ENABLE_DTLS}")
message(STATUS "ENABLE_TCP:......................${ENABLE_TCP}")
message(STATUS "ENABLE_CLIENT_MODE:..............${ENABLE_CLIENT_MODE}")
message(STATUS "ENABLE_SERVER_MODE:..............${ENABLE_SERVER_MODE}")
message(STATUS "ENABLE_DOCS:.....................${ENABLE_DOCS}")
message(STATUS "ENABLE_EXAMPLES:.................${ENABLE_EXAMPLES}")
message(STATUS "DTLS_BACKEND:....................${DTLS_BACKEND}")
message(STATUS "WITH_GNUTLS:.....................${WITH_GNUTLS}")
message(STATUS "WITH_TINYDTLS:...................${WITH_TINYDTLS}")
message(STATUS "WITH_OPENSSL:....................${WITH_OPENSSL}")
message(STATUS "WITH_MBEDTLS:....................${WITH_MBEDTLS}")
message(STATUS "HAVE_LIBTINYDTLS:................${HAVE_LIBTINYDTLS}")
message(STATUS "HAVE_LIBGNUTLS:..................${HAVE_LIBGNUTLS}")
message(STATUS "HAVE_OPENSSL:....................${HAVE_OPENSSL}")
message(STATUS "HAVE_MBEDTLS:....................${HAVE_MBEDTLS}")
message(STATUS "WITH_EPOLL:......................${WITH_EPOLL}")
message(STATUS "CMAKE_C_COMPILER:................${CMAKE_C_COMPILER}")
message(STATUS "BUILD_SHARED_LIBS:...............${BUILD_SHARED_LIBS}")
message(STATUS "CMAKE_BUILD_TYPE:................${CMAKE_BUILD_TYPE}")
message(STATUS "CMAKE_SYSTEM_PROCESSOR:..........${CMAKE_SYSTEM_PROCESSOR}")
set(top_srcdir "${CMAKE_CURRENT_LIST_DIR}")
set(top_builddir "${CMAKE_CURRENT_BINARY_DIR}")
if(ENABLE_TCP)
set(COAP_DISABLE_TCP 0)
else(ENABLE_TCP)
set(COAP_DISABLE_TCP 1)
endif(ENABLE_TCP)
# creates config header file in build directory
configure_file(${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap.h.in
${CMAKE_CURRENT_BINARY_DIR}/include/coap${LIBCOAP_API_VERSION}/coap.h)
configure_file(${CMAKE_CURRENT_LIST_DIR}/cmake_coap_config.h.in
${CMAKE_CURRENT_BINARY_DIR}/coap_config.h)
configure_file(${CMAKE_CURRENT_LIST_DIR}/tests/test_common.h.in
${CMAKE_CURRENT_LIST_DIR}/tests/test_common.h)
#
# sources
#
target_sources(
${COAP_LIBRARY_NAME}
PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src/coap_address.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_asn1.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_async.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_cache.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_debug.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_event.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_hashkey.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_io.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_notls.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_option.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_prng.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_session.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_subscribe.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_tcp.c
${CMAKE_CURRENT_LIST_DIR}/src/coap_time.c
${CMAKE_CURRENT_LIST_DIR}/src/block.c
${CMAKE_CURRENT_LIST_DIR}/src/encode.c
${CMAKE_CURRENT_LIST_DIR}/src/mem.c
${CMAKE_CURRENT_LIST_DIR}/src/net.c
${CMAKE_CURRENT_LIST_DIR}/src/pdu.c
${CMAKE_CURRENT_LIST_DIR}/src/resource.c
${CMAKE_CURRENT_LIST_DIR}/src/str.c
${CMAKE_CURRENT_LIST_DIR}/src/uri.c
# no need to parse those files if we do not need them
$<$<BOOL:${HAVE_OPENSSL}>:${CMAKE_CURRENT_LIST_DIR}/src/coap_openssl.c>
$<$<BOOL:${HAVE_LIBTINYDTLS}>:${CMAKE_CURRENT_LIST_DIR}/src/coap_tinydtls.c>
$<$<BOOL:${HAVE_LIBGNUTLS}>:${CMAKE_CURRENT_LIST_DIR}/src/coap_gnutls.c>
$<$<BOOL:${HAVE_MBEDTLS}>:${CMAKE_CURRENT_LIST_DIR}/src/coap_mbedtls.c>
# headers
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_address.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_async.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_cache.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_debug.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_dtls.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_event.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_hashkey.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_io.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_option.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_prng.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_session.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_subscribe.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/coap_time.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/block.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/encode.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/libcoap.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/lwippools.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/mem.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/net.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/pdu.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/resource.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/str.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/uri.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/uthash.h
${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}/utlist.h)
target_include_directories(
${COAP_LIBRARY_NAME}
PUBLIC # config headers are generated during configuration time
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/>
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include/>
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include/>
$<INSTALL_INTERFACE:include/>
$<$<AND:$<BOOL:${HAVE_LIBTINYDTLS}>,$<BOOL:${USE_VENDORED_TINYDTLS}>>:${CMAKE_BINARY_DIR}/include/tinydtls>
$<$<BOOL:${HAVE_LIBGNUTLS}>:${GNUTLS_INCLUDE_DIR}>
$<$<BOOL:${HAVE_MBEDTLS}>:${MBEDTLS_INCLUDE_DIRS}>)
target_link_libraries(
${COAP_LIBRARY_NAME}
PUBLIC $<$<BOOL:${HAVE_OPENSSL}>:OpenSSL::SSL>
$<$<BOOL:${HAVE_OPENSSL}>:OpenSSL::Crypto>
$<$<BOOL:${HAVE_LIBGNUTLS}>:${GNUTLS_LIBRARIES}>
$<$<BOOL:${HAVE_LIBTINYDTLS}>:tinydtls>
$<$<BOOL:${HAVE_MBEDTLS}>:${MBEDTLS_LIBRARY}>
$<$<BOOL:${HAVE_MBEDTLS}>:${MBEDX509_LIBRARY}>
$<$<BOOL:${HAVE_MBEDTLS}>:${MBEDCRYPTO_LIBRARY}>)
target_compile_options(
${COAP_LIBRARY_NAME}
PUBLIC -DLIBCOAP_PACKAGE_BUILD="${LIBCOAP_PACKAGE_BUILD}")
add_library(
${PROJECT_NAME}::${COAP_LIBRARY_NAME}
ALIAS
${COAP_LIBRARY_NAME})
#
# compiler options
#
add_compile_options(
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-pedantic>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wall>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wcast-qual>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wextra>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wformat-security>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Winline>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wmissing-declarations>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wmissing-prototypes>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wnested-externs>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wpointer-arith>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wshadow>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wstrict-prototypes>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wswitch-default>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wswitch-enum>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wunused>
$<$<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>>:-Wwrite-strings>)
#
# tests
#
if(ENABLE_TESTS)
add_executable(
testdriver
${CMAKE_CURRENT_LIST_DIR}/tests/testdriver.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_common.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_encode.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_encode.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_error_response.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_error_response.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_options.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_options.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_pdu.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_pdu.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_sendqueue.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_sendqueue.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_session.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_session.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_tls.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_tls.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_uri.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_uri.h
${CMAKE_CURRENT_LIST_DIR}/tests/test_wellknown.c
${CMAKE_CURRENT_LIST_DIR}/tests/test_wellknown.h)
# tests require libcunit (e.g. debian libcunit1-dev)
target_link_libraries(testdriver PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME}
-lcunit)
endif()
#
# examples
#
if(ENABLE_EXAMPLES)
add_executable(coap-client ${CMAKE_CURRENT_LIST_DIR}/examples/coap-client.c)
target_link_libraries(coap-client
PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME})
add_executable(coap-rd ${CMAKE_CURRENT_LIST_DIR}/examples/coap-rd.c)
target_include_directories(coap-rd
PRIVATE
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include/coap${LIBCOAP_API_VERSION}>)
target_link_libraries(coap-rd PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME})
add_executable(coap-server ${CMAKE_CURRENT_LIST_DIR}/examples/coap-server.c)
target_link_libraries(coap-server
PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME})
if(NOT WIN32)
add_executable(etsi_iot_01 ${CMAKE_CURRENT_LIST_DIR}/examples/etsi_iot_01.c)
target_link_libraries(etsi_iot_01
PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME})
add_executable(tiny ${CMAKE_CURRENT_LIST_DIR}/examples/tiny.c)
target_link_libraries(tiny PUBLIC ${PROJECT_NAME}::${COAP_LIBRARY_NAME})
endif()
endif()
#
# docs
#
if(ENABLE_DOCS)
find_package(Doxygen)
if(Doxygen_FOUND)
# set input and output files
set(DOXYGEN_IN ${CMAKE_CURRENT_SOURCE_DIR}/doc/Doxyfile.in)
set(DOXYGEN_OUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)
# Make necessary temporary directories
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/doc/man_tmp)
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/doc/man_html)
# request to configure the file
configure_file(
${DOXYGEN_IN}
${DOXYGEN_OUT}
@ONLY)
# note the option ALL which allows to build the docs together with the
# application
add_custom_target(
doc_doxygen ALL
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating API documentation with Doxygen"
VERBATIM)
message(STATUS "Setup up the Doxygen documention build")
else(Doxygen_FOUND)
message(
WARNING
"Doxygen need to be installed to generate the doxygen documentation")
endif(Doxygen_FOUND)
endif()
#
# install
#
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(LIBCOAP_CONFIG_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME})
install(
TARGETS ${COAP_LIBRARY_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT lib
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT lib)
install(
EXPORT ${PROJECT_NAME}Targets
DESTINATION ${LIBCOAP_CONFIG_INSTALL_DIR}
NAMESPACE ${PROJECT_NAME}::
COMPONENT dev)
configure_package_config_file(
cmake/Config.cmake.in
${PROJECT_NAME}Config.cmake
INSTALL_DESTINATION
${LIBCOAP_CONFIG_INSTALL_DIR})
write_basic_package_version_file(
${PROJECT_NAME}ConfigVersion.cmake
COMPATIBILITY SameMajorVersion)
install(
FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
DESTINATION ${LIBCOAP_CONFIG_INSTALL_DIR}
COMPONENT dev)
install(
DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT dev
FILES_MATCHING
PATTERN "*.h"
PATTERN "coap.h" EXCLUDE
PATTERN "coap_riot.h" EXCLUDE
PATTERN "lwippools.h" EXCLUDE
PATTERN "utlist.h" EXCLUDE
PATTERN "uthash.h" EXCLUDE
PATTERN "*_internal.h" EXCLUDE)
install(
DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
COMPONENT dev
FILES_MATCHING
PATTERN "*.h")
if(ENABLE_EXAMPLES)
install(
TARGETS coap-server coap-client coap-rd
DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT dev)
if(NOT WIN32)
install(
TARGETS etsi_iot_01 tiny
DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT dev)
endif()
endif()
@@ -0,0 +1,218 @@
#######################################################
# Developer information for contributing to libcoap #
#######################################################
1. The basics
~~~~~~~~~~~~~
The libcoap project is a FOSS project that is dual licensed. The maintainer
for the libcoap is Olaf Bergmann <bergmann@tzi.org>.
Any contributions have to be made under the terms of the
license
* BSD 2-Clause (The BSD 2-Clause License)
Contributions made up to 2017-06-01 have been made under the dual
license model BSD 2-Clause and GPL v2+ (The GNU General Public License
2.0 or later).
The used VCS for libcoap is Git, the main repository is living on GitHub.
You can clone (or fork directly on GitHub) on the repository site:
https://github.com/obgm/libcoap
Please refer also to the libcoap website for additional information
https://libcoap.net/
The build environment is grounded on the classical autotools, the GNU GCC and
the LLVM C-compiler (CLang) are supported. The Windows systems are not
currently supported (until someone is creating support for it).
Doxygen is used for creating a HTML based online documentation of the
libcoap library.
2. Communications
~~~~~~~~~~~~~~~~~
The main discussion and development platform for libcoap is the mailing list
on Sourceforge.
No matter if you just have a simple question, some specific problem or
want to discuss some patches, please write it to the mailing list. Please
avoid personal mailings to the maintainer (or some other contributor) if
your questions will probably be in the interest of other users too.
You can subscribe to the list here:
https://lists.sourceforge.net/lists/listinfo/libcoap-developers
The archive of the list can be found on:
https://sourceforge.net/p/libcoap/mailman/libcoap-developers
3. Starting contributing
~~~~~~~~~~~~~~~~~~~~~~~~
As written above libcoap is maintained with the Git tools so you should be
familiar with the various git commands.
The libcoap project is using just two main branches, the 'main' branch is
holding the point releases, all the development process is going on in the
'develop' branch.
To start any contributing you first have to clone the git tree from the main
repository on GitHub:
git clone https://github.com/obgm/libcoap.git
4. Working on the source
~~~~~~~~~~~~~~~~~~~~~~~~
As one golden rule you should work on improvements within *your* own local
development branch! To do so you have to first checkout the 'develop' branch
as local branch and then start on top on this branch your own branch. So
create (or better say checkout) the local 'develop' branch:
cd libcoap
git checkout develop origin/develop
Now you can simply start your own local branch (for example 'my-develop')
with the 'origin/develop' as parent so you can later create the patches
against the the upstream development branch:
git checkout -b my-develop
At this point you can now work as known with git, modify the source, commit
the changes, amend if needed and test your work.
At some point you will have to generate patches to post them on the mailing
list (and/or push your changes into your public Git tree). It's a good idea to
post your patch series on the mailing list so other contributors will see your
work and give further suggestions or discuss your work.
To be able to send a patch series you will now create the series itself as
single patches, this will be going easy with the 'git format-patch' command
against the 'develop' branch, remind this is the upstream main development
branch.
To not mix up your series with probably unrelated patches let git place the
patches within a defined directory. Also, while create the patches, tell git to
create a cover letter patch so you can append some introducing words that will
hold probably explanations why you create the patches in the way you have done.
git format-patch --cover-letter -o ../patches4libcoap
This command will create a patch series in ../patches4libcoap where you find a
patch named '0000-cover-letter.patch'. Please modify this patch with some
useful information's for the mailing list. After finish this you now can send
your patches to libcoap-developers@lists.sourceforge.net
git send-email ../patches4libcoap/* --to=libcoap-developers@lists.sourceforge.net
5. Coding rules
~~~~~~~~~~~~~~~
As every FOSS project the libcoap project needs also some rules for coding.
There are loss but the main of them are important!
5.1 License and Copyright
-------------------------
Every new file must contain a license and the copyright holder(s). Please
take a look into existing files and adopt the needed changes to your new
file(s).
5.2 Source Code Indentation
---------------------------
* For better reading the indentation is set to 2 characters as spaces, this
is depended on the often used nested functions like 'if-else'. Don't use
TABs any there! Avoid trailing white spaces at the end of a line.
It's appropriate to set up a modline like this one at first line within
the source file:
--8<----
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
--->8--
* Single lines within the source code should not be longer then 78
characters.
* If there a functions with a lot of parameters that do not fit into the above
rule split the declaration (in the *.h) and the implementation (in the *.c)
into single lines per parameter. For example like this (from src/block.c):
--8<----
int
coap_add_block(coap_pdu_t *pdu,
unsigned int len,
const unsigned char *data,
unsigned int block_num,
unsigned char block_szx);
--->8--
5.3 Source Code Documentation
-----------------------------
* A useful source code documentation is mandatory. Mostly to be done within the
source code files, but more complex description should be done in extra
README files.
* Please set up/adjust the doxygen documentation if you create new functions or
change existing functions. The doxygen documentation has to be done in the
header files as they are the public part of the libcoap and only use the
@-syntax for doxygen commands (akin to javadoc).
5.4 API Changes
---------------
* Never break the API!
Don't remove old functions and if there some changes are needed in some kind
always provide a wrapper for the old call to let the library be backward
compatible and mark the old function as @deprecated in the doxygen comment.
Please discuss needed changes on the mailing list.
5.5 Patches and Commits
-----------------------
* Git commits must be atomic and contain a declarative subject line (max 50
characters if possible) and a body for a statement if needed.
Use the possibility to write a good explanation why your patch/commit is
handle the changes in the way you have done. Remind that other user can
read your code but not necessary understand why the code is written this
way. Don't use something to generic like "bugfix commit".
* A patch/commit or a series of patches/commits have to ensure that the
whole project is able to build up every thing, in short: Do not break
any make target and test your work.
* Every patch/commit should handle one single logical change. If more than
one patch/commit is needed for a change explain it, respect the point
above. If your subject line become much larger than 50 characters then
typically your patch is to big for one single commit.
* Commit message should begin with a submodule or unit the commit is for. By
this your commit message helps to find thematic other changes. If you have
to search and find something with 'git log | grep [foo]' you will see why
this is useful. Examples:
rd.c: Fixed type-specifier warning
Makefile.am: Added missing src/address.c
address.[hc]: make coap_address_equals() not inline on POSIX
6. Where to start contributing?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are various things you could starting on to contribute, the best
is you simply pick up an issue you blindly see and just improve the
situation. Please take also a look into the file TODO and choose a point
from there or point the maintainer to add other things here too.
* Documentation
We are always lacking on a better documentation on the source code, so
maybe you can improve the doxygen documentation.
Also a good documentation on the usage of the libcoap and the example
binaries is always improvable. So we appreciate any help on this.
* Manual Pages
The source is providing some example binaries which originally just should show
how the libcoap can be used. Right now these binaries are fully usable and
quite more than simple examples on a system. There are man pages for these
binaries available, if you found there is a improvement needed please do so and
write to the mailing list explained in section 2.
Maybe you can write up some good HowTo's on the usage for these binaries.
* HowTo's
The libcoap library has now a lot of functions you can use.
Unfortunately there is no good user guide on how to use the libcoap in
any external project. This means there is no HowTo or CheatSheet for a
programming person available. You want to write up something?
* Missing functionality
There are some features that are still missing inside the libcoap. For
example some DTLS implementations and proxy functionality.
@@ -0,0 +1,6 @@
libcoap is published as open-source software without any warranty of any kind.
Use is permitted under the terms of the simplified BSD 2-Clause license.
It includes public domain software. libcoap binaries may also
include open-source software with their respective licensing terms.
Please refer to LICENSE for further details.
@@ -0,0 +1,332 @@
2022-08-17 Olaf Bergmann <bergmann@tzi.org>
Change summary for version 4.3.1:
* Support for Server only and Client only libcoap builds.
* Add support for repeating requests in coap-client.
* Add in support for defining resources that support multicast.
* Add in more support for async delayed requests.
* Add in support for not closing down Observe when closing session.
* Support for RFC7390, RFC8516 and RFC9175.
* Warn when Tokens are re-used.
* Warn when Options are repeated that are not defined as being
repeatable.
* Support for TLS when using Mbed TLS library.
* support for Mbed TLS 3.1
* Add in BERT support for block handling.
* More rigorous error handling for Block transfers.
* Support for using external or submodule TinyDTLS.
* Cmake - add in Apple build support.
* Source files renamed to be more consistent in naming.
* Update native Windows VC builds to use libcoap-3 instead of libcoap-2.
* Reported bugs fixed.
* Example applications Help report include build version.
* Documentation added and updated (Doxygen and man).
2021-05-04 Olaf Bergmann <bergmann@tzi.org>
Change summary for version 4.3.0:
* Include directory updated from include/coap2 to include/coap3 as
this is a major version change.
* Other code references updated from coap2 to coap3.
* Examples now have the underlying (D)TLS library name as a suffix.
E.g. coap-server-openssl
* Examples and libraries can be installed with default names using
./configure --enable-add-default-names
* Many call-back handlers have had their parameter lists changed, some
variables are made const and other ones removed as they can be easily
reconstructed if needed.
* Some functions have their parameters changed to const.
* Internal structures made opaque to applications, requiring the
applications to access the structure information via a new set of
functions. The new functions are of the form coap_X_get_Y() or
coap_X_set_Y() where X is the structure (e.g. session) and Y is
the variable.
* coap_async_state_t
* coap_attr_t
* coap_context_t
* coap_packet_t
* coap_pdu_t
* coap_resource_t
* coap_session_t
* coap_socket_t
* Header files are moved into libcoap space and so are accessed by coap
sub-directory - e.g. #include <coap3/coap.h>.
* RFC7959 (Block handling) moved into libcoap from application code
considerably simplifying application code. See coap_block(3) man page.
* CoAP Cache Key support.
* Support for cmake builds.
* Support for RIOT builds.
* Support for Cygwin builds.
* Proxy support for coap-server, enhanced coap-client capabilities
* Updated async support.
* Multicast requests now randomly delayed befor ethe response is
sent.
* Additional RFC support - RFC8768.
* Mbed TLS DTLS library support.
* (D)TLS support for RPK and PKCS11.
* Additional (D)TLS support for PSK (e.g. Identity Hints).
* PKI support consistent across all supported (D)TLS libraries.
* Support for disabling TCP for code reduction.
* More rigorous checking and appropriate rejection of inbound PDU
options.
* Additional unit tests.
* Reported bugs fixed.
* Example applications help reports on (D)TLS library capabilities
and versions.
* Documentation added and updated (Doxygen and man).
2019-11-05 Olaf Bergmann <bergmann@tzi.org>
Change summary for version 4.2.1:
* Builds now support silent rules
* Support building with TinyDTLS as a shared library
* Added in EPOLL support
* Added in support for constrained stacks
* Server sessions hashed for performance lookup
* coap_endpoint_t and coap_subscription_t made opaque to applications
* Documentation updated
2019-02-11 Olaf Bergmann <bergmann@tzi.org>
Change summary for version 4.2.0:
* DTLS support improvements (OpenSSL, GnuTLS, tinydtls)
* Pre-shared keys, X.509 certificates
* new session abstraction
* TCP and TLS support
* improved documentation; manual pages
* changes in internal PDU structure
* improved examples (DTLS usage, block-wise transfer)
* docker images for continuous integration
* support for Google OSS fuzzer
* MS Visual Studio project for Windows builds
2017-07-10 Olaf Bergmann <bergmann@tzi.org>
* DTLS support (OpenSSL, tinyDTLS) by Jean-Claude Michelou
* Win32 support by Jean-Claude Michelou
* New Session API by Jean-Claude Michelou
2016-02-16 Olaf Bergmann <bergmann@tzi.org>
* Fixed build for Contiki3 and LwIP
* .travis.yml: Enabled continuous integration for platforms
POSIX and Contiki
2015-03-11 Olaf Bergmann <bergmann@tzi.org>
* include/coap/resource.h: Replaced custom list structures by
utlist macros.
2015-03-09 Olaf Bergmann <bergmann@tzi.org>
* src/uri.c (coap_split_path): Fixed URI parser bug and
removed broken parse iterator.
2015-03-05 Olaf Bergmann <bergmann@tzi.org>
* src/coap_time.c (coap_ticks): Changed POSIX implementation
to fixed point arithmetic and removed clock_offset.
2015-02-21 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_send_confirmed): Use fixed point arithmetic
to calculate retransmission timeout.
2015-02-20 Olaf Bergmann <bergmann@tzi.org>
* coap_list.[hc]: Moved old list implementation into
sub-directory examples and replaced by linked lists
from utlist.h. As a result, the list must be sorted
explicitly with LL_SORT).
2015-02-19 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_send_confirmed): Fixed retransmission timeout
calculation and renamed transmission parameters according to
Section 4.8 of RFC 7252.
2015-02-17 Olaf Bergmann <bergmann@tzi.org>
* major rework to get Contiki and lwip running
* many fixed bugs and warnings
2014-06-18 Olaf Bergmann <bergmann@tzi.org>
* mem.c (coap_malloc_type): New functions for allocating memory.
On POSIX systems, coap_malloc_type() and coap_free_type() are just
wrapper functions for malloc() and free(), while on Contiki and
LWIP distinct arrays are used for each type.
2014-03-09 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_cancel): Removed 7.31 again and implemented new
method for cancelling observe relationships.
2014-02-25 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_cancel): Handling of 7.31 responses to cancel
notifications (see Section 4.6 of draft-ietf-core-observe-12)
2014-02-04 Olaf Bergmann <bergmann@tzi.org>
* resource.c (coap_print_link): This function now takes an offset
where printing starts. This is used for generating blocks on the
fly.
* net.c (wellknown_response): Added support for Block2 options
when generating a response for .well-known/core.
* block.h (coap_opt_block_num): Fixed handling of zero-length
options. COAP_OPT_BLOCK_LAST now returns NULL when the option
value's length is zero.
2014-01-07 Olaf Bergmann <bergmann@tzi.org>
* resource.c (coap_print_link): Output partial resource
descriptions. The function now provides a sliding window over the
textual representation of the resource. Output starts at the given
offset and ends at the buffer's upper bound. The meaning of the
return value has changed to allow distinguishing whether or not
the resource description has been truncated at the buffer's upper
bound.
(print_wellknown): Support for the new coap_print_link(). An
additional parameter now is used to provide the offset into the
resource description. The meaning of the return value has been
adjusted accordingly.
2013-12-23 Olaf Bergmann <bergmann@tzi.org>
* configure.in: merged with LWIP port from chrysn
<https://git.gitorious.org/coap-lwip/coap-lwip.git>. This
introduces new compiler flags WITH_POSIX and WITH_LWIP to
distinguish target platforms.
2013-09-03 Olaf Bergmann <bergmann@tzi.org>
* option.h (coap_option_setb): increased size of option type
argument
* tests/test_error_response.c (t_init_error_response_tests): new
tests for error response generation
* tests/test_pdu.c (t_encode_pdu5): fixed number for option Accept
* net.c (coap_new_error_response): fixed option size calculation
2013-07-04 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_new_context): register critical Accept option
* pdu.c: option codes for Accept and Size1 according to coap-18
2013-02-01 Olaf Bergmann <bergmann@tzi.org>
* coap_time.h (coap_clock_init_impl): fix invalid preprocessor
directive. #warning is now only used for gcc only (close sf bug #15)
* net.c (wellknown_response): applied patch from chrysn to
fix bug in generation of .well-known/core representation
2013-01-21 Olaf Bergmann <bergmann@tzi.org>
* option.h: renamed option field in coap_opt_iterator_t to
next_option to detect erroneous use in old code
2013-01-18 Olaf Bergmann <bergmann@tzi.org>
* configure.in: new option --with-tests to enable unit tests
* tests/testdriver.c: unit tests for parser functions
* pdu.c (coap_pdu_parse): new PDU parser for Klaus-encoding
according to coap-13
* net.c (coap_read): call coap_pdu_parse() to check PDU integrity
* option.c: Klaus-encoding for coap-13, including new option
iterator interface
2012-11-20 Olaf Bergmann <bergmann@tzi.org>
* net.c (next_option_safe): made option parsing more robust in
presence of option jumps
* pdu.h: new option codes from draft-ietf-core-coap-12
* option.c (coap_opt_setlength): new function to set option length
* uri.c (make_decoded_option): use coap_opt_setlength() instead of
obsolete macro COAP_OPT_SETLENGTH.
2012-11-19 Olaf Bergmann <bergmann@tzi.org>
* uri.c (make_decoded_option): use coap_opt_encode() instead of writing
2012-11-03 Olaf Bergmann <bergmann@tzi.org>
* net.c (coap_read): read new option encoding
2012-11-01 Olaf Bergmann <bergmann@tzi.org>
* option.c (coap_opt_size, coap_opt_value, coap_opt_length):
several functions to access fields of options (possibly preceeded
by option jump)
2012-10-25 Olaf Bergmann <bergmann@tzi.org>
* option.c (coap_opt_encode): new function for option encoding
with option jumps
2012-03-23 Olaf Bergmann <bergmann@tzi.org>
* examples/client.c (clear_obs): clear observation relationship after
user-specified duration
2012-03-21 Olaf Bergmann <bergmann@tzi.org>
* resource.c (print_wellknown): filtering by attributes
2012-03-19 Olaf Bergmann <bergmann@tzi.org>
* pdu.c (coap_add_option): allow more than 15 options.
2012-03-15 Olaf Bergmann <bergmann@tzi.org>
* examples/client.c (cmdline_uri): split path and query here to
make it easier to include these options in subsequent requests for
block transfer.
2012-03-14 Olaf Bergmann <bergmann@tzi.org>
* examples/etsi_iot_01.c: Support for POST, PUT, DELETE on /test
2012-03-13 Olaf Bergmann <bergmann@tzi.org>
* encode.c (coap_encode_var_bytes): more efficient coding for 0
2012-03-11 Olaf Bergmann <bergmann@tzi.org>
* examples/etsi_iot_01.c: Test cases for 1st ETSI CoAP Plugtest,
March 24/25, 2012 in Paris, France.
2012-03-10 Olaf Bergmann <bergmann@tzi.org>
* block.c: support for block transfer.
2012-03-07 Olaf Bergmann <bergmann@tzi.org>
* examples/client.c (usage): new command line options
-B to set timeout after which the main loop is left.
-e to specify a payload (incompatible with -f)
(message_handler): bugfixes
* resource.h: (coap_method_handler_t): new API for method handlers.
Copyright 2012 Olaf Bergmann, TZI
Copying and distribution of this file, with or without modification, are
permitted provided the copyright notice and this notice are preserved.
@@ -0,0 +1,7 @@
FROM obgm/libcoap:build-env
ENV libcoap_dir=/libcoap
ADD . $libcoap_dir
WORKDIR $libcoap_dir
RUN ./autogen.sh --clean && ./autogen.sh
@@ -0,0 +1,98 @@
############################################################################
#
# GnuTLS dual versions
#
# Works with CentOS 7
#
############################################################################
#
# Add in alternative GnuTLS support into /usr/local, and put all the
# libraries into /usr/local/lib.
#
# Need the latest of the following packages
#
# gmp (used 6.2.0) https://gmplib.org/#DOWNLOAD
# nettle (used 3.6) https://ftp.gnu.org/gnu/nettle/
# gnutls (used 3.6.13) https://www.gnutls.org/download.html
#
GMP_VER=6.2.0
NETTLE_VER=3.6
GNUTLS_VER=3.6.13
#
# gmp
#
tar xovf gmp-${GMP_VER}.tar.xz
cd gmp-${GMP_VER}
./configure
make
sudo make install
cd ..
#
# nettle (by default wants to go into /usr/local/lib64 which gets messy)
#
tar zxovf nettle-${NETTLE_VER}.tar.gz
cd nettle-${NETTLE_VER}
PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./configure --libdir=/usr/local/lib \
LDFLAGS="-L/usr/local/lib"
make
sudo make install
cd ..
tar xovf gnutls-${GNUTLS_VER}.tar.xz
cd gnutls-${GNUTLS_VER}
#
#
# You may need to make the following change if you have an old version of
# p11-kit
#
# $ diff -Nau a/lib/pkcs11_privkey.c b/lib/pkcs11_privkey.c
# --- a/lib/pkcs11_privkey.c 2020-05-26 11:49:27.374385645 +0100
# +++ b/lib/pkcs11_privkey.c 2020-05-26 11:58:24.300510455 +0100
# @@ -265,13 +265,13 @@
# # define CKG_MGF1_SHA384 0x00000003UL
# # define CKG_MGF1_SHA512 0x00000004UL
#
# +#endif
# struct ck_rsa_pkcs_pss_params {
# ck_mechanism_type_t hash_alg;
# /* ck_rsa_pkcs_mgf_type_t is not defined in old versions of p11-kit */
# unsigned long mgf;
# unsigned long s_len;
# };
# -#endif
#
# static const struct hash_mappings_st hash_mappings[] =
# {
#
#
PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./configure --with-included-unistring \
--disable-hardware-acceleration --disable-tests --with-included-libtasn1 \
--disable-doc LDFLAGS="-L/usr/local/lib"
make
sudo make install
cd ..
############################################################################
#
# libcoap build with updated GnuTLS
#
############################################################################
# Get the latest libcoap
git clone https://github.com/obgm/libcoap.git
# Build code
cd libcoap
./autogen.sh
# Update --enable- / --disable- options as appropriate
# libcoap libraries are put into /usr/lib64 for ease of linking
PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./configure --libdir=/usr/lib64 \
--with-gnutls --enable-tests --enable-examples --disable-doxygen \
--enable-manpages
make
sudo make install
cd ..
@@ -0,0 +1,50 @@
############################################################################
#
# OpenSSL dual versions
#
# Works with CentOS 7
#
############################################################################
#
# Add in alternative OpenSSL support into /opt/openssl. /opt/openssl is
# chosen instead of the default of /usr/local so that existing utilities
# continue to use the original version of OpenSSL and so only specific
# applications that requires the newer version of OpenSSL will pick up the
# new code.
#
# Download latest stable version of openssl.X.Y.Z.tar.gz from
# https://www.openssl.org/source/
tar zxovf openssl.X.Y.Z.tar.gz
cd openssl.X.Y.X
./config --prefix=/opt/openssl --openssldir=/opt/openssl
make
sudo make install_sw
# The following should not clash the existing OpenSSL lib*.so.1.0 usage unless
# the previous OpenSSL version is 1.1.0 or later.
# It just makes things for running executables a lot simpler.
sudo cp /opt/openssl/lib/lib*.so.1.1 /lib64
cd ..
############################################################################
#
# libcoap build with updated OpenSSL
#
############################################################################
# Get the latest libcoap
git clone https://github.com/obgm/libcoap.git
# Build code
cd libcoap
./autogen.sh
# Update --enable- / --disable- options as appropriate
# libcoap libraries are put into /usr/lib64 for ease of linking
PKG_CONFIG_PATH=/opt/openssl/lib/pkgconfig ./configure --libdir=/usr/lib64 \
--with-openssl --enable-tests --enable-examples --disable-doxygen \
--disable-manpages
make
sudo make install
cd ..
@@ -0,0 +1,90 @@
############################################################################
#
# SoftHSMv2 dual versions
#
# Works with CentOS 7
#
# The opensc package needs to be installed.
#
############################################################################
#
# Install a software HSM module for doing the PKCS11 testing of libcoap.
# Real hardware can be used if you have the appropriate library module.
#
# It is assumed that the opensc package is installed.
#
# When installing SoftHSMv2 from your system's package manager, check that the
# OpenSSL version is at least 1.1.0. If not, then you will need to dual
# install SoftHSMv2 as below; otherwise you can use the existing SoftHSMv2.
#
# SoftHSMv2 is built using OpenSSL, but GnuTLS can use the PKCS11 interface.
# Note that if the default OpenSSL version is less than 1.1.0, you will need
# to install a dual stack version of OpenSSL as per HOWTO.dual.openssl.
#
# Creates module /usr/local/lib/softhsm/libsofthsm2.so
#
# Add line below to /etc/security/limits.conf to support memory locking
* - memlock unlimited
# Get the latest SoftHSM
git clone https://github.com/opendnssec/SoftHSMv2.git
# Build code
cd SoftHSMv2/
sh autogen.sh
PKG_CONFIG_PATH=/opt/openssl/lib/pkgconfig ./configure --enable-silent-rules \
--with-crypto-backend=openssl --disable-gost LDFLAGS=-L/opt/openssl/lib \
CPPFLAGS=-I/opt/openssl/include --with-openssl=/opt/openssl
make
# You may need to comment out constexpr lines (fixes for gcc10) in
# src/lib/crypto/PublicKey.h src/lib/crypto/PrivateKey.h if you get
# compile errors.
sudo make install
cd ..
# Make sure p11-kit softhsm modules have the correct module: fully qualified
# path where the entry is of the form (in particular for GnuTLS) :-
# /usr/share/p11-kit/modules/softhsm*
#
# module: /usr/local/lib/softhsm/libsofthsm2.so
# The user you are running this as needs to be in the group defined for
# /var/lib/softhsm/tokens/. E.g.
# $ sudo ls -ld /var/lib/softhsm/tokens/
# drwxrws--- 3 root softhsm 4096 May 3 09:52 /var/lib/softhsm/tokens/
# which is softhsm in this case (It could be ods). To verify if you are in
# the correct group
# $ id
# To add user to this group
# $ sudo usermod -a -G softhsm <user>
# and log out and back in again.
#
############################################################################
#
# libp11 (needed for OpenSSL as it provides the PKCS11 engine)
#
############################################################################
#
# Install a pkcs11 library for OpenSSL to use as an engine.
# [GnuTLS has this built in]
#
# Get the latest libp11
git clone https://github.com/OpenSC/libp11.git
# Build code
cd libp11
./bootstrap
PKG_CONFIG_PATH=/opt/openssl/lib/pkgconfig ./configure \
--with-pkcs11-module=/usr/local/lib/softhsm/libsofthsm2.so
make
sudo make install
cd ..
# Verify that pkcs11 is available
/opt/openssl/bin/openssl engine pkcs11 -t
@@ -0,0 +1,129 @@
#
# Using PKCS11 with libcoap.
#
# This HOWTO works for CentOS 7.
#
# As CentOS 7 uses OpenSSL prior to 1.1.0, dual OpenSSL support needs to be
# set up and used for libcoap. See HOWTO.dual.openssl for setting this up.
#
# It also is possible that you want to use GnuTLS - and want to use a later
# version. HOWTO.dual.gnutls for setting this up.
#
# OpenSSL and GnuTLS are currently supported
#
############################################################################
#
# Testing examples
#
############################################################################
#
# Update PKCS11 token with certificates and keys
#
# Assumption is that you already have the following PEM files
# ca-cert.pem - The certificate of the CA that signed Server and Client
# server-cert.pem - Contains the server certificate in PEM format
# server-key.pem - Contains the server private key in PEM format
# client-cert.pem - Contains the server certificate in PEM format
# client-key.pem - Contains the server private key in PEM format
#
# Tokens will be stored under /var/lib/softhsm/tokens/
#
# The user you are running this as needs to be in the group defined for
# /var/lib/softhsm/tokens/. E.g.
# $ sudo ls -ld /var/lib/softhsm/tokens/
# drwxrws--- 3 root softhsm 4096 May 3 09:52 /var/lib/softhsm/tokens/
# which is softhsm in this case (It could be ods). To verify if you are in
# the correct group
# $ id
# To add user to this group
# $ sudo usermod -a -G softhsm <user>
# and log out and back in again.
#
# Set libsofthsm2.so to use (may be /usr/lib/softhsm/libsofthsm2.so)
LIBSOFTHSM=/usr/local/lib/softhsm/libsofthsm2.so
# Initialize Soft HSM token
# Note: slot 0 is re-allocated to slot XXX. This is presented as a decimal
# number, the hex equivalent (leading 0x) can be used for any slot options..
# Set SO PIN to 4321, user PIN to 1234
softhsm2-util --init-token --slot 0 --label "token-0" --pin 1234 --so-pin 4321
# CA Certificate (different id to Server/Client Public Certificate)
# (GnuTLS requires this to be trusted)
p11tool --so-login --load-certificate ca-cert.pem --write --label ca-cert \
--set-so-pin 4321 --id cc00 --mark-trusted "pkcs11:token=token-0"
# Server Private Key
openssl pkcs8 -topk8 -inform PEM -outform PEM -in server-key.pem \
-out server-key.pk8 -nocrypt
softhsm2-util --import server-key.pk8 --label "server-key" --id aa00 \
--pin 1234 --token "token-0"
# Server Public Certificate
# (Use different id to private key, but not the same as CA/Client cert)
openssl x509 -in server-cert.pem -out server-cert.der -outform DER
pkcs11-tool --module $LIBSOFTHSM --pin 1234 \
--write-object ./server-cert.der --type cert --id aa01 \
--label "server-cert" --token-label "token-0"
# Client Private Key
openssl pkcs8 -topk8 -inform PEM -outform PEM -in client-key.pem \
-out client-key.pk8 -nocrypt
softhsm2-util --import client-key.pk8 --label "client-key" --id bb00 \
--pin 1234 --token "token-0"
# Client Public Certificate
# (Use different id to private key, but not the same as CA/Client cert)
openssl x509 -in client-cert.pem -out client-cert.der -outform DER
pkcs11-tool --module $LIBSOFTHSM --pin 1234 \
--write-object ./client-cert.der --type cert --id bb01 \
--label "client-cert" --token-label "token-0"
# Verify token is correctly populated
pkcs11-tool --module=$LIBSOFTHSM -t
pkcs11-tool --module=$LIBSOFTHSM --list-objects \
--pin 1234 --token-label "token-0"
p11tool --list-all pkcs11:model=SoftHSM%20v2
#
# Run coap-server using PKCS11 (-C option may need to be -C cert.der)
#
coap-server -C 'pkcs11:token=token-0;id=%cc%00?pin-value=1234' \
-c 'pkcs11:token=token-0;id=%aa%01?pin-value=1234' \
-j 'pkcs11:token=token-0;id=%aa%00?pin-value=1234' -v9
# or
coap-server -C 'pkcs11:token=token-0;id=%cc%00' \
-c 'pkcs11:token=token-0;id=%aa%01' \
-j 'pkcs11:token=token-0;id=%aa%00' -J 1234 -v9
# or
coap-server -C 'pkcs11:token=token-0;object=ca-cert' \
-c 'pkcs11:token=token-0;object=server-cert' \
-j 'pkcs11:token=token-0;object=server-key' -J 1234 -v9
#
# Run coap-client using PKCS11 (-C option may need to be -C cert.der)
#
coap-client -C 'pkcs11:token=token-0;id=%cc%00?pin-value=1234' \
-c 'pkcs11:token=token-0;id=%bb%01?pin-value=1234' \
-j 'pkcs11:token=token-0;id=%bb%00?pin-value=1234' -v9 coaps://[::1]
# or
coap-client -C 'pkcs11:token=token-0;id=%cc%00' \
-c 'pkcs11:token=token-0;id=%bb%01' \
-j 'pkcs11:token=token-0;id=%bb%00' -J 1234 -v9 coaps://[::1]
# or
coap-client -C 'pkcs11:token=token-0;object=ca-cert' \
-c 'pkcs11:token=token-0;object=client-cert' \
-j 'pkcs11:token=token-0;object=client-key' -J 1234 -v9 coaps://[::1]
#
# Client and Server using RPK (GnuTLS only)
#
coap-server -M 'pkcs11:token=token-0;object=server-key' -J 1234 -v9
# and
coap-client -M 'pkcs11:token=token-0;object=client-key' -J 1234 -v9 coaps://[::1]
@@ -0,0 +1,85 @@
Copyright (c) 2010--2022, Olaf Bergmann and others
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================
getopt.c
License information for getopt.c. This file is only used on Windows
builds of the executables in the examples folder:
/*
* This file was copied from the following newsgroup posting:
*
* Newsgroups: mod.std.unix
* Subject: public domain AT&T getopt source
* Date: 3 Nov 85 19:34:15 GMT
*
* Here's something you've all been waiting for: the AT&T public domain
* source for getopt(3). It is the code which was given out at the 1985
* UNIFORUM conference in Dallas. I obtained it by electronic mail
* directly from AT&T. The people there assure me that it is indeed
* in the public domain.
*/
========================================================================
uthash
libcoap uses uthash.h and utlist.h from Troy D. Hanson
(https://troydhanson.github.io/uthash/). These files use the revised
BSD license (BSD-1-Clause license) as included in these two source
files.
========================================================================
OpenSSL
Binaries that are linked against OpenSSL include software developed
by the OpenSSL Project for use in the OpenSSL Toolkit.
(http://www.openssl.org/). Please consult the OpenSSL license
(https://www.openssl.org/source/license.html) for licensing terms.
========================================================================
GnuTLS
When compiled with GnuTLS support, this software includes components
that are licensed under the terms of the the GNU Lesser General Public
License, version 2.1
(https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html).
========================================================================
tinyDTLS
When compiled with tinyDTLS support, this software includes components
that are licensed under the terms of the Eclipse Distribution License 1.0
(http://www.eclipse.org/org/documents/edl-v10.php).
========================================================================
Mbed TLS
When compiled with Mbed TLS support, this software includes components
that are licensed under the terms of the Apache 2.0 license
(http://www.apache.org/licenses/LICENSE-2.0).
@@ -0,0 +1,281 @@
# Makefile.am for libcoap
#
# Copyright (C) 2010-2022 Olaf Bergmann <bergmann@tzi.org>
# Copyright (C) 2015-2017 Carsten Schoenert <c.schoenert@t-online.de>
# Copyright (C) 2018-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
#
# SPDX-License-Identifier: BSD-2-Clause
#
# This file is part of the CoAP C library libcoap. Please see README and
# COPYING for terms of use.
## Place generated object files (.o) into the same directory as their source
## files, in order to avoid collisions when non-recursive make is used.
AUTOMAKE_OPTIONS = subdir-objects
ACLOCAL_AMFLAGS = ${ACLOCAL_FLAGS} -I m4
LIBCOAP_PACKAGE_BUILD = @DOLLAR_SIGN@(shell git describe --tags --dirty --always 2>/dev/null || echo @PACKAGE_VERSION@)
## Additional files for the distribution archive
EXTRA_DIST = \
BUILDING \
CONTRIBUTE \
TODO \
LICENSE \
CMakeLists.txt \
cmake_coap_config.h.in \
cmake/Config.cmake.in \
cmake/FindMbedTLS.cmake \
cmake/FindTinyDTLS.cmake \
coap_config.h.lwip \
coap_config.h.riot \
coap_config.h.windows \
libcoap-$(LIBCOAP_API_VERSION).pc.in \
libcoap-$(LIBCOAP_API_VERSION).map \
libcoap-$(LIBCOAP_API_VERSION).sym \
examples/coap_list.h \
examples/getopt.c \
include/coap$(LIBCOAP_API_VERSION)/coap_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_riot.h \
include/coap$(LIBCOAP_API_VERSION)/coap_asn1_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_async_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_block_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_cache_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_dtls_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_io_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_net_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_pdu_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_resource_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_session_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_subscribe_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap_tcp_internal.h \
include/coap$(LIBCOAP_API_VERSION)/coap.h.in \
include/coap$(LIBCOAP_API_VERSION)/coap.h.windows \
include/coap$(LIBCOAP_API_VERSION)/coap.h.windows.in \
include/coap$(LIBCOAP_API_VERSION)/lwippools.h \
include/coap$(LIBCOAP_API_VERSION)/uthash.h \
include/coap$(LIBCOAP_API_VERSION)/utlist.h \
src/coap_io_riot.c \
tests/test_error_response.h \
tests/test_encode.h \
tests/test_options.h \
tests/test_pdu.h \
tests/test_sendqueue.h \
tests/test_session.h \
tests/test_tls.h \
tests/test_uri.h \
tests/test_wellknown.h \
win32/coap-client/coap-client.vcxproj \
win32/coap-client/coap-client.vcxproj.filters \
win32/coap-rd/coap-rd.vcxproj \
win32/coap-rd/coap-rd.vcxproj.filters \
win32/coap-server/coap-server.vcxproj \
win32/coap-server/coap-server.vcxproj.filters \
win32/libcoap.sln \
win32/libcoap.vcxproj \
win32/libcoap.vcxproj.filters \
win32/testdriver/testdriver.vcxproj \
win32/testdriver/testdriver.vcxproj.filters \
win32/testdriver/testdriver.vcxproj.user
AM_CFLAGS = -I$(top_builddir)/include -I$(top_srcdir)/include $(WARNING_CFLAGS) \
$(DTLS_CFLAGS) -std=c99 $(EXTRA_CFLAGS) \
-DLIBCOAP_PACKAGE_BUILD='"$(LIBCOAP_PACKAGE_BUILD)"'
SUBDIRS = $(subdirs) . man doc tests examples
## Define a libtool archive target "libcoap-@LIBCOAP_NAME_SUFFIX@.la", with
## @LIBCOAP_NAME_SUFFIX@ substituted into the generated Makefile at configure
## time.
## The libtool archive file (.la) will be installed into the directory named
## by the predefined variable $(bindir), along with the actual shared library
## file (.so).
lib_LTLIBRARIES = libcoap-@LIBCOAP_NAME_SUFFIX@.la
libcoap_@LIBCOAP_NAME_SUFFIX@_la_CFLAGS = \
-fPIC \
-fPIE \
$(AM_CFLAGS)
## Define the source file list for the "libcoap.la" target.
## Note that it is not necessary to list header files which are already listed
## elsewhere in a _HEADERS variable assignment.
libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \
src/block.c \
src/coap_address.c \
src/coap_asn1.c \
src/coap_async.c \
src/coap_cache.c \
src/coap_debug.c \
src/coap_event.c \
src/coap_hashkey.c \
src/coap_gnutls.c \
src/coap_io.c \
src/coap_mbedtls.c \
src/coap_notls.c \
src/coap_openssl.c \
src/coap_option.c \
src/coap_prng.c \
src/coap_session.c \
src/coap_subscribe.c \
src/coap_tcp.c \
src/coap_time.c \
src/coap_tinydtls.c \
src/encode.c \
src/mem.c \
src/net.c \
src/pdu.c \
src/resource.c \
src/str.c \
src/uri.c
## Define the list of public header files and their install location.
## The API version is appended to the install folder to being able to
## co-install various versions of libcoap.
libcoap_includedir = $(includedir)/coap$(LIBCOAP_API_VERSION)/
# If there is a API change to something $(LIBCOAP_API_VERSION) > 1 the install
# prefix for the header files has to change to not conflict the older version
# if the user want's to install both versions. There will be something used like
# libcoap_include_HEADERS = \
# $(top_srcdir)/include/coap-$(LIBCOAP_API_VERSION)/*
libcoap_include_HEADERS = \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/block.h \
$(top_builddir)/include/coap$(LIBCOAP_API_VERSION)/coap.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_address.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_async.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_cache.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_debug.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_dtls.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_event.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_forward_decls.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_hashkey.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_io.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_mutex.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_option.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_session.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_subscribe.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_time.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/encode.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/libcoap.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/mem.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/net.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/pdu.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/coap_prng.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/resource.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/str.h \
$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION)/uri.h
## Instruct libtool to include API version information in the generated shared
## library file (.so). The library ABI version will later defined in configure.ac,
## so that all version information is kept in one place.
libcoap_@LIBCOAP_NAME_SUFFIX@_la_LDFLAGS = \
-version-info $(LT_LIBCOAP_CURRENT):$(LT_LIBCOAP_REVISION):$(LT_LIBCOAP_AGE) \
@libcoap_SYMBOLS@ \
$(DTLS_LIBS) \
-pie
## Collect symbols here we want to ignore while building the helper files
## libcoap-$(LIBCOAP_API_VERSION).{map,sym} for the linker.
CTAGS_IGNORE=-I " \
coap_pdu_from_pbuf \
"
# This helper is called by libcoap-$(LIBCOAP_API_VERSION).{map,sym} to see if
# configure has detected a usable version of the ctags program and aborts if not.
check_ctags:
@if [ "$(CTAGS_PROG)" = "" ]; then \
echo ;\
echo "There was no ctags program found by the configure script!" ;\
echo "ctags is needed for running this target! Please note the warning about the missed ctags program of the configure script." ;\
echo ;\
exit 1;\
fi
## Helper target to generate the symbol table needed by libtool.
## The .map format is used when ld supports linker scripts, otherwise
## it must fall back to a plain symbol file.
update-map-file: libcoap-$(LIBCOAP_API_VERSION).map libcoap-$(LIBCOAP_API_VERSION).sym
libcoap-$(LIBCOAP_API_VERSION).map: check_ctags $(libcoap_include_HEADERS)
( echo "VER_$(LIBCOAP_API_VERSION) {" ; \
echo "global:" ; \
$(CTAGS_PROG) $(CTAGS_IGNORE) -f - --c-kinds=p $(libcoap_include_HEADERS) | awk '/^coap_/ { print " " $$1 ";" }' | sort -u ; \
echo "local:" ; \
echo " *;" ; \
echo "};" ) > $(top_builddir)/$@.new
mv $(top_builddir)/$@.new $(top_builddir)/$@
libcoap-$(LIBCOAP_API_VERSION).sym: check_ctags $(libcoap_include_HEADERS)
( $(CTAGS_PROG) $(CTAGS_IGNORE) -f - --c-kinds=p $(libcoap_include_HEADERS) | awk '/^coap_/ { print $$1 }' | sort -u ) \
> $(top_builddir)/$@.new
mv $(top_builddir)/$@.new $(top_builddir)/$@
## Install the generated pkg-config file (.pc) into the expected location for
## architecture-dependent package configuration information. Occasionally,
## pkg-config files are also used for architecture-independent data packages,
## in which case the correct install location would be $(datadir)/pkgconfig.
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libcoap-$(LIBCOAP_NAME_SUFFIX).pc
## Define an independent executable script for inclusion in the distribution
## archive. However, it will not be installed on an end user's system due to
## the noinst_ prefix.
dist_noinst_SCRIPTS = autogen.sh
## Set up a common library that causes linking against the common library
## to link with the actual library with (D)TLS support
if BUILD_ADD_DEFAULT_NAMES
install-exec-hook:
(cd $(DESTDIR)$(libdir) ; \
if [ -f libcoap-$(LIBCOAP_NAME_SUFFIX).so ] ; then \
rm -f libcoap-$(LIBCOAP_API_VERSION).so ; \
$(LN_S) libcoap-$(LIBCOAP_NAME_SUFFIX).so libcoap-$(LIBCOAP_API_VERSION).so ; \
fi ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).a ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).la ; \
$(LN_S) libcoap-$(LIBCOAP_NAME_SUFFIX).a libcoap-$(LIBCOAP_API_VERSION).a ; \
$(LN_S) libcoap-$(LIBCOAP_NAME_SUFFIX).la libcoap-$(LIBCOAP_API_VERSION).la ; \
$(MKDIR_P) $(DESTDIR)$(pkgconfigdir) ; \
cd $(DESTDIR)$(pkgconfigdir) ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).pc ; \
$(LN_S) libcoap-$(LIBCOAP_NAME_SUFFIX).pc libcoap-$(LIBCOAP_API_VERSION).pc)
uninstall-hook:
(cd $(DESTDIR)$(libdir) ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).a ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).la ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).so ; \
cd $(DESTDIR)$(pkgconfigdir) ; \
rm -f libcoap-$(LIBCOAP_API_VERSION).pc)
endif # BUILD_ADD_DEFAULT_NAMES
## various *-local targets
## Remove the helper files for the linker and the pkg-config file if there
## is 'make distclean' called. NOTE: To re create the *.{map,sym} files you
## need to call the target update-map-file after the configure script was
## running!
clean-local:
-find \( -name '*.gcda' -o -name '*.gcno' -o -name '*.gcov' \) -delete
distclean-local:
@rm -f src/*.o src/*.lo
rm -f libcoap-$(LIBCOAP_API_VERSION).map
rm -f libcoap-$(LIBCOAP_API_VERSION).sym
rm -f libcoap-$(LIBCOAP_NAME_SUFFIX).pc
@echo
@echo " ---> Please note the following important advice! <---"
@echo " The files libcoap-$(LIBCOAP_API_VERSION).{map,sym} are removed by the distclean target!"
@echo " To regenerate this two files you need to call 'make update-map-file' first before any"
@echo " other Make target. Otherwise the build of libcoap will fail!"
@echo
## Ensure we have actual *.{map,sym} files if we create a release tarball.
dist-local: update-map-file
## Finaly some phony targets, just to ensure those targets are always buildable
## no matter if the user has created same called files.
.PHONY: update-map-file check_ctags
@@ -0,0 +1,7 @@
libcoap_src = pdu.c net.c coap_cache.c coap_debug.c encode.c uri.c coap_subscribe.c resource.c str.c coap_option.c coap_async.c block.c mem.c coap_io.c coap_session.c coap_notls.c coap_hashkey.c coap_address.c coap_tcp.c
libcoap_dir := $(filter %libcoap,$(APPDS))
vpath %c $(libcoap_dir)/src
# set include path for coap sources
CFLAGS += -I$(libcoap_dir)/include
@@ -0,0 +1,89 @@
# libcoap: A C implementation of the Constrained Application Protocol (RFC 7252)
[![Build Status: main](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/obgm/libcoap/actions?query=branch:main)
[![Build Status: develop](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=develop)](https://github.com/obgm/libcoap/actions?query=branch:develop)
[![Static Analysis](https://scan.coverity.com/projects/10970/badge.svg?flat=1)](https://scan.coverity.com/projects/obgm-libcoap)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/libcoap.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:libcoap)
Copyright (C) 2010—2022 by Olaf Bergmann <bergmann@tzi.org> and others
ABOUT LIBCOAP
=============
libcoap is a C implementation of a lightweight application-protocol
for devices that are constrained their resources such as computing
power, RF range, memory, bandwidth, or network packet sizes. This
protocol, CoAP, is standardized by the IETF as RFC 7252. For further
information related to CoAP, see <http://coap.technology>.
You might want to check out
[libcoap-minimal](https://github.com/obgm/libcoap-minimal) for usage
examples.
DOCUMENTATION
=============
Documentation and further information can be found at
<https://libcoap.net>.
PACKAGE CONTENTS
================
This package contains a protocol parser and basic networking
functions for platforms with support for malloc() and BSD-style
sockets. In addition, there is support for Contiki, LwIP and
Espressif/ESP-IDF hosted environments.
The following RFCs are supported
* RFC7252: The Constrained Application Protocol (CoAP)
* RFC7390: Group Communication for the Constrained Application Protocol (CoAP)
* RFC7641: Observing Resources in the Constrained Application Protocol (CoAP)
* RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)
* RFC7967: Constrained Application Protocol (CoAP) Option for No Server Response
* RFC8132: PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
* RFC8323: CoAP (Constrained Application Protocol) over TCP, TLS, and WebSockets
[No WebSockets support]
* RFC8516: "Too Many Requests" Response Code for the Constrained Application Protocol
* RFC8768: Constrained Application Protocol (CoAP) Hop-Limit Option
* RFC9175: CoAP: Echo, Request-Tag, and Token Processing
There is (D)TLS support for the following libraries
* OpenSSL (Minimum version 1.1.0) [PKI, PSK and PKCS11]
* GnuTLS (Minimum version 3.3.0) [PKI, PSK, RPK(3.6.6+) and PKCS11]
* Mbed TLS (Minimum version 2.7.10) [PKI and PSK]
* TinyDTLS [PSK and RPK] [DTLS Only]
The examples directory contain a CoAP client, CoAP Resource Directory server
and a CoAP server to demonstrate the use of this library.
BUILDING
========
Further information can be found at <https://libcoap.net/install.html>
and [BUILDING](https://raw.githubusercontent.com/obgm/libcoap/develop/BUILDING).
LICENSE INFORMATION
===================
This library is published as open-source software without any warranty
of any kind. Use is permitted under the terms of the simplified BSD
license. It includes public domain software. libcoap binaries may also
include open-source software with their respective licensing terms.
Please refer to
[LICENSE](https://raw.githubusercontent.com/obgm/libcoap/develop/LICENSE)
for further details.
@@ -0,0 +1,89 @@
# libcoap: A C implementation of the Constrained Application Protocol (RFC 7252)
[![Build Status: main](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/obgm/libcoap/actions?query=branch:main)
[![Build Status: develop](https://github.com/obgm/libcoap/actions/workflows/main.yml/badge.svg?branch=develop)](https://github.com/obgm/libcoap/actions?query=branch:develop)
[![Static Analysis](https://scan.coverity.com/projects/10970/badge.svg?flat=1)](https://scan.coverity.com/projects/obgm-libcoap)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/libcoap.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:libcoap)
Copyright (C) 2010—2022 by Olaf Bergmann <bergmann@tzi.org> and others
ABOUT LIBCOAP
=============
libcoap is a C implementation of a lightweight application-protocol
for devices that are constrained their resources such as computing
power, RF range, memory, bandwidth, or network packet sizes. This
protocol, CoAP, is standardized by the IETF as RFC 7252. For further
information related to CoAP, see <http://coap.technology>.
You might want to check out
[libcoap-minimal](https://github.com/obgm/libcoap-minimal) for usage
examples.
DOCUMENTATION
=============
Documentation and further information can be found at
<https://libcoap.net>.
PACKAGE CONTENTS
================
This package contains a protocol parser and basic networking
functions for platforms with support for malloc() and BSD-style
sockets. In addition, there is support for Contiki, LwIP and
Espressif/ESP-IDF hosted environments.
The following RFCs are supported
* RFC7252: The Constrained Application Protocol (CoAP)
* RFC7390: Group Communication for the Constrained Application Protocol (CoAP)
* RFC7641: Observing Resources in the Constrained Application Protocol (CoAP)
* RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)
* RFC7967: Constrained Application Protocol (CoAP) Option for No Server Response
* RFC8132: PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
* RFC8323: CoAP (Constrained Application Protocol) over TCP, TLS, and WebSockets
[No WebSockets support]
* RFC8516: "Too Many Requests" Response Code for the Constrained Application Protocol
* RFC8768: Constrained Application Protocol (CoAP) Hop-Limit Option
* RFC9175: CoAP: Echo, Request-Tag, and Token Processing
There is (D)TLS support for the following libraries
* OpenSSL (Minimum version 1.1.0) [PKI, PSK and PKCS11]
* GnuTLS (Minimum version 3.3.0) [PKI, PSK, RPK(3.6.6+) and PKCS11]
* Mbed TLS (Minimum version 2.7.10) [PKI and PSK]
* TinyDTLS [PSK and RPK] [DTLS Only]
The examples directory contain a CoAP client, CoAP Resource Directory server
and a CoAP server to demonstrate the use of this library.
BUILDING
========
Further information can be found at <https://libcoap.net/install.html>
and [BUILDING](https://raw.githubusercontent.com/obgm/libcoap/develop/BUILDING).
LICENSE INFORMATION
===================
This library is published as open-source software without any warranty
of any kind. Use is permitted under the terms of the simplified BSD
license. It includes public domain software. libcoap binaries may also
include open-source software with their respective licensing terms.
Please refer to
[LICENSE](https://raw.githubusercontent.com/obgm/libcoap/develop/LICENSE)
for further details.
@@ -0,0 +1,27 @@
This is a simple file for all kinds of stuff related on development for
libcoap. Please append (and remove) any issue you think its worthy.
Classification of issues:
Critical -> Break the library in some kind or a missing feature, maybe not
directly but later
Serious -> No regression on the user side, more likly on the libcoap
development
Minor -> Things that are nice to have, but they are not time critical
=================
* CRITICAL ISSUES
=================
================
* SERIOUS ISSUES
================
-> Create some development rules like:
--> How to submit patches? What about pull requests?
--> How to implement/change platform related code?
-> Further improve the API documentation
==============
* MINOR ISSUES
==============
-> Adding a logo for libcoap
@@ -0,0 +1,142 @@
#!/bin/sh -e
# uncomment the set command for debugging
#set -x
# function to check for needed helper tools
check_helper() {
#echo "Checking for $1 ..."
TOOL=`which "$1" || echo none`
if [ "$TOOL" = "none" ]; then
echo
echo "Couldn't find '$1'!"
RET=1
else
RET=0
fi
}
PROJECT="libcoap"
AUTOGEN_FILES="
INSTALL
aclocal.m4 ar-lib
coap_config.h coap_config.h.in* compile config.guess config.h* config.log config.status config.sub configure
depcomp
doc/Doxyfile doc/doxyfile.stamp doc/doxygen_sqlite3.db doc/Makefile doc/Makefile.in
examples/*.o examples/coap-client examples/coap-server examples/coap-rd
examples/Makefile examples/Makefile.in
include/coap3/coap.h
install-sh
libcoap-*.pc libtool ltmain.sh
man/coap*.[357] man/coap*.txt man/Makefile man/Makefile.in
missing
Makefile Makefile.in
stamp-h1 src/.dirstamp libcoap*.la* src/*.*o
tests/*.o tests/Makefile tests/Makefile.in tests/testdriver tests/test_common.h
tests/oss-fuzz/Makefile.ci
m4/libtool.m4 m4/lt~obsolete.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4
"
AUTOGEN_DIRS="
.deps
.libs autom4te.cache/
doc/html/
examples/.deps/ examples/.libs
man/.deps
man/tmp
src/.deps/ src/.libs/
tests/.deps/
"
# checking for cleaner argument
echo
if [ "$1" = "--clean" ]; then
echo "removing autogenerated files ..."
rm -rf $AUTOGEN_FILES $AUTOGEN_DIRS
echo "done"
exit
else
echo "[HINT] You can run 'autogen.sh --clean' to remove all generated files by the autotools."
echo
fi
# checking for autoreconf
check_helper autoconf
if [ "$RET" = "1" ]; then
echo "You probably need to install the package 'autoconf'."
ERROR=1
else
echo "Found 'autoconf'."
fi
# checking for aclocal
check_helper aclocal
if [ "$RET" = "1" ]; then
echo "You probably need to install the package 'automake'."
ERROR=1
else
echo "Found 'aclocal'."
fi
# checking for pkg-config
check_helper pkg-config
if [ "$RET" = "1" ]; then
echo "You probably need to install the package 'pkg-config|pkgconf'."
ERROR=1
else
echo "Found 'pkg-config'."
fi
# checking for libtool
# The libtool helper maybe installed as 'libtoolize', checking for 'libtool' first.
check_helper libtool
if [ "$RET" = "1" ]; then
# O.k. libtool not found, searching for libtoolize.
check_helper libtoolize
if [ "$RET" = "1" ]; then
echo "You probably need to install the package 'libtool'."
# That's bad, we found nothing!
ERROR=1
else
echo "Found 'libtoolize'."
break
fi
else
echo "Found 'libtool'."
fi
# exit if one tool isn't available
if [ "$ERROR" = "1" ]; then
echo
echo "One or more needed tools are missing, exiting ..."
echo "Please install the needed software packages and restart 'autogen.sh' again."
echo
exit 1
fi
echo
echo " ---> Found all needed tools! That's fine."
echo
# countinue otherwise
test -n "$srcdir" || srcdir=`dirname "$0"`
test -n "$srcdir" || srcdir=.
# Creating the directory m4 before calling autoreconf to
# not struggle with old versions of aclocal.
mkdir -p $srcdir/m4
# create ar-lib if not present to avoid autoreconf throwing an error
# when the file is missing. As autoreconf is called with --force
# the file will get updated with the proper contents afterwards.
touch ar-lib
echo "Generating needed autotools files for $PROJECT by running autoreconf ..."
autoreconf --force --install --verbose "$srcdir"
echo
echo "You can now run './configure --help' to see possible configuration options."
echo "Otherwise process the configure script to create the makefiles and generated helper files."
echo
@@ -0,0 +1,5 @@
imagename
build.sh
*~
.*.swp
\#*#
@@ -0,0 +1,7 @@
FROM debian:testing-slim
RUN apt-get update && apt-get install -y autoconf automake gcc clang \
libtool libtool-bin make pkg-config libcunit1-dev libssl-dev \
libgnutls28-dev libmbedtls-dev exuberant-ctags git valgrind \
graphviz doxygen libxml2-utils xsltproc docbook-xml docbook-xsl asciidoc
RUN apt-get clean
@@ -0,0 +1,36 @@
FROM obgm/libcoap:build-env
RUN apt-get update && apt-get install -y cmake git g++
RUN apt-get clean
ENV libcoap_dir=/home/libcoap
ADD . $libcoap_dir
WORKDIR $libcoap_dir
RUN ./autogen.sh --clean && ./autogen.sh
RUN ./configure --disable-documentation --enable-tests --enable-examples --with-openssl && make install clean
WORKDIR /home
RUN git clone --depth 1 https://github.com/cabo/cn-cbor.git && cd cn-cbor && ./build.sh all doc install
# The image for development with libcoap
FROM debian:testing-slim
RUN apt-get update && apt-get install -y autoconf automake gcc g++ gdb libtool libtool-bin make \
pkg-config libssl-dev libgnutls28-dev libmbedtls-dev
RUN apt-get install -y iproute2 lsof net-tools inetutils-ping netcat-openbsd less vim
RUN apt-get clean
COPY --from=0 /usr/local/include/coap3 /usr/local/include/coap3
COPY --from=0 /usr/local/lib /usr/local/lib
COPY --from=0 /usr/local/bin/coap-client /usr/local/bin/
COPY --from=0 /usr/local/include/cn-cbor /usr/local/include/cn-cbor
RUN echo "/usr/local/lib" >>/etc/ld.so.conf.d/usr_local.conf && ldconfig /usr/local/lib
ARG user=user
RUN adduser --disabled-password --gecos '' $user
RUN chown -R $user:$user /home/$user
WORKDIR /home/$user
USER $user
EXPOSE 5683 5684
@@ -0,0 +1,16 @@
#! /usr/bin/env bash
pushd $(dirname $0)
. ./imagename
# see https://stackoverflow.com/a/2924755 for switching boldface on/off
bold=$(tput bold)
normal=$(tput sgr0)
echo "${bold}**** Creating build-env image ****${normal}"
docker build -f Dockerfile.build-env -t $USER/$IMAGE:build-env .
echo "${bold}**** Creating develop image ****${normal}"
docker build -f Dockerfile.develop -t $USER/$IMAGE:develop ..
popd
@@ -0,0 +1,2 @@
USER=obgm
IMAGE=libcoap
@@ -0,0 +1,25 @@
# to format cmake files we use cmake-format:
# pip install cmake-format --upgrade
# information about the configuration here:
# https://github.com/cheshirekow/cmake_format
# How wide to allow formatted cmake files
line_width: 80
# How many spaces to tab for indent
tab_size: 2
# Format command names consistently as 'lower' or 'upper' case
command_case: "lower"
first_comment_is_literal: False
# enable comment markup parsing and reflow
enable_markup: False
# If arglists are longer than this, break them always
max_subargs_per_line: 1
max_subgroups_hwrap: 2
max_pargs_hwrap: 2
@@ -0,0 +1,35 @@
find_path(MBEDTLS_INCLUDE_DIRS mbedtls/ssl.h)
find_library(MBEDTLS_LIBRARY mbedtls)
find_library(MBEDX509_LIBRARY mbedx509)
find_library(MBEDCRYPTO_LIBRARY mbedcrypto)
set(MBEDTLS_LIBRARIES
"${MBEDTLS_LIBRARY}"
"${MBEDX509_LIBRARY}"
"${MBEDCRYPTO_LIBRARY}")
if(MBEDTLS_LIBRARY)
set(MbedTLS_FOUND TRUE)
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
MBEDTLS
DEFAULT_MSG
MBEDTLS_INCLUDE_DIRS
MBEDTLS_LIBRARY
MBEDX509_LIBRARY
MBEDCRYPTO_LIBRARY)
mark_as_advanced(
MBEDTLS_INCLUDE_DIRS
MBEDTLS_LIBRARY
MBEDX509_LIBRARY
MBEDCRYPTO_LIBRARY)
message(STATUS "MBEDTLS_INCLUDE_DIRS: ${MBEDTLS_INCLUDE_DIRS}")
message(STATUS "MBEDTLS_LIBRARY: ${MBEDTLS_LIBRARY}")
message(STATUS "MBEDX509_LIBRARY: ${MBEDX509_LIBRARY}")
message(STATUS "MBEDCRYPTO_LIBRARY: ${MBEDCRYPTO_LIBRARY}")
message(STATUS "MBEDTLS_LIBRARIES: ${MBEDTLS_LIBRARIES}")
@@ -0,0 +1,88 @@
# FindTinyDTLS
# -----------
#
# Find the tinyDTLS encryption library.
#
# Imported Targets
# ^^^^^^^^^^^^^^^^
#
# This module defines the following :prop_tgt:`IMPORTED` targets:
#
# ``tinydtls``
# The tinyDTLS ``tinydtls`` library, if found.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
#
# This module will set the following variables in your project:
#
# ``TINYDTLS_FOUND``
# System has the tinyDTLS library.
# ``TINYDTLS_INCLUDE_DIR``
# The tinyDTLS include directory.
# ``TINYDTLS_LIBRARIES``
# All tinyDTLS libraries.
#
# Hints
# ^^^^^
#
# Set ``TINYDTLS_ROOT_DIR`` to the root directory of an tinyDTLS installation.
if(TINYDTLS_ROOT_DIR)
set(_EXTRA_FIND_ARGS "NO_CMAKE_FIND_ROOT_PATH")
endif()
find_path(
TINYDTLS_INCLUDE_DIR
NAMES tinydtls/dtls.h
PATH_SUFFIXES include
HINTS ${PROJECT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${TINYDTLS_ROOT_DIR}
${_EXTRA_FIND_ARGS})
find_library(
TINYDTLS_LIBRARIES
NAMES tinydtls
PATH_SUFFIXES lib
HINTS ${PROJECT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${TINYDTLS_ROOT_DIR}
${_EXTRA_FIND_ARGS})
if(TINYDTLS_LIBRARIES)
set(TINYDTLS_FOUND TRUE)
else()
set(TINYDTLS_FOUND FALSE)
if(TinyDTLS_FIND_REQUIRED)
message(FATAL_ERROR "Tinydtls could not be found")
endif()
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
tinyDTLS
FOUND_VAR
TINYDTLS_FOUND
REQUIRED_VARS
TINYDTLS_INCLUDE_DIR
TINYDTLS_LIBRARIES
VERSION_VAR)
if(NOT
TARGET
tinydtls)
add_library(
tinydtls
UNKNOWN
IMPORTED)
set_target_properties(
tinydtls
PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${TINYDTLS_INCLUDE_DIR}"
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
IMPORTED_LOCATION "${TINYDTLS_LIBRARIES}")
endif()
message(STATUS "TINYDTLS_INCLUDE_DIR: ${TINYDTLS_INCLUDE_DIR}")
message(STATUS "TINYDTLS_LIBRARIES: ${TINYDTLS_LIBRARIES}")
message(STATUS "TINYDTLS_ROOT_DIR: ${TINYDTLS_ROOT_DIR}")
@@ -0,0 +1,177 @@
/*
* cmake_coap_config.h -- cmake configuration for libcoap
*
* Copyright (C) 2020 Carlos Gomes Martinho <carlos.gomes_martinho@siemens.com>
* Copyright (C) 2021-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#if ! defined(_WIN32)
#define _GNU_SOURCE
#endif
/* Define to 1 if you have <ws2tcpip.h> header file. */
#cmakedefine HAVE_WS2TCPIP_H @HAVE_WS2TCPIP_H@
/* Define if the system has small stack size */
#cmakedefine COAP_CONSTRAINED_STACK @COAP_CONSTRAINED_STACK@
/* Define to 1 if you have <winsock2.h> header file. */
#cmakedefine HAVE_WINSOCK2_H @HAVE_WINSOCK2_H@
/* Define if the library has client support */
#cmakedefine COAP_CLIENT_SUPPORT @COAP_CLIENT_SUPPORT@
/* Define if the library has server support */
#cmakedefine COAP_SERVER_SUPPORT @COAP_SERVER_SUPPORT@
/* Define if the system has epoll support */
#cmakedefine COAP_EPOLL_SUPPORT @COAP_EPOLL_SUPPORT@
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H @HAVE_ARPA_INET_H@
/* Define to 1 if you have the <assert.h> header file. */
#cmakedefine HAVE_ASSERT_H @HAVE_ASSERT_H@
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H @HAVE_DLFCN_H@
/* Define to 1 if you have the `getaddrinfo' function. */
#cmakedefine HAVE_GETADDRINFO @HAVE_GETADDRINFO@
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine HAVE_INTTYPES_H @HAVE_INTTYPES_H@
/* Define if the system has openssl */
#cmakedefine HAVE_OPENSSL @HAVE_OPENSSL@
/* Define if the system has libgnutls28 */
#cmakedefine HAVE_LIBGNUTLS @HAVE_LIBGNUTLS@
/* Define if the system has libtinydtls */
#cmakedefine HAVE_LIBTINYDTLS @HAVE_LIBTINYDTLS@
/* Define if the system has libmbedtls */
#cmakedefine HAVE_MBEDTLS @HAVE_MBEDTLS@
/* Define to 1 to build without TCP support. */
#cmakedefine01 COAP_DISABLE_TCP
/* Define to 1 if you have the <limits.h> header file. */
#cmakedefine HAVE_LIMITS_H @HAVE_LIMITS_H@
/* Define to 1 if you have the `malloc' function. */
#cmakedefine HAVE_MALLOC @HAVE_MALLOC@
/* Define to 1 if you have the <memory.h> header file. */
#cmakedefine HAVE_MEMORY_H @HAVE_MEMORY_H@
/* Define to 1 if you have the `memset' function. */
#cmakedefine HAVE_MEMSET @HAVE_MEMSET@
/* Define to 1 if you have the `if_nametoindex' function. */
#cmakedefine HAVE_IF_NAMETOINDEX @HAVE_IF_NAMETOINDEX@
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine HAVE_NETDB_H @HAVE_NETDB_H@
/* Define to 1 if you have the <net/if.h> header file. */
#cmakedefine HAVE_NET_IF_H @HAVE_NET_IF_H@
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine HAVE_NETINET_IN_H @HAVE_NETINET_IN_H@
/* Define to 1 if you have the <pthread.h> header file. */
#cmakedefine HAVE_PTHREAD_H @HAVE_PTHREAD_H@
/* Define to 1 if you have the `pthread_mutex_lock' function. */
#cmakedefine HAVE_PTHREAD_MUTEX_LOCK @HAVE_PTHREAD_MUTEX_LOCK@
/* Define to 1 if you have the `select' function. */
#cmakedefine HAVE_SELECT @HAVE_SELECT@
/* Define to 1 if you have the `socket' function. */
#cmakedefine HAVE_SOCKET @HAVE_SOCKET@
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H @HAVE_STDINT_H@
/* Define to 1 if you have the <stdlib.h> header file. */
#cmakedefine HAVE_STDLIB_H @HAVE_STDLIB_H@
/* Define to 1 if you have the `strcasecmp' function. */
#cmakedefine HAVE_STRCASECMP @HAVE_STRCASECMP@
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H @HAVE_STRINGS_H@
/* Define to 1 if you have the <string.h> header file. */
#cmakedefine HAVE_STRING_H @HAVE_STRING_H@
/* Define to 1 if you have the `strnlen' function. */
#cmakedefine HAVE_STRNLEN @HAVE_STRNLEN@
/* Define to 1 if you have the `strrchr' function. */
#cmakedefine HAVE_STRRCHR @HAVE_STRRCHR@
/* Define to 1 if the system has the type `struct cmsghdr'. */
#cmakedefine HAVE_STRUCT_CMSGHDR @HAVE_STRUCT_CMSGHDR@
/* Define to 1 if you have the <syslog.h> header file. */
#cmakedefine HAVE_SYSLOG_H @HAVE_SYSLOG_H@
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H @HAVE_SYS_IOCTL_H@
/* Define to 1 if you have the <sys/socket.h> header file. */
#cmakedefine HAVE_SYS_SOCKET_H @HAVE_SYS_SOCKET_H@
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H @HAVE_SYS_STAT_H@
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine HAVE_SYS_TIME_H @HAVE_SYS_TIME_H@
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H @HAVE_SYS_TYPES_H@
/* Define to 1 if you have the <sys/unistd.h> header file. */
#cmakedefine HAVE_SYS_UNISTD_H @HAVE_SYS_UNISTD_H@
/* Define to 1 if you have the <time.h> header file. */
#cmakedefine HAVE_TIME_H @HAVE_TIME_H@
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H @HAVE_UNISTD_H@
/* Define to the address where bug reports for this package should be sent. */
#cmakedefine PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@"
/* Define to the full name of this package. */
#cmakedefine PACKAGE_NAME "@PACKAGE_NAME@"
/* Define to the full name and version of this package. */
#cmakedefine PACKAGE_STRING "@PACKAGE_STRING@"
/* Define to the one symbol short name of this package. */
#cmakedefine PACKAGE_TARNAME "@PACKAGE_TARNAME@"
/* Define to the home page for this package. */
#cmakedefine PACKAGE_URL "@PACKAGE_URL@"
/* Define to the version of this package. */
#cmakedefine PACKAGE_VERSION "@PACKAGE_VERSION@"
#if defined(_MSC_VER) && (_MSC_VER < 1900) && !defined(snprintf)
#define snprintf _snprintf
#endif
#endif /* COAP_CONFIG_H_ */
@@ -0,0 +1,215 @@
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#include "contiki.h"
#include "contiki-lib.h"
#include "contiki-net.h"
#define WITH_CONTIKI 1
#ifndef COAP_CONSTRAINED_STACK
#define COAP_CONSTRAINED_STACK 1
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 1
#endif
#define PACKAGE_STRING "libcoap"
#define PACKAGE_NAME "libcoap"
#ifndef COAP_DEFAULT_PDU_SIZE
#define COAP_DEFAULT_PDU_SIZE 64
#endif /* COAP_DEFAULT_PDU_SIZE */
#ifndef COAP_RXBUFFER_SIZE
#define COAP_RXBUFFER_SIZE 64
#endif /* COAP_RXBUFFER_SIZE */
/** Number of resources that can be handled by a CoAP server in addition to
* @c /.well-known/core */
#ifndef COAP_MAX_RESOURCES
#define COAP_MAX_RESOURCES 3
#endif /* COAP_MAX_RESOURCES */
/** Number of attributes that can be handled (should be at least
* @c 2 * COAP_MAX_RESOURCES. to carry the content type and the
* resource type. */
#ifndef COAP_MAX_ATTRIBUTES
#define COAP_MAX_ATTRIBUTES 4
#endif /* COAP_MAX_ATTRIBUTES */
/**
* Number of PDUs that can be stored simultaneously. This number
* includes both, the PDUs stored for retransmission as well as the
* PDUs received. Beware that choosing a too small value can lead to
* many retransmissions to be dealt with.
*/
#ifndef COAP_PDU_MAXCNT
#define COAP_PDU_MAXCNT 4
#endif /* COAP_PDU_MAXCNT */
/**
* Maximum number of sessions.
*/
#ifndef COAP_MAX_SESSIONS
#define COAP_MAX_SESSIONS 2
#endif /* COAP_MAX_SESSIONS */
/**
* Maximum number of subscriptions. Every additional subscriber costs
* 36 B.
*/
#ifndef COAP_MAX_SUBSCRIBERS
#define COAP_MAX_SUBSCRIBERS 3
#endif /* COAP_MAX_SUBSCRIBERS */
/**
* The maximum number of cache-key entries that allocate
* fixed-size memory blocks.
*/
#ifndef COAP_MAX_CACHE_KEYS
#define COAP_MAX_CACHE_KEYS (2U)
#endif /* COAP_MAX_CACHE_KEYS */
/**
* The maximum number of cache-entry entries that allocate
* fixed-size memory blocks.
*/
#ifndef COAP_MAX_CACHE_ENTRIES
#define COAP_MAX_CACHE_ENTRIES (2U)
#endif /* COAP_MAX_CACHE_ENTRIES */
/**
* Maximum number of large body transmissions.
*/
#ifndef COAP_MAX_LG_XMIT
#define COAP_MAX_LG_XMIT 2
#endif /* COAP_MAX_LG_XMIT */
/**
* Maximum number of large body client receives.
*/
#ifndef COAP_MAX_LG_CRCV
#define COAP_MAX_LG_CRCV 2
#endif /* COAP_MAX_LG_CRCV */
/**
* Maximum number of large body server receives.
*/
#ifndef COAP_MAX_LG_SRCV
#define COAP_MAX_LG_SRCV 2
#endif /* COAP_MAX_LG_SRCV */
/**
* Number of notifications that may be sent non-confirmable before a confirmable
* message is sent to detect if observers are alive. The maximum allowed value
* here is @c 255.
*/
#ifndef COAP_OBS_MAX_NON
#define COAP_OBS_MAX_NON 5
#endif /* COAP_OBS_MAX_NON */
#if COAP_OBS_MAX_NON > 255
#error COAP_OBS_MAX_NON is too large
#endif /* COAP_OBS_MAX_NON > 255 */
/**
* Number of different confirmable notifications that may fail (i.e. those
* that have hit MAX_RETRANSMIT multiple times) before an observer is removed.
* The maximum value for COAP_OBS_MAX_FAIL is @c 255.
*/
#ifndef COAP_OBS_MAX_FAIL
#define COAP_OBS_MAX_FAIL 1
#endif /* COAP_OBS_MAX_FAIL */
#if COAP_OBS_MAX_FAIL > 255
#error COAP_OBS_MAX_FAIL is too large
#endif /* COAP_OBS_MAX_FAIL > 255 */
#ifndef DEBUG
# define DEBUG DEBUG_PRINT
#endif
#define HAVE_STRNLEN 1
#define HAVE_SNPRINTF 1
#define HAVE_STRINGS_H 1
/* there is no file-oriented output */
#define COAP_DEBUG_FD NULL
#define COAP_ERR_FD NULL
#include "contiki-conf.h"
#if (defined(PLATFORM) && PLATFORM == PLATFORM_MC1322X) || defined(CONTIKI_TARGET_ECONOTAG)
/* Redbee econotags get a special treatment here: endianness is set
* explicitly, and
*/
#define BYTE_ORDER UIP_LITTLE_ENDIAN
#define HAVE_ASSERT_H
#define HAVE_UNISTD_H
#define HAVE_SYS_TYPES_H
#define HAVE_LIMITS_H
#endif /* PLATFORM_MC1322X || CONTIKI_TARGET_ECONOTAG */
#if defined(TMOTE_SKY) || defined(CONTIKI_TARGET_SKY) || defined(CONTIKI_TARGET_WISMOTE)
/* Need to set the byte order for TMote Sky explicitely */
#define BYTE_ORDER UIP_LITTLE_ENDIAN
#undef COAP_DEFAULT_PDU_SIZE
#undef COAP_RXBUFFER_SIZE
#define COAP_DEFAULT_PDU_SIZE 100
#define COAP_RXBUFFER_SIZE 100
#define COAP_MAX_BLOCK_SZX 2
typedef int ssize_t;
typedef void FILE;
#define HAVE_LIMITS_H 1
#undef HAVE_ASSERT_H
#define HAVE_VPRINTF 1
#endif /* defined(TMOTE_SKY) */
#ifdef CONTIKI_TARGET_MINIMAL_NET
#undef COAP_DEFAULT_PDU_SIZE
#undef COAP_RXBUFFER_SIZE
#define COAP_DEFAULT_PDU_SIZE 1152
#define COAP_RXBUFFER_SIZE 1472
#define HAVE_ASSERT_H 1
#define HAVE_VPRINTF 1
#define HAVE_SYS_TYPES_H 1
#endif /* CONTIKI_TARGET_MINIMAL_NET */
#ifdef CONTIKI_TARGET_CC2538DK
#define BYTE_ORDER UIP_LITTLE_ENDIAN
#undef COAP_DEFAULT_PDU_SIZE
#undef COAP_RXBUFFER_SIZE
#define COAP_DEFAULT_PDU_SIZE 100
#define COAP_RXBUFFER_SIZE 100
#undef COAP_MAX_BLOCK_SZX
#define COAP_MAX_BLOCK_SZX 2
#define HAVE_LIMITS_H 1
#endif /* CONTIKI_TARGET_CC2538DK */
#ifndef BYTE_ORDER
# ifdef UIP_CONF_BYTE_ORDER
# define BYTE_ORDER UIP_CONF_BYTE_ORDER
# else
# error "UIP_CONF_BYTE_ORDER not defined"
# endif /* UIP_CONF_BYTE_ORDER */
#endif /* BYTE_ORDER */
/* Define assert() as empty directive unless HAVE_ASSERT_H is given. */
#ifndef HAVE_ASSERT_H
# define assert(x)
#endif
#define ntohs uip_ntohs
#include <stdio.h>
#define coap_log(fd, ...) printf(__VA_ARGS__)
#endif /* COAP_CONFIG_H_ */
@@ -0,0 +1,42 @@
/*
* coap_config.h.lwip -- LwIP configuration for libcoap
*
* Copyright (C) 2021-2022 Olaf Bergmann <bergmann@tzi.org> and others
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#include <lwip/opt.h>
#include <lwip/debug.h>
#include <lwip/def.h> /* provide ntohs, htons */
#define WITH_LWIP 1
#ifndef COAP_CONSTRAINED_STACK
#define COAP_CONSTRAINED_STACK 1
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 1
#endif
#define PACKAGE_NAME "libcoap"
#define PACKAGE_VERSION "4.3.1"
#define PACKAGE_STRING "libcoap 4.3.1"
#define assert(x) LWIP_ASSERT("CoAP assert failed", x)
/* it's just provided by libc. i hope we don't get too many of those, as
* actually we'd need autotools again to find out what environment we're
* building in */
#define HAVE_STRNLEN 1
#define HAVE_LIMITS_H
#endif /* COAP_CONFIG_H_ */
@@ -0,0 +1,42 @@
/*
* coap_config.h.lwip -- LwIP configuration for libcoap
*
* Copyright (C) 2021-2022 Olaf Bergmann <bergmann@tzi.org> and others
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#include <lwip/opt.h>
#include <lwip/debug.h>
#include <lwip/def.h> /* provide ntohs, htons */
#define WITH_LWIP 1
#ifndef COAP_CONSTRAINED_STACK
#define COAP_CONSTRAINED_STACK 1
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 1
#endif
#define PACKAGE_NAME "@PACKAGE_NAME@"
#define PACKAGE_VERSION "@PACKAGE_VERSION@"
#define PACKAGE_STRING "@PACKAGE_STRING@"
#define assert(x) LWIP_ASSERT("CoAP assert failed", x)
/* it's just provided by libc. i hope we don't get too many of those, as
* actually we'd need autotools again to find out what environment we're
* building in */
#define HAVE_STRNLEN 1
#define HAVE_LIMITS_H
#endif /* COAP_CONFIG_H_ */
@@ -0,0 +1,143 @@
/*
* coap_config.h.riot -- RIOT configuration for libcoap
*
* Copyright (C) 2021-2022 Olaf Bergmann <bergmann@tzi.org> and others
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_CONFIG_H_RIOT_
#define COAP_CONFIG_H_RIOT_
#define WITH_POSIX 1
#ifndef COAP_CONSTRAINED_STACK
#define COAP_CONSTRAINED_STACK 1
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 1
#endif
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to 1 if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
/* #undef HAVE_GETADDRINFO */
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
/* #undef HAVE_LIMITS_H */
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#undef HAVE_MALLOC
/* Define to 1 if you have the <memory.h> header file. */
/* #undef HAVE_MEMORY_H */
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netdb.h> header file. */
/* #undef HAVE_NETDB_H */
/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1
/* Define to 1 if you have the `select' function. */
/* #undef HAVE_SELECT */
/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strcasecmp' function. */
#define HAVE_STRCASECMP 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strnlen' function. */
/* #undef HAVE_STRNLEN */
/* Define to 1 if you have the `strrchr' function. */
#define HAVE_STRRCHR 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
/* #undef HAVE_SYS_STAT_H */
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/unistd.h> header file. */
#define HAVE_SYS_UNISTD_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "libcoap-developers@lists.sourceforge.net"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libcoap"
/* Define to the version of this package. */
#define PACKAGE_VERSION "4.3.1"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libcoap 4.3.1"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
#endif /* COAP_CONFIG_H_RIOT_ */
@@ -0,0 +1,143 @@
/*
* coap_config.h.riot -- RIOT configuration for libcoap
*
* Copyright (C) 2021-2022 Olaf Bergmann <bergmann@tzi.org> and others
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#ifndef COAP_CONFIG_H_RIOT_
#define COAP_CONFIG_H_RIOT_
#define WITH_POSIX 1
#ifndef COAP_CONSTRAINED_STACK
#define COAP_CONSTRAINED_STACK 1
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 1
#endif
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to 1 if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
/* #undef HAVE_GETADDRINFO */
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
/* #undef HAVE_LIMITS_H */
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#undef HAVE_MALLOC
/* Define to 1 if you have the <memory.h> header file. */
/* #undef HAVE_MEMORY_H */
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netdb.h> header file. */
/* #undef HAVE_NETDB_H */
/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1
/* Define to 1 if you have the `select' function. */
/* #undef HAVE_SELECT */
/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strcasecmp' function. */
#define HAVE_STRCASECMP 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strnlen' function. */
/* #undef HAVE_STRNLEN */
/* Define to 1 if you have the `strrchr' function. */
#define HAVE_STRRCHR 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
/* #undef HAVE_SYS_STAT_H */
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/unistd.h> header file. */
#define HAVE_SYS_UNISTD_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@"
/* Define to the full name of this package. */
#define PACKAGE_NAME "@PACKAGE_NAME@"
/* Define to the version of this package. */
#define PACKAGE_VERSION "@PACKAGE_VERSION@"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "@PACKAGE_STRING@"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
#endif /* COAP_CONFIG_H_RIOT_ */
@@ -0,0 +1,118 @@
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#if defined(_WIN32)
/* Define to 1 if you have <ws2tcpip.h> header file. */
#define HAVE_WS2TCPIP_H 1
/* Define to 1 if you have <winsock2.h> header file. */
#define HAVE_WINSOCK2_H 1
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
#define HAVE_GETADDRINFO 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the `malloc' function. */
#define HAVE_MALLOC 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the `select' function. */
#define HAVE_SELECT 1
/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strnlen' function. */
#define HAVE_STRNLEN 1
/* Define to 1 if you have the `strrchr' function. */
#define HAVE_STRRCHR 1
/* Define to 1 if the system has the type `struct cmsghdr'. */
#define HAVE_STRUCT_CMSGHDR 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
#if defined(_MSC_VER) && (_MSC_VER < 1900) && !defined(snprintf)
#define snprintf _snprintf
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 0
#endif
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "libcoap-developers@lists.sourceforge.net"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libcoap"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libcoap 4.3.1"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libcoap"
/* Define to the home page for this package. */
#define PACKAGE_URL "https://libcoap.net/"
/* Define to the version of this package. */
#define PACKAGE_VERSION "4.3.1"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define this to 1 for ancillary data on MacOS */
/* #undef __APPLE_USE_RFC_3542 */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
#endif
#endif /* COAP_CONFIG_H_ */
@@ -0,0 +1,118 @@
#ifndef COAP_CONFIG_H_
#define COAP_CONFIG_H_
#if defined(_WIN32)
/* Define to 1 if you have <ws2tcpip.h> header file. */
#define HAVE_WS2TCPIP_H 1
/* Define to 1 if you have <winsock2.h> header file. */
#define HAVE_WINSOCK2_H 1
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
#define HAVE_GETADDRINFO 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the `malloc' function. */
#define HAVE_MALLOC 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the `select' function. */
#define HAVE_SELECT 1
/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strnlen' function. */
#define HAVE_STRNLEN 1
/* Define to 1 if you have the `strrchr' function. */
#define HAVE_STRRCHR 1
/* Define to 1 if the system has the type `struct cmsghdr'. */
#define HAVE_STRUCT_CMSGHDR 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
#if defined(_MSC_VER) && (_MSC_VER < 1900) && !defined(snprintf)
#define snprintf _snprintf
#endif
#ifndef COAP_DISABLE_TCP
#define COAP_DISABLE_TCP 0
#endif
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@"
/* Define to the full name of this package. */
#define PACKAGE_NAME "@PACKAGE_NAME@"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "@PACKAGE_STRING@"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "@PACKAGE_TARNAME@"
/* Define to the home page for this package. */
#define PACKAGE_URL "@PACKAGE_URL@"
/* Define to the version of this package. */
#define PACKAGE_VERSION "@PACKAGE_VERSION@"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define this to 1 for ancillary data on MacOS */
/* #undef __APPLE_USE_RFC_3542 */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
#endif
#endif /* COAP_CONFIG_H_ */
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,288 @@
# doc/Makefile.am
#
# Copyright (C) 2015-2018 Carsten Schoenert <c.schoenert@t-online.de>
# 2018-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
#
# SPDX-License-Identifier: BSD-2-Clause
#
# This file is part of the CoAP C library libcoap. Please see README and
# COPYING for terms of use.
# We can only perfom the targets in this directory if doxygen is present.
CLEANFILES = \
doxygen_sqlite3.db
EXTRA_DIST = \
docbook.local.css \
upgrade_4.2.1_4.3.0.txt \
upgrade_4.3.0_4.3.1.txt \
main.md \
module_api_wrap.h
if HAVE_DOXYGEN
man-page-cleanup:
@rm -f $(top_builddir)/doc/DoxygenLayout.xml
@rm -rf $(top_builddir)/doc/man_tmp
@rm -rf $(top_builddir)/doc/man_html
man-page-prepare: man-page-cleanup
@$(MKDIR_P) $(top_builddir)/doc/man_tmp
@$(MKDIR_P) $(top_builddir)/doc/man_html
man-page-start: man-page-prepare
## Setup the man page tab
@echo '' > $(top_builddir)/doc/scratch_insert_file
@echo ' <tab type="usergroup" visible="yes" url="@ref manpage" title="Manual Pages">' > $(top_builddir)/doc/insert_file
@echo ' <tab type="usergroup" visible="yes" url="@ref man_summary" title="Man Pages Summary">' >> $(top_builddir)/doc/insert_file
##
@echo '/** @page manpage Manual Pages' > $(top_builddir)/doc/man_tmp/manpage.dox
@echo ' Here are the libcoap API and Example manual pages:' >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo ' <table class="directory">' >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " <tr>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " <td class=\"entry\" align=\"left\"> @ref man_summary </td><td class=\"desc\" align=\"left\">Man Pages Summary</td>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " </tr>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " <tr class=\"even\">" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " <td class=\"entry\" align=\"left\"> @ref man_individual </td><td class=\"desc\" align=\"left\">Individual Man Pages</td>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " </tr>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo " </table>" >> $(top_builddir)/doc/man_tmp/manpage.dox
@echo ' */' >> $(top_builddir)/doc/man_tmp/manpage.dox
##
@echo '/** @page man_summary Manual Pages Summary' > $(top_builddir)/doc/man_tmp/man_summary.dox
@echo ' Here are a list of libcoap API summary man pages, some of which have code examples, and Examples:' >> $(top_builddir)/doc/man_tmp/man_summary.dox
@echo ' <table class="directory">' >> $(top_builddir)/doc/man_tmp/man_summary.dox
##
@echo '/** @page man_individual Individual Manual Pages' > $(top_builddir)/doc/man_tmp/man_individual.dox
@echo ' Here are a list of libcoap API individual man pages, some of which have code examples:' >> $(top_builddir)/doc/man_tmp/man_individual.dox
@echo ' <table class="directory">' >> $(top_builddir)/doc/man_tmp/man_individual.dox
##
## Setup the upgrading tab
@echo '/** @page upgrading Upgrading' > $(top_builddir)/doc/man_tmp/upgrading.dox
@echo ' Upgrading between libcoap versions:' >> $(top_builddir)/doc/man_tmp/upgrading.dox
@echo ' <table class="directory">' >> $(top_builddir)/doc/man_tmp/upgrading.dox
man-page-build: upg-page-build man-page-start
@MAN_FILES=`find $(top_srcdir)/man/ -type f -name "coap.txt.in" ; find $(top_srcdir)/man/ -type f -name "coap_*.in" | ALL=C sort ; find $(top_srcdir)/man/ -type f -name "coap-*.in" | LC_ALL=C sort` ;\
UPG_FILES=`find $(top_srcdir)/doc/ -type f -name "upgrade_*.txt" | ALL=C sort` ;\
HTML_FILES=`find $(top_builddir)/man/ -type f -name "*.html"` ;\
COUNT_MAN_FILES=`echo $${MAN_FILES} | wc -w` ;\
COUNT_HTML_FILES=`echo $${HTML_FILES} | wc -w` ;\
## We need the HTML files from the Asciidoc source files, check if they around, otherwise build them.
if [ "$${COUNT_MAN_FILES}" != "$${COUNT_HTML_FILES}" ]; then \
$(MAKE) -C ../man ;\
fi ;\
##
## Build the summary man pages
##
for FILE in $${MAN_FILES} ; do \
BASE=`basename $${FILE} | cut -d. -f 1` ;\
MANUAL=`egrep -B 1 "^====" $${FILE} | head -1` ;\
SUMMARY=`egrep -B 2 "^SYNOPSIS" $${FILE} | ${SED} 's/coap-//g' | cut -d\- -f2 | cut -c2- | head -1` ;\
##
## Fix and copy .html file across
##
if [ -f $(top_builddir)/man/$${BASE}.html ]; then \
## Correct case sensitive Name and Synopsis on master (used later)
$(SED) -i 's^<h2>Name</h2>^<h2>NAME</h2>^g' $(top_builddir)/man/$${BASE}.html ;\
$(SED) -i 's^<h2>Synopsis</h2>^<h2>SYNOPSIS</h2>^g' $(top_builddir)/man/$${BASE}.html ;\
cp -f $(top_builddir)/man/$${BASE}.html $(top_builddir)/doc/man_html/$${BASE}.html ;\
else \
echo "ERROR: $(top_builddir)/man/$${BASE}.html not found!";\
exit 1 ;\
fi ;\
## Build the manual insert page
echo "/// @page man_$${BASE} $${MANUAL}" > $(top_builddir)/doc/man_tmp/$${MANUAL}.dox ;\
echo "/// @htmlinclude $${BASE}.html $${MANUAL}" >> $(top_builddir)/doc/man_tmp/$${MANUAL}.dox ;\
## Update insert_file (the list is sorted appropriately)
echo " <tab type=\"user\" visible=\"yes\" url=\"@ref man_$${BASE}\" title=\"$${MANUAL} - $${SUMMARY}\" intro=\"\"/>" >> $(top_builddir)/doc/insert_file ;\
## Update the summary man page
echo " <tr$${ROW_EVEN}>" >> $(top_builddir)/doc/man_tmp/man_summary.dox ;\
echo " <td class=\"entry\" align=\"left\"> @ref man_$${BASE} </td><td class=\"desc\" align=\"left\">$${SUMMARY}</td>" >> $(top_builddir)/doc/man_tmp/man_summary.dox ;\
echo " </tr>" >> $(top_builddir)/doc/man_tmp/man_summary.dox ;\
if [ -z "$${ROW_EVEN}" ] ; then \
ROW_EVEN=" class=\"even\"" ;\
else \
ROW_EVEN= ;\
fi \
done ;\
##
## Close off the man page summary file
##
echo ' </table>' >> $(top_builddir)/doc/man_tmp/man_summary.dox ;\
echo ' */' >> $(top_builddir)/doc/man_tmp/man_summary.dox ;\
echo ' </tab>' >> $(top_builddir)/doc/insert_file ;\
##
## Build the individual man pages
##
echo ' <tab type="usergroup" visible="yes" url="@ref man_individual" title="Individual Man Pages">' >> $(top_builddir)/doc/insert_file ;\
for FILE in $${MAN_FILES} ; do \
BASE=`basename $${FILE} | cut -d. -f 1` ;\
LIST=`${SED} -ne '/^NAME/,/^SYNOPSIS/p;/^SYNOPSIS/q' $${FILE} | ${SED} -ne '/coap_/{ s/ *, *//g ; p }' | egrep -v "^$${BASE}$$"` ;\
for ENTRY in $${LIST} ; do \
MANUAL="$${ENTRY}(3)" ;\
## Build the manual insert page
echo "/// @page man_$${ENTRY} $${MANUAL}" > $(top_builddir)/doc/man_tmp/$${MANUAL}.dox ;\
echo "/// @htmlinclude $${ENTRY}.html $${MANUAL}" >> $(top_builddir)/doc/man_tmp/$${MANUAL}.dox ;\
## Create html file
cat $(top_builddir)/man/$${BASE}.html | ${SED} "s/Function: $${ENTRY}(/<a class=\"anchor\" id=\"$${ENTRY}\"><\/a>\0/" > $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
## Update scratch_insert_file for sorting later
echo "$${ENTRY}" >> $(top_builddir)/doc/scratch_insert_file ;\
done ;\
done ;\
##
## Process the (sorted) list of individual man pages
##
for ENTRY in `cat $(top_builddir)/doc/scratch_insert_file | ALL=C sort -u` ; do \
## Update the individual man page
MANUAL="$${ENTRY}(3)" ;\
echo " <tab type=\"user\" visible=\"yes\" url=\"@ref man_$${ENTRY}\" title=\"$${MANUAL}\" intro=\"\"/>" >> $(top_builddir)/doc/insert_file ;\
echo " <tr$${ROW_EVEN}>" >> $(top_builddir)/doc/man_tmp/man_individual.dox ;\
echo " <td class=\"entry\" align=\"left\"> @ref man_$${ENTRY} </td><td class=\"desc\" align=\"left\"></td>" >> $(top_builddir)/doc/man_tmp/man_individual.dox ;\
echo " </tr>" >> $(top_builddir)/doc/man_tmp/man_individual.dox ;\
if [ -z "$${ROW_EVEN}" ] ; then \
ROW_EVEN=" class=\"even\"" ;\
else \
ROW_EVEN= ;\
fi \
done ;\
##
## Close off the individual man pages
##
echo ' </table>' >> $(top_builddir)/doc/man_tmp/man_individual.dox ;\
echo ' */' >> $(top_builddir)/doc/man_tmp/man_individual.dox ;\
echo ' </tab>' >> $(top_builddir)/doc/insert_file ;\
##
## Close off the man page top level
##
echo ' </tab>' >> $(top_builddir)/doc/insert_file ;\
##
## Add in the deprecated tab
##
echo ' <tab type="user" visible="yes" url="@ref deprecated" title="Deprecated Items" intro=""/>' >> $(top_builddir)/doc/insert_file ;\
##
## Start the upgrade tab
##
echo ' <tab type="usergroup" visible="yes" url="@ref upgrading" title="Upgrading">' >> $(top_builddir)/doc/insert_file ;\
for FILE in $${UPG_FILES} ; do \
BASE=`basename $${FILE} | $(SED) "s/\.txt$$//g"`; \
UPGRADE=`echo $${BASE} | $(SED) "s/^upgrade_//g"`; \
CUPGRADE=`echo $${UPGRADE} | $(SED) "s/\./-/g"`; \
SUMMARY=`head -1 $${FILE} | ${SED} 's/^= //g'` ;\
## Build the upgrade insert page
echo "/// @page upg_$${CUPGRADE} $${UPGRADE}" > $(top_builddir)/doc/man_tmp/$${UPGRADE}.dox ;\
echo "/// @htmlinclude $${BASE}.html $${UPGRADE}" >> $(top_builddir)/doc/man_tmp/$${UPGRADE}.dox ;\
## Update insert_file
echo " <tab type=\"user\" visible=\"yes\" url=\"@ref upg_$${CUPGRADE}\" title=\"$${SUMMARY}\" intro=\"\"/>" >> $(top_builddir)/doc/insert_file ;\
## Update the upgrading page
echo " <tr$${ROW_EVEN}>" >> $(top_builddir)/doc/man_tmp/upgrading.dox ;\
echo " <td class=\"entry\" align=\"left\"> @ref upg_$${CUPGRADE} </td><td class=\"desc\" align=\"left\">$${SUMMARY}</td>" >> $(top_builddir)/doc/man_tmp/upgrading.dox ;\
echo " </tr>" >> $(top_builddir)/doc/man_tmp/upgrading.dox ;\
if [ -z "$${ROW_EVEN}" ] ; then \
ROW_EVEN=" class=\"even\"" ;\
else \
ROW_EVEN= ;\
fi ;\
if [ -f $(top_builddir)/doc/$${BASE}.html ]; then \
cp -f $(top_builddir)/doc/$${BASE}.html $(top_builddir)/doc/man_html/$${BASE}.html ;\
## Correct case sensitive Name and Synopsis
$(SED) -i 's^<div class="toc"><p><strong>^<div class="section"><p><strong>^' $(top_builddir)/doc/man_html/$${BASE}.html ;\
else \
echo "ERROR: $(top_builddir)/doc/$${BASE}.html not found!";\
exit 1 ;\
fi \
done ;\
##
## Close off the upgrading tab
##
echo ' </table>' >> $(top_builddir)/doc/man_tmp/upgrading.dox ;\
echo ' */' >> $(top_builddir)/doc/man_tmp/upgrading.dox ;\
##
## Close off the insert file list
##
echo ' </tab>' >> $(top_builddir)/doc/insert_file ;\
##
## Create and Update the DoxygenLayout.xml file
##
$(DOXYGEN) -l ;\
$(SED) -i 's/<tab type="pages" visible="yes" /<tab type="pages" visible="no" /g' $(top_builddir)/doc/DoxygenLayout.xml ;\
$(SED) -i '/<tab type="examples" visible=.*/r insert_file' $(top_builddir)/doc/DoxygenLayout.xml ;\
##
## Fix up man html files, adding links
##
for FILE in $${MAN_FILES} `cat $(top_builddir)/doc/scratch_insert_file` ; do \
ENTRY=`basename $${FILE} | cut -d . -f1` ;\
## Functions defined in the body
$(SED) -i "s^\(<span class=\"strong\"><strong>\)\(coap[_-][0-9a-z_]*\)\(</strong></span>(\|(\)^\1<a class=\"st-desc\" href=\"man_\2.html#\2\" target=\"_self\">\2</a>\3^g" $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
## The SYNOPSIS entries
$(SED) -i "s^\(<p><span class=\"strong\"><strong>[a-z0-9_ \*]*\)\(coap_[0-9a-z_]*\)\([(;]\)^\1<a class=\"st-synopsis\" href=\"man_\2.html#\2\" target=\"_self\">\2</a>\3^g" $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
## Function in NAME and Examples
$(SED) -i "s^\([ =,] \|[(!>]\|\^\)\(coap_[0-9a-z_]*\)\([(,]\| \-\| \xe2\x80\x94\)^\1<a href=\"man_\2.html#\2\" target=\"_self\">\2</a>\3^g" $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
## Do for a second time in case of overlaps
$(SED) -i "s^\([ =,] \|[(!>]\|\^\)\(coap_[0-9a-z_]*\)\([(,]\| \-\| \xe2\x80\x94\)^\1<a href=\"man_\2.html#\2\" target=\"_self\">\2</a>\3^g" $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
done ;\
##
## Do the highlighting
##
for ENTRY in `cat $(top_builddir)/doc/scratch_insert_file` ; do \
${SED} -i "s/\($${ENTRY}\)\([<(\*, ]\)/<span class=\"man-highlight\">\1<\/span>\2/g" $(top_builddir)/doc/man_html/$${ENTRY}.html ;\
done
if BUILD_MANPAGES
UPG_LIST = upgrade_4.2.1_4.3.0.txt upgrade_4.3.0_4.3.1.txt
upg-page-build:
@for FILE in $(UPG_LIST) ; do \
$(A2X) -d article --format xhtml -D $(top_builddir)/doc/ $(top_srcdir)/doc/$${FILE} ;\
done
all: man-page-build
$(DOXYGEN) Doxyfile
@$(RM) $(top_builddir)/doc/insert_file $(top_builddir)/doc/scratch_insert_file
@cp -f $(top_srcdir)/doc/docbook.local.css $(top_builddir)/doc/html/docbook-xsl.css
else
#
# Need to make sure the man directories are in place, but empty
all: man-page-prepare
$(DOXYGEN) Doxyfile
endif # BUILD_MANPAGES
clean-local:
-rm -rf $(top_builddir)/doc/html $(top_builddir)/doc/man_tmp $(top_builddir)/doc/man_html $(top_builddir)/doc/DoxygenLayout.xml $(top_builddir)/doc/docbook-xsl.css $(top_builddir)/doc/*.html
distclean-local: clean-local
endif # HAVE_DOXYGEN
install-data-hook:
if HAVE_DOXYGEN
@if [ ! -d $(top_builddir)/doc/html ]; then \
echo ;\
echo " No install data in '$(top_builddir)/doc/html' found! Please run 'make all' first." ;\
echo ;\
exit 1 ;\
fi
$(MKDIR_P) $(DESTDIR)$(htmldir)/html || exit 1
cp -a -f $(top_builddir)/doc/html $(DESTDIR)$(htmldir)
find $(DESTDIR)$(htmldir) -type f -name "*.md5" -delete
endif # HAVE_DOXYGEN
if BUILD_LICENSE_INSTALL
$(MKDIR_P) $(DESTDIR)$(docdir) || exit 1
$(INSTALL_DATA) $(top_srcdir)/LICENSE $(DESTDIR)$(docdir)
$(INSTALL_DATA) $(top_srcdir)/COPYING $(DESTDIR)$(docdir)
$(INSTALL_DATA) $(top_srcdir)/README $(DESTDIR)$(docdir)
endif # BUILD_LICENSE_INSTALL
uninstall-hook:
if BUILD_LICENSE_INSTALL
@if [ -d $(DESTDIR)$(docdir) ] ; then \
(cd $(DESTDIR)$(docdir) ; rm -f LICENSE README COPYING) ; \
fi
endif # BUILD_LICENSE_INSTALL
if HAVE_DOXYGEN
-rm -rf $(DESTDIR)$(htmldir)/html
endif # HAVE_DOXYGEN
.PHONY: man-page-cleanup man-page-prepare man-page-start man-page-build
@@ -0,0 +1,47 @@
body pre {
margin: 0.5em 10% 0.5em 1em;
line-height: 1.0;
color: navy;
}
dl {
margin: .2em 0;
line-height: 1.2;
}
dt {
margin-top: 0.1em;
}
span.man-highlight { background: yellow; }
a.st-desc {
font-weight: bold;
color: black;
text-decoration: none;
}
a.st-desc:visited {
font-weight: bold;
color: black;
text-decoration: none;
}
a.st-desc:hover {
text-decoration: underline;
}
a.st-synopsis {
font-weight: bold;
color: black;
text-decoration: none;
}
a.st-synopsis:visited {
font-weight: bold;
color: black;
text-decoration: none;
}
a.st-synopsis:hover {
text-decoration: underline;
}
@@ -0,0 +1,69 @@
libcoap {#mainpage}
=======
A C implementation of the Constrained Application Protocol (RFC 7252)
=====================================================================
Copyright (C) 2010--2022 by Olaf Bergmann <bergmann@tzi.org> and others
About libcoap
=============
libcoap is a C implementation of a lightweight application-protocol
for devices that are constrained their resources such as computing
power, RF range, memory, bandwidth, or network packet sizes. This
protocol, CoAP, is standardized by the IETF as RFC 7252. For further
information related to CoAP, see <http://coap.technology>.
You might want to check out
[libcoap-minimal](https://github.com/obgm/libcoap-minimal) for usage
examples.
The following RFCs are supported
* RFC7252: The Constrained Application Protocol (CoAP)
* RFC7390: Group Communication for the Constrained Application Protocol (CoAP)
* RFC7641: Observing Resources in the Constrained Application Protocol (CoAP)
* RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)
* RFC7967: Constrained Application Protocol (CoAP) Option for No Server Response
* RFC8132: PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
* RFC8323: CoAP (Constrained Application Protocol) over TCP, TLS, and WebSockets
[No WebSockets support]
* RFC8516: "Too Many Requests" Response Code for the Constrained Application Protocol
* RFC8768: Constrained Application Protocol (CoAP) Hop-Limit Option
* RFC9175: CoAP: Echo, Request-Tag, and Token Processing
There is (D)TLS support for the following libraries
* OpenSSL (Minimum version 1.1.0) [PKI, PSK and PKCS11]
* GnuTLS (Minimum version 3.3.0) [PKI, PSK, RPK(3.6.6+) and PKCS11]
* Mbed TLS (Minimum version 2.7.10) [PKI and PSK]
* TinyDTLS [PSK and RPK] [DTLS Only]
Documentation
=============
This set of pages contains the current set of documention for the libcoap APIs.
License Information
===================
This library is published as open-source software without any warranty
of any kind. Use is permitted under the terms of the simplified BSD
license. It includes public domain software. libcoap binaries may also
include open-source software with their respective licensing terms.
Please refer to
[LICENSE](https://raw.githubusercontent.com/obgm/libcoap/develop/LICENSE)
for further details in the source.
@@ -0,0 +1,21 @@
/* doc/module_api_wrap.h
*
* Copyright (C) 2021-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP C library libcoap. Please see README and
* COPYING for terms of use.
*/
/**
* @file module_api_wrap.h
* @brief Doxygen specific wrapper for Modules layout
*/
/**
* @defgroup application_api Application API
* Application API Structures, Macros, Typedefs, Enums and Functions
* @defgroup internal_api Libcoap Internal API
* libcoap Internal API Structures, Macros, Typedefs, Enums and Functions
*/
@@ -0,0 +1,431 @@
= Upgrade from 4.2.1 to 4.3.0
== Summary
When compiling 4.2.1 based code with a 4.3.0 environment, this will initially
throw up many errors as the API has been updated to make future coding simpler,
adds more functionality and adds more rigorous coding checks. Updating your
code with the following steps will significantly reduce the reported issues.
The examples are now also named with the (D)TLS library type as a suffix.
E.g. coap-client is now coap-client-openssl.
== Include directory changes
Because of the API changes, the libcoap's include file directory has changed from `coap2/` to `coap3/`. Also, there is now no need to define additional include paths to the compiler options such as `-I include/coap3`.
=== Update coap2 to coap3
Example
----
4.2.1
#include <coap2/coap.h>
4.3.0
#include <coap3/coap.h>
----
No other libcoap include files need to be included in your application.
== Call-back handler updates
Infrequently used parameters (which can easily be recreated) have been removed
and others have been made const. These call-back handlers are those
registered with the `coap_register_*()` functions as follows:
=== coap_register_handler()
The definition of `coap_method_handler_t` has been updated, so all the
functions registered by `coap_register_handler()` need to be updated. Any
application functions called by these functions may need to include `const` in
their calling parameters.
Example
----
4.2.1
static void
hnd_get_time(coap_context_t *context,
coap_resource_t *resource,
coap_session_t *session,
coap_pdu_t *request,
coap_binary_t *token,
coap_string_t *query,
coap_pdu_t *response) {
4.3.0
static void
hnd_get_time(coap_resource_t *resource,
coap_session_t *session,
const coap_pdu_t *request,
const coap_string_t *query,
coap_pdu_t *response) {
----
If `context` or `token` need to be recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
coap_bin_const_t rcvd_token = coap_pdu_get_token(request);
----
=== coap_register_response_handler()
The definition of `coap_response_handler_t` has been updated, so all the
functions registered by `coap_register_response_handler()` need to be updated.
Any application functions called by these functions may need to include `const`
in their calling parameters. There is a new handler function exit code
`COAP_RESPONSE_FAIL` (if the response is not liked and needs to be rejected
with a `RST` packet) or `COAP_RESPONSE_OK`. Note that `coap_tid_t` has been
replaced with `coap_mid_t` to reflect the parameter is the message id.
Example
----
4.2.1
static void
message_handler(struct coap_context_t *context,
coap_session_t *session,
coap_pdu_t *sent,
coap_pdu_t *received,
const coap_tid_t id) {
4.3.0
static coap_response_t
message_handler(coap_session_t *session,
const coap_pdu_t *sent,
const coap_pdu_t *received,
const coap_mid_t mid) {
----
If `context` needs to be recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
----
=== coap_register_nack_handler()
The definition of `coap_nack_handler_t` has been updated, so all the functions
registered by `coap_register_nack_handler()` need to be updated. Any
application functions called by these functions may need to include `const` in
their calling parameters. Note that `coap_tid_t` has been replaced with
`coap_mid_t` to reflect the parameter is the message id.
Example
----
4.2.1
static void
nack_handler(coap_context_t *context,
coap_session_t *session,
coap_pdu_t *sent,
coap_nack_reason_t reason,
const coap_tid_t id) {
4.3.0
static void
nack_handler(coap_session_t *session,
const coap_pdu_t *sent,
const coap_nack_reason_t reason,
const coap_mid_t mid) {
----
If `context` needs to be recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
----
=== coap_register_event_handler()
The definition of `coap_event_handler_t` been updated, so all the functions
registered by `coap_register_event_handler()` need to be updated. Any
application functions called by these functions may need to include `const` in
their calling parameters.
Example
----
4.2.1
static int
event_handler(coap_context_t *context,
coap_event_t event,
struct coap_session_t *session) {
4.3.0
static int
event_handler(coap_session_t *session,
const coap_event_t event) {
----
Note the reversed order of the parameters. If `context` needs to be
recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
----
=== coap_register_ping_handler()
The definition of `coap_ping_handler_t` been updated, so all the functions
registered by `coap_register_ping_handler()` need to be updated. Any
application functions called by these functions may need to include `const` in
their calling parameters. Note that `coap_tid_t` has been replaced with
`coap_mid_t` to reflect the parameter is the message id.
Example
----
4.2.1
void
ping_handler(coap_context_t *context,
coap_session_t *session,
coap_pdu_t *received,
const coap_tid_t id);
4.3.0
void
ping_handler(coap_session_t *session,
const coap_pdu_t *received,
const coap_mid_t mid);
----
If `context` needs to be recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
----
=== coap_register_pong_handler()
The definition of `coap_pong_handler_t` been updated, so all the functions
registered by `coap_register_pong_handler()` need to be updated. Any
application functions called by these functions may need to include `const` in
their calling parameters. Note that `coap_tid_t` has been replaced with
`coap_mid_t` to reflect the parameter is the message id.
Example
----
4.2.1
void
pong_handler(coap_context_t *context,
coap_session_t *session,
coap_pdu_t *received,
const coap_tid_t id);
4.3.0
void
pong_handler(coap_session_t *session,
const coap_pdu_t *received,
const coap_mid_t mid);
----
If `context` needs to be recreated, this is done by
----
coap_context_t *context = coap_session_get_context(session);
----
== libcoap structures no longer directly accessible
Many of the structures internally used by libcoap are no longer exposed to
applications. Additional functions of the form `coap_X_get_Y()` and
`coap_X_set_Y()` where `X` is the structure type and `Y` is the variable. Below
is a non exhaustive set of examples,
=== coap_pdu_t code variable
Example
----
4.2.1
if (received->code ==
4.3.0
coap_pdu_code_t rcvd_code = coap_pdu_get_code(received);
...
if (rcvd_code ==
----
Example
----
4.2.1
response->code = COAP_RESPONSE_CODE(404);
4.3.0
coap_pdu_set_code(response, COAP_RESPONSE_CODE_NOT_FOUND);
----
Note that more descriptive names are now supported for the response codes, but
the old form can still be used.
=== coap_pdu_t type variable
Example
----
4.2.1
if (received->type ==
4.3.0
coap_pdu_code_t rcvd_type = coap_pdu_get_type(received);
...
if (rcvd_type ==
----
Example
----
4.2.1
request->type = COAP_MESSAGE_NON;
4.3.0
coap_pdu_set_type(request, COAP_MESSAGE_NON);
----
=== coap_pdu_t token variable
Example
----
4.2.1
static inline int
check_token(coap_pdu_t *received) {
return received->token_length == the_token.length &&
memcmp(received->token, the_token.s, the_token.length) == 0;
}
4.3.0
static inline int
check_token(const coap_pdu_t *received) {
coap_bin_const_t rcvd_token = coap_pdu_get_token(received);
return rcvd_token.length == the_token.length &&
memcmp(rcvd_token.s, the_token.s, the_token.length) == 0;
}
----
=== coap_session_t context variable
Example
----
4.2.1
if (session->context ==
4.3.0
coap_context_t context = coap_session_get_context(session);
...
if (context ==
----
=== coap_session_t proto variable
Example
----
4.2.1
if (session->proto ==
4.3.0
coap_proto_t proto = coap_session_get_proto(session);
...
if (proto ==
----
== Functions with changed parameters
Some functions have had the parameters updated. Below are some of the more common ones.
=== coap_pdu_init()
The definition of the second parameter has changed from `coap_request_t` to
`coap_pdu_code_t`.
Example
----
4.2.1
pdu = coap_pdu_init(msgtype,
COAP_REQUEST_GET,
coap_new_message_id(session),
coap_session_max_pdu_size(session));
4.3.0
pdu = coap_pdu_init(msgtype,
COAP_REQUEST_CODE_GET,
coap_new_message_id(session),
coap_session_max_pdu_size(session));
----
Note that the second parameter (`COAP_REQUEST_CODE_GET`) goes further than
just request codes and includes the possibility of response codes (e.g.
`COAP_RESPONSE_CODE_CREATED`) from the `enum coap_pdu_code_t`. Hence the
addition of `_CODE` in the parameter value.
=== coap_get_data()
The definition of the third parameter has been changed to be `const`
Example
----
4.2.1
uint8_t *data;
...
ret = coap_get_data(pdu, &length, &data);
4.3.0
const uint8_t *data;
...
ret = coap_get_data(pdu, &length, &data);
----
== Large Data Handling
Splitting up large data transmission into blocks (RFC7959) can now all be
handled by internally by libcoap, removing the need for applications to know
anything about how to work with blocks, or need to do any block packet loss
recovery. In simple terms, `coap_context_set_block_mode()` must be called,
`coap_add_data()` (or `coap_add_data_blocked_response()`) is replaced by
`coap_add_data_large_response()` or `coap_add_data_large_request()`, and
`coap_get_data_large()` used instead of `coap_get_data()`. See man page
`coap_block(3)` for further information.
There are 3 ways of handling the block transfers
=== Application does all the work
This is how things were done in 4.2.1. The application recognizes the next
block request coming in and then generates the next block response (including
setting up the PDU if client). To continue using this method,
`coap_context_set_block_mode()` must not be called and none of the `_large`
functions used.
=== Application sees individual blocks
By calling `coap_context_set_block_mode(context, COAP_BLOCK_USE_LIBCOAP)` and
using the `_large` functions, all the existing code that builds the next block
response is no longer needed (and must be removed to prevent packet
request/response duplication) as libcoap does this for the application.
By calling `coap_get_data_large()`, the application can determine if this is
the first block or not (using `offset` value), whether the first block is all
the data (`offset` = `0`, `length` = `total`) and whether this is the last
block (`offset` + `length` = `total`). It is the responsibility of the
application to re-assemble the individual blocks into a single body of data.
If this is the request handler in a server, the server still needs to return a
`2.31 (Continue)` response code if the received data is not for the final block,
otherwise a `2.01 (Created)` or `2.04 (Changed)` should be returned.
=== Application only sees all the data
By calling `coap_context_set_block_mode(context,
COAP_BLOCK_USE_LIBCOAP|COAP_BLOCK_SINGLE_BODY)` and using the `_large`
functions, all the existing code that builds the next block response is no
longer needed (and must be removed to prevent request/response packet
duplication) as libcoap does this for the application.
`coap_get_data_large()` will only return the entire body of data (`offset`
always `0`, `length` = `total`) and there is no need to re-assemble individual
blocks into a large body of data.
In RAM constrained environments, option 2 may be the preferred method.
== Observe Handling
In the server's request handler's call-back, there is no longer any need to
check whether this is an Observe call (or Observe triggered requesting
additional response call) and add in the Observe Option into the response pdu.
This is now added by libcoap, and trying to add in the Observe Option for the
second time in the call-back handler will throw up a Informational warning.
For the client, there is a new function `coap_cancel_observe()` that can be
called to cancel an observation on the server. To use it,
`coap_context_set_block_mode()` has to be called prior to sending the initial
request containing the Observe option.
== Unused function parameters
`UNUSED_PARAM` has been replaced with `COAP_UNUSED`. If `COAP_UNUSED` is used,
then the definition for `UNUSED_PARAM` can be removed.
== CoAP Message IDs
`coap_tid_t` has been replaced with `coap_mid_t`, as well as `COAP_TID_INVALID`
has been replaced with `COAP_MID_INVALID`. This is so that the Message ID aligns
with the definition in RFC7252.
== Async Support
The `async` support has been re-written to simplify usage, and allows the
underlying libcoap to do the main management / work. A primary change is to
register the async request with a defined delay time before triggering - which
if set to 0 is an infinite time and the delay time subsequently updated if
required. Consequently the `coap_async_*()` functions now have different
parameters.
@@ -0,0 +1,6 @@
= Upgrade from 4.3.0 to 4.3.1
== Summary
The source and binary APIs are the same for 4.3.0 and 4.3.1 with just extra
functionality making it forward, but not necessarily backward compatible.
@@ -0,0 +1,129 @@
# examples/Makefile.am
#
# Copyright (C) 2015 Carsten Schoenert <c.schoenert@t-online.de>
# Copyright (C) 2018-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
#
# SPDX-License-Identifier: BSD-2-Clause
#
# This file is part of the CoAP C library libcoap. Please see README and
# COPYING for terms of use.
EXTRA_DIST = share.libcoap.examples.Makefile share.libcoap.examples.README
# just do nothing if 'BUILD_EXAMPLES' isn't defined
if BUILD_EXAMPLES
# picking up the default warning CFLAGS into AM_CFLAGS
AM_CFLAGS = -I$(top_builddir)/include -I$(top_srcdir)/include \
$(WARNING_CFLAGS) $(DTLS_CFLAGS) -std=c99 $(EXTRA_CFLAGS)
#
bin_PROGRAMS =
noinst_PROGRAMS =
check_PROGRAMS =
if HAVE_CLIENT_SUPPORT
bin_PROGRAMS += coap-client@LIBCOAP_DTLS_LIB_EXTENSION_NAME@
check_PROGRAMS += coap-tiny
if BUILD_ADD_DEFAULT_NAMES
noinst_PROGRAMS += coap-client
endif # BUILD_ADD_DEFAULT_NAMES
endif # HAVE_CLIENT_SUPPORT
if HAVE_SERVER_SUPPORT
bin_PROGRAMS += coap-server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ \
coap-rd@LIBCOAP_DTLS_LIB_EXTENSION_NAME@
check_PROGRAMS += coap-etsi_iot_01
if BUILD_ADD_DEFAULT_NAMES
noinst_PROGRAMS += coap-server coap-rd
endif # BUILD_ADD_DEFAULT_NAMES
if ! HAVE_CLIENT_SUPPORT
coap_server_CPPFLAGS=-DSERVER_CAN_PROXY=0
coap_server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_CPPFLAGS=-DSERVER_CAN_PROXY=0
endif # HAVE_CLIENT_SUPPORT
endif # HAVE_SERVER_SUPPORT
coap_client_SOURCES = coap-client.c
coap_client_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_server_SOURCES = coap-server.c
coap_server_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_rd_SOURCES = coap-rd.c
coap_rd_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_client@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_SOURCES = coap-client.c
coap_client@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_SOURCES = coap-server.c
coap_server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_rd@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_SOURCES = coap-rd.c
coap_rd@LIBCOAP_DTLS_LIB_EXTENSION_NAME@_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_etsi_iot_01_SOURCES = etsi_iot_01.c
coap_etsi_iot_01_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
coap_tiny_SOURCES = tiny.c
coap_tiny_LDADD = $(DTLS_LIBS) \
$(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
endif # BUILD_EXAMPLES
if BUILD_EXAMPLES_SOURCE
EXAMPLES_DIR = $(DESTDIR)$(datadir)/libcoap/examples
EXAMPLES_SRC = coap-client.c coap-server.c
endif # BUILD_EXAMPLES_SOURCE
## Install example files
install-exec-hook:
if BUILD_EXAMPLES_SOURCE
$(MKDIR_P) $(EXAMPLES_DIR)
(cd $(top_srcdir)/examples ; \
$(INSTALL_DATA) $(EXAMPLES_SRC) ../LICENSE ../COPYING $(EXAMPLES_DIR) ; \
$(INSTALL_DATA) share.libcoap.examples.Makefile $(EXAMPLES_DIR)/Makefile; \
$(INSTALL_DATA) share.libcoap.examples.README $(EXAMPLES_DIR)/README)
endif # BUILD_EXAMPLES_SOURCE
if BUILD_ADD_DEFAULT_NAMES
if [ -d "$(DESTDIR)$(bindir)" ] ; then \
(cd $(DESTDIR)$(bindir) && \
(if [ -f coap-client@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ ] ; then \
rm -f coap-client ; \
$(LN_S) coap-client@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ coap-client ; \
fi ; \
if [ -f coap-server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ ] ; then \
rm -f coap-server ; \
$(LN_S) coap-server@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ coap-server ; \
fi ; \
if [ -f coap-rd@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ ] ; then \
rm -f coap-rd ; \
$(LN_S) coap-rd@LIBCOAP_DTLS_LIB_EXTENSION_NAME@ coap-rd ; \
fi) \
) ; \
fi
endif # BUILD_ADD_DEFAULT_NAMES
uninstall-hook:
if BUILD_EXAMPLES_SOURCE
rm -rf $(DESTDIR)$(datadir)/libcoap/examples
endif # BUILD_EXAMPLES_SOURCE
if BUILD_ADD_DEFAULT_NAMES
rm -f $(DESTDIR)$(bindir)/coap-client
rm -f $(DESTDIR)$(bindir)/coap-server
rm -f $(DESTDIR)$(bindir)/coap-rd
endif # BUILD_ADD_DEFAULT_NAMES
@@ -0,0 +1,43 @@
This README documents the test cases supported for the 1st ETSI CoAP
plugtest on March 24/25 in Paris, France.
<http://www.etsi.org/plugtests/coap/coap.htm>
Legend:
[+] full support
[o] partial support
[-] no support
[?] needs check
[ ] has open issues
Mandatory Tests
[+] TD_COAP_CORE_01 Perform GET transaction (CON mode)
[+] TD_COAP_CORE_02 Perform POST transaction (CON mode)
[+] TD_COAP_CORE_03 Perform PUT transaction (CON mode)
[+] TD_COAP_CORE_04 Perform DELETE transaction (CON mode)
[+] TD_COAP_CORE_05 Perform GET transaction (NON mode)
[+] TD_COAP_CORE_06 Perform POST transaction (NON mode)
[+] TD_COAP_CORE_07 Perform PUT transaction (NON mode)
[+] TD_COAP_CORE_08 Perform DELETE transaction (NON mode)
[+] TD_COAP_CORE_09 Perform GET transaction with delayed response (CON mode, no piggyback)
[+] TD_COAP_CORE_10 Handle request containing Token option
[+] TD_COAP_CORE_11 Handle request not containing Token option
[+] TD_COAP_CORE_12 Handle request containing several Uri-Path options
[+] TD_COAP_CORE_13 Handle request containing several Uri-Query options
[?] TD_COAP_CORE_14 Interoperate in lossy context (CON mode, piggybacked response)
[?] TD_COAP_CORE_15 Interoperate in lossy context (CON mode, delayed response)
Optional Tests
[ ] TD_COAP_LINK_01 Access to well-known interface for resource discovery
[-] TD_COAP_LINK_02 Use filtered requests for limiting discovery results
[+] TD_COAP_BLOCK_01 Handle GET blockwise transfer for large resource (early negotiation)
[+] TD_COAP_BLOCK_02 Handle GET blockwise transfer for large resource (late negotiation)
[-] TD_COAP_BLOCK_03 Handle PUT blockwise transfer for large resource
[-] TD_COAP_BLOCK_04 Handle POST blockwise transfer for large resource
[-] TD_COAP_OBS_01 Handle resource observation
[-] TD_COAP_OBS_02 Stop resource observation
[-] TD_COAP_OBS_03 Client detection of deregistration (Max-Age)
[-] TD_COAP_OBS_04 Server detection of deregistration (client OFF)
[-] TD_COAP_OBS_05 Server detection of deregistration (explicit RST)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,879 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 * -*- */
/* coap -- simple implementation of the Constrained Application Protocol (CoAP)
* as defined in RFC 7252
*
* Copyright (C) 2010--2015,2022 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms of
* use.
*/
/**
* @file coap-rd.c
* @brief CoRE resource directory
*
* @see https://tools.ietf.org/html/draft-ietf-core-resource-directory
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#include "getopt.c"
#if !defined(S_ISDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
#else
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <dirent.h>
#endif
#include <coap3/coap.h>
#define COAP_RESOURCE_CHECK_TIME 2
#define RD_ROOT_STR "rd"
#define RD_ROOT_SIZE 2
static char *cert_file = NULL; /* Combined certificate and private key in PEM */
static char *ca_file = NULL; /* CA for cert_file - for cert checking in PEM */
static char *root_ca_file = NULL; /* List of trusted Root CAs in PEM */
static int verify_peer_cert = 1; /* PKI granularity - by default set */
#define MAX_KEY 64 /* Maximum length of a pre-shared key in bytes. */
static uint8_t key[MAX_KEY];
static ssize_t key_length = 0;
static int key_defined = 0;
static const char *hint = "CoAP";
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
typedef struct rd_t {
size_t etag_len; /**< actual length of @c etag */
unsigned char etag[8]; /**< ETag for current description */
coap_string_t data; /**< points to the resource description */
} rd_t;
rd_t *resources = NULL;
static ssize_t
cmdline_read_key(char *arg, unsigned char *buf, size_t maxlen) {
size_t len = strnlen(arg, maxlen);
if (len) {
memcpy(buf, arg, len);
return len;
}
return -1;
}
static inline rd_t *
rd_new(void) {
rd_t *rd;
rd = (rd_t *)coap_malloc(sizeof(rd_t));
if (rd)
memset(rd, 0, sizeof(rd_t));
return rd;
}
static void
rd_delete(rd_t *rd) {
if (rd) {
coap_free(rd->data.s);
coap_free(rd);
}
}
static void
resource_rd_delete(void *ptr) {
rd_delete(ptr);
}
static int quit = 0;
/* SIGINT handler: set quit to 1 for graceful termination */
static void
handle_sigint(int signum COAP_UNUSED) {
quit = 1;
}
static void
hnd_get_resource(coap_resource_t *resource,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
rd_t *rd = coap_resource_get_userdata(resource);
unsigned char buf[3];
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
coap_add_option(response,
COAP_OPTION_CONTENT_TYPE,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT),
buf);
if (rd && rd->etag_len)
coap_add_option(response, COAP_OPTION_ETAG, rd->etag_len, rd->etag);
if (rd && rd->data.s)
coap_add_data(response, rd->data.length, rd->data.s);
}
static void
hnd_put_resource(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
#if 1
coap_pdu_set_code(response, COAP_RESPONSE_CODE_NOT_IMPLEMENTED);
#else /* FIXME */
coap_opt_iterator_t opt_iter;
coap_opt_t *token, *etag;
coap_pdu_t *response;
size_t size = sizeof(coap_hdr_t);
int type = (request->hdr->type == COAP_MESSAGE_CON)
? COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
rd_t *rd = NULL;
unsigned char code; /* result code */
const uint8_t *data;
coap_string_t tmp;
HASH_FIND(hh, resources, resource->uri_path.s, resource->uri_path.length, rd);
if (rd) {
/* found resource object, now check Etag */
etag = coap_check_option(request, COAP_OPTION_ETAG, &opt_iter);
if (!etag || (COAP_OPT_LENGTH(etag) != rd->etag_len)
|| memcmp(COAP_OPT_VALUE(etag), rd->etag, rd->etag_len) != 0) {
if (coap_get_data(request, &tmp.length, &data)) {
tmp.s = (unsigned char *)coap_malloc(tmp.length);
if (!tmp.s) {
coap_log(LOG_DEBUG,
"hnd_put_rd: cannot allocate storage for new rd\n");
code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE;
goto finish;
}
coap_free(rd->data.s);
rd->data.s = tmp.s;
rd->data.length = tmp.length;
memcpy(rd->data.s, data, rd->data.length);
}
}
if (etag) {
rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag));
memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len);
}
code = COAP_RESPONSE_CODE_CHANGED;
/* FIXME: update lifetime */
} else {
code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE;
}
finish:
/* FIXME: do not create a new response but use the old one instead */
response = coap_pdu_init(type, code, request->hdr->id, size);
if (!response) {
coap_log(LOG_DEBUG, "cannot create response for mid=0x%x\n",
request->hdr->id);
return;
}
if (request->hdr->token_length)
coap_add_token(response, request->hdr->token_length, request->hdr->token);
if (coap_send(ctx, peer, response) == COAP_INVALID_MID) {
coap_log(LOG_DEBUG, "hnd_get_rd: cannot send response for mid=0x%x\n",
request->hdr->id);
}
#endif
}
static void
hnd_delete_resource(coap_resource_t *resource,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
rd_t *rd = coap_resource_get_userdata(resource);
if (rd) {
rd_delete(rd);
}
/* FIXME: link attributes for resource have been created dynamically
* using coap_malloc() and must be released. */
coap_delete_resource(NULL, resource);
coap_pdu_set_code(response, COAP_RESPONSE_CODE_DELETED);
}
static void
hnd_get_rd(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
unsigned char buf[3];
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
coap_add_option(response,
COAP_OPTION_CONTENT_TYPE,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT),
buf);
coap_add_option(response,
COAP_OPTION_MAXAGE,
coap_encode_var_safe(buf, sizeof(buf), 0x2ffff), buf);
}
static int
parse_param(const uint8_t *search,
size_t search_len,
unsigned char *data,
size_t data_len,
coap_string_t *result) {
if (result)
memset(result, 0, sizeof(coap_string_t));
if (!search_len)
return 0;
while (search_len <= data_len) {
/* handle parameter if found */
if (memcmp(search, data, search_len) == 0) {
data += search_len;
data_len -= search_len;
/* key is only valid if we are at end of string or delimiter follows */
if (!data_len || *data == '=' || *data == '&') {
while (data_len && *data != '=') {
++data; --data_len;
}
if (data_len > 1 && result) {
/* value begins after '=' */
result->s = ++data;
while (--data_len && *data != '&') {
++data; result->length++;
}
}
return 1;
}
}
/* otherwise proceed to next */
while (--data_len && *data++ != '&')
;
}
return 0;
}
static void
add_source_address(coap_resource_t *resource,
const coap_address_t *peer) {
#define BUFSIZE 64
char *buf;
size_t n = 1;
coap_str_const_t attr_val;
buf = (char *)coap_malloc(BUFSIZE);
if (!buf)
return;
buf[0] = '"';
switch(peer->addr.sa.sa_family) {
case AF_INET:
/* FIXME */
break;
case AF_INET6:
n += snprintf(buf + n, BUFSIZE - n,
"[%02x%02x:%02x%02x:%02x%02x:%02x%02x" \
":%02x%02x:%02x%02x:%02x%02x:%02x%02x]",
peer->addr.sin6.sin6_addr.s6_addr[0],
peer->addr.sin6.sin6_addr.s6_addr[1],
peer->addr.sin6.sin6_addr.s6_addr[2],
peer->addr.sin6.sin6_addr.s6_addr[3],
peer->addr.sin6.sin6_addr.s6_addr[4],
peer->addr.sin6.sin6_addr.s6_addr[5],
peer->addr.sin6.sin6_addr.s6_addr[6],
peer->addr.sin6.sin6_addr.s6_addr[7],
peer->addr.sin6.sin6_addr.s6_addr[8],
peer->addr.sin6.sin6_addr.s6_addr[9],
peer->addr.sin6.sin6_addr.s6_addr[10],
peer->addr.sin6.sin6_addr.s6_addr[11],
peer->addr.sin6.sin6_addr.s6_addr[12],
peer->addr.sin6.sin6_addr.s6_addr[13],
peer->addr.sin6.sin6_addr.s6_addr[14],
peer->addr.sin6.sin6_addr.s6_addr[15]);
if (peer->addr.sin6.sin6_port != htons(COAP_DEFAULT_PORT)) {
n +=
snprintf(buf + n, BUFSIZE - n, ":%d", peer->addr.sin6.sin6_port);
}
break;
default:
;
}
if (n < BUFSIZE)
buf[n++] = '"';
attr_val.s = (const uint8_t *)buf;
attr_val.length = n;
coap_add_attr(resource,
coap_make_str_const("A"),
&attr_val,
0);
coap_free(buf);
#undef BUFSIZE
}
static rd_t *
make_rd(const coap_pdu_t *pdu) {
rd_t *rd;
const uint8_t *data;
coap_opt_iterator_t opt_iter;
coap_opt_t *etag;
rd = rd_new();
if (!rd) {
coap_log(LOG_DEBUG, "hnd_get_rd: cannot allocate storage for rd\n");
return NULL;
}
if (coap_get_data(pdu, &rd->data.length, &data)) {
rd->data.s = (unsigned char *)coap_malloc(rd->data.length);
if (!rd->data.s) {
coap_log(LOG_DEBUG, "hnd_get_rd: cannot allocate storage for rd->data\n");
rd_delete(rd);
return NULL;
}
memcpy(rd->data.s, data, rd->data.length);
}
etag = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter);
if (etag) {
rd->etag_len = min(coap_opt_length(etag), sizeof(rd->etag));
memcpy(rd->etag, coap_opt_value(etag), rd->etag_len);
}
return rd;
}
static void
hnd_post_rd(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_resource_t *r;
#define LOCSIZE 68
unsigned char *loc;
size_t loc_size;
coap_string_t h = {0, NULL}, ins = {0, NULL}, rt = {0, NULL}, lt = {0, NULL}; /* store query parameters */
unsigned char *buf;
coap_str_const_t attr_val;
coap_str_const_t resource_val;
loc = (unsigned char *)coap_malloc(LOCSIZE);
if (!loc) {
coap_pdu_set_code(response, COAP_RESPONSE_CODE_INTERNAL_ERROR);
return;
}
memcpy(loc, RD_ROOT_STR, RD_ROOT_SIZE);
loc_size = RD_ROOT_SIZE;
loc[loc_size++] = '/';
/* store query parameters for later use */
if (query) {
parse_param((const uint8_t *)"h", 1, query->s, query->length, &h);
parse_param((const uint8_t *)"ins", 3, query->s, query->length, &ins);
parse_param((const uint8_t *)"lt", 2, query->s, query->length, &lt);
parse_param((const uint8_t *)"rt", 2, query->s, query->length, &rt);
}
if (h.length) { /* client has specified a node name */
memcpy(loc + loc_size, h.s, min(h.length, LOCSIZE - loc_size - 1));
loc_size += min(h.length, LOCSIZE - loc_size - 1);
if (ins.length && loc_size > 1) {
loc[loc_size++] = '-';
memcpy((char *)(loc + loc_size),
ins.s, min(ins.length, LOCSIZE - loc_size - 1));
loc_size += min(ins.length, LOCSIZE - loc_size - 1);
}
} else { /* generate node identifier */
loc_size +=
snprintf((char *)(loc + loc_size), LOCSIZE - loc_size - 1,
"%x", coap_pdu_get_mid(request));
if (loc_size > 1) {
if (ins.length) {
loc[loc_size++] = '-';
memcpy((char *)(loc + loc_size),
ins.s,
min(ins.length, LOCSIZE - loc_size - 1));
loc_size += min(ins.length, LOCSIZE - loc_size - 1);
} else {
coap_tick_t now;
coap_ticks(&now);
loc_size += snprintf((char *)(loc + loc_size),
LOCSIZE - loc_size - 1,
"-%x",
(unsigned int)(now & (unsigned int)-1));
}
}
}
/* TODO:
* - use lt to check expiration
*/
resource_val.s = loc;
resource_val.length = loc_size;
r = coap_resource_init(&resource_val, 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_resource);
coap_register_request_handler(r, COAP_REQUEST_PUT, hnd_put_resource);
coap_register_request_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource);
if (ins.s) {
buf = (unsigned char *)coap_malloc(ins.length + 2);
if (buf) {
/* add missing quotes */
buf[0] = '"';
memcpy(buf + 1, ins.s, ins.length);
buf[ins.length + 1] = '"';
attr_val.s = buf;
attr_val.length = ins.length + 2;
coap_add_attr(r,
coap_make_str_const("ins"),
&attr_val,
0);
coap_free(buf);
}
}
if (rt.s) {
buf = (unsigned char *)coap_malloc(rt.length + 2);
if (buf) {
/* add missing quotes */
buf[0] = '"';
memcpy(buf + 1, rt.s, rt.length);
buf[rt.length + 1] = '"';
attr_val.s = buf;
attr_val.length = rt.length + 2;
coap_add_attr(r,
coap_make_str_const("rt"),
&attr_val,
0);
coap_free(buf);
}
}
add_source_address(r, coap_session_get_addr_remote(session));
{
rd_t *rd;
rd = make_rd(request);
if (rd) {
coap_resource_set_userdata(r, rd);
} else {
/* FIXME: send error response and delete r */
}
}
coap_add_resource(coap_session_get_context(session), r);
/* create response */
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CREATED);
{ /* split path into segments and add Location-Path options */
unsigned char _b[LOCSIZE];
unsigned char *b = _b;
size_t buflen = sizeof(_b);
int nseg;
nseg = coap_split_path(loc, loc_size, b, &buflen);
while (nseg--) {
coap_add_option(response,
COAP_OPTION_LOCATION_PATH,
coap_opt_length(b),
coap_opt_value(b));
b += coap_opt_size(b);
}
}
coap_free(loc);
}
static void
init_resources(coap_context_t *ctx) {
coap_resource_t *r;
r = coap_resource_init(coap_make_str_const(RD_ROOT_STR), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_rd);
coap_register_request_handler(r, COAP_REQUEST_POST, hnd_post_rd);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("40"), 0);
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("\"core.rd\""), 0);
coap_add_attr(r, coap_make_str_const("ins"), coap_make_str_const("\"default\""), 0);
coap_add_resource(ctx, r);
coap_resource_release_userdata_handler(ctx, resource_rd_delete);
}
static void
usage( const char *program, const char *version) {
const char *p;
char buffer[72];
const char *lib_build = coap_package_build();
p = strrchr( program, '/' );
if ( p )
program = ++p;
fprintf( stderr, "%s v%s -- CoRE Resource Directory implementation\n"
"(c) 2011-2012,2019-2022 Olaf Bergmann <bergmann@tzi.org> and others\n\n"
"Build: %s\n"
"%s\n"
, program, version, lib_build,
coap_string_tls_version(buffer, sizeof(buffer)));
fprintf(stderr, "%s\n", coap_string_tls_support(buffer, sizeof(buffer)));
fprintf(stderr, "\n"
"Usage: %s [-g group] [-G group_if] [-p port] [-v num] [-A address]\n"
"\t [[-h hint] [-k key]]\n"
"\t [[-c certfile] [-C cafile] [-n] [-R trust_casfile]]\n"
"General Options\n"
"\t-g group\tJoin the given multicast group.\n"
"\t \t\tNote: DTLS over multicast is not currently supported\n"
"\t-G group_if\tUse this interface for listening for the multicast\n"
"\t \t\tgroup. This can be different from the implied interface\n"
"\t \t\tif the -A option is used\n"
"\t-p port\t\tListen on specified port\n"
"\t-v num \t\tVerbosity level (default 3, maximum is 9). Above 7,\n"
"\t \t\tthere is increased verbosity in GnuTLS and OpenSSL logging\n"
"\t-A address\tInterface address to bind to\n"
"PSK Options (if supported by underlying (D)TLS library)\n"
"\t-h hint\t\tIdentity Hint. Default is CoAP. Zero length is no hint\n"
"\t-k key \t\tPre-Shared Key. This argument requires (D)TLS with PSK\n"
"\t \t\tto be available. This cannot be empty if defined.\n"
"\t \t\tNote that both -c and -k need to be defined\n"
"\t \t\tfor both PSK and PKI to be concurrently supported\n"
"PKI Options (if supported by underlying (D)TLS library)\n"
"\t-c certfile\tPEM file containing both CERTIFICATE and PRIVATE KEY\n"
"\t \t\tThis argument requires (D)TLS with PKI to be available\n"
"\t-n \t\tDisable remote peer certificate checking. This gives\n"
"\t \t\tclients the ability to use PKI, but without any defined\n"
"\t \t\tcertificates\n"
"\t-C cafile\tPEM file that contains a list of one or\n"
"\t \t\tmore CAs that are to be passed to the client for the\n"
"\t \t\tclient to determine what client certificate to use.\n"
"\t \t\tNormally, this list of CAs would be the root CA and and\n"
"\t \t\tany intermediate CAs. Ideally the server certificate\n"
"\t \t\tshould be signed by the same CA so that mutual\n"
"\t \t\tauthentication can take place. The contents of cafile\n"
"\t \t\tare added to the trusted store of root CAs.\n"
"\t \t\tUsing the -C or -R options will will trigger the\n"
"\t \t\tvalidation of the client certificate unless overridden\n"
"\t \t\tby the -n option\n"
"\t-R trust_casfile\tPEM file containing the set of trusted root CAs\n"
"\t \t\tthat are to be used to validate the client certificate.\n"
"\t \t\tAlternatively, this can point to a directory containing\n"
"\t \t\ta set of CA PEM files.\n"
"\t \t\tUsing '-R trust_casfile' disables common CA mutual\n"
"\t \t\tauthentication which can only be done by using\n"
"\t \t\t'-C cafile'.\n"
"\t \t\tUsing the -C or -R options will will trigger the\n"
"\t \t\tvalidation of the client certificate unless overridden\n"
"\t \t\tby the -n option\n"
,
program);
}
static void
fill_keystore(coap_context_t *ctx) {
if (cert_file == NULL && key_defined == 0) {
if (coap_dtls_is_supported() || coap_tls_is_supported()) {
coap_log(LOG_DEBUG,
"(D)TLS not enabled as neither -k or -c options specified\n");
}
}
if (cert_file) {
coap_dtls_pki_t dtls_pki;
memset (&dtls_pki, 0, sizeof(dtls_pki));
dtls_pki.version = COAP_DTLS_PKI_SETUP_VERSION;
if (ca_file || root_ca_file) {
/*
* Add in additional certificate checking.
* This list of enabled can be tuned for the specific
* requirements - see 'man coap_encryption'.
*/
dtls_pki.verify_peer_cert = verify_peer_cert;
dtls_pki.check_common_ca = !root_ca_file;
dtls_pki.allow_self_signed = 1;
dtls_pki.allow_expired_certs = 1;
dtls_pki.cert_chain_validation = 1;
dtls_pki.cert_chain_verify_depth = 2;
dtls_pki.check_cert_revocation = 1;
dtls_pki.allow_no_crl = 1;
dtls_pki.allow_expired_crl = 1;
dtls_pki.validate_cn_call_back = NULL;
dtls_pki.cn_call_back_arg = NULL;
dtls_pki.validate_sni_call_back = NULL;
dtls_pki.sni_call_back_arg = NULL;
}
dtls_pki.pki_key.key_type = COAP_PKI_KEY_PEM;
dtls_pki.pki_key.key.pem.public_cert = cert_file;
dtls_pki.pki_key.key.pem.private_key = cert_file;
dtls_pki.pki_key.key.pem.ca_file = ca_file;
/* If general root CAs are defined */
if (root_ca_file) {
struct stat stbuf;
if ((stat(root_ca_file, &stbuf) == 0) && S_ISDIR(stbuf.st_mode)) {
coap_context_set_pki_root_cas(ctx, NULL, root_ca_file);
} else {
coap_context_set_pki_root_cas(ctx, root_ca_file, NULL);
}
}
coap_context_set_pki(ctx, &dtls_pki);
}
if (key_defined) {
coap_dtls_spsk_t dtls_psk;
memset (&dtls_psk, 0, sizeof(dtls_psk));
dtls_psk.version = COAP_DTLS_SPSK_SETUP_VERSION;
dtls_psk.validate_id_call_back = NULL;
dtls_psk.validate_sni_call_back = NULL;
dtls_psk.psk_info.hint.s = (const uint8_t *)hint;
dtls_psk.psk_info.hint.length = hint ? strlen(hint) : 0;
dtls_psk.psk_info.key.s = key;
dtls_psk.psk_info.key.length = key_length;
coap_context_set_psk2(ctx, &dtls_psk);
}
}
static coap_context_t *
get_context(const char *node, const char *port) {
coap_context_t *ctx = NULL;
int s;
struct addrinfo hints;
struct addrinfo *result, *rp;
ctx = coap_new_context(NULL);
if (!ctx) {
return NULL;
}
/* Need PSK set up before we set up (D)TLS endpoints */
fill_keystore(ctx);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
s = getaddrinfo(node, port, &hints, &result);
if ( s != 0 ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
coap_free_context(ctx);
return NULL;
}
/* iterate through results until success */
for (rp = result; rp != NULL; rp = rp->ai_next) {
coap_address_t addr, addrs;
coap_endpoint_t *ep_udp = NULL, *ep_dtls = NULL, *ep_tcp = NULL, *ep_tls = NULL;
if (rp->ai_addrlen <= (socklen_t)sizeof(addr.addr)) {
coap_address_init(&addr);
addr.size = (socklen_t)rp->ai_addrlen;
memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
addrs = addr;
if (addr.addr.sa.sa_family == AF_INET) {
uint16_t temp = ntohs(addr.addr.sin.sin_port) + 1;
addrs.addr.sin.sin_port = htons(temp);
} else if (addr.addr.sa.sa_family == AF_INET6) {
uint16_t temp = ntohs(addr.addr.sin6.sin6_port) + 1;
addrs.addr.sin6.sin6_port = htons(temp);
} else {
goto finish;
}
ep_udp = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP);
if (ep_udp) {
if (coap_dtls_is_supported() && (key_defined || cert_file)) {
ep_dtls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_DTLS);
if (!ep_dtls)
coap_log(LOG_CRIT, "cannot create DTLS endpoint\n");
}
} else {
coap_log(LOG_CRIT, "cannot create UDP endpoint\n");
continue;
}
ep_tcp = coap_new_endpoint(ctx, &addr, COAP_PROTO_TCP);
if (ep_tcp) {
if (coap_tls_is_supported() && (key_defined || cert_file)) {
ep_tls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_TLS);
if (!ep_tls)
coap_log(LOG_CRIT, "cannot create TLS endpoint\n");
}
} else {
coap_log(LOG_CRIT, "cannot create TCP endpoint\n");
}
if (ep_udp)
goto finish;
}
}
fprintf(stderr, "no context available for interface '%s'\n", node);
finish:
freeaddrinfo(result);
return ctx;
}
int
main(int argc, char **argv) {
coap_context_t *ctx;
int result;
char addr_str[NI_MAXHOST] = "::";
char port_str[NI_MAXSERV] = "5683";
char *group = NULL;
char *group_if = NULL;
int opt;
coap_log_t log_level = LOG_WARNING;
#ifndef _WIN32
struct sigaction sa;
#endif
while ((opt = getopt(argc, argv, "A:c:C:g:G:h:k:n:R:p:v:")) != -1) {
switch (opt) {
case 'A' :
strncpy(addr_str, optarg, NI_MAXHOST-1);
addr_str[NI_MAXHOST - 1] = '\0';
break;
case 'c' :
cert_file = optarg;
break;
case 'C' :
ca_file = optarg;
break;
case 'g' :
group = optarg;
break;
case 'G' :
group_if = optarg;
break;
case 'h' :
if (!optarg[0]) {
hint = NULL;
break;
}
hint = optarg;
break;
case 'k' :
key_length = cmdline_read_key(optarg, key, MAX_KEY);
if (key_length < 0) {
coap_log( LOG_CRIT, "Invalid Pre-Shared Key specified\n" );
break;
}
key_defined = 1;
break;
case 'n':
verify_peer_cert = 0;
break;
case 'R' :
root_ca_file = optarg;
break;
case 'p' :
strncpy(port_str, optarg, NI_MAXSERV-1);
port_str[NI_MAXSERV - 1] = '\0';
break;
case 'v' :
log_level = strtol(optarg, NULL, 10);
break;
default:
usage( argv[0], LIBCOAP_PACKAGE_VERSION );
exit( 1 );
}
}
coap_startup();
coap_dtls_set_log_level(log_level);
coap_set_log_level(log_level);
ctx = get_context(addr_str, port_str);
if (!ctx)
return -1;
if (group)
coap_join_mcast_group_intf(ctx, group, group_if);
init_resources(ctx);
#ifdef _WIN32
signal(SIGINT, handle_sigint);
#else
memset (&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = handle_sigint;
sa.sa_flags = 0;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
/* So we do not exit on a SIGPIPE */
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
#endif
while ( !quit ) {
result = coap_io_process( ctx, COAP_RESOURCE_CHECK_TIME * 1000 );
if ( result >= 0 ) {
/* coap_check_resource_list( ctx ); */
}
}
coap_free_context( ctx );
coap_cleanup();
return 0;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,67 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 * -*- */
/* coap_list.c -- CoAP list structures
*
* Copyright (C) 2010,2011,2015 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms of
* use.
*/
/*
* examples/coap_list.[ch] are DEPRECATED. You should be using
* struct coap_optlist_t instead with the following functions which are a part
* of libcoap.
*
* coap_new_optlist()
* coap_insert_optlist()
* coap_delete_optlist()
* coap_add_optlist_pdu()
*
* See 'man coap_pdu_setup' for further information.
*
* examples/coap_list.[ch] files will be removed in a future release
* They are left here to support building backward compatability of old versions
* of coap-client
*/
#include <stdio.h>
#include <string.h>
#include <coap3/coap.h>
int
coap_insert(coap_list_t **head, coap_list_t *node) {
if (!node) {
coap_log(LOG_WARNING, "cannot create option Proxy-Uri\n");
} else {
/* must append at the list end to avoid re-ordering of
* options during sort */
LL_APPEND((*head), node);
}
return node != NULL;
}
int
coap_delete(coap_list_t *node) {
if (node) {
coap_free(node);
}
return 1;
}
void
coap_delete_list(coap_list_t *queue) {
coap_list_t *elt, *tmp;
if (!queue)
return;
LL_FOREACH_SAFE(queue, elt, tmp) {
coap_delete(elt);
}
}
@@ -0,0 +1,52 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 * -*- */
/* coap_list.h -- CoAP list structures
*
* Copyright (C) 2010,2011,2015 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms of
* use.
*/
/*
* examples/coap_list.[ch] are DEPRECATED. You should be using
* struct coap_optlist_t instead with the following functions which are a part
* of libcoap.
*
* coap_new_optlist()
* coap_insert_optlist()
* coap_delete_optlist()
* coap_add_optlist_pdu()
*
* See 'man coap_pdu_setup' for further information.
*
* examples/coap_list.[ch] files will be removed in a future release
* They are left here to support building backward compatibility of old versions
* of coap-client
*/
#ifndef COAP_LIST_H_
#define COAP_LIST_H_
#include <coap3/utlist.h>
typedef struct coap_list_t {
struct coap_list_t *next;
char data[];
} coap_list_t;
/**
* Adds node to given queue, ordered by specified order function. Returns 1
* when insert was successful, 0 otherwise.
*/
int coap_insert(coap_list_t **queue, coap_list_t *node);
/* destroys specified node */
int coap_delete(coap_list_t *node);
/* removes all items from given queue and frees the allocated storage */
void coap_delete_list(coap_list_t *queue);
#endif /* COAP_LIST_H_ */
@@ -0,0 +1,7 @@
contiki-minimal-net.a
contiki-minimal-net.map
contiki/
obj_minimal-net/
server.minimal-net
symbols.c
symbols.h
@@ -0,0 +1,33 @@
########################################################################
# platform-specific options
ifeq ($(TARGET), econotag)
CONTIKI_WITH_RPL=0
CFLAGS += -DUIP_CONF_TCP=0 -DCOAP_MAX_BLOCK_SZX=1
endif
ifeq ($(TARGET), mbxxx)
CFLAGS += -DUIP_CONF_TCP=0 -DCOAP_MAX_BLOCK_SZX=1 -DHAVE_ASSERT_H -DHAVE_LIMITS_H
STM32W_CPUREV=CC
#STM32W_CPUREV=xB
endif
# usually, you should not need changing anything beyond this line
########################################################################
CONTIKI?=../../../..
ifneq ($(NODE_ADDR),)
CFLAGS += -DNODE_ADDR=$(NODE_ADDR)
endif
all: server
CFLAGS += -Os -ffunction-sections
LDFLAGS += -Wl,--gc-sections,--undefined=_reset_vector__,--undefined=InterruptVectors,--undefined=_copy_data_init__,--undefined=_clear_bss_init__,--undefined=_end_of_init__
CFLAGS += #-DSHORT_ERROR_RESPONSE -DNDEBUG
APPS += libcoap
include $(CONTIKI)/Makefile.include
@@ -0,0 +1,30 @@
Example of libcoap running on contiki
=====================================
To run the example, do
$ make
$ sudo ./server.minimal-net
(and in a second terminal)
$ sudo ip -6 a a aaaa::1/64 dev tap0
and query `coap://[aaaa::1000]/time?ticks` with any coap tool,
or query `coap://[aaaa::1000]/.well-known/core`
This will
* download contiki from the upstream git sources
* build the server application
* run the server application, creating a virtual network device tap0 (unless
that exists)
* configure your network interface to make the server accessible.
* return the appropriate response from the server to the client.
The server creates a resource for 'time' with a query 'ticks'. This is
reported for `.well-known/core`. The work flow for adding more resources does
not differ from regular libcoap usage. If you seem to run out of memory
creating the resources, tweak the number of pre-allocated resources
in `coap_config.h.contiki`.
@@ -0,0 +1,186 @@
/* coap-server.c -- Example CoAP server using Contiki and libcoap
*
* Copyright (C) 2011,2015,2018-2019 Olaf Bergmann <bergmann@tzi.org> and others
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*
*/
#include "coap_config.h"
#include "net/uip-debug.h"
#include <string.h>
#include "coap3/coap.h"
static coap_context_t *coap_context;
/* Where the resource to subscribe is hosted */
static coap_address_t dst;
/* The resource to observe */
static char resource[] = "/s/light";
/* when did the last notify arrive? (0 == never) */
static coap_tick_t last_seen = 0;
PROCESS(coap_server_process, "CoAP server process");
AUTOSTART_PROCESSES(&coap_server_process);
/*---------------------------------------------------------------------------*/
void
init_coap() {
coap_address_t listen_addr;
coap_address_init(&listen_addr);
listen_addr.port = UIP_HTONS(COAP_DEFAULT_PORT);
#ifdef WITH_CONTIKI
/* initialize uIP address for SLAAC */
uip_ip6addr(&listen_addr.addr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
uip_ds6_set_addr_iid(&listen_addr.addr, &uip_lladdr);
uip_ds6_addr_add(&listen_addr.addr, 0, ADDR_AUTOCONF);
uip_debug_lladdr_print(&uip_lladdr);
printf("\r\n");
uip_debug_ipaddr_print(&listen_addr.addr);
printf("\r\n");
#endif /* WITH_CONTIKI */
#ifdef WITH_CONTIKI
printf("tentative address: [%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]:%d\r\n",
listen_addr.addr.u8[0], listen_addr.addr.u8[1],
listen_addr.addr.u8[2], listen_addr.addr.u8[3],
listen_addr.addr.u8[4], listen_addr.addr.u8[5],
listen_addr.addr.u8[6], listen_addr.addr.u8[7],
listen_addr.addr.u8[8], listen_addr.addr.u8[9],
listen_addr.addr.u8[10], listen_addr.addr.u8[11],
listen_addr.addr.u8[12], listen_addr.addr.u8[13],
listen_addr.addr.u8[14], listen_addr.addr.u8[15] ,
uip_ntohs(listen_addr.port));
#endif
coap_context = coap_new_context(&listen_addr);
coap_set_log_level(LOG_DEBUG);
if (!coap_context)
coap_log(LOG_CRIT, "cannot create CoAP context\r\n");
}
void
message_handler(coap_context_t *ctx,
const coap_address_t *remote,
coap_pdu_t *sent,
coap_pdu_t *received,
const coap_tid_t id) {
/* send ACK if received message is confirmable (i.e. a separate response) */
coap_send_ack(ctx, remote, received);
coap_log(LOG_DEBUG, "** process incoming %d.%02d response:\n",
(received->hdr->code >> 5), received->hdr->code & 0x1F);
coap_show_pdu(LOG_WARNING, received);
coap_ticks(&last_seen);
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(coap_server_process, ev, data)
{
coap_pdu_t *request;
coap_uri_t uri;
PROCESS_BEGIN();
init_coap();
if (!coap_context) {
coap_log(LOG_EMERG, "cannot create context\n");
PROCESS_EXIT();
}
coap_register_response_handler(coap_context, message_handler);
/* setup subscription request */
coap_address_init(&dst);
dst.port = uip_htons(COAP_DEFAULT_PORT);
uip_ip6addr(&dst.addr, 0xaaaa, 0, 0, 0, 0x206, 0x98ff, 0xfe00, 0x232);
/* uip_ip6addr(&dst.addr, 0xfe80, 0, 0, 0, 0x206, 0x98ff, 0xfe00, 0x232); */
request = coap_pdu_init(COAP_MESSAGE_CON, COAP_REQUEST_GET,
coap_new_message_id(coap_context),
COAP_DEFAULT_MTU);
coap_split_uri((unsigned char *)resource, strlen(resource), &uri);
if (uri.port != COAP_DEFAULT_PORT) {
unsigned char portbuf[2];
coap_add_option(request, COAP_OPTION_URI_PORT,
coap_encode_var_safe(portbuf, sizeof(portbuf),
uri.port),
portbuf);
}
if (uri.path.length) {
#define BUFSIZE 20
unsigned char _buf[BUFSIZE];
unsigned char *buf = _buf;
size_t buflen;
int res;
buflen = BUFSIZE;
#undef BUFSIZE
res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
while (res--) {
coap_add_option(request, COAP_OPTION_URI_PATH,
coap_opt_length(buf), coap_opt_value(buf));
buf += coap_opt_size(buf);
}
}
coap_add_option(request, COAP_OPTION_OBSERVE, 0, NULL);
{
unsigned char buf[2];
coap_prng(buf, 2);
coap_add_option(request, COAP_OPTION_TOKEN, 2, buf);
}
if (COAP_INVALID_TID == coap_send_confirmed(coap_context, &dst, request))
coap_delete_pdu(request);
while(1) {
PROCESS_YIELD();
if(ev == tcpip_event) {
coap_io_do_io(coap_context); /* read received data */
coap_dispatch(coap_context); /* and dispatch PDUs from receivequeue */
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
@@ -0,0 +1,14 @@
interface tap0
{
AdvSendAdvert on;
MinRtrAdvInterval 3;
MaxRtrAdvInterval 20;
prefix aaaa::/64
{
AdvOnLink on;
AdvAutonomous on;
AdvRouterAddr on;
};
};
@@ -0,0 +1,222 @@
/* coap-server.c -- Example CoAP server using Contiki and libcoap
*
* Copyright (C) 2011 Olaf Bergmann <bergmann@tzi.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*
*/
#include "coap_config.h"
#define DEBUG DEBUG_PRINT
#include "net/ip/uip-debug.h"
#include "net/net-debug.h"
#include <string.h>
#include "coap3/coap.h"
static coap_context_t *coap_context;
static clock_time_t clock_offset;
/* changeable clock base (see handle_put_time()) */
static clock_time_t my_clock_base = 0;
static coap_resource_t *time_resource = NULL; /* just for testing */
PROCESS(coap_server_process, "CoAP server process");
AUTOSTART_PROCESSES(&coap_server_process);
/*---------------------------------------------------------------------------*/
void
init_coap_server(coap_context_t **ctx) {
coap_address_t listen_addr;
uip_ipaddr_t gw_addr;
assert(ctx);
coap_set_log_level(LOG_DEBUG);
coap_address_init(&listen_addr);
listen_addr.port = UIP_HTONS(COAP_DEFAULT_PORT);
uip_ip6addr(&listen_addr.addr, 0xaaaa, 0, 0, 0, 0, 0, 0, NODE_ADDR);
#ifndef CONTIKI_TARGET_MINIMAL_NET
uip_ds6_prefix_add(&listen_addr.addr, 64, 0, 0, 0, 0);
#endif /* not CONTIKI_TARGET_MINIMAL_NET */
uip_ds6_addr_add(&listen_addr.addr, 0, ADDR_MANUAL);
/* set default route to gateway aaaa::1 */
uip_ip6addr(&gw_addr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0x0001);
uip_ds6_defrt_add(&gw_addr, 0);
PRINTLLADDR(&uip_lladdr);
printf("\r\n");
PRINT6ADDR(&listen_addr.addr);
printf("\r\n");
*ctx = coap_new_context(&listen_addr);
if (!*ctx) {
coap_log(LOG_CRIT, "cannot create CoAP context\r\n");
}
}
/*---------------------------------------------------------------------------*/
#ifndef min
# define min(a,b) ((a) < (b) ? (a) : (b))
#endif
void
hnd_get_time(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query,
coap_pdu_t *response) {
unsigned char buf[40];
size_t len;
coap_tick_t now;
coap_tick_t t;
if (my_clock_base) {
/* calculate current time */
coap_ticks(&t);
now = my_clock_base + (t / COAP_TICKS_PER_SECOND);
if (query != NULL
&& coap_string_equal(query, coap_make_str_const("ticks"))) {
/* output ticks */
len = snprintf((char *)buf, sizeof(buf), "%u", (unsigned int)now);
} else { /* output human-readable time */
struct tm *tmp;
time_t tnow = now;
tmp = gmtime(&tnow);
if (!tmp) {
/* If 'tnow' is not valid */
coap_pdu_set_code(response, COAP_RESPONSE_CODE_NOT_FOUND);
return;
}
else {
len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp);
}
}
coap_add_data_blocked_response(request, response,
COAP_MEDIATYPE_TEXT_PLAIN, 1,
len,
buf);
}
else {
/* if my_clock_base was deleted, we pretend to have no such resource */
coap_pdu_set_code(response, COAP_RESPONSE_CODE_NOT_FOUND);
}
}
void
init_coap_resources(coap_context_t *ctx) {
coap_resource_t *r;
#if 0
r = coap_resource_init(NULL, 0, 0);
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_index);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"General Info\""), 0);
coap_add_resource(ctx, r);
#endif
/* store clock base to use in /time */
my_clock_base = clock_offset;
r = coap_resource_init(coap_make_str_const("time"), 0);
if (!r)
goto error;
coap_resource_set_get_observable(r, 1);
time_resource = r;
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time);
#if 0
coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time);
coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time);
#endif
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
/* coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"Internal Clock\""), 0); */
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("\"ticks\""), 0);
coap_add_attr(r, coap_make_str_const("if"), coap_make_str_const("\"clock\""), 0);
coap_add_resource(ctx, r);
#if 0
#ifndef WITHOUT_ASYNC
r = coap_resource_init(coap_make_str_const("async"), 0);
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_async);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_resource(ctx, r);
#endif /* WITHOUT_ASYNC */
#endif
return;
error:
coap_log(LOG_CRIT, "cannot create resource\n");
}
/* struct etimer notify_timer; */
struct etimer dirty_timer;
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(coap_server_process, ev, data)
{
PROCESS_BEGIN();
clock_offset = clock_time();
init_coap_server(&coap_context);
if (!coap_context) {
coap_log(LOG_EMERG, "cannot create context\n");
PROCESS_EXIT();
}
init_coap_resources(coap_context);
if (!coap_context) {
coap_log(LOG_EMERG, "cannot create context\n");
PROCESS_EXIT();
}
/* etimer_set(&notify_timer, 5 * CLOCK_SECOND); */
etimer_set(&dirty_timer, 30 * CLOCK_SECOND);
while(1) {
PROCESS_YIELD();
if(ev == tcpip_event) {
/* There is something to read on the endpoint */
coap_io_process(coap_context, COAP_IO_WAIT);
} else if (ev == PROCESS_EVENT_TIMER && etimer_expired(&dirty_timer)) {
coap_resource_notify_observers(time_resource, NULL);
etimer_reset(&dirty_timer);
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
@@ -0,0 +1,210 @@
#!/bin/bash
# test coap implementation for the ETSI CoAP Plugtest in March 2012
# with test cases described in Plugtests Guide First Draft V0.0.16
COAP_CLIENT=./coap-client
tcpdump=/usr/sbin/tcpdump
DEFAULTPORT=5683
CLIENTPORT=61701
# directory for logging
LOGDIR=logs
# set client's verbose level
callopts=" -v 5"
longtimeout=180
clienttimeout=$longtimeout
timeoutcmd=/usr/bin/timeout
#URIREGEX=.*\/.*
# resembles approximately an ip address
IPADDRREGEX="^[1-2]?[0-9]{1,2}\.[1-2]?[0-9]{1,2}\.[1-2]?[0-9]{1,2}\.[1-2]?[0-9]{1,2}"
# FIXME IPV6 address
IP6REGEX=".*:.*:.*"
# Testcase groups
CORE=( TD_COAP_CORE_01 TD_COAP_CORE_02 TD_COAP_CORE_03
TD_COAP_CORE_04 TD_COAP_CORE_05 TD_COAP_CORE_06 TD_COAP_CORE_07
TD_COAP_CORE_08 TD_COAP_CORE_09 TD_COAP_CORE_10 TD_COAP_CORE_11
TD_COAP_CORE_12 TD_COAP_CORE_13 TD_COAP_CORE_14 TD_COAP_CORE_15 )
LINK=( TD_COAP_LINK_01 TD_COAP_LINK_02 )
BLOCK=( TD_COAP_BLOCK_01 TD_COAP_BLOCK_02 TD_COAP_BLOCK_03 TD_COAP_BLOCK_04 )
OBS=( TD_COAP_OBS_01 TD_COAP_OBS_02 TD_COAP_OBS_03 TD_COAP_OBS_04 TD_COAP_OBS_05 )
testgroups=( CORE LINK BLOCK OBS )
# if no test cases are specified, we want to run all tests
testnumber=-1
group=''
source `dirname $0`/etsi_testcases.sh
function usage {
echo "Usage: `basename $0` [-n testnumber] [-g groupname] [-t timeout] [-P server_port] [-p client port] [-d logdir] [-v] -i interface server_address" 1>&2
echo "-n test case to be accomplished" 1>&2
echo "-g group to be tested" 1>&2
echo "-t time in seconds until timout for single test" 1>&2
echo "-i interface to use for tcpdump" 1>&2
echo "-P port of server" 1>&2
echo "-p port client listens on" 1>&2
echo "-d directory for logfiles" 1>&2
echo "-v verbose level" 1>&2
}
function run_test {
tn=$1
clientopts=''
if [ -z $1 ]; then
echo "missing argument for run_test"
exit 1
fi
echo -e "running test: $tn"
if [ $(type -t $tn) ] ; then
$tn $tn
echo
else
echo "not implemented"
echo
fi
}
while getopts "n:g:t:i:P:p:d:v" OPTION;
do
# A missing argument for an option leads getopts to take the next
# option as the parameter. We want to prevent that.
case $OPTARG in
-*) echo "Missing argument for option \"-$OPTION\"."
echo $USAGE
exit 1
;;
esac
case $OPTION in
n) # number of test case
testnumber=$((OPTARG-1))
;;
g) # name of test group
# is there a group with that name?
for i in "${testgroups[@]}"
do
# group doesn't have to be case sensitive
tmpgroup=$(echo $OPTARG | tr '[:lower:]' '[:upper:]')
if [ $i == $tmpgroup ] ; then
group=$tmpgroup
break
fi
done
if [ -z $group ] ; then
echo "No such group:" $OPTARG". Available groups are: ${testgroups[@]}"
exit 1
fi
;;
t)
# add timeout to client parameters
clienttimeout=$((OPTARG))
callopts="$callopts -B $clienttimeout"
;;
i)
# interface tcpdump listens on
INTERFACE=$OPTARG
;;
P)
# port the server listens on
SERVERPORT=$((OPTARG))
;;
p)
# port the client listens on
CLIENTPORT=$((OPTARG))
;;
d)
# directory tcpdump writes the logfiles into
LOGDIR=$OPTARG
;;
v)
verbose=1
;;
?)
# any other option is invalid
echo -e $USAGE 1>&2
exit 1
;;
esac
done
# catch last argument: server address
ARGS=$(($#+1))
SERVERADDRESS=${@: -1}
if [[ ! $((ARGS-OPTIND)) -eq 1 ]]; then
echo -e "\nno server address specified"
usage
exit 1
fi
# if no port number was specified by user, the server address for the
# coap-client is $SERVERADDRESS
if [ -z $SERVERPORT ]; then
SERVERPORT=$DEFAULTPORT
if [[ $SERVERADDRESS =~ $IP6REGEX ]]; then
SERVERTUP=\[$SERVERADDRESS\]
else
SERVERTUP=$SERVERADDRESS
fi
else
if [[ $SERVERADDRESS =~ $IP6REGEX ]]; then
SERVERTUP=\[$SERVERADDRESS\]:$SERVERPORT
else
SERVERTUP=$SERVERADDRESS:$SERVERPORT
fi
fi
# create directory for logging, if it's not already there
if [[ ! -e $LOGDIR ]]; then
mkdir -p $LOGDIR
if [ $? ]; then
echo created directory \""$LOGDIR"\" for logging
fi
fi
# the interface for tcpdump is mandatory
if [ -z $INTERFACE ]; then
echo -e "\nno interface given"
exit 1
fi
# determine which tests to run
if [ -n "$group" ] ; then
echo group: $group
if [[ ! $testnumber -eq -1 ]] ; then
groupsize=$(eval "echo \${#$(echo $group)[@]}")
# is there a testcase with number $testnumber in group $group
if [ $testnumber -ge $groupsize -o $testnumber -lt 0 ] ; then
echo "No such testcase number: $OPTARG. Test cases numbers are 1 to" $groupsize
exit 1
else
# run test with group $group and number $testnumber
run_test $(eval "echo \${$(echo $group)[$testnumber]}")
fi
else
# if no testnumber was specified, we want to run all tests in that group
for i in $(eval "echo \${$(echo $group)[@]}") ; do
run_test $i
done
fi
else
# run all tests of all groups
for j in ${testgroups[@]} ; do
echo "group: $j"
for k in $(eval "echo \${$(echo $j)[@]}") ; do
run_test $k
done
done
fi
@@ -0,0 +1,633 @@
/* CoAP server for first ETSI CoAP plugtest, March 2012
*
* Copyright (C) 2012--2013 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <signal.h>
#include <coap3/coap.h>
#define COAP_RESOURCE_CHECK_TIME_SEC 1
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
/* temporary storage for dynamic resource representations */
static int quit = 0;
#define COAP_OPT_BLOCK_SZX_MAX 6 /**< allowed maximum for block szx value */
#define REQUIRE_ETAG 0x01 /* flag for coap_payload_t: require ETag option */
typedef struct {
unsigned int flags; /* some flags to control behavior */
size_t max_data; /* maximum size allocated for @p data */
uint16_t media_type; /* media type for this object */
size_t length; /* length of data */
unsigned char data[]; /* the actual contents */
} coap_payload_t;
/* SIGINT handler: set quit to 1 for graceful termination */
static void
handle_sigint(int signum COAP_UNUSED) {
quit = 1;
}
#define INDEX "libcoap server for ETSI CoAP Plugtest, March 2012, Paris\n" \
"Copyright (C) 2012 Olaf Bergmann <bergmann@tzi.org>\n\n"
static coap_payload_t *
coap_new_payload(size_t size) {
coap_payload_t *p;
p = (coap_payload_t *)coap_malloc(sizeof(coap_payload_t) + size);
if (p) {
memset(p, 0, sizeof(coap_payload_t));
p->max_data = size;
}
return p;
}
static inline coap_payload_t *
coap_find_payload(coap_resource_t *resource) {
return coap_resource_get_userdata(resource);
}
static void
coap_add_payload(coap_resource_t *resource, coap_payload_t *payload){
assert(payload);
coap_resource_set_userdata(resource, payload);
}
static inline void
coap_delete_payload(coap_resource_t *resource) {
coap_free(coap_resource_get_userdata(resource));
coap_resource_set_userdata(resource, NULL);
}
static void
coap_free_userdata(void *data) {
coap_free(data);
}
#if 0
static void
hnd_get_index(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
coap_pdu_t *request COAP_UNUSED,
coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
unsigned char buf[3];
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_TEXT_PLAIN),
buf);
coap_add_option(response, COAP_OPTION_MAXAGE,
coap_encode_var_safe(buf, sizeof(buf), 0x2ffff), buf);
coap_add_data(response, strlen(INDEX), (const uint8_t *)INDEX);
}
#endif
static void
hnd_get_resource(coap_resource_t *resource,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_payload_t *test_payload;
test_payload = coap_find_payload(resource);
if (!test_payload) {
coap_pdu_set_code(response, COAP_RESPONSE_CODE_INTERNAL_ERROR);
return;
}
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
coap_add_data_blocked_response(request, response,
test_payload->media_type, -1,
test_payload->length,
test_payload->data);
return;
}
/* DELETE handler for dynamic resources created by POST /test */
static void
hnd_delete_resource(coap_resource_t *resource,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_payload_t *payload;
payload = coap_find_payload(resource);
if (payload)
coap_delete_payload(resource);
coap_delete_resource(NULL, resource);
coap_pdu_set_code(response, COAP_RESPONSE_CODE_DELETED);
}
static void
hnd_post_test(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
coap_payload_t *test_payload;
size_t len;
coap_str_const_t *uri;
const uint8_t *data;
#define BUFSIZE 20
int res;
unsigned char _buf[BUFSIZE];
unsigned char *buf = _buf;
size_t buflen = BUFSIZE;
coap_get_data(request, &len, &data);
/* allocate storage for resource and to hold URI */
test_payload = coap_new_payload(len);
snprintf((char *)buf, buflen, "test/%p", (void *)test_payload);
uri = coap_new_str_const(buf, strlen((char *)buf));
if (!(test_payload && uri)) {
coap_log(LOG_CRIT, "cannot allocate new resource under /test");
coap_pdu_set_code(response, COAP_RESPONSE_CODE_INTERNAL_ERROR);
coap_free(test_payload);
coap_free(uri);
} else {
coap_resource_t *r;
test_payload->length = len;
memcpy(test_payload->data, data, len);
r = coap_resource_init(uri, COAP_RESOURCE_FLAGS_RELEASE_URI);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_resource);
coap_register_request_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource);
/* set media_type if available */
option = coap_check_option(request, COAP_OPTION_CONTENT_TYPE, &opt_iter);
if (option) {
test_payload->media_type =
coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
}
coap_add_resource(coap_session_get_context(session), r);
coap_add_payload(r, test_payload);
/* add Location-Path */
res = coap_split_path(uri->s, uri->length, buf, &buflen);
while (res--) {
coap_add_option(response, COAP_OPTION_LOCATION_PATH,
coap_opt_length(buf), coap_opt_value(buf));
buf += coap_opt_size(buf);
}
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CREATED);
}
}
static void
hnd_put_test(coap_resource_t *resource,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
coap_payload_t *payload;
size_t len;
const uint8_t *data;
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CHANGED);
coap_get_data(request, &len, &data);
payload = coap_find_payload(resource);
if (payload && payload->max_data < len) { /* need more storage */
coap_delete_payload(resource);
payload = NULL;
/* bug: when subsequent coap_new_payload() fails, our old contents
is gone */
}
if (!payload) { /* create new payload */
payload = coap_new_payload(len);
if (!payload)
goto error;
coap_add_payload(resource, payload);
}
payload->length = len;
memcpy(payload->data, data, len);
option = coap_check_option(request, COAP_OPTION_CONTENT_TYPE, &opt_iter);
if (option) {
/* set media type given in request */
payload->media_type =
coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
} else {
/* set default value */
payload->media_type = COAP_MEDIATYPE_TEXT_PLAIN;
}
/* FIXME: need to change attribute ct of resource.
To do so, we need dynamic management of the attribute value
*/
return;
error:
coap_log(LOG_WARNING, "cannot modify resource\n");
coap_pdu_set_code(response, COAP_RESPONSE_CODE_INTERNAL_ERROR);
}
static void
hnd_delete_test(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request COAP_UNUSED,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
/* the ETSI validation tool does not like empty resources... */
#if 0
coap_payload_t *payload;
payload = coap_find_payload(resource);
if (payload)
payload->length = 0;
#endif
coap_pdu_set_code(response, COAP_RESPONSE_CODE_DELETED);
}
static void
hnd_get_query(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session COAP_UNUSED,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_opt_iterator_t opt_iter;
coap_opt_filter_t f;
coap_opt_t *q;
size_t len, L;
unsigned char buf[70];
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_TEXT_PLAIN),
buf);
coap_option_filter_clear(&f);
coap_option_filter_set(&f, COAP_OPTION_URI_QUERY);
coap_option_iterator_init(request, &opt_iter, &f);
len = 0;
while ((len < sizeof(buf)) && (q = coap_option_next(&opt_iter))) {
L = min(sizeof(buf) - len, 11);
memcpy(buf + len, "Uri-Query: ", L);
len += L;
L = min(sizeof(buf) - len, coap_opt_length(q));
memcpy(buf + len, coap_opt_value(q), L);
len += L;
if (len < sizeof(buf))
buf[len++] = '\n';
}
coap_add_data(response, len, buf);
}
/* handler for TD_COAP_CORE_16 */
static void
hnd_get_separate(coap_resource_t *resource COAP_UNUSED,
coap_session_t *session,
const coap_pdu_t *request,
const coap_string_t *query COAP_UNUSED,
coap_pdu_t *response) {
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
coap_opt_filter_t f;
unsigned long delay = 5;
if (request) {
coap_async_t *async;
coap_bin_const_t token = coap_pdu_get_token(request);
async = coap_find_async(session, token);
if (!async) {
/* Set up an async request to trigger delay in the future */
/* search for option delay in query list */
coap_option_filter_clear(&f);
coap_option_filter_set(&f, COAP_OPTION_URI_QUERY);
coap_option_iterator_init(request, &opt_iter, &f);
while ((option = coap_option_next(&opt_iter))) {
if (strncmp("delay=", (const char *)coap_opt_value(option), 6) == 0) {
unsigned int i;
unsigned long d = 0;
for (i = 6; i < coap_opt_length(option); ++i)
d = d * 10 + coap_opt_value(option)[i] - '0';
/* don't allow delay to be less than COAP_RESOURCE_CHECK_TIME*/
delay = d < COAP_RESOURCE_CHECK_TIME_SEC
? COAP_RESOURCE_CHECK_TIME_SEC
: d;
coap_log(LOG_DEBUG, "set delay to %lu\n", delay);
break;
}
}
async = coap_register_async(session,
request,
COAP_TICKS_PER_SECOND * delay);
if (async == NULL) {
coap_pdu_set_code(response, COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE);
return;
}
/* Not setting response code will cause empty ACK to be sent
if Confirmable */
return;
}
}
/* no request (observe) or async set up, so this is the delayed request */
coap_add_data(response, 4, (const uint8_t *)"done");
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
/* async is automatically removed by libcoap */
}
static coap_payload_t *
make_large(const char *filename) {
coap_payload_t *payload;
FILE *inputfile = NULL;
struct stat statbuf;
if (!filename)
return NULL;
/* read from specified input file */
if (stat(filename, &statbuf) < 0) {
coap_log(LOG_WARNING, "cannot stat file %s\n", filename);
return NULL;
}
payload = coap_new_payload(statbuf.st_size);
if (!payload)
return NULL;
inputfile = fopen(filename, "r");
if ( !inputfile ) {
coap_log(LOG_WARNING, "cannot read file %s\n", filename);
coap_free(payload);
return NULL;
}
payload->length = fread(payload->data, 1, statbuf.st_size, inputfile);
payload->media_type = 41;
fclose(inputfile);
return payload;
}
static void
init_resources(coap_context_t *ctx) {
coap_resource_t *r;
coap_payload_t *test_payload;
test_payload = coap_new_payload(200);
if (!test_payload)
coap_log(LOG_CRIT, "cannot allocate resource /test");
else {
test_payload->length = 13;
memcpy(test_payload->data, "put data here", test_payload->length);
/* test_payload->media_type is 0 anyway */
r = coap_resource_init(coap_make_str_const("test"), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_resource);
coap_register_request_handler(r, COAP_REQUEST_POST, hnd_post_test);
coap_register_request_handler(r, COAP_REQUEST_PUT, hnd_put_test);
coap_register_request_handler(r, COAP_REQUEST_DELETE, hnd_delete_test);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("test"), 0);
coap_add_attr(r, coap_make_str_const("if"), coap_make_str_const("core#b"), 0);
#if 0
coap_add_attr(r, coap_make_str_const("obs"), NULL, 0);
#endif
coap_add_resource(ctx, r);
coap_resource_release_userdata_handler(ctx, coap_free_userdata);
coap_add_payload(r, test_payload);
}
/* TD_COAP_BLOCK_01
* TD_COAP_BLOCK_02 */
test_payload = make_large("etsi_iot_01_largedata.txt");
if (!test_payload)
coap_log(LOG_CRIT, "cannot allocate resource /large\n");
else {
r = coap_resource_init(coap_make_str_const("large"), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_resource);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("41"), 0);
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("large"), 0);
coap_add_resource(ctx, r);
test_payload->flags |= REQUIRE_ETAG;
coap_add_payload(r, test_payload);
}
/* For TD_COAP_CORE_12 */
test_payload = coap_new_payload(20);
if (!test_payload)
coap_log(LOG_CRIT, "cannot allocate resource /seg1/seg2/seg3\n");
else {
test_payload->length = 10;
memcpy(test_payload->data, "segsegseg!", test_payload->length);
/* test_payload->media_type is 0 anyway */
r = coap_resource_init(coap_make_str_const("seg1/seg2/seg3"), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_resource);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_resource(ctx, r);
coap_add_payload(r, test_payload);
}
/* For TD_COAP_CORE_13 */
r = coap_resource_init(coap_make_str_const("query"), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_query);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_resource(ctx, r);
/* For TD_COAP_CORE_16 */
r = coap_resource_init(coap_make_str_const("separate"), 0);
coap_register_request_handler(r, COAP_REQUEST_GET, hnd_get_separate);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("seperate"), 0);
coap_add_resource(ctx, r);
}
static void
usage( const char *program, const char *version) {
const char *p;
p = strrchr( program, '/' );
if ( p )
program = ++p;
fprintf( stderr, "%s v%s -- ETSI CoAP plugtest server\n"
"(c) 2012 Olaf Bergmann <bergmann@tzi.org>\n\n"
"usage: %s [-A address] [-p port]\n\n"
"\t-A address\tinterface address to bind to\n"
"\t-p port\t\tlisten on specified port\n"
"\t-v num\t\tverbosity level (default: 3)\n",
program, version, program );
}
static coap_context_t *
get_context(const char *node, const char *port) {
coap_context_t *ctx = NULL;
int s;
struct addrinfo hints;
struct addrinfo *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
s = getaddrinfo(node, port, &hints, &result);
if ( s != 0 ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return NULL;
}
/* iterate through results until success */
for (rp = result; rp != NULL; rp = rp->ai_next) {
coap_address_t addr;
if (rp->ai_addrlen <= (socklen_t)sizeof(addr.addr)) {
coap_address_init(&addr);
addr.size = rp->ai_addrlen;
memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
ctx = coap_new_context(&addr);
if (ctx) {
/* TODO: output address:port for successful binding */
goto finish;
}
}
}
fprintf(stderr, "no context available for interface '%s'\n", node);
finish:
freeaddrinfo(result);
return ctx;
}
int
main(int argc, char **argv) {
coap_context_t *ctx;
int result;
char addr_str[NI_MAXHOST] = "::";
char port_str[NI_MAXSERV] = "5683";
int opt;
coap_log_t log_level = LOG_WARNING;
struct sigaction sa;
while ((opt = getopt(argc, argv, "A:p:v:")) != -1) {
switch (opt) {
case 'A' :
strncpy(addr_str, optarg, NI_MAXHOST-1);
addr_str[NI_MAXHOST - 1] = '\0';
break;
case 'p' :
strncpy(port_str, optarg, NI_MAXSERV-1);
port_str[NI_MAXSERV - 1] = '\0';
break;
case 'v' :
log_level = strtol(optarg, NULL, 10);
break;
default:
usage( argv[0], LIBCOAP_PACKAGE_VERSION );
exit( 1 );
}
}
coap_set_log_level(log_level);
ctx = get_context(addr_str, port_str);
if (!ctx)
return -1;
init_resources(ctx);
memset (&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = handle_sigint;
sa.sa_flags = 0;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
/* So we do not exit on a SIGPIPE */
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
while ( !quit ) {
result = coap_io_process( ctx, COAP_RESOURCE_CHECK_TIME * 1000 );
if ( result >= 0 ) {
/* coap_check_resource_list( ctx ); */
}
}
coap_free_context( ctx );
coap_cleanup();
return 0;
}
@@ -0,0 +1,7 @@
<large>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet sapien ac leo bibendum suscipit at sed ipsum. Aliquam in mauris nec felis dictum lobortis a et erat. Pellentesque tempus urna vulputate purus faucibus ac pretium massa volutpat. Maecenas at tellus neque, quis elementum ante. Morbi molestie, elit placerat rhoncus faucibus, urna nunc accumsan diam, vel porta eros sem vel augue. Proin metus dolor, tristique a accumsan eget, suscipit vel ante. Suspendisse feugiat, nisl non viverra convallis, ante nibh congue lectus, sodales ultrices turpis massa sed elit.
Praesent posuere laoreet nulla eu accumsan. Vestibulum consequat molestie erat, ut laoreet arcu mattis non. Maecenas viverra elementum mauris, vitae pretium elit ultrices sit amet. Sed sit amet elit sit amet dui imperdiet consequat. Donec viverra leo mollis lorem varius lacinia mollis nulla posuere. Phasellus felis odio, tempor et sodales non, facilisis fermentum eros. Duis dignissim massa at ante euismod vel laoreet mi tristique. Nulla libero dolor, pretium vitae vulputate eget, luctus at sapien. Praesent aliquam nisl ut urna pretium eu rhoncus ipsum eleifend. Sed lobortis vestibulum est eu eleifend. Sed vitae luctus erat. Sed vel dolor quam, tempor venenatis dolor.
Vivamus a est a neque condimentum fermentum sed quis dui. Maecenas rhoncus imperdiet tortor, vitae viverra lectus ornare vulputate. Nam congue pulvinar faucibus. Vivamus id mauris at tortor porta volutpat. Donec non velit a tellus placerat iaculis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse at felis ligula, vel euismod velit. Aliquam in odio urna.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac risus ipsum. Donec vel purus risus, eu molestie nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse consequat libero eu augue ornare volutpat mollis sed dui. Ut sed. </large>
@@ -0,0 +1,765 @@
#!/bin/bash
function start_tcpdump {
testfunc=$1
logfile=$LOGDIR/"$testfunc"_$(date +%s).dump
tcpdumpcmd="$tcpdump -i $INTERFACE host $SERVERADDRESS and (udp port $SERVERPORT or icmp) -s0 -n -w $logfile"
if [ $verbose ]; then
echo "$tcpdumpcmd"
$tcpdumpcmd&
else
$tcpdumpcmd 2>/dev/null&
fi
tcpdumppid=$!
# wait until tcpdump is ready to write
for t in {0..20} ; do
if [ ! -e $logfile ] ; then
sleep 0.1
else
sleep 1
if [ $verbose ]; then
echo "tcpdump started"
fi
break
fi
done
}
function kill_tcpdump {
kill $tcpdumppid 2>/dev/null || ERROR=1
if [ $ERROR ]; then
echo "tcpdump failed."
exit 1
fi
}
function start_coap_test {
if [ -z $1 ]; then
echo "missing argument for start_coap_test"
exit 1
fi
start_tcpdump $1
if [ $verbose ]; then
echo "client command: $COAP_CLIENT $clientopts $testaddress"
fi
echo -e "\nOutput of client:"
# for OBS
if [[ ! -z $2 ]]; then
testfifo=/tmp/tmpfifo$(date +%s)
mkfifo $testfifo
$COAP_CLIENT $clientopts "$testaddress" &> $testfifo &
clientpid=$!
($timeoutcmd $clienttimeout cat $testfifo | if read -n 1 char; then echo "output: $char" ; fi) 2>/dev/null
# when client has written an output to fifo, kill client
kill $clientpid
rm $testfifo
if [[ $2 == "wait" ]] ; then
echo "Client killed. Waiting.."
sleep $longtimeout
fi
else
$COAP_CLIENT $clientopts "$testaddress"
fi
kill_tcpdump
}
##
# Perform GET (CON mode) on resource /test
#
# pre: resource /test exists and can handle GET with arbitrary payload
#
# client sends GET request with Type=0(CON) and Code=1(GET)
#
# check if sent request contains Type value indicating 0 and Code
# value indicating 1
#
# check if server sends response containing Code = 69(2.05 Content),
# the same Message ID as that of previous request, content type option
#
# verify that server displays received information
#
function TD_COAP_CORE_01 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/test
echo "perform GET (CON mode) on resource $testaddress"
start_coap_test $1
}
##
# Perform POST transaction (CON mode) on resource /test: create
# resource /test
#
# pre: resource /test doesn't exist but can be created on /test
#
# client sends POST with Type=0(CON), Code=2(POST), arbitrary payload,
# Content type option
#
# check: client sends request containing Type value indicating 0 and
# Code value indicating 2
#
# verify: Server displays received information
#
# check: server sends response containing Code=69(2.01 Created), same
# message ID as that of the previous request, Content type option
#
# verify: client displays received information
#
function TD_COAP_CORE_02 {
# -t 0: content type text/plain
clientopts="$callopts -m post -t 0 -e sometext"
testaddress=coap://$SERVERTUP/test
echo "perform POST (CON) on resource $testaddress"
start_coap_test $1
}
##
# Perform PUT transaction (CON mode) on resource /test
#
# pre: resource /test exists which can handle PUT
#
# Client sends a PUT request with Type=0(CON), Code=3(PUT), arbitrary
# payload, content type option
#
# check: sent request contains Type value indicating 0 and Code value
# indicating 3
#
# verify: server displays received information
#
# check: Server sends response containing Code=68(2.04 Changed), same
# Message ID as that of the previous request
#
# verify: client displays received response
#
function TD_COAP_CORE_03 {
clientopts="$callopts -m put -t 0 -e sometext"
testaddress=coap://$SERVERTUP/test
echo "perform PUT (CON) on resource $testaddress"
start_coap_test $1
}
##
# Perform DELETE transaction (CON mode) on resource /test
#
# pre: resource /test exists which can handle DELETE
#
# Client sends a DELETE request with Type=0(CON), Code=4(DELETE)
#
# check: sent request contains Type value indicating 0 and Code value
# indicating 4
#
# check: Server sends response containing Code=66(2.02 Deleted), same
# Message ID as that of the previous request
#
# verify: client displays received response
#
function TD_COAP_CORE_04 {
clientopts="$callopts -m delete"
testaddress=coap://$SERVERTUP/test
echo "perform DELETE (CON) on resource $testaddress"
start_coap_test $1
}
##
# Perform GET transaction (NON mode) on resource /test
#
# pre: resource /test exits which can handle GET
#
# Client sends a GET request with Type=1(NON), Code=1(GET)
#
# check: sent request contains Type value indicating 1 and Code value
# indicating 1
#
# check: Server sends response containing Type=1(NON), Code=69(2.05
# Content), content type option
#
# verify: client displays received response
#
function TD_COAP_CORE_05 {
# -N: send non-confirmable message
clientopts="$callopts -m get -N"
testaddress=coap://$SERVERTUP/test
echo "perform GET (NON mode) on resource $testaddress"
start_coap_test $1
}
##
# Perform POST transaction (NON mode), create resource on /test
#
# pre: resource on /test doesn't exist but can be created
#
# Client sends a POST request with Type=1(NON), Code=2(POST),
# arbitrary payload, content type option
#
# check: sent request contains Type value indicating 1 and Code value
# indicating 2
#
# verify: Server displays the received information
#
# check: Server sends response containing Type=1(NON), Code=65(2.01
# Created)
#
# verify: client displays received response
#
function TD_COAP_CORE_06 {
clientopts="$callopts -m post -t 0 -e sometext -N"
testaddress=coap://$SERVERTUP/test
echo "perform POST (NON) on resource $testaddress"
start_coap_test $1
}
##
# Perform PUT transaction (NON mode) on resource /test
#
# pre: /test exists and can handle PUT
#
# Client sends a PUT request with Type=1(NON), Code=3(PUT),
# arbitrary payload, content type option
#
# check: sent request contains Type value indicating 1 and Code value
# indicating 3
#
# verify: Server displays the received information
#
# check: Server sends response containing Type=1(NON), Code=68(2.04
# Changed)
#
# verify: client displays received response
#
function TD_COAP_CORE_07 {
clientopts="$callopts -m put -t 0 -e sometext -N"
testaddress=coap://$SERVERTUP/test
echo "perform PUT (NON) on resource $testaddress"
start_coap_test $1
}
##
# Perform DELETE transaction (NON mode) on resource /test
#
# pre: /test exists and can handle DELETE
#
# Client sends a DELETE request with Type=1(NON), Code=4(DELETE)
#
# check: sent request contains Type value indicating 1 and Code value
# indicating 4
#
# check: Server sends response containing Type=1(NON), Code=66(2.02
# Deleted)
#
# verify: client displays received response
#
function TD_COAP_CORE_08 {
clientopts="$callopts -m delete -N"
testaddress=coap://$SERVERTUP/test
echo "perform DELETE (NON) on resource $testaddress"
start_coap_test $1
}
##
# Perform GET transaction with a separate response on resource /separate
#
# pre: resource /separate exists which cannot be served immediately and which
# cannot be acknowledged in a piggy-backed way
#
# Client sends a confirmable GET request to server's resource
#
# check: sent request contains Type=0(CON), Code=1(GET), client
# generated Message ID
#
# check: Server sends response containing Type=2(ACK), message ID same
# as the request, empty Payload
#
# check: Server sends response containing Type=0(CON), Code=69(2.05
# content), Payload=Content of the requested resource, Content type option
#
# check: Client sends response containing Type=2(ACK), message ID same
# as the response, empty Payload
#
# verify: client displays received response
#
function TD_COAP_CORE_09 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/separate
echo "perform GET (CON) on resource $testaddress which cannot be served immediately"
start_coap_test $1
}
##
# Perform GET transaction with Token on resource /test
#
# pre: resource /test exists which can handle GET requests
#
# Client sends a confirmable GET request to server's resource
# including Token option
#
# check: sent request contains Type=0(CON) and Code=1(GET), client
# generated Token value, length of the token which should be between 1
# to 8 B, Option Type=Token
#
# check: Server sends response containing Code=69(2.05 content),
# length of the token should be between 1 to 8 B, Token value same as
# the requested, Payload=Content of the requested resource, Content
# type option
#
# verify: client displays received response
#
function TD_COAP_CORE_10 {
clientopts="$callopts -m get -T sometok"
testaddress=coap://$SERVERTUP/test
echo "perform GET (CON) on resource $testaddress with Token"
start_coap_test $1
}
##
# Perform GET transaction without Token on resource /test
#
# pre: resource /test exists which can handle GET requests
#
# Client sends a confirmable GET request to server's resource
# not containing Token option
#
# check: sent request contains Type=0(CON) and Code=1(GET), no Token
# option
#
# check: Server sends response containing Code=69(2.05 content), no
# Token option, Payload=Content of the requested resource, Content
# type option
#
# verify: client displays received response
#
function TD_COAP_CORE_11 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/test
echo "perform GET (CON mode) without Token on resource $testaddress"
start_coap_test $1
}
##
# Perform GET transaction to resource /seg1/seg2/seg3
#
# pre: resource /seg1/seg2/seg3 exists on server
#
# Client sends a confirmable GET request to server's resource
#
# check: sent request contains Type=0(CON) and Code=1(GET), Option
# type=URI-Path (one for each path segment)
#
# check: Server sends response containing Code=69(2.05 content),
# Payload=Content of the requested resource, Content type option
#
# verify: client displays received response
#
function TD_COAP_CORE_12 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/seg1/seg2/seg3
echo "perform GET (CON mode) on resource $testaddress"
start_coap_test $1
}
##
# Perform GET transaction to resource /query
#
# pre: resource /query exists on server
#
# Client sends a confirmable GET request with three Query parameters
# (e.g. ?first=1&second=2&third=3) to server's resource
#
# check: sent request contains Type=0(CON) and Code=1(GET), Option
# type=URI-Query (More than one query parameter)
#
# check: Server sends response containing Type=0/2(Con/ACK),
# Code=69(2.05 content), Payload=Content of the requested resource,
# Content type option
#
# verify: client displays received response
#
function TD_COAP_CORE_13 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/query
query="?first=1&second=2&third=3"
echo -e "perform GET (CON mode) on resource $testaddress with query $query"
testaddress=$testaddress$query
start_coap_test $1
}
##
# Perform GET transaction to resource /test in lossy context
#
# pre: gateway is introduced and configured to produce packet loss,
# resource /test exists on server
#
# Configuration=CoAP_CFG_02
#
# observe: One dropped request, one dropped request ACK, one dropped
# response, one dropped response ACK and its retransmission, test
# sequence should be executed several times
#
# Client sends a confirmable GET request to server's resource
#
# check: sent request contains Type=0(CON) and Code=1(GET), Client
# generated Message ID
#
# check: Server sends response containing Type=2(ACK), Code=69(2.05
# content), Payload=Content of the requested resource, Content type
# option
#
# verify: client displays received response
#
function TD_COAP_CORE_14 {
clientopts="$callopts -m get"
#FIXME: address for lossy context?
testaddress=coap://$SERVERTUP/test
echo "perform GET (CON mode) on resource $testaddress in lossy context"
start_coap_test $1
}
##
# Perform GET transaction to resource /separate in lossy context
#
# pre: gateway is introduced and configured to produce packet loss,
# resource /separate exists which cannot be served immediately and
# which cannot be acknowledged in a piggy-backed way
#
# Configuration=CoAP_CFG_02
#
# observe: One dropped request, one dropped request ACK, one dropped
# response, one dropped response ACK and its retransmission, test
# sequence should be executed several times
#
# Client sends a confirmable GET request to server's resource
#
# check: sent request contains Type=0(CON) and Code=1(GET), Client
# generated Message ID
#
# check: server sends response containing Type=2(ACK), Message ID same
# as the request, empty Payload
#
# check: Server sends response containing Type=0(CON), Code=69(2.05
# content), Payload=Content of the requested resource, Content type
# option
#
# check: Client sends response containing Type=2(ACK), message ID same
# as the response, empty Payload
#
# verify: client displays received response
#
function TD_COAP_CORE_15 {
clientopts="$callopts -m get"
#FIXME: address for lossy context?
testaddress=coap://$SERVERTUP/separate
echo "perform GET (CON mode) on resource $testaddress in lossy context"
start_coap_test $1
}
### LINK ###
##
# Access to well-known interface for resource discovery
#
# Pre: client supports CoRE Link Format, server supports
# /.well-known/core resource and the CoRE Link Format
#
# Client retrieves Server's list of resource
#
# check: client sends GET request for /.well-known/core resource
#
# check: server sends response containing content-type option
# indicating 40 (application/link-format), payload indicating all the
# links available on Server
#
# client displays the list of resources available on Server
#
function TD_COAP_LINK_01 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/.well-known/core
echo "retrieve server's list of resource"
start_tcpdump $1
if [ $verbose ]; then
echo "client command: $COAP_CLIENT $clientopts $testaddress"
fi
clientoutput=$($COAP_CLIENT $clientopts "$testaddress")
if [[ ! $(echo $clientoutput | grep rt) ]] ; then
echo "no resource with attribute rt found on server"
else
rt="${clientoutput##*rt=}"
rt="${rt%%;*}"
fi
echo -e "\nOutput of client:"
echo -e $clientoutput
echo
kill_tcpdump
}
##
# Use filtered requests for limiting discovery results
#
# Pre: client supports CoRE Link Format, server supports CoRE Link
# Format and offers different types of resources (Type 1, Type 2
# (extracted from /.well-knwon/core resource
#
# Client retrieves Server's list of resource of a specific Type 1
#
# check: client sends GET request for /.well-known/core resource
# containing URI-Query indicating "rt=Type1"
#
# check: server sends response containing content-type option
# indicating 40 (application/link-format), payload indicating only the
# links of type Type1 available on server
#
# client displays the list of resources of type Type1 available on Server
#
function TD_COAP_LINK_02 {
clientopts="$callopts -m get"
echo "retrieve server's list of resource for appropriate type"
if [[ ! -z $rt ]]; then
testaddress="coap://$SERVERTUP/.well-known/core?rt=$rt"
else
echo "no appropriate resource found. Skipping test"
return
fi
start_coap_test $1
}
### BLOCK ###
##
# Perform GET blockwise transfer for large resource (early negotiation)
#
# pre: Client supports Block transfers, Server supports Block
# transfers, Server offers a large resource /large, client knows
# /large requires block transfer
#
# Client is requested to retrieve resource /large
#
# check: client sends a GET request containing Block2 option indicating block
# number 0 and desired block size
#
# check: Each request contains Block2 option indicating block number
# of the next block and size of the last received block
#
# check: server sends further responses containing Block2 option
# indicating block number and size
#
# verify: client displays received response
#
function TD_COAP_BLOCK_01 {
clientopts="$callopts -m get -b 1024"
testaddress=coap://$SERVERTUP/large
echo "perform GET on large resource $testaddress (early negotiation)"
start_coap_test $1
}
##
# Perform GET blockwise transfer for large resource (late negotiation)
#
# pre: Client supports Block transfers, Server supports Block
# transfers, Server offers a large resource /large, client does not
# know /large requires block transfer
#
# Client is requested to retrieve resource /large
#
# check: client sends a GET request not containing Block2 option
#
# check: server sends response containing Block2 option indicating
# block number and size
#
# check: Each request contains Block2 option indicating block number
# of the next block and size of the last received block or the desired
# size of the next block
#
# check: server sends further responses containing Block2 option
# indicating block number and size
#
# verify: client displays received response
#
function TD_COAP_BLOCK_02 {
clientopts="$callopts -m get"
testaddress=coap://$SERVERTUP/large
echo "perform GET blockwise transfer for large resource (late negotiation) on resource $testaddress"
start_coap_test $1 stop
}
##
# Perform PUT blockwise transfer for large resource
#
# pre: Client supports Block transfers, Server supports Block
# transfers, Server offers a large updatable resource /large-update
#
# Client is requested to retrieve resource /large-update on server
#
# check: client sends a PUT request containing Block1 option
# indicating block number 0 and block size
#
# check: client sends further request containing Block1 option
# indicating block number and size
#
# verify: server indicates presence of the complete updated resource
# /large-update
#
function TD_COAP_BLOCK_03 {
clientopts="$callopts -m put -b 1024"
testaddress=coap://$SERVERTUP/large-update
echo "perform PUT on large resource $testaddress"
start_coap_test $1
}
##
# Perform POST blockwise transfer for large resource
#
# pre: Client supports Block transfers, Server supports Block
# transfers, Server accepts creation of new resources on /large-create
#
# Client is requested to create a new resource on server
#
# check: client sends a POST request containing Block1 option
# indicating block number 0 and block size
#
# check: client sends further requests containing Block1 option
# indicating block number and size
#
# verify: server indicates presence of the complete new resource
#
function TD_COAP_BLOCK_04 {
clientopts="$callopts -m post -b 1024"
testaddress=coap://$SERVERTUP/large-create
echo "perform POST on large resource $testaddress"
start_coap_test $1
}
# # OBS
##
# Handle observe option
#
# pre: client supports Observe option, server supports observe option,
# server offers an observable resource /obs which changes periodically
# (e.g. every 5s.)
#
# client is requested to observe resource /obs on server
#
# check: client sends a GET request containing observe option
#
# verify: client displays the received information
#
# check: server sends response containing observe option indicating
# increasing values, as resource changes
#
# verify: client displays the updated information
#
function TD_COAP_OBS_01 {
# we need some time to verify the correct behavior
clientopts="$callopts -s 0" #"-v 5 -B $longtimeout -s 0"
testaddress=coap://$SERVERTUP/obs
echo "observe resource $testaddress"
start_coap_test $1
}
##
# Stop resource observation
#
# pre: client supports Observe option, server supports observe option,
# server offers an observable resource /obs which changes periodically
# (e.g. every 5s.), client is observing /obs on server
#
# client is requested to stop observing resource /obs on server
#
# check: client sends a GET request not containing observe option
#
# verify: client displays the received information
#
# check: server does not send further response
#
# verify: client does not display the updated information
#
# function TD_COAP_OBS_02 {
# #FIXME: client does not support stopping yet
# we need some time to verify the correct behavior
# clientopts="-v 5 -B $longtimeout -s 1"
# testaddress=coap://$SERVERTUP/obs
# echo "stop observing resource $testaddress"
# start_coap_test $1
# }
##
# client detection of deregistration (Max-Age)
#
# pre: client supports Observe option, server supports observe option,
# server offers an observable resource /obs which changes periodically
# (e.g. every 5s.), client is observing /obs on server
#
# Server is rebooted
#
# check: Server does not send notifications
#
# verify: Client does not display updated information
#
# verify: After Max-Age expiration, client sends a new GET with observe
# option for Server's observable resource
#
# check: Sent request contains Observe option indicating 0
#
# check: Server sends response containing Observe option
#
# verify: client displays the received information
#
# check: Server sends response containing Observe option indicating
# increasing values, as resource changes
#
# verify: Client displays the updated information
#
function TD_COAP_OBS_03 {
clientopts="$callopts -s 0"#"-v5 -B $longtimeout -s 0"
testaddress=coap://$SERVERTUP/obs
echo "client detection of deregistration (Max-Age)"
start_coap_test $1
}
##
# Server detection of deregistration (client OFF)
#
# pre: client supports Observe option, server supports observe option,
# server offers an observable resource /obs which changes periodically
# (e.g. every 5s.), client is observing /obs on server
#
# Client is switched off
#
# check: Servers confirmable responses are not acknowledged
#
# verify: After some delay, Server does not send further responses
#
function TD_COAP_OBS_04 {
clientopts="$callopts -s 0"
#"-v 5 -B $longtimeout -s 0"
testaddress=coap://$SERVERTUP/obs
echo "server detection of deregistration (client off)"
start_coap_test $1 wait
}
##
# Server detection of deregistration (explicit RST)
#
# pre: client supports Observe option, server supports observe option,
# server offers an observable resource /obs which changes periodically
# (e.g. every 5s.), client is observing /obs on server
#
# Client is rebooted
#
# check: Server sends response containing Observe option
#
# verify: Client discards response and does not display information
#
# check: Client sends RST to Server
#
# check: Server does not send further response
#
function TD_COAP_OBS_05 {
clientopts="$callopts -s 0 -p $CLIENTPORT"
#"-v 5 -B $longtimeout -p $CLIENTPORT -s 0"
testaddress=coap://$SERVERTUP/obs
echo "server detection of deregistration (explicit RST)"
start_coap_test $1 stop
clientopts="$callopts -p $CLIENTPORT -s 0 -N"
#"-v 5 -B $clienttimeout -p $CLIENTPORT -s 0 -N"
testaddress=coap://[::1]/obs
start_coap_test $1
}
@@ -0,0 +1,66 @@
/*
* This file was copied from the following newsgroup posting:
*
* Newsgroups: mod.std.unix
* Subject: public domain AT&T getopt source
* Date: 3 Nov 85 19:34:15 GMT
*
* Here's something you've all been waiting for: the AT&T public domain
* source for getopt(3). It is the code which was given out at the 1985
* UNIFORUM conference in Dallas. I obtained it by electronic mail
* directly from AT&T. The people there assure me that it is indeed
* in the public domain.
*/
#include <stdio.h>
#include <string.h>
static int opterr = 1;
static int optind = 1;
static int optopt;
static char *optarg;
static int getopt(int argc, char *argv[], char *opts)
{
static int sp = 1;
int c;
char *cp;
if (sp == 1) {
if (optind >= argc ||
argv[optind][0] != '-' || argv[optind][1] == '\0')
return EOF;
else if (!strcmp(argv[optind], "--")) {
optind++;
return EOF;
}
}
optopt = c = argv[optind][sp];
if (c == ':' || !(cp = strchr(opts, c))) {
fprintf(stderr, ": illegal option -- %c\n", c);
if (argv[optind][++sp] == '\0') {
optind++;
sp = 1;
}
return '?';
}
if (*++cp == ':') {
if (argv[optind][sp+1] != '\0')
optarg = &argv[optind++][sp+1];
else if(++optind >= argc) {
fprintf(stderr, ": option requires an argument -- %c\n", c);
sp = 1;
return '?';
} else
optarg = argv[optind++];
sp = 1;
} else {
if (argv[optind][++sp] == '\0') {
sp = 1;
optind++;
}
optarg = NULL;
}
return c;
}
@@ -0,0 +1,7 @@
# not going for submodules here to keep things easy
lwip
lwip-contrib
# never objects, and not the resulting binary
*.o
server
@@ -0,0 +1,30 @@
Example of libcoap running on lwIP
==================================
To run the example, do
$ make
$ sudo ./server
(and in a second terminal)
$ sudo ip a a dev tap0 192.168.113.1/24
and query `coap://192.168.113.2/time?ticks` with any coap tool,
or query `coap://[aaaa::1000]/.well-known/core`
This will
* download lwip and lwip-contrib from the upstream git sources
* build the server application
* run the server application, creating a virtual network device tap0 (unless
that exists)
* configure your network interface to make the server accessible.
* return the appropriate response from the server to the client.
The server creates a resource for 'time' with a query 'ticks'. This is
reported for `.well-known/core`. The work flow for adding more resources does
not differ from regular libcoap usage. If you seem to run out of memory
creating the resources, tweak the number of pre-allocated resources
in `include/coap/lwippools.h`.
@@ -0,0 +1,37 @@
/*
* lwipopts.h -- LwIP example
*
* Copyright (C) 2013-2016 Christian Amsüss <chrysn@fsfe.org>
* Copyright (C) 2018 John Shallow <supjps-libcoap@jpshallow.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
typedef unsigned int sys_prot_t;
#define NO_SYS 1
#define LWIP_SOCKET (NO_SYS==0)
#define LWIP_NETCONN (NO_SYS==0)
#define LWIP_NETIF_API (NO_SYS==0)
#define LWIP_IPV6 1
#define LWIP_IPV6_REASS 0
#ifndef LWIP_RAND
#define LWIP_RAND() ((u32_t)rand())
#endif
#ifndef netif_get_index
#define netif_get_index(netif) ((u8_t)((netif)->num + 1))
#endif
#if NO_SYS
#include <pthread.h>
extern pthread_mutex_t lwprot_mutex;
extern pthread_t lwprot_thread;
extern int lwprot_count;
#endif
#define MEMP_USE_CUSTOM_POOLS 1
@@ -0,0 +1,147 @@
/*
* server-coap.h -- LwIP example
*
* Copyright (C) 2013-2016 Christian Amsüss <chrysn@fsfe.org>
* Copyright (C) 2018-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#include "coap_config.h"
#include <coap3/coap.h>
coap_context_t *main_coap_context;
static coap_time_t clock_offset;
/* changeable clock base (see handle_put_time()) */
static coap_time_t my_clock_base = 0;
static coap_resource_t *time_resource = NULL; /* just for testing */
#ifndef min
# define min(a,b) ((a) < (b) ? (a) : (b))
#endif
void
hnd_get_time(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query,
coap_pdu_t *response) {
unsigned char buf[40];
size_t len;
coap_tick_t now;
coap_tick_t t;
/* FIXME: return time, e.g. in human-readable by default and ticks
* when query ?ticks is given. */
/* if my_clock_base was deleted, we pretend to have no such resource */
response->code =
my_clock_base ? COAP_RESPONSE_CODE(205) : COAP_RESPONSE_CODE(404);
if (my_clock_base)
coap_add_option(response, COAP_OPTION_CONTENT_FORMAT,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_TEXT_PLAIN),
buf);
coap_add_option(response, COAP_OPTION_MAXAGE,
coap_encode_var_safe(buf, sizeof(buf), 0x01), buf);
if (my_clock_base) {
/* calculate current time */
coap_ticks(&t);
now = my_clock_base + (t / COAP_TICKS_PER_SECOND);
if (query != NULL
&& coap_string_equal(query, coap_make_str_const("ticks"))) {
/* output ticks */
len = snprintf((char *)buf, sizeof(buf), "%u", (unsigned int)now);
coap_add_data(response, len, buf);
}
}
}
void
init_coap_resources(coap_context_t *ctx) {
coap_resource_t *r;
#if 0
r = coap_resource_init(NULL, 0, 0);
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_index);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"General Info\""), 0);
coap_add_resource(ctx, r);
#endif
/* store clock base to use in /time */
my_clock_base = clock_offset;
r = coap_resource_init(coap_make_str_const("time"), 0);
if (!r)
goto error;
coap_resource_set_get_observable(r, 1);
time_resource = r;
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time);
#if 0
coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time);
coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time);
#endif
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
/* coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"Internal Clock\""), 0); */
coap_add_attr(r, coap_make_str_const("rt"), coap_make_str_const("\"ticks\""), 0);
coap_add_attr(r, coap_make_str_const("if"), coap_make_str_const("\"clock\""), 0);
coap_add_resource(ctx, r);
#if 0
#ifndef WITHOUT_ASYNC
r = coap_resource_init(coap_make_str_const("async"), 0);
coap_register_handler(r, COAP_REQUEST_GET, hnd_get_async);
coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0);
coap_add_resource(ctx, r);
#endif /* WITHOUT_ASYNC */
#endif
return;
error:
coap_log(LOG_CRIT, "cannot create resource\n");
}
void server_coap_init(void)
{
coap_address_t listenaddress;
coap_address_init(&listenaddress);
/* looks like a server address, but is used as end point for clients too */
listenaddress.addr = *(IP_ANY_TYPE);
listenaddress.port = COAP_DEFAULT_PORT;
coap_set_log_level(LOG_DEBUG);
main_coap_context = coap_new_context(&listenaddress);
LWIP_ASSERT("Failed to initialize context", main_coap_context != NULL);
clock_offset = 1; /* Need a non-zero value */
init_coap_resources(main_coap_context);
}
void server_coap_poll(void)
{
static coap_time_t last_time = 0;
coap_tick_t ticks_now;
coap_time_t time_now;
coap_ticks(&ticks_now);
time_now = coap_ticks_to_rt(ticks_now);
if (last_time != time_now) {
/* This takes place once a second */
last_time = time_now;
coap_resource_notify_observers(time_resource, NULL);
}
coap_check_notify(main_coap_context);
}
@@ -0,0 +1,17 @@
/*
* server-coap.h -- LwIP example
*
* Copyright (C) 2013-2016 Christian Amsüss <chrysn@fsfe.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#include "coap_config.h"
#include <coap3/coap.h>
void server_coap_init(void);
/* call this when you think that resources could be dirty */
void server_coap_poll(void);
@@ -0,0 +1,91 @@
/*
* Demo for libcoap on lwIP
*
* partially copied from lwip-contrib/ports/unix/proj/minimal/main.c
*
*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Adam Dunkels <adam@sics.se>
* RT timer modifications by Christiaan Simons
* lwip adaptions: chrysn <chrysn@fsfe.org>
* also, https://savannah.nongnu.org/bugs/?40245 was applied */
#include "server-coap.h"
#include <lwip/init.h>
#include <lwip/timeouts.h>
#include <netif/etharp.h>
#include <netif/tapif.h>
#include <signal.h>
static ip4_addr_t ipaddr, netmask, gw;
int
main(int argc, char **argv)
{
struct netif netif;
/* startup defaults (may be overridden by one or more opts). this is
* hard-coded v4 even in presence of v6, which does auto-discovery and
* should thus wind up with an address of fe80::12:34ff:fe56:78ab%tap0
* */
IP4_ADDR(&gw, 192,168,113,1);
IP4_ADDR(&ipaddr, 192,168,113,2);
IP4_ADDR(&netmask, 255,255,255,0);
lwip_init();
printf("TCP/IP initialized.\n");
netif_add(&netif, &ipaddr, &netmask, &gw, NULL, tapif_init, ethernet_input);
netif.flags |= NETIF_FLAG_ETHARP;
netif_set_default(&netif);
netif_set_up(&netif);
#if LWIP_IPV6
netif_create_ip6_linklocal_address(&netif, 1);
#endif
/* start applications here */
server_coap_init();
printf("Applications started.\n");
while (1) {
/* poll netif, pass packet to lwIP */
tapif_select(&netif);
sys_check_timeouts();
server_coap_poll();
}
return 0;
}
@@ -0,0 +1,43 @@
# Makefile for libcoap standalone examples
#
# Copyright (C) 2021 Olaf Bergmann <bergmann@tzi.org>
#
# This file is part of the CoAP C library libcoap. Please see README and
# COPYING for terms of use.
# Set external variable LIBCOAP if you need a specific libcoap library.
# E.g. libcoap-3-openssl, libcoap-3-gnutls, libcoap-3-mbedtls or libcoap-3-notls
#
LIBCOAP?=libcoap-3
WARNING_CFLAGS= \
-pedantic \
-Wall \
-Wcast-qual \
-Wextra \
-Wformat-security \
-Winline \
-Wmissing-declarations \
-Wmissing-prototypes \
-Wnested-externs \
-Wpointer-arith \
-Wshadow \
-Wstrict-prototypes \
-Wswitch-default \
-Wswitch-enum \
-Wunused \
-Wwrite-strings
pkgconfig=$(shell pkg-config $(1) $(2))
CPPFLAGS=-D_GNU_SOURCE $(WARNING_CFLAGS) $(call pkgconfig,--cflags,$(LIBCOAP))
CFLAGS=-std=c99
LDLIBS=$(call pkgconfig,--libs-only-l,$(LIBCOAP))
libdirs=$(call pkgconfig,--libs-only-L,$(LIBCOAP))
rpath=$(shell echo "$(libdirs)" | sed -e 's/^-L/-Wl,--rpath /')
LDFLAGS=$(libdirs) $(rpath)
all: coap-client coap-server
clean:
rm -f *.o coap-client coap-server
@@ -0,0 +1,9 @@
This directory contains some example libcoap code for a client or server which
can easily be modified as per your requirements.
The provided code is the same as used to build the installed binaries
coap-client and coap-server.
Simply 'cd' into this directory and then run 'make' to build the executables.
@@ -0,0 +1,183 @@
/* tiny -- tiny sender
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <coap3/coap.h>
#define Nn 8 /* duplicate definition of N if built on sky motes */
#define ENCODE_HEADER_SIZE 4
#define HIBIT (1 << (Nn - 1))
#define EMASK ((1 << ENCODE_HEADER_SIZE) - 1)
#define MMASK ((1 << Nn) - 1 - EMASK)
#define MAX_VALUE ( (1 << Nn) - (1 << ENCODE_HEADER_SIZE) ) * (1 << ((1 << ENCODE_HEADER_SIZE) - 1))
#define COAP_PSEUDOFP_DECODE_8_4(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK))
/* ls and s must be integer variables */
/* #define COAP_PSEUDOFP_ENCODE_8_4_DOWN(v,ls) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (v >> ls) & MMASK) + ls) */
COAP_STATIC_INLINE unsigned char
COAP_PSEUDOFP_ENCODE_8_4_DOWN(unsigned int v, int *ls) {
if (v < HIBIT) return v;
*ls = coap_fls(v) - Nn;
return ((v >> *ls) & MMASK) + *ls;
}
#define COAP_PSEUDOFP_ENCODE_8_4_UP(v,ls,s) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (s = (((v + ((1<<ENCODE_HEADER_SIZE<<ls)-1)) >> ls) & MMASK)), s == 0 ? HIBIT + ls + 1 : s + ls))
static int quit = 0;
/* SIGINT handler: set quit to 1 for graceful termination */
static void
handle_sigint(int signum COAP_UNUSED) {
quit = 1;
}
static coap_pdu_t *
make_pdu( coap_session_t *session, unsigned int value ) {
coap_pdu_t *pdu;
unsigned char enc;
static unsigned char buf[20];
int len, ls;
if (!(pdu = coap_pdu_init(COAP_MESSAGE_NON, COAP_REQUEST_CODE_POST,
coap_new_message_id(session), COAP_DEFAULT_MTU)))
return NULL;
enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value, &ls);
len = sprintf((char *)buf, "%c%u", enc, COAP_PSEUDOFP_DECODE_8_4(enc));
coap_add_data( pdu, len, buf );
return pdu;
}
static void
usage( const char *program ) {
const char *p;
p = strrchr( program, '/' );
if ( p )
program = ++p;
fprintf( stderr, "%s -- tiny fake sensor\n"
"(c) 2010 Olaf Bergmann <bergmann@tzi.org>\n\n"
"usage: %s [group address]\n"
"\n\nSends some fake sensor values to specified multicast group\n",
program, program );
}
static coap_session_t *
get_session(coap_context_t *ctx, const char *group) {
int s;
struct addrinfo hints;
struct addrinfo *result, *rp;
coap_session_t *session;
int hops = 16;
if (!ctx)
return NULL;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */
hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
s = getaddrinfo(group, NULL, &hints, &result);
if ( s != 0 ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return NULL;
}
/* iterate through results until success */
for (rp = result; rp != NULL; rp = rp->ai_next) {
coap_address_t addr;
coap_address_init(&addr);
addr.size = rp->ai_addrlen;
memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen);
session = coap_new_client_session(ctx, NULL, &addr, COAP_PROTO_UDP);
if (!session)
continue;
if (IN6_IS_ADDR_MULTICAST(&addr.addr.sin6.sin6_addr) ) {
/* set socket options for multicast */
if (!coap_mcast_set_hops(session, hops))
perror("setsockopt: IPV6_MULTICAST_HOPS");
}
freeaddrinfo(result);
return session;
}
fprintf(stderr, "no session available for group '%s'\n", group);
freeaddrinfo(result);
return NULL;
}
int
main(int argc, char **argv) {
struct timeval tv;
coap_pdu_t *pdu;
coap_session_t *session;
struct sigaction sa;
coap_context_t *ctx;
if ( argc > 1 && strncmp(argv[1], "-h", 2) == 0 ) {
usage( argv[0] );
exit( 1 );
}
ctx = coap_new_context(NULL);
if (!ctx)
return -1;
session = get_session(ctx, argc > 1 ? argv[1] : "::1");
if ( !session )
return -1;
memset (&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = handle_sigint;
sa.sa_flags = 0;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
/* So we do not exit on a SIGPIPE */
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
while ( !quit ) {
if (! (pdu = make_pdu( session, rand() & 0xfff ) ) )
break;
coap_send(session, pdu);
tv.tv_sec = 5; tv.tv_usec = 0;
select( 0, 0, 0, 0, &tv );
}
coap_free_context(ctx);
return 0;
}
@@ -0,0 +1,60 @@
# About This Content
2015-12-18
# License
The Eclipse Foundation makes available all content in this plug-in
("Content"). Unless otherwise indicated below, the Content is provided
to you under the terms and conditions of the Eclipse Public License
Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0
(“EDL”). A copy of the EPL is available at
http://www.eclipse.org/legal/epl-v10.html and a copy of the EDL is
available at http://www.eclipse.org/org/documents/edl-v10.php. For
purposes of the EPL, "Program" will mean the Content.
If you did not receive this Content directly from the Eclipse
Foundation, the Content is being redistributed by another party
("Redistributor") and different terms and conditions may apply to your
use of any object code in the Content. Check the Redistributors
license that was provided with the Content. If no such license exists,
contact the Redistributor. Unless otherwise indicated below, the terms
and conditions of the EPL and EDL still apply to any source code in
the Content and such source code may be obtained at
http://www.eclipse.org.
# Third Party Content
The Content includes items that have been sourced from third parties
as set out below. If you did not receive this Content directly from
the Eclipse Foundation, the following is provided for informational
purposes only, and you should look to the Redistributors license for
terms and conditions of use.
## Uthash 1.9.9
[Uthash](https://troydhanson.github.io/uthash/) is an implementation
of hash tables and linked lists for C structures by Troy D. Hanson.
Uthash is licensed under the BSD revised license, see
https://troydhanson.github.io/uthash/license.html,
## rijndael 3.0
The library uses an implementation of the Rijndael algorithm (AES)
from [OpenBSD](http://www.openbsd.org/) by Vincent Rijmen, Antoon
Bosselaers, and Paulo Barreto. The authors have placed the code in the
public domain under the license included in the file rijndael.h (see
http://www.openbsd.org/cgi-bin/cvsweb).
## SHA-256 1.0
The SHA-256 implementation from Aaron D. Gifford is available at
http://www.aarongifford.com/computers/sha2-1.0.1.tgz under a
3-clause BSD license.
## ECC 1.0
The implementation of the ECC curve secp256r1 was originally developed
by Chris K Cockrum and has been put under MIT license for inclusion
with tinydtls. The original source is made available in
https://cockrum.net/Implementation_of_ECC_on_an_8-bit_microcontroller.pdf
@@ -0,0 +1,101 @@
###############################################################################
#
# Copyright (c) 2022 Contributors to the Eclipse Foundation
#
# See the LICENSE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 1.0
# which is available at https://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License v. 1.0
# available at http://www.eclipse.org/org/documents/edl-v10.php
#
# SPDX-License-Identifier: EPL-1.0
#
# Contributors:
# Jimmy Björklund - initial version
# Achim Kraus - add getrandom and libcunit
# additional minor fixes
#
###############################################################################
include(CheckIncludeFile)
include(CheckFunctionExists)
include(CheckLibraryExists)
include(TestBigEndian)
include(CheckCSourceCompiles)
include(CheckStructHasMember)
check_include_file(assert.h HAVE_ASSERT_H)
check_include_file(arpa/inet.h HAVE_ARPA_INET_H)
check_include_file(fcntl.h HAVE_FCNTL_H)
check_include_file(inttypes.h HAVE_INTTYPES_H)
check_include_file(memory.h HAVE_MEMORY_H)
check_include_file(netdb.h HAVE_NETDB_H)
check_include_file(netinet/in.h HAVE_NETINET_IN_H)
check_include_file(stddef.h HAVE_STDDEF_H)
check_include_file(stdint.h HAVE_STDINT_H)
check_include_file(stdlib.h HAVE_STDLIB_H)
check_include_file(string.h HAVE_STRING_H)
check_include_file(strings.h HAVE_STRINGS_H)
check_include_file(time.h HAVE_TIME_H)
check_include_file(sys/param.h HAVE_SYS_PARAM_H)
check_include_file(sys/random.h HAVE_SYS_RANDOM_H)
check_include_file(sys/socket.h HAVE_SYS_SOCKET_H)
check_include_file(sys/stat.h HAVE_SYS_STAT_H)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(unistd.h HAVE_UNISTD_H)
check_include_file(float.h HAVE_FLOAT_H)
check_include_file(dlfcn.h HAVE_DLFCN_H)
if(NOT ZEPHYR_BASE)
# zephyr/ncs 1.9.1 has issues including this header
check_include_file(sys/time.h HAVE_SYS_TIME_H)
endif()
if(ZEPHYR_BASE)
# zephyr/ncs 1.9.1 has issues with check_include_file
# https://github.com/zephyrproject-rtos/zephyr/issues/31193
# zephyr/ncs 1.9.1 has net/socket.h instead of sys/socket.h
set(HAVE_NET_SOCKET_H 1)
endif()
check_function_exists (memset HAVE_MEMSET)
check_function_exists (select HAVE_SELECT)
check_function_exists (socket HAVE_SOCKET)
check_function_exists (strdup HAVE_STRDUP)
check_function_exists (strerror HAVE_STRERROR)
check_function_exists (strnlen HAVE_STRNLEN)
check_function_exists (fls HAVE_FLS)
check_function_exists (vprintf HAVE_VPRINTF)
check_function_exists (inet_ntop HAVE_INET_NTOP)
if(HAVE_SYS_RANDOM_H)
# zephyr/ncs 1.9.1 seems to link getrandom but doesn't offer a header
check_function_exists (getrandom HAVE_GETRANDOM)
endif()
if( ${make_tests} )
if(BUILD_SHARED_LIBS)
check_library_exists (libcunit.so CU_initialize_registry "" HAVE_LIBCUNIT)
else()
# this link options only intended to be used for the cunit tests
set(CMAKE_REQUIRED_LINK_OPTIONS -no-pie)
check_library_exists (libcunit.a CU_initialize_registry "" HAVE_LIBCUNIT)
endif()
endif()
if( "${HAVE_STRING_H}" AND "${HAVE_STRINGS_H}" AND
"${HAVE_FLOAT_H}" AND "${HAVE_STDLIB_H}" AND
"${HAVE_STDDEF_H}" AND "${HAVE_STDINT_H}" AND
"${HAVE_INTTYPES_H}" AND "${HAVE_DLFCN_H}" )
set( STDC_HEADERS 1)
endif()
check_struct_has_member ("struct sockaddr_in6" sin6_len "netinet/in.h" HAVE_SOCKADDR_IN6_SIN6_LEN)
TEST_BIG_ENDIAN(IS_BIG_ENDIAN)
if(IS_BIG_ENDIAN)
set(WORDS_BIGENDIAN 1)
endif()
@@ -0,0 +1,85 @@
###############################################################################
#
# Copyright (c) 2022 Contributors to the Eclipse Foundation
#
# See the LICENSE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 1.0
# which is available at https://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License v. 1.0
# available at http://www.eclipse.org/org/documents/edl-v10.php
#
# SPDX-License-Identifier: EPL-1.0
#
# Contributors:
# Jimmy Björklund - initial version
# Achim Kraus - minor fixes
#
###############################################################################
cmake_minimum_required(VERSION 3.5)
project(tinydtls)
include (AutoConf.cmake)
option(BUILD_SHARED_LIBS "Link using shared libs" OFF)
option(make_tests "Make test programs and examples" OFF)
if(NOT PLATFORM)
# PLATFORM seems to be not used
set(PLATFORM "posix" CACHE STRING "Choose platform." FORCE)
set_property(CACHE PLATFORM PROPERTY STRINGS "contiki" "espidf" "posix" "riot" "zephyr")
endif()
set(PACKAGE_NAME "tinydtls")
set(PACKAGE_VERSION "0.8.6" )
set(SOVERSION "0" )
option(DTLS_ECC "disable/enable support for TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" ON )
option(DTLS_PSK "disable/enable support for TLS_PSK_WITH_AES_128_CCM_8" ON)
configure_file(dtls_config.h.cmake.in dtls_config.h )
add_library(tinydtls)
target_sources(tinydtls PRIVATE
dtls.c
netq.c
peer.c
session.c
crypto.c
ccm.c
hmac.c
dtls_time.c
dtls_debug.c
dtls_prng.c
aes/rijndael.c
aes/rijndael_wrap.c
sha2/sha2.c
ecc/ecc.c)
target_include_directories(tinydtls PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
target_compile_definitions(tinydtls PUBLIC DTLSv12 WITH_SHA256 SHA2_USE_INTTYPES_H DTLS_CHECK_CONTENTTYPE)
if(NOT ZEPHYR_BASE)
target_compile_options(tinydtls PRIVATE -fPIC -pedantic -std=c99 -Wall -Wextra -Wformat-security -Winline -Wmissing-declarations -Wmissing-prototypes -Wnested-externs -Wpointer-arith -Wshadow -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wunused)
endif()
set_target_properties(tinydtls PROPERTIES VERSION ${PACKAGE_VERSION} SOVERSION ${SOVERSION})
if( ${make_tests} )
add_subdirectory(tests)
endif()
if(BUILD_SHARED_LIBS)
install(TARGETS tinydtls LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} )
else()
install(TARGETS tinydtls DESTINATION ${CMAKE_INSTALL_LIBDIR} )
endif()
file(CONFIGURE OUTPUT .gitignore
NEWLINE_STYLE UNIX
CONTENT "*")
@@ -0,0 +1,144 @@
Contributing to tinydtls
========================
Thanks for your interest in this project.
Project description:
--------------------
tinydtls is a library for Datagram Transport Layer Security (DTLS) covering
both the client and the server state machine. It is implemented in C and
provides support for the mandatory cipher suites specified in CoAP.
- https://projects.eclipse.org/projects/iot.tinydtls
Developer resources:
--------------------
Information regarding source code management, builds, and more.
- https://projects.eclipse.org/projects/iot.tinydtls/developer
Eclipse Contributor Agreement
-----------------------------
Before your contribution can be accepted by the project team contributors must
electronically sign the Eclipse Contributor Agreement (ECA).
* http://www.eclipse.org/legal/ECA.php
Commits that are provided by non-committers must have a Signed-off-by field in
the footer indicating that the author is aware of the terms by which the
contribution has been provided to the project. The non-committer must
additionally have an Eclipse Foundation account and must have a signed Eclipse
Contributor Agreement (ECA) on file.
For more information, please see the Eclipse Committer Handbook:
https://www.eclipse.org/projects/handbook/#resources-commit
Contact:
--------
Contact the project developers via the project's "dev" list.
- https://dev.eclipse.org/mailman/listinfo/tinydtls-dev
Search for bugs:
----------------
This project uses Bugzilla to track ongoing development and issues.
- https://bugs.eclipse.org/bugs/buglist.cgi?product=tinydtls
Create a new bug:
-----------------
Be sure to search for existing bugs before you create another one.
Remember that contributions are always welcome!
- https://bugs.eclipse.org/bugs/enter_bug.cgi?product=tinydtls
Submit Patches via GitHub:
--------------------------
Patches must follow to the tinydtls coding style and must be submitted
as pull request at https://github.com/eclipse/tinydtls for review. To
submit a patch, the author needs to have a Eclipse Contributor Agreement
as explained above.
Every new file must contain the Eclipse license information and the
copyright holder(s). Please take a look into existing files and adopt
the needed changes to your new file(s).
Main and Develop:
-----------------
Please prepare all patches against the "main" branch.
It may take sometimes a little longer for a pull request to be processed
and merged to "main". Therefore some of the pending pull requests will be
available on the "develop" branch as preview. If you want to test a specific
pending pull request which is currently not on "develop", let us know by
adding a comment to that pull request. If a pull request is cherry-picked
to the "develop" branch, that doesn't grant that it is merged as-it-is.
For house-keeping, it may in some cases be required to push the "develop"
branch with "--force-with-lease" in order to adjust the branch for later
changes in a pull request before it gets merged into "main" or if "develop"
is rebased to "main".
In some rare cases, it may be required to include another still pending pull
request/commit into your pull request additionally. If that other pull request
gets merged, please rebase then your pull request using the new "main".
Currently (July 2022) this process change is in progress. Therefore some
pull requests are merged into "develop" and will be included in "main"
after the review finally completes.
Tinydtls Coding style:
----------------------
* For better reading the indentation is set to 2 characters as spaces,
this is depended on the often used nested functions like
'if-else'. Don't use TABs any there! Avoid trailing white spaces at
the end of a line.
* Single lines within the source code should not be longer than 72
characters and must not be longer than 80.
* In the implementation (i.e., in files ending with '.c'), function
identifiers start on the first column of a line. The function's
return type preceeds the function identifier on a line of its
own. For example, in `dtls.c` the following definition is found:
```
dtls_peer_t *
dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
...
}
```
* Declarations in header files do not follow the previous rule. For
example, the declaration for `dtls_get_peer()` in `dtls.h` reads as
follows:
```
dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
const session_t *session);
```
* A useful source code documentation is mandatory. Mostly to be done
within the source code files.
* Please set up/adjust the doxygen documentation if you create new
functions or change existing functions. The doxygen documentation
has to be done in the header files as they are the public part of
tinydtls and only use the @-syntax for doxygen commands (akin to
javadoc).
* Never break the API!
Do not remove old functions unless absolutely necessary. If changes
are needed in some kind always provide a wrapper for the old call to
let the library be backward compatible and mark the old function as
@deprecated in the doxygen comment. Please discuss needed changes
on the mailing list.
@@ -0,0 +1,12 @@
/*******************************************************************************
* Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
* Contributors:
* Olaf Bergmann - initial API and implementation
* Hauke Mehrtens - memory optimization, ECC integration
*******************************************************************************/
@@ -0,0 +1,7 @@
MODULE = tinydtls
CFLAGS += -DDTLSv12 -DWITH_SHA256
SRC := ccm.c crypto.c dtls.c dtls_debug.c dtls_time.c hmac.c netq.c peer.c session.c dtls_prng.c
include $(RIOTBASE)/Makefile.base
@@ -0,0 +1,9 @@
# This is a -*- Makefile -*-
CFLAGS += -DDTLSv12 -DWITH_SHA256
tinydtls_src = dtls.c crypto.c hmac.c rijndael.c rijndael_wrap.c sha2.c ccm.c netq.c ecc.c dtls_time.c peer.c session.c dtls_prng.c
# This activates debugging support
# CFLAGS += -DNDEBUG
tinydtls_src += dtls_debug.c
@@ -0,0 +1,81 @@
# About tinydtls
tinydtls is a library for Datagram Transport Layer Security (DTLS)
covering both the client and the server state machine. It is
implemented in C and provides support for a minimal set of cipher
suites suitable for the Internet of Things.
This library contains functions and structures that can help
constructing a single-threaded UDP server with DTLS support in
C99. The following components are available:
* dtls
Basic support for DTLS with pre-shared key mode and RPK mode with ECC.
* tests
The subdirectory tests contains test programs that show how each
component is used.
# BUILDING
When using the code from the git
[repository](https://github.com/eclipse/tinydtls) at GitHub, invoke
$ ./autogen.sh
$ ./configure
to re-create the configure script.
## Contiki
On Contiki, place the tinydtls library into the apps folder. After
configuration, invoke make to build the library and associated test
programs. To add tinydtls as Contiki application, drop it into the
apps directory and add the following line to your Makefile:
APPS += tinydtls/aes tinydtls/sha2 tinydtls/ecc tinydtls
## RIOT
On RIOT, you need to add the line `USEPKG += tinydtls`.
You can use `RIOT/examples/dtls-echo/` as a guide for integrating tinyDTLS
to your application.
Also, if you need a specific commit of tinyDTLS you can modify
`RIOT/pkg/tinydtls/Makefile`.
## CMake
The current cmake support is experimental. Don't hesitate to report issues
and/or provided fixes for it. For general and more details on using CMake,
please consider [CMake - help](https://cmake.org/cmake/help/latest/index.html).
Usage:
```
mkdir tinydtls_build
cd tinydtls_build
cmake -Dmake_tests=ON <path-to-tinydtls>
cmake --build .
```
Available options:
| Option | Description | Default |
| ------ | ----------- | ------- |
| BUILD_SHARED_LIBS | build shared libraries instead of static link library | OFF |
| make_tests | build tests including the examples | OFF |
| DTLS_ECC | enable/disable ECDHE_ECDSA cipher suites | ON |
| DTLS_PSK | enable/disable PSK cipher suites | ON |
# License
Copyright (c) 20112022 Olaf Bergmann (TZI) and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v. 1.0 which accompanies this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
@@ -0,0 +1,5 @@
MODULE := tinydtls_aes
SRC := rijndael.c rijndael_wrap.c
include $(RIOTBASE)/Makefile.base
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,69 @@
/* $OpenBSD: rijndael.h,v 1.13 2008/06/09 07:49:45 djm Exp $ */
/**
* rijndael-alg-fst.h
*
* @version 3.0 (December 2000)
*
* Optimised ANSI C code for the Rijndael cipher (now AES)
*
* @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
* @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
* @author Paulo Barreto <paulo.barreto@terra.com.br>
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __RIJNDAEL_H
#define __RIJNDAEL_H
#include <stdint.h>
#define AES_MAXKEYBITS (256)
#define AES_MAXKEYBYTES (AES_MAXKEYBITS/8)
/* for 256-bit keys we need 14 rounds for a 128 we only need 10 round */
#define AES_MAXROUNDS 10
/* bergmann: to avoid conflicts with typedefs from certain Contiki platforms,
* the following type names have been prefixed with "aes_": */
typedef unsigned char u_char;
typedef uint8_t aes_u8;
typedef uint16_t aes_u16;
typedef uint32_t aes_u32;
/* The structure for key information */
typedef struct {
#ifdef WITH_AES_DECRYPT
int enc_only; /* context contains only encrypt schedule */
#endif
int Nr; /* key-length-dependent number of rounds */
aes_u32 ek[4*(AES_MAXROUNDS + 1)]; /* encrypt key schedule */
#ifdef WITH_AES_DECRYPT
aes_u32 dk[4*(AES_MAXROUNDS + 1)]; /* decrypt key schedule */
#endif
} rijndael_ctx;
int rijndael_set_key(rijndael_ctx *, const u_char *, int);
int rijndael_set_key_enc_only(rijndael_ctx *, const u_char *, int);
void rijndael_decrypt(rijndael_ctx *, const u_char *, u_char *);
void rijndael_encrypt(rijndael_ctx *, const u_char *, u_char *);
int rijndaelKeySetupEnc(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits);
int rijndaelKeySetupDec(aes_u32 rk[/*4*(Nr + 1)*/], const aes_u8 cipherKey[], int keyBits);
void rijndaelEncrypt(const aes_u32 rk[/*4*(Nr + 1)*/], int Nr, const aes_u8 pt[16], aes_u8 ct[16]);
#ifdef WITH_AES_DECRYPT
void rijndaelDecrypt(const aes_u32 rk[/*4*(Nr + 1)*/], int Nr, const aes_u8 ct[16], aes_u8 pt[16]);
#endif
#endif /* __RIJNDAEL_H */
@@ -0,0 +1,69 @@
/*******************************************************************************
*
* Copyright (c) 2019 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Olaf Bergmann - initial API and implementation
* Jon Shallow - split out wrapper code to support external rijndael code
*
*
*******************************************************************************/
#include "rijndael.h"
/* setup key context for encryption only */
int
rijndael_set_key_enc_only(rijndael_ctx *ctx, const u_char *key, int bits)
{
int rounds;
rounds = rijndaelKeySetupEnc(ctx->ek, key, bits);
if (rounds == 0)
return -1;
ctx->Nr = rounds;
#ifdef WITH_AES_DECRYPT
ctx->enc_only = 1;
#endif
return 0;
}
#ifdef WITH_AES_DECRYPT
/* setup key context for both encryption and decryption */
int
rijndael_set_key(rijndael_ctx *ctx, const u_char *key, int bits)
{
int rounds;
rounds = rijndaelKeySetupEnc(ctx->ek, key, bits);
if (rounds == 0)
return -1;
if (rijndaelKeySetupDec(ctx->dk, key, bits) != rounds)
return -1;
ctx->Nr = rounds;
ctx->enc_only = 0;
return 0;
}
void
rijndael_decrypt(rijndael_ctx *ctx, const u_char *src, u_char *dst)
{
rijndaelDecrypt(ctx->dk, ctx->Nr, src, dst);
}
#endif
void
rijndael_encrypt(rijndael_ctx *ctx, const u_char *src, u_char *dst)
{
rijndaelEncrypt(ctx->ek, ctx->Nr, src, dst);
}
@@ -0,0 +1,85 @@
/*******************************************************************************
*
* Copyright (c) 2011, 2012, 2013, 2014, 2015 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Olaf Bergmann - initial API and implementation
* Hauke Mehrtens - memory optimization, ECC integration
*
*******************************************************************************/
/**
* @file alert.h
* @brief DTLS alert protocol
*/
#ifndef _DTLS_ALERT_H_
#define _DTLS_ALERT_H_
typedef enum {
DTLS_ALERT_LEVEL_WARNING=1,
DTLS_ALERT_LEVEL_FATAL=2
} dtls_alert_level_t;
typedef enum {
DTLS_ALERT_CLOSE_NOTIFY = 0, /* close_notify */
DTLS_ALERT_UNEXPECTED_MESSAGE = 10, /* unexpected_message */
DTLS_ALERT_BAD_RECORD_MAC = 20, /* bad_record_mac */
DTLS_ALERT_RECORD_OVERFLOW = 22, /* record_overflow */
DTLS_ALERT_DECOMPRESSION_FAILURE = 30, /* decompression_failure */
DTLS_ALERT_HANDSHAKE_FAILURE = 40, /* handshake_failure */
DTLS_ALERT_BAD_CERTIFICATE = 42, /* bad_certificate */
DTLS_ALERT_UNSUPPORTED_CERTIFICATE = 43, /* unsupported_certificate */
DTLS_ALERT_CERTIFICATE_REVOKED = 44, /* certificate_revoked */
DTLS_ALERT_CERTIFICATE_EXPIRED = 45, /* certificate_expired */
DTLS_ALERT_CERTIFICATE_UNKNOWN = 46, /* certificate_unknown */
DTLS_ALERT_ILLEGAL_PARAMETER = 47, /* illegal_parameter */
DTLS_ALERT_UNKNOWN_CA = 48, /* unknown_ca */
DTLS_ALERT_ACCESS_DENIED = 49, /* access_denied */
DTLS_ALERT_DECODE_ERROR = 50, /* decode_error */
DTLS_ALERT_DECRYPT_ERROR = 51, /* decrypt_error */
DTLS_ALERT_PROTOCOL_VERSION = 70, /* protocol_version */
DTLS_ALERT_INSUFFICIENT_SECURITY = 71, /* insufficient_security */
DTLS_ALERT_INTERNAL_ERROR = 80, /* internal_error */
DTLS_ALERT_USER_CANCELED = 90, /* user_canceled */
DTLS_ALERT_NO_RENEGOTIATION = 100, /* no_renegotiation */
DTLS_ALERT_UNSUPPORTED_EXTENSION = 110 /* unsupported_extension */
} dtls_alert_t;
#define DTLS_EVENT_CONNECT 0x01DC /**< initiated handshake */
#define DTLS_EVENT_CONNECTED 0x01DE /**< handshake or re-negotiation
* has finished */
#define DTLS_EVENT_RENEGOTIATE 0x01DF /**< re-negotiation has started */
static inline int
dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
{
return -((level << 8) | desc);
}
static inline int
dtls_alert_fatal_create(dtls_alert_t desc)
{
return dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, desc);
}
/**
* Test, if error code represents an alert.
*
* \param err error code
* \return 0 (false), if not, not 0 (true), if it represents an alert.
*/
static inline int
dtls_is_alert(int err)
{
return (err < -(1 << 8) && err > -(3 << 8));
}
#endif /* _DTLS_ALERT_H_ */
@@ -0,0 +1,21 @@
#! /bin/sh -e
srcdir=`dirname "$0"`
GENERATED_FILES="aclocal.m4 ar-lib compile depcomp src/.dirstamp
Makefile aes/Makefile doc/Makefile ecc/Makefile
platform-specific/Makefile sha2/Makefile
tests/Makefile tests/unit-tests/Makefile
config.status configure config.log tinydtls.pc"
GENERATED_DIRS="autom4te.cache src/.deps"
if test "x$1" = "x--clean"; then
rm -f $GENERATED_FILES
rm -rf $GENERATED_DIRS
exit 0
fi
# create fake ar-lib if not present
test -e ar-lib || touch ar-lib
autoreconf --force --install --verbose "$srcdir"
@@ -0,0 +1,303 @@
/*******************************************************************************
*
* Copyright (c) 2011, 2012, 2013, 2014, 2015 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Olaf Bergmann - initial API and implementation
* Hauke Mehrtens - memory optimization, ECC integration
*
*******************************************************************************/
#include <string.h>
#include "tinydtls.h"
#include "global.h"
#include "numeric.h"
#include "ccm.h"
#ifdef HAVE_ASSERT_H
# include <assert.h>
#endif
#define CCM_FLAGS(A,M,L) (((A > 0) << 6) | (((M - 2)/2) << 3) | (L - 1))
#define MASK_L(_L) ((1 << 8 * _L) - 1)
#define SET_COUNTER(A,L,cnt,C) { \
unsigned int i_; \
memset((A) + DTLS_CCM_BLOCKSIZE - (L), 0, (L)); \
(C) = (cnt) & MASK_L(L); \
for (i_ = DTLS_CCM_BLOCKSIZE - 1; (C) && (i_ > (L)); --i_, (C) >>= 8) \
(A)[i_] |= (C) & 0xFF; \
}
static inline void
block0(size_t M, /* number of auth bytes */
size_t L, /* number of bytes to encode message length */
size_t la, /* l(a) octets additional authenticated data */
size_t lm, /* l(m) message length */
const unsigned char nonce[DTLS_CCM_BLOCKSIZE],
unsigned char *result) {
unsigned int i;
result[0] = CCM_FLAGS(la, M, L);
/* copy the nonce */
memcpy(result + 1, nonce, DTLS_CCM_BLOCKSIZE - L - 1);
for (i=0; i < L; i++) {
result[15-i] = lm & 0xff;
lm >>= 8;
}
}
/**
* Creates the CBC-MAC for the additional authentication data that
* is sent in cleartext.
*
* \param ctx The crypto context for the AES encryption.
* \param msg The message starting with the additional authentication data.
* \param la The number of additional authentication bytes in \p msg.
* \param B The input buffer for crypto operations. When this function
* is called, \p B must be initialized with \c B0 (the first
* authentication block.
* \param X The output buffer where the result of the CBC calculation
* is placed.
* \return The result is written to \p X.
*/
static void
add_auth_data(rijndael_ctx *ctx, const unsigned char *msg, uint64_t la,
unsigned char B[DTLS_CCM_BLOCKSIZE],
unsigned char X[DTLS_CCM_BLOCKSIZE]) {
uint64_t i,j;
rijndael_encrypt(ctx, B, X);
memset(B, 0, DTLS_CCM_BLOCKSIZE);
if (!la)
return;
#ifndef WITH_CONTIKI
if (la < 0xFF00) { /* 2^16 - 2^8 */
j = 2;
dtls_int_to_uint16(B, la);
} else if (la <= UINT32_MAX) {
j = 6;
dtls_int_to_uint16(B, 0xFFFE);
dtls_int_to_uint32(B+2, la);
} else {
j = 10;
dtls_int_to_uint16(B, 0xFFFF);
dtls_int_to_uint64(B+2, la);
}
#else /* WITH_CONTIKI */
/* With Contiki, we are building for small devices and thus
* anticipate that the number of additional authentication bytes
* will not exceed 65280 bytes (0xFF00) and we can skip the
* workarounds required for j=6 and j=10 on devices with a word size
* of 32 bits or 64 bits, respectively.
*/
assert(la < 0xFF00);
j = 2;
dtls_int_to_uint16(B, la);
#endif /* WITH_CONTIKI */
i = min(DTLS_CCM_BLOCKSIZE - j, la);
memcpy(B + j, msg, i);
la -= i;
msg += i;
memxor(B, X, DTLS_CCM_BLOCKSIZE);
rijndael_encrypt(ctx, B, X);
while (la > DTLS_CCM_BLOCKSIZE) {
for (i = 0; i < DTLS_CCM_BLOCKSIZE; ++i)
B[i] = X[i] ^ *msg++;
la -= DTLS_CCM_BLOCKSIZE;
rijndael_encrypt(ctx, B, X);
}
if (la) {
memset(B, 0, DTLS_CCM_BLOCKSIZE);
memcpy(B, msg, la);
memxor(B, X, DTLS_CCM_BLOCKSIZE);
rijndael_encrypt(ctx, B, X);
}
}
static inline void
encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
unsigned char *msg, size_t len,
unsigned char A[DTLS_CCM_BLOCKSIZE],
unsigned char S[DTLS_CCM_BLOCKSIZE]) {
static unsigned long counter_tmp;
SET_COUNTER(A, L, counter, counter_tmp);
rijndael_encrypt(ctx, A, S);
memxor(msg, S, len);
}
static inline void
mac(rijndael_ctx *ctx,
unsigned char *msg, size_t len,
unsigned char B[DTLS_CCM_BLOCKSIZE],
unsigned char X[DTLS_CCM_BLOCKSIZE]) {
size_t i;
for (i = 0; i < len; ++i)
B[i] = X[i] ^ msg[i];
rijndael_encrypt(ctx, B, X);
}
long int
dtls_ccm_encrypt_message(rijndael_ctx *ctx, size_t M, size_t L,
const unsigned char nonce[DTLS_CCM_BLOCKSIZE],
unsigned char *msg, size_t lm,
const unsigned char *aad, size_t la) {
size_t i, len;
unsigned long counter_tmp;
unsigned long counter = 1; /* \bug does not work correctly on ia32 when
lm >= 2^16 */
unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */
unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */
unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */
unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */
len = lm; /* save original length */
/* create the initial authentication block B0 */
block0(M, L, la, lm, nonce, B);
add_auth_data(ctx, aad, la, B, X);
/* initialize block template */
A[0] = L-1;
/* copy the nonce */
memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L - 1);
while (lm >= DTLS_CCM_BLOCKSIZE) {
/* calculate MAC */
mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X);
/* encrypt */
encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S);
/* update local pointers */
lm -= DTLS_CCM_BLOCKSIZE;
msg += DTLS_CCM_BLOCKSIZE;
counter++;
}
if (lm) {
/* Calculate MAC. The remainder of B must be padded with zeroes, so
* B is constructed to contain X ^ msg for the first lm bytes (done in
* mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes
* (i.e., we can use memcpy() here).
*/
memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm);
mac(ctx, msg, lm, B, X);
/* encrypt */
encrypt(ctx, L, counter, msg, lm, A, S);
/* update local pointers */
msg += lm;
}
/* calculate S_0 */
SET_COUNTER(A, L, 0, counter_tmp);
rijndael_encrypt(ctx, A, S);
for (i = 0; i < M; ++i)
*msg++ = X[i] ^ S[i];
return len + M;
}
long int
dtls_ccm_decrypt_message(rijndael_ctx *ctx, size_t M, size_t L,
const unsigned char nonce[DTLS_CCM_BLOCKSIZE],
unsigned char *msg, size_t lm,
const unsigned char *aad, size_t la) {
size_t len;
unsigned long counter_tmp;
unsigned long counter = 1; /* \bug does not work correctly on ia32 when
lm >= 2^16 */
unsigned char A[DTLS_CCM_BLOCKSIZE]; /* A_i blocks for encryption input */
unsigned char B[DTLS_CCM_BLOCKSIZE]; /* B_i blocks for CBC-MAC input */
unsigned char S[DTLS_CCM_BLOCKSIZE]; /* S_i = encrypted A_i blocks */
unsigned char X[DTLS_CCM_BLOCKSIZE]; /* X_i = encrypted B_i blocks */
if (lm < M)
goto error;
len = lm; /* save original length */
lm -= M; /* detract MAC size*/
/* create the initial authentication block B0 */
block0(M, L, la, lm, nonce, B);
add_auth_data(ctx, aad, la, B, X);
/* initialize block template */
A[0] = L-1;
/* copy the nonce */
memcpy(A + 1, nonce, DTLS_CCM_BLOCKSIZE - L - 1);
while (lm >= DTLS_CCM_BLOCKSIZE) {
/* decrypt */
encrypt(ctx, L, counter, msg, DTLS_CCM_BLOCKSIZE, A, S);
/* calculate MAC */
mac(ctx, msg, DTLS_CCM_BLOCKSIZE, B, X);
/* update local pointers */
lm -= DTLS_CCM_BLOCKSIZE;
msg += DTLS_CCM_BLOCKSIZE;
counter++;
}
if (lm) {
/* decrypt */
encrypt(ctx, L, counter, msg, lm, A, S);
/* Calculate MAC. Note that msg ends in the MAC so we must
* construct B to contain X ^ msg for the first lm bytes (done in
* mac() and X ^ 0 for the remaining DTLS_CCM_BLOCKSIZE - lm bytes
* (i.e., we can use memcpy() here).
*/
memcpy(B + lm, X + lm, DTLS_CCM_BLOCKSIZE - lm);
mac(ctx, msg, lm, B, X);
/* update local pointers */
msg += lm;
}
/* calculate S_0 */
SET_COUNTER(A, L, 0, counter_tmp);
rijndael_encrypt(ctx, A, S);
memxor(msg, S, M);
/* return length if MAC is valid, otherwise continue with error handling */
if (equals(X, msg, M))
return len - M;
error:
return -1;
}
@@ -0,0 +1,61 @@
/*******************************************************************************
*
* Copyright (c) 2011, 2012, 2013, 2014, 2015 Olaf Bergmann (TZI) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Olaf Bergmann - initial API and implementation
* Hauke Mehrtens - memory optimization, ECC integration
*
*******************************************************************************/
#ifndef _DTLS_CCM_H_
#define _DTLS_CCM_H_
#include "aes/rijndael.h"
/* implementation of Counter Mode CBC-MAC, RFC 3610 */
#define DTLS_CCM_BLOCKSIZE 16 /**< size of hmac blocks */
#define DTLS_CCM_MAX 16 /**< max number of bytes in digest */
#define DTLS_CCM_NONCE_SIZE 12 /**< size of nonce */
/**
* Authenticates and encrypts a message using AES in CCM mode. Please
* see also RFC 3610 for the meaning of \p M, \p L, \p lm and \p la.
*
* \param ctx The initialized rijndael_ctx object to be used for AES operations.
* \param M The number of authentication octets.
* \param L The number of bytes used to encode the message length.
* \param N The nonce value to use. You must provide \c DTLS_CCM_BLOCKSIZE
* nonce octets, although only the first \c 16 - \p L - 1 are used.
* \param msg The message to encrypt. The first \p la octets are additional
* authentication data that will be cleartext. Note that the
* encryption operation modifies the contents of \p msg and adds
* \p M bytes MAC. Therefore, the buffer must be at least
* \p lm + \p M bytes large.
* \param lm The actual length of \p msg.
* \param aad A pointer to the additional authentication data (can be \c NULL if
* \p la is zero).
* \param la The number of additional authentication octets (may be zero).
* \return FIXME
*/
long int
dtls_ccm_encrypt_message(rijndael_ctx *ctx, size_t M, size_t L,
const unsigned char nonce[DTLS_CCM_BLOCKSIZE],
unsigned char *msg, size_t lm,
const unsigned char *aad, size_t la);
long int
dtls_ccm_decrypt_message(rijndael_ctx *ctx, size_t M, size_t L,
const unsigned char nonce[DTLS_CCM_BLOCKSIZE],
unsigned char *msg, size_t lm,
const unsigned char *aad, size_t la);
#endif /* _DTLS_CCM_H_ */
@@ -0,0 +1,153 @@
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
#
# Copyright (c) 2011-2021 Olaf Bergmann (TZI) and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v. 1.0 which accompanies this distribution.
#
# The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
# Olaf Bergmann - initial API and implementation
# Hauke Mehrtens - memory optimization, ECC integration
# Hugo Damer - support for pkg-config
AC_PREREQ([2.65])
AC_INIT([tinydtls], [0.8.6], [], [], [https://projects.eclipse.org/projects/iot.tinydtls])
AC_CONFIG_SRCDIR([dtls.c])
dnl AC_CONFIG_HEADERS([config.h])
AC_PATH_PROG(DOXYGEN, doxygen, [:])
AC_PATH_PROG(ETAGS, etags, [/bin/false])
# Make configure happy
test -e install-sh || touch install-sh
# Checks for programs.
AC_PROG_MAKE_SET
AC_PROG_CC
AC_PROG_RANLIB
m4_ifdef([AM_PROG_AR], [AM_PROG_AR], [AR=ar])
AC_C_BIGENDIAN
CFLAGS="${CFLAGS} -fPIC"
# Adding some default warning options for code QS
# see https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
# and http://www.gnu.org/software/automake/manual/html_node/Flag-Variables-Ordering.html
WARNING_CFLAGS="\
-pedantic \
-Wall \
-Wextra \
-Wformat-security \
-Winline \
-Wmissing-declarations \
-Wmissing-prototypes \
-Wnested-externs \
-Wpointer-arith \
-Wshadow \
-Wstrict-prototypes \
-Wswitch-default \
-Wswitch-enum \
-Wunused \
"
AC_SUBST([WARNING_CFLAGS])
# Checks for libraries.
AC_SEARCH_LIBS([gethostbyname], [nsl])
AC_SEARCH_LIBS([socket], [socket])
AC_ARG_WITH(debug,
[AS_HELP_STRING([--without-debug],[disable all debug output and assertions])],
[CPPFLAGS="${CPPFLAGS} -DNDEBUG"
NDEBUG=1],
[])
AC_ARG_WITH(ecc,
[AS_HELP_STRING([--without-ecc],[disable support for TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8])],
[],
[AC_DEFINE(DTLS_ECC, 1, [Define to 1 if building with ECC support.])
OPT_OBJS="${OPT_OBJS} ecc/ecc.o"
DTLS_ECC=1])
AC_ARG_WITH(psk,
[AS_HELP_STRING([--without-psk],[disable support for TLS_PSK_WITH_AES_128_CCM_8])],
[],
[AC_DEFINE(DTLS_PSK, 1, [Define to 1 if building with PSK support])
DTLS_PSK=1])
# configure options
# __tests__
AC_ARG_ENABLE([tests],
[AS_HELP_STRING([--enable-tests],
[Enable building the binary testsuite [default=no]])],
[build_tests="$enableval"],
[build_tests="no"])
if test "x$build_tests" = "xyes"; then
PKG_CHECK_MODULES([CUNIT],
[cunit],
[have_cunit=yes
AC_DEFINE(HAVE_LIBCUNIT, [1], [Define if the system has libcunit])
AC_DEFINE(TEST_INCLUDE, [1], [Define to include test wrappers for static functions])],
[have_cunit=no])
fi
AC_SUBST(have_cunit)
AC_ARG_ENABLE(shared,
[AS_HELP_STRING([--disable-shared],[disable build of shared library])],
[],
[enable_shared=yes])
if test "$enable_shared" = "yes" ; then
ENABLE_SHARED=1
fi
CPPFLAGS="${CPPFLAGS} -DDTLSv12 -DWITH_SHA256"
OPT_OBJS="${OPT_OBJS} sha2/sha2.o"
AC_SUBST(OPT_OBJS)
AC_SUBST(NDEBUG)
AC_SUBST(DTLS_ECC)
AC_SUBST(DTLS_PSK)
AC_SUBST(ENABLE_SHARED)
AC_SUBST(AR)
# Checks for header files.
AC_CHECK_HEADERS([assert.h arpa/inet.h fcntl.h inttypes.h netdb.h netinet/in.h stddef.h stdint.h stdlib.h string.h strings.h sys/param.h sys/socket.h unistd.h])
AC_CHECK_HEADERS([sys/time.h time.h])
AC_CHECK_HEADERS([sys/types.h sys/stat.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_C_INLINE
AC_TYPE_SIZE_T
AC_CHECK_MEMBER([struct sockaddr_in6.sin6_len],
[AC_DEFINE(HAVE_SOCKADDR_IN6_SIN6_LEN, [1],
[Define to 1 if struct sockaddr_in6 has a member sin6_len.])], [],
[#include <netinet/in.h>])
# Checks for library functions.
AC_CHECK_FUNCS([memset select socket strdup strerror strnlen fls vprintf \
getrandom inet_ntop])
AC_CONFIG_HEADERS([dtls_config.h])
AC_CONFIG_FILES([Makefile
doc/Makefile
doc/Doxyfile
tests/Makefile
tests/unit-tests/Makefile
platform-specific/Makefile
tinydtls.pc
sha2/Makefile
aes/Makefile
ecc/Makefile])
AC_OUTPUT

Some files were not shown because too many files have changed in this diff Show More