├── .appveyor.yml ├── .gitignore ├── .travis.yml ├── .travis ├── install-nodejs.sh └── install-swig.sh ├── LICENSE.md ├── README.md ├── SConscript ├── SConstruct ├── application ├── SConscript ├── include │ └── my_app.h └── src │ └── my_app.c ├── asan.supp ├── doc ├── Building-and-Running.dox ├── Data-Series.dox ├── Doxyfile ├── Doxyfile_dev ├── Examples.dox ├── Introduction.dox ├── Mesh-Network.dox ├── Message-Types-and-Flows.dox ├── Retained-Publications.dox ├── Security.dox ├── Topic-Strings.dox ├── Tutorials.dox ├── html │ └── footer.html ├── images │ └── dps_mesh.jpg └── tutorial │ ├── certs │ └── create_certs │ ├── hello_world.dox │ ├── link.dox │ ├── security.dox │ ├── tutorial.c │ └── tutorial_certs.c ├── dps-micro ├── .gitignore ├── SConscript ├── SConstruct ├── dps_shared.def ├── ext │ ├── .gitignore │ ├── SConscript.mbedtls │ ├── mbedtls_config.h │ └── mbedtls_config_zephyr.h ├── include │ └── dps │ │ ├── dbg.h │ │ ├── discovery.h │ │ ├── dps.h │ │ ├── err.h │ │ ├── keystore.h │ │ ├── private │ │ ├── ack.h │ │ ├── bitvec.h │ │ ├── cbor.h │ │ ├── coap.h │ │ ├── cose.h │ │ ├── crypto.h │ │ ├── dps.h │ │ ├── dtls.h │ │ ├── ec.h │ │ ├── gcm.h │ │ ├── hkdf.h │ │ ├── io_buf.h │ │ ├── keywrap.h │ │ ├── malloc.h │ │ ├── mbedtls.h │ │ ├── network.h │ │ ├── node.h │ │ ├── pub.h │ │ ├── sha2.h │ │ ├── sub.h │ │ ├── timer.h │ │ └── topics.h │ │ ├── targets.h │ │ └── uuid.h ├── src │ ├── ack.c │ ├── bitvec.c │ ├── cbor.c │ ├── coap.c │ ├── cose.c │ ├── discovery.c │ ├── dps.c │ ├── dtls.c │ ├── ec.c │ ├── err.c │ ├── gcm.c │ ├── hkdf.c │ ├── io_buf.c │ ├── keystore.c │ ├── keywrap.c │ ├── mbedtls.c │ ├── posix │ │ ├── dbg.c │ │ ├── malloc.c │ │ ├── network.c │ │ └── timer.c │ ├── pub.c │ ├── sha2.c │ ├── sub.c │ ├── topics.c │ ├── uuid.c │ ├── win32 │ │ ├── dbg.c │ │ ├── malloc.c │ │ ├── network.c │ │ └── timer.c │ └── zephyr │ │ ├── dbg.c │ │ ├── entropy.c │ │ ├── malloc.c │ │ └── network.c ├── test │ ├── bitvec_unit_test.c │ ├── discoverable.c │ ├── keys.c │ ├── keys.h │ ├── mcast_unit_test.c │ ├── pub_unit_test.c │ ├── serialize.c │ ├── sub_unit_test.c │ ├── test.h │ ├── topic_match.c │ └── topics_unit_test.c └── zephyr │ ├── CMakeLists.txt │ ├── config_stm.bat │ ├── prj.conf │ └── sample.yaml ├── dps_ns3.pc.in ├── dps_shared.def ├── examples ├── common.c ├── common.h ├── keys.c ├── keys.h ├── pub_many.c ├── publisher.c ├── reg_pubs.c ├── reg_subs.c ├── registry.c └── subscriber.c ├── ext ├── 0001-DPS.patch ├── SConscript.intel-ipsec-mb ├── SConscript.libuv ├── SConscript.mbedtls ├── SConscript.safestring ├── mbedtls_config.h └── mbedtls_sha512_process_alt.c ├── go ├── README.md ├── dps.go ├── examples │ ├── keys │ │ └── keys.go │ ├── simple_pub │ │ └── simple_pub.go │ ├── simple_pub_ks │ │ └── simple_pub_ks.go │ ├── simple_sub │ │ └── simple_sub.go │ └── simple_sub_ks │ │ └── simple_sub_ks.go └── test │ ├── perf_publisher │ └── perf_publisher.go │ └── perf_subscriber │ └── perf_subscriber.go ├── inc └── dps │ ├── dbg.h │ ├── discovery.h │ ├── dispatcher.h │ ├── dps.h │ ├── err.h │ ├── event.h │ ├── json.h │ ├── private │ ├── cbor.h │ ├── dps.h │ └── network.h │ ├── registration.h │ ├── synchronous.h │ └── uuid.h ├── js_scripts ├── README.md ├── simple_pub.js ├── simple_pub_ks.js ├── simple_sub.js └── simple_sub_ks.js ├── libdps_shared.map ├── py_scripts ├── README.md ├── late_sub.py ├── retained_pub.py ├── simple_pub.py ├── simple_pub_ks.py ├── simple_sub.py ├── simple_sub_ks.py └── subs_tree.py ├── site_scons ├── site_init.py ├── site_tools │ └── Make.py └── swig_doc.py ├── src ├── ack.c ├── ack.h ├── bitvec.c ├── bitvec.h ├── cbor.c ├── coap.c ├── coap.h ├── compat.h ├── cose.c ├── cose.h ├── crypto.h ├── dbg.c ├── discovery.c ├── dispatcher.c ├── dps.c ├── dtls │ └── network.c ├── ec.c ├── ec.h ├── err.c ├── event.c ├── fuzzer │ └── network.c ├── gcm.c ├── gcm.h ├── history.c ├── history.h ├── hkdf.c ├── hkdf.h ├── json.c ├── keystore.c ├── keywrap.c ├── keywrap.h ├── mbedtls.c ├── mbedtls.h ├── multicast │ └── network.c ├── network.c ├── node.h ├── pipe │ └── network.c ├── pub.c ├── pub.h ├── queue.c ├── queue.h ├── registration.c ├── resolver.c ├── resolver.h ├── sha2.c ├── sha2.h ├── sub.c ├── sub.h ├── synchronous.c ├── tcp │ └── network.c ├── topics.c ├── topics.h ├── udp │ └── network.c ├── uuid.c ├── uv_extra.c └── uv_extra.h ├── swig ├── dps.i ├── js │ ├── dps_impl.i │ └── dps_map.i └── py │ ├── dps_impl.i │ └── dps_map.i ├── test ├── cbor_fuzzer.c ├── cbortest.c ├── cosetest.c ├── countvec.c ├── discover.c ├── dtls_fuzzer.c ├── hist_unit.c ├── jsontest.c ├── keys.c ├── keys.h ├── keystoretest.c ├── link.c ├── link_drop.c ├── ll_unit.c ├── make_mesh.c ├── mesh_stress.c ├── meshes │ ├── box.txt │ ├── double.txt │ ├── dumbell.txt │ ├── hot_mesh.txt │ ├── loop10.txt │ ├── maxmesh16.txt │ ├── self.txt │ └── simple.txt ├── multicast_receive_fuzzer.c ├── net_receive_fuzzer.c ├── node.c ├── packtest.c ├── perf │ ├── publisher.c │ └── subscriber.c ├── publish.c ├── pubsub.c ├── rle_compression.c ├── test.c ├── test.h ├── topic_match.c ├── uuid.c └── version.c ├── test_scripts ├── auth.py ├── chain_test.py ├── common.py ├── discover.py ├── e2esec.py ├── fanout.py ├── fuzzer_check.py ├── hot_mesh.py ├── link_drop.py ├── loop25.py ├── loop3.py ├── mesh_stress.py ├── pub100.py ├── reg1.py ├── retained_py.py ├── run.py ├── simple_go_ks_test.py ├── simple_go_test.py ├── simple_js_ks_test.py ├── simple_js_test.py ├── simple_py_ks_test.py ├── simple_py_test.py ├── simple_test.py ├── topic_match.py ├── tree0.py ├── tree1.py ├── tree2.py ├── tutorial.py └── versioning.py ├── tools ├── README.md ├── asan_addr2line ├── corpus_pcap ├── coverity_scan ├── docs_upload ├── dps_graph.pl ├── dtls_fuzzer ├── exports ├── exports_gcc ├── fuzzer_cov ├── fuzzer_run ├── graph_nodes.pl └── showmesh ├── tox.ini └── yocto └── recipes-connectivity └── dps └── dps_git.bb /.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 0.9.0+{build} 2 | 3 | image: 4 | - Visual Studio 2017 5 | 6 | install: 7 | - cinst swig 8 | - curl -L http://prdownloads.sourceforge.net/scons/scons-3.0.1.zip --output scons-3.0.1.zip 9 | - 7z x scons-3.0.1.zip 10 | - cd scons-3.0.1 11 | - python setup.py install 12 | 13 | environment: 14 | matrix: 15 | - VARIANT: debug 16 | TRANSPORT: udp 17 | - VARIANT: debug 18 | TRANSPORT: tcp 19 | - VARIANT: debug 20 | TRANSPORT: dtls 21 | - VARIANT: release 22 | TRANSPORT: udp 23 | - VARIANT: release 24 | TRANSPORT: tcp 25 | - VARIANT: release 26 | TRANSPORT: dtls 27 | 28 | build_script: 29 | - cd C:\projects\dps-for-iot 30 | - scons variant=%VARIANT% transport=%TRANSPORT% PYTHON_PATH=C:\Python27-x64 SWIG=C:\ProgramData\chocolatey\bin\swig.exe 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | *.o 3 | build/* 4 | dps_ns3.pc 5 | ext 6 | core.* 7 | *~ 8 | out 9 | *.pyc 10 | *.pdb 11 | go/bin/* 12 | go/pkg/* 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | language: c 4 | 5 | compiler: 6 | - clang 7 | - gcc 8 | 9 | env: 10 | - VARIANT=debug TRANSPORT=udp BINDINGS=all ASAN=yes FSAN=no 11 | - VARIANT=debug TRANSPORT=tcp BINDINGS=all ASAN=yes FSAN=no 12 | - VARIANT=debug TRANSPORT=dtls BINDINGS=all ASAN=yes FSAN=no 13 | - VARIANT=debug TRANSPORT=pipe BINDINGS=all ASAN=yes FSAN=no 14 | - VARIANT=release TRANSPORT=udp BINDINGS=all ASAN=yes FSAN=no 15 | - VARIANT=release TRANSPORT=tcp BINDINGS=all ASAN=yes FSAN=no 16 | - VARIANT=release TRANSPORT=dtls BINDINGS=all ASAN=yes FSAN=no 17 | - VARIANT=release TRANSPORT=dtls BINDINGS=python,nodejs ASAN=yes FSAN=yes 18 | - VARIANT=release TRANSPORT=pipe BINDINGS=all ASAN=yes FSAN=no 19 | - VARIANT=release TRANSPORT=fuzzer BINDINGS=python,nodejs ASAN=yes FSAN=yes 20 | matrix: 21 | exclude: 22 | - compiler: clang 23 | - compiler: gcc 24 | env: VARIANT=release TRANSPORT=dtls BINDINGS=python,nodejs ASAN=yes FSAN=yes 25 | - compiler: gcc 26 | env: VARIANT=release TRANSPORT=fuzzer BINDINGS=python,nodejs ASAN=yes FSAN=yes 27 | include: 28 | - compiler: clang 29 | env: VARIANT=release TRANSPORT=dtls BINDINGS=python,nodejs ASAN=yes FSAN=yes 30 | - compiler: clang 31 | env: VARIANT=release TRANSPORT=fuzzer BINDINGS=python,nodejs ASAN=yes FSAN=yes 32 | 33 | addons: 34 | apt: 35 | sources: 36 | - ubuntu-toolchain-r-test 37 | - llvm-toolchain-xenial-6.0 38 | packages: 39 | - clang-6.0 40 | - doxygen 41 | - g++-7 42 | - nasm 43 | - scons 44 | - zlib1g-dev 45 | 46 | before_install: 47 | - "[ $CC = gcc ] && export CC=gcc-7 CXX=g++-7 || true" 48 | - "[ $CC = clang ] && export CC=clang-6.0 CXX=clang++-6.0 || true" 49 | 50 | install: 51 | - ./.travis/install-swig.sh 52 | - ./.travis/install-nodejs.sh 53 | - pip install --user cryptography 54 | - pip install --user pexpect 55 | 56 | script: 57 | - scons CC=$CC CXX=$CXX variant=$VARIANT transport=$TRANSPORT bindings=$BINDINGS asan=$ASAN ubsan=yes fsan=$FSAN; 58 | - ./test_scripts/run.py -d; 59 | -------------------------------------------------------------------------------- /.travis/install-nodejs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -ex 3 | curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - 4 | sudo apt-get install -y nodejs 5 | -------------------------------------------------------------------------------- /.travis/install-swig.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -ex 3 | git clone https://github.com/swig/swig.git swig/swig 4 | cd swig/swig 5 | git checkout rel-3.0.12 6 | wget -O 968.patch https://github.com/swig/swig/pull/968.patch 7 | git am 968.patch 8 | ./autogen.sh 9 | ./configure --prefix=/usr 10 | make -j 4 11 | sudo make install 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DISCONTINUATION OF PROJECT 2 | 3 | This project will no longer be maintained by Intel. 4 | 5 | Intel has ceased development and contributions including, but not limited to, maintenance, bug fixes, new releases, or updates, to this project. 6 | 7 | Intel no longer accepts patches to this project. 8 | 9 | If you have an ongoing need to use this project, are interested in independently developing it, or would like to maintain patches for the open source software community, please create your own fork of this project. 10 | 11 | Contact: webadmin@linux.intel.com 12 | # Distributed Publish & Subscribe for IoT 13 | 14 | [![Build Status](https://travis-ci.org/intel/dps-for-iot.svg?branch=master)](https://travis-ci.org/intel/dps-for-iot) 15 | 16 | Distributed Publish & Subscribe for IoT (DPS) is a new protocol that 17 | implements the publish/subscribe (pub/sub) communication pattern. 18 | 19 | Devices or applications running the protocol form a dynamic 20 | multiply-connected mesh where each node functions as a message 21 | router. The protocol is light-weight and amenable to implementation on 22 | very small devices such as sensors that primarily publish data. The 23 | architecture is well suited for applications that leverage edge 24 | computing in combination with cloud-based analytics. 25 | 26 | ## [Building and Running](https://intel.github.io/dps-for-iot/building-and-running.html) 27 | 28 | ## [Documentation](https://intel.github.io/dps-for-iot) 29 | -------------------------------------------------------------------------------- /application/SConscript: -------------------------------------------------------------------------------- 1 | import os 2 | import string 3 | Import(['env', 'lib_dps']) 4 | 5 | platform = env['PLATFORM'] 6 | 7 | app_env = env.Clone() 8 | if app_env['PLATFORM'] == 'win32': 9 | app_env.Append(CPPDEFINES = ['_CRT_SECURE_NO_WARNINGS']) 10 | 11 | # Add local include directory to the include path 12 | app_env.Append(CPPPATH=['./include']) 13 | 14 | # Libraries will be statically linked 15 | app_env['LIBS'] = [lib_dps] + env['DPS_LIBS'] 16 | 17 | # Source files 18 | app_srcs = Glob('src/*.c') 19 | 20 | # Application depends on the libraries 21 | Depends(app_srcs, app_env['LIBS']) 22 | 23 | # Build the executable 24 | app_program = app_env.Program(app_srcs) 25 | 26 | # Install the executable in the bin directory 27 | app_env.Install('#/' + app_env['application'] + '/bin', app_program) 28 | -------------------------------------------------------------------------------- /application/include/my_app.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _MY_APP_H 24 | #define _MY_APP_H 25 | 26 | #include 27 | 28 | #ifdef __cplusplus 29 | extern "C" { 30 | #endif 31 | 32 | DPS_Node* node; 33 | 34 | #ifdef __cplusplus 35 | } 36 | #endif 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /application/src/my_app.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "my_app.h" 4 | 5 | int main(int argc, char** argv) 6 | { 7 | DPS_Status ret; 8 | 9 | node = DPS_CreateNode("/", NULL, 0); 10 | if (!node) { 11 | DPS_ERRPRINT("Could not create node - exiting\n"); 12 | return 1; 13 | } 14 | ret = DPS_StartNode(node, DPS_MCAST_PUB_ENABLE_SEND, NULL); 15 | if (ret != DPS_OK) { 16 | DPS_ERRPRINT("DPS_StartNode failed: %s\n", DPS_ErrTxt(ret)); 17 | return 1; 18 | } 19 | DPS_DestroyNode(node, NULL, NULL); 20 | return 0; 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /asan.supp: -------------------------------------------------------------------------------- 1 | leak:libpython* 2 | leak:python2.7* 3 | -------------------------------------------------------------------------------- /doc/Data-Series.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @page data-series Data Series 3 | 4 | DPS has built-in support for data series. In addition to topic 5 | strings, every publication has a UUID and serial number. Publications 6 | with same UUID (and topic strings) form a series, the serial number is 7 | incremented each time the publication is sent to the network. The UUID 8 | and serial number are available to the receiving subscribers. 9 | */ 10 | -------------------------------------------------------------------------------- /doc/Examples.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @example publisher.c 3 | 4 | This application shows how to initialize a DPS node, create a 5 | publication and send it. It supports IP multicast or publication 6 | to a specific host and port number over the configured transport 7 | (udp, tcp, or dtls). Optionally the application will request 8 | acknowledgements from the receiving subscribers. 9 | @code 10 | publisher a/b/c "hello world" 11 | @endcode 12 | sends a single publication to the topic string @b a/b/c and exits. 13 | */ 14 | 15 | /** 16 | @example subscriber.c 17 | 18 | This application is the subscription counterpart to publisher.c, it 19 | creates a subscription and either listens for multicast 20 | publications or links another node to form a subscriber mesh. With 21 | the following commands the subscriber application listens for 22 | multicast subscriptions that match the specified topic string. 23 | @code 24 | subscriber a/b/c 25 | subscriber a/+/c 26 | subscriber a/# 27 | @endcode 28 | In the examples above the subscriptions all match @b a/b/c. On 29 | receiving a matching publication the application prints out the 30 | subscription topic string that was matched and all the topic 31 | strings that were in the publication, if the publication had a 32 | payload that is printed also. 33 | */ 34 | 35 | /** 36 | @example registry.c 37 | 38 | This applications uses DPS to implement an experimental discovery 39 | service. There are two companion applications, @em reg_pubs and @em 40 | reg_subs described below that make use of this service to find and 41 | join a mesh identified by a @em tenant topic string. 42 | */ 43 | 44 | /** 45 | @example reg_pubs.c 46 | 47 | This application is similar to @em publisher but it uses the @em 48 | registry service to find other nodes to link with. The result is a 49 | randomly multiply-connected mesh. 50 | */ 51 | 52 | /** 53 | @example reg_subs.c 54 | 55 | This application is subscription counterpart to @em reg_subs, it 56 | uses the @em registry service to find other node and links into the 57 | mesh. 58 | */ 59 | 60 | /** 61 | @example pub_many.c 62 | 63 | This is application sends a series of publications as fast as they 64 | are acknowledged. It can be used with the @em subscriber 65 | application. 66 | */ 67 | -------------------------------------------------------------------------------- /doc/Retained-Publications.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @page retained-publications Retained Publications 3 | 4 | If there are no subscribers for the topic strings in a publication the 5 | publication will be discarded, typically at the first hop. There are 6 | use cases where it is desirable for a publication to be held for later 7 | delivery. MQTT has a feature that supports this use case; if an MQTT 8 | publication is flagged as "retained" the MQTT broker holds onto the 9 | publication until a subscriber is available to consume the 10 | message. DPS implements a similar feature where a TTL (time-to-live) 11 | can be set on a publication which is then held for delivery up until 12 | the time the TTL expires. For a publication to be retained it must 13 | match a subscription somewhere in the network, this allows specific 14 | nodes to take on responsibility for retaining matching publications. A 15 | retained publication can be replaced if the publisher sends a new 16 | publications having the same UUID but a later serial number. A 17 | retained publication can be explicitly expired by sending a new 18 | publication with the same UUID and a negative TTL. 19 | 20 | Retained publications provide support for sleepy nodes, that is, nodes 21 | that are only periodically active on the network. For example, a 22 | wireless sensor node publishes a telemetry reading in the payload of a 23 | retained publication with a ten minute TTL then drops into low power 24 | mode waking within ten to deliver the next reading. The most recent 25 | telemetry will be available to subscribers no matter when they join 26 | the network. Similarly a sleepy subscriber can periodically connect to 27 | the network to receive publications updates. 28 | */ 29 | -------------------------------------------------------------------------------- /doc/Topic-Strings.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @page topic-strings Topic Strings 3 | 4 | DPS like other pub/sub protocols expresses publications and 5 | subscriptions as structured text strings called topic strings. A topic 6 | string is a sequence of substrings delineated by a standalone 7 | separator character. In DPS almost any character or set of characters 8 | the publisher and subscriber agree on can be used as a separator. A 9 | publication matches a subscription if the substrings and separators in 10 | the publication are the same as the substrings and separators in the 11 | publication. Subscription topic strings can also include wildcard 12 | characters as described below. These are all valid publication topic 13 | strings: 14 | 15 | @verbatim 16 | foo/bar 17 | x,y,z 18 | 1.2.3 19 | a/b/c?val=5 20 | @endverbatim 21 | 22 | In the last example @c /, @c ?, and @c = are separators. Separators must 23 | standalone, two or more consecutive separators are 24 | disallowed. Subscription topics strings have the same form as 25 | publication topics strings but can include wild-card characters. DPS 26 | uses the same wildcard characters as MQTT with the same meanings: the 27 | plus sign @c + wild card matches to any substring in the same position; 28 | the hash or pound sign @c # matches any number of trailing 29 | substrings. In DPS @c + and @c # are currently the only characters that 30 | are reserved. These are some valid wild-carded subscription topic 31 | strings: 32 | 33 | @verbatim 34 | +/bar 35 | x,+,z 36 | 1.# 37 | a/b/c?val=+ 38 | @endverbatim 39 | 40 | In MQTT and other pub/sub protocols a subscription or publication is a 41 | single topic string. A unique feature of DPS is that subscriptions and 42 | publications can have multiple topic strings. A subscription with more 43 | than one topic string will only match publications that have matching 44 | topic strings for all of topic strings in the subscription. As an 45 | example of how this might be used consider a set of devices that 46 | publish a topic string describing device type and a topic string 47 | describing the physical location of the device. An application could 48 | subscribe to all devices at a specific location by only specifying the 49 | location topic string, all devices of a specific type by only 50 | specifying the device type, or home in on a device with a specific 51 | type at specific location by using both topic strings in the same 52 | subscription. Another unique feature of DPS is that publisher control 53 | over the kinds of wild-card matches a subscriber is permitted to 54 | use. For example, a publisher can decide that wild-card matches must 55 | fully specify at least the first N elements in order to match. This 56 | offers a publisher control over wide-open wildcard subscriptions such 57 | as @c +/#, the most generic form allowed by DPS, that will match any 58 | publication with two or more elements. 59 | */ 60 | -------------------------------------------------------------------------------- /doc/Tutorials.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @page tutorials Tutorials 3 | 4 | @details 5 | The tutorials provide an introduction into the DPS APIs. It's 6 | recommended they be read in the order below and assumes some 7 | familiarity with pub/sub terminology. 8 | 9 | For compactness, the tutorials use the @c a/b/c/d topic string, 10 | where @c a, @c b, @c c, and @c d are the levels and @c / is the 11 | level separator, and strings for payload data. A real application 12 | would likely use more meaningful topic strings and structured 13 | payloads. 14 | 15 | - @subpage tutorials-hello-world 16 | - @subpage tutorials-link 17 | - @subpage tutorials-security 18 | 19 | @see @ref index, @ref topic-strings, @ref mesh-network, @ref security 20 | */ 21 | -------------------------------------------------------------------------------- /doc/html/footer.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /doc/images/dps_mesh.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/dps-for-iot/b92a83660427bcbe1482b75cf01e9d7ec000ca0d/doc/images/dps_mesh.jpg -------------------------------------------------------------------------------- /doc/tutorial/certs/create_certs: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # The output of this script is a C source file containing the 4 | # certificates needed for the tutorial. 5 | # 6 | 7 | CURVE=secp521r1 8 | SHA=sha512 9 | 10 | # 11 | # Create the certificate authority. 12 | # 13 | CA_N="Tutorial Certificate Authority" 14 | CA_NAME=${CA_N// /_} 15 | openssl ecparam -name $CURVE -genkey -out $CA_NAME-key.pem 16 | openssl req -new -x509 -key $CA_NAME-key.pem -nodes -subj "/C=US/O=DPS/CN=$CA_N" -out $CA_NAME-cert.pem -days 3650 17 | 18 | echo "const char* CA_CERTIFICATE =" 19 | cat $CA_NAME-cert.pem | sed 's/^/ "/' | sed 's/$/\\r\\n"/' | sed '$s/$/;/' 20 | 21 | # 22 | # Create a certificate, signed by the certificate authority, for each 23 | # name specified on the command line. 24 | # 25 | echo "const Certificate CERTIFICATES[] = {" 26 | 27 | for N in "$@"; do 28 | NAME=${N// /_} 29 | 30 | openssl ecparam -name $CURVE -genkey -out $NAME-key.pem 31 | openssl req -new -key $NAME-key.pem -nodes -subj "/C=US/O=DPS/CN=$N" -out $NAME.csr 32 | openssl x509 -req -in $NAME.csr -CA $CA_NAME-cert.pem -CAkey $CA_NAME-key.pem -CAcreateserial -out $NAME-cert.pem -days 3650 -$SHA 33 | openssl ec -aes-256-cbc -in $NAME-key.pem -passout "pass:$N Password" -out $NAME-key.pem 34 | 35 | echo " {" 36 | echo " BYTE_STR(\"$N\")," 37 | echo " {" 38 | echo " DPS_KEY_EC_CERT," 39 | echo " {" 40 | echo " .cert = {" 41 | cat $NAME-cert.pem | sed 's/^/ "/' | sed 's/$/\\r\\n"/' | sed '$s/$/,/' 42 | cat $NAME-key.pem | sed 's/^/ "/' | sed 's/$/\\r\\n"/' | sed '$s/$/,/' 43 | echo " \"$N Password\"" 44 | echo " }" 45 | echo " }" 46 | echo " }" 47 | echo " }," 48 | done 49 | 50 | echo " {" 51 | echo " { NULL, 0 }, { DPS_KEY_EC_CERT, { .cert = { NULL, NULL, NULL } } }" 52 | echo " }" 53 | echo "};" 54 | 55 | # 56 | # Create a certificate for protecting the payload. 57 | # 58 | N="Tutorial Asymmetric Key" 59 | NAME=${N// /_} 60 | 61 | openssl ecparam -name $CURVE -genkey -out $NAME-key.pem 62 | openssl req -new -key $NAME-key.pem -nodes -subj "/C=US/O=DPS/CN=$N" -out $NAME.csr 63 | openssl x509 -req -in $NAME.csr -CA $CA_NAME-cert.pem -CAkey $CA_NAME-key.pem -CAcreateserial -out $NAME-cert.pem -days 3650 -$SHA 64 | openssl ec -aes-256-cbc -in $NAME-key.pem -passout "pass:$N Password" -out $NAME-key.pem 65 | 66 | echo "const DPS_Key ASYMMETRIC_KEY = {" 67 | echo " DPS_KEY_EC_CERT," 68 | echo " {" 69 | echo " .cert = {" 70 | cat $NAME-cert.pem | sed 's/^/ "/' | sed 's/$/\\r\\n"/' | sed '$s/$/,/' 71 | cat $NAME-key.pem | sed 's/^/ "/' | sed 's/$/\\r\\n"/' | sed '$s/$/,/' 72 | echo " \"$N Password\"" 73 | echo " }" 74 | echo " }" 75 | echo "};" 76 | -------------------------------------------------------------------------------- /doc/tutorial/link.dox: -------------------------------------------------------------------------------- 1 | /** 2 | @page tutorials-link Building a DPS network 3 | @tableofcontents 4 | 5 | @details 6 | The @ref tutorials-hello-world tutorial showed how to build a simple 7 | multicast publisher and subscriber network. This tutorial will 8 | show how to use the link functionality of DPS to create more 9 | complex networks that can span subnets. 10 | 11 | As before, we need to create nodes for the publisher and subscriber 12 | using @link creating-a-node DPS_CreateNode() @endlink. But this 13 | time we will create a third type of node that is neither a 14 | publisher or subscriber that will forward publications and 15 | subscriptions between the publisher and subscriber nodes. 16 | 17 | Note that a third node is not strictly necessary. It is possible to 18 | use the same mechanisms described below to link the publisher and 19 | subscriber nodes. 20 | 21 | @section starting-a-unicast-node Starting a node 22 | @snippet tutorial.c Starting a unicast node 23 | 24 | The first thing we will do is disable multicast sending and 25 | receiving for our three nodes by using @ref DPS_MCAST_PUB_DISABLED for 26 | the @c mcastPub parameter of DPS_StartNode(). All publications and 27 | subscriptions will go through the forwarding node. 28 | 29 | The second thing we do is specify the @c listenAddr parameter to 30 | DPS_StartNode(). In this instance we bind the node to all available 31 | interfaces at the port provided. A port value of zero lets DPS assign 32 | an ephemeral listening port. A value of non-zero requests a specific 33 | port. 34 | 35 | The last thing we do is get the port DPS has chosen with 36 | DPS_GetListenAddress(). This will be used by the subscriber and 37 | publisher to link to the forwarding node. 38 | 39 | @section linking Linking to a node 40 | @snippet tutorial.c Linking to a node 41 | 42 | Now that we know the host (@c localhost in this example) and 43 | listening port of the forwarding node, we can call DPS_Link() to 44 | create the link from the subscriber and publisher to the forwarding 45 | node. 46 | 47 | @snippet tutorial.c Linking complete 48 | 49 | The link is now complete and we can proceed with @link 50 | receiving-a-publication subscribing @endlink or @link 51 | sending-a-publication publishing @endlink as before. 52 | 53 | @note The link complete callback is dispatched from the @c 54 | DPS_Node's thread. 55 | 56 | @see DPS_Unlink(), DPS_LinkTo(), DPS_UnlinkFrom() 57 | */ 58 | -------------------------------------------------------------------------------- /dps-micro/.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | !.gitignore 3 | build 4 | ext/lib 5 | ext/mbedtls 6 | *.pdb 7 | -------------------------------------------------------------------------------- /dps-micro/dps_shared.def: -------------------------------------------------------------------------------- 1 | LIBRARY dps_shared 2 | 3 | EXPORTS 4 | 5 | DPS_Debug 6 | DPS_ErrTxt 7 | -------------------------------------------------------------------------------- /dps-micro/ext/.gitignore: -------------------------------------------------------------------------------- 1 | src 2 | tmp 3 | -------------------------------------------------------------------------------- /dps-micro/ext/SConscript.mbedtls: -------------------------------------------------------------------------------- 1 | import os 2 | Import(['extEnv']) 3 | 4 | platform = extEnv['PLATFORM'] 5 | 6 | # Pull down mbedtls from github and build the library 7 | 8 | mtenv = extEnv.Clone() 9 | 10 | git = mtenv.Command('./mbedtls/.git', None, 11 | ['git clone -n https://github.com/ARMmbed/mbedtls ext/mbedtls']) 12 | 13 | dep = mtenv.Command('./mbedtls/Makefile', git, 14 | ['git fetch', 'git checkout -q tags/mbedtls-2.16.0'], 15 | chdir = 'ext/mbedtls') 16 | 17 | mtenv.Append(CPPPATH = ['.', './mbedtls/include/',]) 18 | mtenv.Append(CPPDEFINES = ['MBEDTLS_USER_CONFIG_FILE=\\"mbedtls_config.h\\"',]) 19 | 20 | sources = [ 21 | './mbedtls/library/aes.c', 22 | './mbedtls/library/aesni.c', 23 | './mbedtls/library/asn1write.c', 24 | './mbedtls/library/asn1parse.c', 25 | './mbedtls/library/base64.c', 26 | './mbedtls/library/bignum.c', 27 | './mbedtls/library/cipher.c', 28 | './mbedtls/library/cipher_wrap.c', 29 | './mbedtls/library/ctr_drbg.c', 30 | './mbedtls/library/debug.c', 31 | './mbedtls/library/ecdh.c', 32 | './mbedtls/library/ecdsa.c', 33 | './mbedtls/library/ecp.c', 34 | './mbedtls/library/ecp_curves.c', 35 | './mbedtls/library/entropy.c', 36 | './mbedtls/library/entropy_poll.c', 37 | './mbedtls/library/error.c', 38 | './mbedtls/library/gcm.c', 39 | './mbedtls/library/hkdf.c', 40 | './mbedtls/library/hmac_drbg.c', 41 | './mbedtls/library/md.c', 42 | './mbedtls/library/md_wrap.c', 43 | './mbedtls/library/md5.c', 44 | './mbedtls/library/nist_kw.c', 45 | './mbedtls/library/oid.c', 46 | './mbedtls/library/pem.c', 47 | './mbedtls/library/pk.c', 48 | './mbedtls/library/pk_wrap.c', 49 | './mbedtls/library/pkparse.c', 50 | './mbedtls/library/platform.c', 51 | './mbedtls/library/platform_util.c', 52 | './mbedtls/library/sha256.c', 53 | './mbedtls/library/sha512.c', 54 | './mbedtls/library/timing.c', 55 | './mbedtls/library/x509.c', 56 | './mbedtls/library/x509_crt.c', 57 | ] 58 | 59 | sources += [ 60 | './mbedtls/library/ssl_cache.c', 61 | './mbedtls/library/ssl_ciphersuites.c', 62 | './mbedtls/library/ssl_cli.c', 63 | './mbedtls/library/ssl_cookie.c', 64 | './mbedtls/library/ssl_srv.c', 65 | './mbedtls/library/ssl_tls.c', 66 | ] 67 | 68 | objects = mtenv.Object(sources) 69 | 70 | Depends(sources, dep) 71 | Depends(objects, './mbedtls_config.h') 72 | 73 | libs = [mtenv.Library('lib/libmbedtls', objects)] 74 | Return('libs') 75 | -------------------------------------------------------------------------------- /dps-micro/ext/mbedtls_config.h: -------------------------------------------------------------------------------- 1 | /* Use config file, to replace mbed defaults. It is set during 2 | * compilation with MBEDTLS_USER_CONFIG_FILE environment variable. */ 3 | 4 | #define MBEDTLS_DEBUG_C 5 | 6 | #define MBEDTLS_DEPRECATED_REMOVED 7 | #define MBEDTLS_NIST_KW_C 8 | 9 | #undef MBEDTLS_ARC4_C 10 | #undef MBEDTLS_BLOWFISH_C 11 | #undef MBEDTLS_CAMELLIA_C 12 | #undef MBEDTLS_CCM_C 13 | #undef MBEDTLS_CHACHA20_C 14 | #undef MBEDTLS_CHACHAPOLY_C 15 | #undef MBEDTLS_CIPHER_MODE_OFB 16 | #undef MBEDTLS_CIPHER_MODE_XTS 17 | #undef MBEDTLS_DES_C 18 | #undef MBEDTLS_DHM_C 19 | #undef MBEDTLS_ECP_DP_BP256R1_ENABLED 20 | #undef MBEDTLS_ECP_DP_BP384R1_ENABLED 21 | #undef MBEDTLS_ECP_DP_BP512R1_ENABLED 22 | #undef MBEDTLS_ECP_DP_CURVE25519_ENABLED 23 | #undef MBEDTLS_ECP_DP_CURVE448_ENABLED 24 | #undef MBEDTLS_ECP_DP_SECP192K1_ENABLED 25 | #undef MBEDTLS_ECP_DP_SECP192R1_ENABLED 26 | #undef MBEDTLS_ECP_DP_SECP224K1_ENABLED 27 | #undef MBEDTLS_ECP_DP_SECP224R1_ENABLED 28 | #undef MBEDTLS_ECP_DP_SECP256K1_ENABLED 29 | #undef MBEDTLS_ECP_DP_SECP256R1_ENABLED 30 | #undef MBEDTLS_FS_IO 31 | #undef MBEDTLS_GENPRIME 32 | #undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED 33 | #undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED 34 | #undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED 35 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED 36 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED 37 | #undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED 38 | #undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED 39 | #undef MBEDTLS_NET_C 40 | #undef MBEDTLS_PEM_WRITE_C 41 | #undef MBEDTLS_PKCS12_C 42 | #undef MBEDTLS_PKCS5_C 43 | #undef MBEDTLS_PK_RSA_ALT_SUPPORT 44 | #undef MBEDTLS_POLY1305_C 45 | #undef MBEDTLS_RIPEMD160_C 46 | #undef MBEDTLS_RSA_C 47 | #undef MBEDTLS_SELF_TEST 48 | #undef MBEDTLS_SHA1_C 49 | #undef MBEDTLS_SSL_CBC_RECORD_SPLITTING 50 | #undef MBEDTLS_SSL_PROTO_TLS1 51 | #undef MBEDTLS_SSL_PROTO_TLS1_1 52 | #undef MBEDTLS_X509_RSASSA_PSS_SUPPORT 53 | -------------------------------------------------------------------------------- /dps-micro/ext/mbedtls_config_zephyr.h: -------------------------------------------------------------------------------- 1 | /* Use config file, to replace mbed defaults. It is set during 2 | * compilation with MBEDTLS_USER_CONFIG_FILE environment variable. */ 3 | 4 | #define MBEDTLS_DEPRECATED_REMOVED 5 | 6 | #undef MBEDTLS_ARC4_C 7 | #undef MBEDTLS_BLOWFISH_C 8 | #undef MBEDTLS_CAMELLIA_C 9 | #undef MBEDTLS_CCM_C 10 | #include 11 | 12 | #undef MBEDTLS_DES_C 13 | #undef MBEDTLS_DHM_C 14 | #undef MBEDTLS_ECP_DP_BP256R1_ENABLED 15 | #undef MBEDTLS_ECP_DP_BP384R1_ENABLED 16 | #undef MBEDTLS_ECP_DP_BP512R1_ENABLED 17 | #undef MBEDTLS_ECP_DP_CURVE25519_ENABLED 18 | #undef MBEDTLS_ECP_DP_SECP192K1_ENABLED 19 | #undef MBEDTLS_ECP_DP_SECP192R1_ENABLED 20 | #undef MBEDTLS_ECP_DP_SECP224K1_ENABLED 21 | #undef MBEDTLS_ECP_DP_SECP224R1_ENABLED 22 | #undef MBEDTLS_ECP_DP_SECP256K1_ENABLED 23 | #undef MBEDTLS_ECP_DP_SECP256R1_ENABLED 24 | #undef MBEDTLS_FS_IO 25 | #undef MBEDTLS_GENPRIME 26 | #undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED 27 | #undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED 28 | #undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED 29 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED 30 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED 31 | #undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED 32 | #undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED 33 | #undef MBEDTLS_NET_C 34 | #undef MBEDTLS_PEM_WRITE_C 35 | #undef MBEDTLS_PKCS12_C 36 | #undef MBEDTLS_PKCS5_C 37 | #undef MBEDTLS_PK_RSA_ALT_SUPPORT 38 | #undef MBEDTLS_RIPEMD160_C 39 | #undef MBEDTLS_RSA_C 40 | #undef MBEDTLS_SELF_TEST 41 | #undef MBEDTLS_SHA1_C 42 | #undef MBEDTLS_SSL_CBC_RECORD_SPLITTING 43 | #undef MBEDTLS_SSL_PROTO_TLS1 44 | #undef MBEDTLS_SSL_PROTO_TLS1_1 45 | #undef MBEDTLS_X509_RSASSA_PSS_SUPPORT 46 | 47 | /* For Zephyr */ 48 | #define MBEDTLS_NO_PLATFORM_ENTROPY 49 | #define MBEDTLS_ENTROPY_HARDWARE_ALT 50 | #undef MBEDTLS_ENTROPY_PLATFORM 51 | #undef MBEDTLS_TIMING_C 52 | #undef MBEDTLS_FS_IO 53 | #undef MBEDTLS_HAVE_TIME_DATE 54 | #undef MBEDTLS_HAVE_TIME 55 | /* Replace malloc and free */ 56 | #define MBEDTLS_PLATFORM_MEMORY 57 | extern void* DPS_CallocCrypto(size_t num, size_t sz); 58 | #define MBEDTLS_PLATFORM_STD_CALLOC DPS_CallocCrypto 59 | extern void DPS_FreeCrypto(void* mem); 60 | #define MBEDTLS_PLATFORM_STD_FREE DPS_FreeCrypto 61 | -------------------------------------------------------------------------------- /dps-micro/include/dps/discovery.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Make local node discoverable 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2019 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DISCOVERY_H 29 | #define _DISCOVERY_H 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #ifdef __cplusplus 36 | extern "C" { 37 | #endif 38 | 39 | 40 | #ifdef __cplusplus 41 | } 42 | #endif 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/ack.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Send and receive acknowledgement messages 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _ACK_H 29 | #define _ACK_H 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | 37 | #ifdef __cplusplus 38 | extern "C" { 39 | #endif 40 | 41 | /** 42 | * Decode and process a received acknowledgement 43 | * 44 | * @param node The local node 45 | * @param from The address of the sender 46 | * @param buffer The encoded acknowledgement 47 | * 48 | * @return DPS_OK if decoding and processing is successful, an error otherwise 49 | */ 50 | DPS_Status DPS_DecodeAcknowledgement(DPS_Node* node, DPS_NodeAddress* from, DPS_RxBuffer* buffer); 51 | 52 | /** 53 | * Send an previously serialized acknowledgement 54 | * 55 | * Must be called with the node lock held. 56 | * 57 | * @param pub The publication to acknowledge 58 | * @param data Optional payload for the acknowledgment 59 | * @param dataLen The length of the optional payload 60 | * 61 | * @return DPS_OK if sending is successful, an error otherwise 62 | */ 63 | DPS_Status DPS_AckPublication(const DPS_Publication* pub, const uint8_t* data, size_t dataLen); 64 | 65 | #ifdef __cplusplus 66 | } 67 | #endif 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/crypto.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Common cryptographic macros and functions 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _CRYPTO_H 29 | #define _CRYPTO_H 30 | 31 | #include "dps.h" 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | #define AES_256_KEY_LEN 32 /**< AES 256 key length, in bytes */ 38 | 39 | #define EC_MAX_COORD_LEN 66 /**< Maximum length of an EC coordinate (x, y, or d) */ 40 | 41 | /** 42 | * Opaque type of random byte generator 43 | */ 44 | typedef struct _DPS_RBG DPS_RBG; 45 | 46 | /** 47 | * Create an instance of a random byte generator 48 | * 49 | * @return the random byte generator 50 | */ 51 | DPS_RBG* DPS_CreateRBG(); 52 | 53 | /** 54 | * Destroy a previously-created instance of a random byte generator 55 | * 56 | * @param rbg the random byte generator 57 | */ 58 | void DPS_DestroyRBG(DPS_RBG* rbg); 59 | 60 | /** 61 | * Create a random AES key 62 | * 63 | * @param rbg a random byte generator 64 | * @param key the created key 65 | * 66 | * @return DPS_OK if creation is successful, an error otherwise 67 | */ 68 | DPS_Status DPS_RandomKey(DPS_RBG *rbg, uint8_t key[AES_256_KEY_LEN]); 69 | 70 | /** 71 | * Create an ephemeral elliptic curve key 72 | * 73 | * @param rbg a random byte generator 74 | * @param curve a named curve 75 | * @param x the created key's x coordinate 76 | * @param y the created key's y coordinate 77 | * @param d the created key's d coordinate 78 | * 79 | * @return DPS_OK if creation is successful, an error otherwise 80 | */ 81 | DPS_Status DPS_EphemeralKey(DPS_RBG* rbg, DPS_ECCurve curve, 82 | uint8_t x[EC_MAX_COORD_LEN], uint8_t y[EC_MAX_COORD_LEN], 83 | uint8_t d[EC_MAX_COORD_LEN]); 84 | 85 | /** 86 | * Decode the common name (CN) attribute of an X.509 certificate. 87 | * 88 | * @param cert the X.509 certificate 89 | * 90 | * @return the CN value, must be freed by the caller. 91 | */ 92 | char* DPS_CertificateCN(const char* cert); 93 | 94 | #ifdef __cplusplus 95 | } 96 | #endif 97 | 98 | #endif 99 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/dps.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Internal APIs 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_INTERNAL_H 29 | #define _DPS_INTERNAL_H 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | #ifdef __cplusplus 38 | extern "C" { 39 | #endif 40 | 41 | #define A_SIZEOF(x) (sizeof(x) / sizeof((x)[0])) 42 | 43 | /* 44 | * Map keys for CBOR serialization of DPS messages 45 | */ 46 | #define DPS_CBOR_KEY_PORT 1 /**< uint */ 47 | #define DPS_CBOR_KEY_TTL 2 /**< int */ 48 | #define DPS_CBOR_KEY_PUB_ID 3 /**< bstr (UUID) */ 49 | #define DPS_CBOR_KEY_SEQ_NUM 4 /**< uint */ 50 | #define DPS_CBOR_KEY_ACK_REQ 5 /**< bool */ 51 | #define DPS_CBOR_KEY_BLOOM_FILTER 6 /**< bstr */ 52 | #define DPS_CBOR_KEY_SUB_FLAGS 7 /**< uint */ 53 | #define DPS_CBOR_KEY_MESH_ID 8 /**< bstr (UUID) */ 54 | #define DPS_CBOR_KEY_NEEDS 9 /**< bstr */ 55 | #define DPS_CBOR_KEY_INTERESTS 10 /**< bstr */ 56 | #define DPS_CBOR_KEY_TOPICS 11 /**< array (tstr) */ 57 | #define DPS_CBOR_KEY_DATA 12 /**< bstr */ 58 | #define DPS_CBOR_KEY_ACK_SEQ_NUM 13 /**< uint */ 59 | #define DPS_CBOR_KEY_PATH 14 /**< tstr */ 60 | #define DPS_CBOR_KEY_HOP_COUNT 15 /**< uint */ 61 | 62 | #ifdef __cplusplus 63 | } 64 | #endif 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/hkdf.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * HMAC-based extract-and-expand Key Derivation Function 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _HKDF_H 29 | #define _HKDF_H 30 | 31 | #include 32 | #include "crypto.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * Applies an HMAC-based extract-and-expand Key Derivation Function to 40 | * generate a key. 41 | * 42 | * @param secret the secret 43 | * @param secretLen the size of the secret, in bytes 44 | * @param context the context for the hash function 45 | * @param contextLen the size of the hash context, in bytes 46 | * @param key returns the generated key 47 | * 48 | * @return 49 | * - DPS_OK if the key is generated 50 | * - DPS_ERR_INVALID if the key cannot be generated 51 | */ 52 | DPS_Status HKDF_SHA256(const uint8_t* secret, size_t secretLen, 53 | const uint8_t* context, size_t contextLen, 54 | uint8_t key[AES_256_KEY_LEN]); 55 | 56 | #ifdef __cplusplus 57 | } 58 | #endif 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/keywrap.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * AES key wrap algorithm 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _KEYWRAP_H 29 | #define _KEYWRAP_H 30 | 31 | #include 32 | #include "crypto.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | #define AES_256_KEY_WRAP_LEN 40 /**< The length of the wrapped AES-256 key in bytes */ 39 | 40 | /** 41 | * Wrap a key per the algorithm specified in RFC 3394. 42 | * 43 | * @param cek the content encryption key (aka the plaintext) 44 | * @param kek the key encryption key 45 | * @param cipherText returns the wrapped content encryption key 46 | * 47 | * @return DPS_OK if wrapped, an error otherwise 48 | */ 49 | DPS_Status KeyWrap(const uint8_t cek[AES_256_KEY_LEN], const uint8_t kek[AES_256_KEY_LEN], 50 | uint8_t cipherText[AES_256_KEY_WRAP_LEN]); 51 | 52 | /** 53 | * Unwrap a key per the algorithm specified in RFC 3394. 54 | * 55 | * @param cipherText the wrapped content encryption key 56 | * @param kek the key encryption key 57 | * @param cek returns the content encryption key (aka the plaintext) 58 | * 59 | * @return DPS_OK if unwrapped, an error otherwise 60 | */ 61 | DPS_Status KeyUnwrap(const uint8_t cipherText[AES_256_KEY_WRAP_LEN], const uint8_t kek[AES_256_KEY_LEN], 62 | uint8_t cek[AES_256_KEY_LEN]); 63 | 64 | #ifdef __cplusplus 65 | } 66 | #endif 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/malloc.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Abstraction layer for memory allocation 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2018 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_MALLOC_H 29 | #define _DPS_MALLOC_H 30 | 31 | #include 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | /** 38 | * To avoid fragmentation on embedded targets will limited resources memory allocations 39 | * are segmented into pools based on the lifetime of the allocation. 40 | */ 41 | 42 | typedef enum { 43 | DPS_ALLOC_BRIEF, /**< Pool for allocations that are short term - e.g. within one function */ 44 | DPS_ALLOC_LONG_TERM, /**< Pool for allocations that are longer term - e.g. until a callback is made */ 45 | DPS_ALLOC_PERMANENT, /**< Pool for allocations that are for the lifetime of the application */ 46 | } DPS_AllocPool; 47 | 48 | /** 49 | * Allocate memory from one of the pools 50 | */ 51 | void* DPS_Malloc(size_t len, DPS_AllocPool pool); 52 | 53 | /** 54 | * Allocate and clear memory from one of the pools 55 | */ 56 | void* DPS_Calloc(size_t len, DPS_AllocPool pool); 57 | 58 | /** 59 | * Return memory to the pool from which it was allocated 60 | */ 61 | void DPS_Free(void* mem, DPS_AllocPool pool); 62 | 63 | 64 | #ifdef __cplusplus 65 | } 66 | #endif 67 | 68 | #endif 69 | 70 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/mbedtls.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Common mbedTLS functions 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _MBEDTLS_H 29 | #define _MBEDTLS_H 30 | 31 | #include "mbedtls/ecdh.h" 32 | #include "mbedtls/x509_crt.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * The text string representation of the mbedTLS status code. 40 | * 41 | * @param ret the status code 42 | * 43 | * @return the text string representation 44 | */ 45 | const char *TLSErrTxt(int ret); 46 | 47 | /** 48 | * Get the mbedTLS elliptic curve parameters 49 | * 50 | * @param curve the elliptic curve ID 51 | * @param id the mbedtls elliptic curve ID 52 | * @param len the size of a coordinate, in bytes 53 | * 54 | * @return 0 on success, an mbedTLS error code otherwise 55 | */ 56 | int TLSGetCurveParams(DPS_ECCurve curve, mbedtls_ecp_group_id* id, size_t* len); 57 | 58 | /** 59 | * Decode the common name (CN) attribute of an X.509 certificate. 60 | * 61 | * @param crt the X.509 certificate 62 | * 63 | * @return the CN value, must be freed by the caller. 64 | */ 65 | const mbedtls_x509_name* TLSCertificateCN(const mbedtls_x509_crt* crt); 66 | 67 | #ifdef __cplusplus 68 | } 69 | #endif 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/sha2.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * SHA-256 algorithm 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _SHA2_H 29 | #define _SHA2_H 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #ifdef __cplusplus 36 | extern "C" { 37 | #endif 38 | 39 | #define DPS_SHA2_DIGEST_LEN 32 /**< Size of SHA-256 hash in bytes */ 40 | 41 | /** 42 | * Compute the SHA2 hash of some data 43 | * 44 | * @param digest The result 45 | * @param data The data to hash 46 | * @param len The length of the data to hash 47 | */ 48 | void DPS_Sha2(uint8_t digest[DPS_SHA2_DIGEST_LEN], const uint8_t* data, size_t len); 49 | 50 | #ifdef __cplusplus 51 | } 52 | #endif 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /dps-micro/include/dps/private/timer.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Wrapper for platform dependent timer function 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2019 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _TIMER_H 29 | #define _TIMER_H 30 | 31 | #include 32 | #include 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | typedef struct _DPS_Timer DPS_Timer; 39 | 40 | typedef void (*DPS_TimeoutCallback)(DPS_Timer* timer, void* data); 41 | 42 | /** 43 | * Allocate a timer and start it running 44 | * 45 | * @param timeout Timeout specified in milliseconds 46 | * @param cb Callback function called when the timeout expires 47 | * @param data Data passed to the callback function 48 | */ 49 | DPS_Timer* DPS_TimerSet(uint16_t timeout, DPS_TimeoutCallback cb, void* data); 50 | 51 | /** 52 | * Restart an existing timer 53 | * 54 | * @param timer The timer to restart 55 | * @param timeout Timeout specified in milliseconds 56 | */ 57 | DPS_Status DPS_TimerReset(DPS_Timer* timer, uint16_t timeout); 58 | 59 | /** 60 | * Cancel an existing timer and free any resources 61 | * 62 | * @param timer The timer to cancel 63 | */ 64 | DPS_Status DPS_TimerCancel(DPS_Timer* timer); 65 | 66 | #ifdef __cplusplus 67 | } 68 | #endif 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /dps-micro/include/dps/uuid.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Create and compare UUIDs 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_UUID_H 29 | #define _DPS_UUID_H 30 | 31 | #include 32 | #include 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * @defgroup uuid UUID 40 | * Create and compare UUIDs. 41 | * @{ 42 | */ 43 | 44 | /** 45 | * Type definition for a UUID 46 | */ 47 | typedef struct _DPS_UUID { 48 | /**< The UUID value */ 49 | union { 50 | uint8_t val[16]; /**< The UUID as an array of 8-bit values */ 51 | uint64_t val64[2]; /**< The UUID as an array of 64-bit values */ 52 | }; 53 | } DPS_UUID; 54 | 55 | /** 56 | * One time initialization 57 | * 58 | * @return DPS_OK if initialization succeeds, an error otherwise 59 | */ 60 | DPS_Status DPS_InitUUID(); 61 | 62 | /** 63 | * Non secure generation of a random UUID. 64 | * 65 | * @param uuid The generated UUID. 66 | */ 67 | void DPS_GenerateUUID(DPS_UUID* uuid); 68 | 69 | /** 70 | * Return a string representation of a UUID. 71 | * 72 | * @note This function uses a static string and is non-reentrant. 73 | * 74 | * @param uuid The UUID 75 | * 76 | * @return The string representation 77 | */ 78 | const char* DPS_UUIDToString(const DPS_UUID* uuid); 79 | 80 | /** 81 | * Numerical comparison of two UUIDs 82 | * 83 | * @param a One of the UUIDs to compare 84 | * @param b The other UUID to compare 85 | * 86 | * @return 87 | * - <0 if a less than b 88 | * - 0 if a equal to b 89 | * - >0 if a greater than b 90 | */ 91 | int DPS_UUIDCompare(const DPS_UUID* a, const DPS_UUID* b); 92 | 93 | /** @} */ 94 | 95 | #ifdef __cplusplus 96 | } 97 | #endif 98 | 99 | #endif 100 | -------------------------------------------------------------------------------- /dps-micro/src/err.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | #define ERR_CASE(_s) case _s: return # _s + 8 27 | 28 | const char* DPS_ErrTxt(DPS_Status s) 29 | { 30 | static char buf[8]; 31 | 32 | switch (s) { 33 | ERR_CASE(DPS_ERR_OK); 34 | ERR_CASE(DPS_ERR_FAILURE); 35 | ERR_CASE(DPS_ERR_NULL); 36 | ERR_CASE(DPS_ERR_ARGS); 37 | ERR_CASE(DPS_ERR_RESOURCES); 38 | ERR_CASE(DPS_ERR_READ); 39 | ERR_CASE(DPS_ERR_WRITE); 40 | ERR_CASE(DPS_ERR_TIMEOUT); 41 | ERR_CASE(DPS_ERR_EOD); 42 | ERR_CASE(DPS_ERR_OVERFLOW); 43 | ERR_CASE(DPS_ERR_NETWORK); 44 | ERR_CASE(DPS_ERR_INVALID); 45 | ERR_CASE(DPS_ERR_BUSY); 46 | ERR_CASE(DPS_ERR_EXISTS); 47 | ERR_CASE(DPS_ERR_MISSING); 48 | ERR_CASE(DPS_ERR_STALE); 49 | ERR_CASE(DPS_ERR_NO_ROUTE); 50 | ERR_CASE(DPS_ERR_NOT_STARTED); 51 | ERR_CASE(DPS_ERR_NOT_INITIALIZED); 52 | ERR_CASE(DPS_ERR_EXPIRED); 53 | ERR_CASE(DPS_ERR_UNRESOLVED); 54 | ERR_CASE(DPS_ERR_NODE_DESTROYED); 55 | ERR_CASE(DPS_ERR_EOF); 56 | ERR_CASE(DPS_ERR_NOT_IMPLEMENTED); 57 | ERR_CASE(DPS_ERR_SECURITY); 58 | ERR_CASE(DPS_ERR_NOT_ENCRYPTED); 59 | ERR_CASE(DPS_ERR_STOPPING); 60 | ERR_CASE(DPS_ERR_RANGE); 61 | ERR_CASE(DPS_ERR_LOST_PRECISION); 62 | ERR_CASE(DPS_ERR_NO_DATA); 63 | default: 64 | snprintf(buf, sizeof(buf), "ERR%d", s); 65 | return buf; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /dps-micro/src/hkdf.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2017 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | /* 31 | * Debug control for this module 32 | */ 33 | DPS_DEBUG_CONTROL(DPS_DEBUG_ON); 34 | 35 | DPS_Status HKDF_SHA256(const uint8_t* secret, size_t secretLen, 36 | const uint8_t* context, size_t contextLen, 37 | uint8_t key[AES_256_KEY_LEN]) 38 | { 39 | mbedtls_md_context_t md; 40 | const mbedtls_md_info_t* info; 41 | uint8_t digest[MBEDTLS_MD_MAX_SIZE]; 42 | uint8_t count; 43 | int ret; 44 | 45 | mbedtls_md_init(&md); 46 | 47 | /* 48 | * Extract 49 | */ 50 | info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); 51 | ret = mbedtls_md_setup(&md, info, 1); 52 | if (ret != 0) { 53 | goto Exit; 54 | } 55 | ret = mbedtls_md_hmac_starts(&md, NULL, 0); 56 | if (ret != 0) { 57 | goto Exit; 58 | } 59 | ret = mbedtls_md_hmac_update(&md, secret, secretLen); 60 | if (ret != 0) { 61 | goto Exit; 62 | } 63 | ret = mbedtls_md_hmac_finish(&md, digest); 64 | if (ret != 0) { 65 | goto Exit; 66 | } 67 | 68 | /* 69 | * Expand 70 | */ 71 | ret = mbedtls_md_hmac_starts(&md, digest, mbedtls_md_get_size(info)); 72 | if (ret != 0) { 73 | goto Exit; 74 | } 75 | ret = mbedtls_md_hmac_update(&md, context, contextLen); 76 | if (ret != 0) { 77 | goto Exit; 78 | } 79 | count = 1; 80 | ret = mbedtls_md_hmac_update(&md, &count, sizeof(count)); 81 | if (ret != 0) { 82 | goto Exit; 83 | } 84 | ret = mbedtls_md_hmac_finish(&md, digest); 85 | if (ret != 0) { 86 | goto Exit; 87 | } 88 | memcpy(key, digest, AES_256_KEY_LEN); 89 | 90 | Exit: 91 | mbedtls_md_free(&md); 92 | if (ret == 0) { 93 | return DPS_OK; 94 | } else { 95 | return DPS_ERR_INVALID; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /dps-micro/src/posix/dbg.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | int DPS_Debug = 1; 27 | 28 | /* TODO - platform dependent timestamp */ 29 | #define DPS_DBG_TIME 0 30 | 31 | static const char* LevelTxt[] = { "ERROR", "WARNING", "" /* PRINT */, "" /* PRINTT */, "TRACE", "DEBUG" }; 32 | 33 | #define stream stdout 34 | 35 | void DPS_Log(DPS_LogLevel level, const char* file, int line, const char *function, const char *fmt, ...) 36 | { 37 | va_list ap; 38 | va_start(ap, fmt); 39 | switch (level) { 40 | case DPS_LOG_ERROR: 41 | case DPS_LOG_WARNING: 42 | case DPS_LOG_DBGPRINT: 43 | fprintf(stream, "%09u %-7s %s@%d: ", DPS_DBG_TIME, LevelTxt[level], file, line); 44 | vfprintf(stream, fmt, ap); 45 | break; 46 | case DPS_LOG_PRINTT: 47 | fprintf(stream, "%09u ", DPS_DBG_TIME); 48 | /* FALLTHROUGH */ 49 | case DPS_LOG_PRINT: 50 | vfprintf(stream, fmt, ap); 51 | break; 52 | case DPS_LOG_DBGTRACE: 53 | fprintf(stream, "%09u %-7s %s@%d: %s() ", DPS_DBG_TIME, LevelTxt[level], file, line, function); 54 | vfprintf(stream, fmt, ap); 55 | break; 56 | } 57 | va_end(ap); 58 | } 59 | 60 | void DPS_LogBytes(DPS_LogLevel level, const char* file, int line, const char *function, const uint8_t *bytes, size_t n) 61 | { 62 | size_t i; 63 | for (i = 0; i < n; ++i) { 64 | if ((i % 16) == 0) { 65 | fprintf(stream, "%s%09u %-7s %s@%d: ", i ? "\n" : "", DPS_DBG_TIME, LevelTxt[level], file, line); 66 | } 67 | fprintf(stream, "%02x ", bytes[i]); 68 | } 69 | fprintf(stream, "\n"); 70 | } 71 | -------------------------------------------------------------------------------- /dps-micro/src/posix/malloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | 27 | void* DPS_Malloc(size_t len, DPS_AllocPool pool) 28 | { 29 | return malloc(len); 30 | } 31 | 32 | void* DPS_Calloc(size_t len, DPS_AllocPool pool) 33 | { 34 | return calloc(1, len); 35 | } 36 | 37 | void DPS_Free(void* mem, DPS_AllocPool pool) 38 | { 39 | free(mem); 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /dps-micro/src/sha2.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | void DPS_Sha2(uint8_t digest[DPS_SHA2_DIGEST_LEN], const uint8_t* data, size_t len) 29 | { 30 | const mbedtls_md_info_t* info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); 31 | mbedtls_md(info, data, len, digest); 32 | } 33 | -------------------------------------------------------------------------------- /dps-micro/src/win32/dbg.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | int DPS_Debug = 1; 28 | 29 | static uint32_t Timestamp() 30 | { 31 | static struct timeb start; 32 | struct timeb t; 33 | ftime(&t); 34 | 35 | if (!start.time) { 36 | start = t; 37 | } 38 | return (uint32_t)((t.time - start.time) * 1000 + (t.millitm - start.millitm)); 39 | } 40 | 41 | #define DPS_DBG_TIME Timestamp() 42 | 43 | static const char* LevelTxt[] = { "ERROR", "WARNING", "" /* PRINT */, "" /* PRINTT */, "TRACE", "DEBUG" }; 44 | 45 | #define stream stdout 46 | 47 | void DPS_Log(DPS_LogLevel level, const char* file, int line, const char *function, const char *fmt, ...) 48 | { 49 | va_list ap; 50 | va_start(ap, fmt); 51 | switch (level) { 52 | case DPS_LOG_ERROR: 53 | case DPS_LOG_WARNING: 54 | case DPS_LOG_DBGPRINT: 55 | fprintf(stream, "%09u %-7s %s@%d: ", DPS_DBG_TIME, LevelTxt[level], file, line); 56 | vfprintf(stream, fmt, ap); 57 | break; 58 | case DPS_LOG_PRINTT: 59 | fprintf(stream, "%09u ", DPS_DBG_TIME); 60 | /* FALLTHROUGH */ 61 | case DPS_LOG_PRINT: 62 | vfprintf(stream, fmt, ap); 63 | break; 64 | case DPS_LOG_DBGTRACE: 65 | fprintf(stream, "%09u %-7s %s@%d: %s() ", DPS_DBG_TIME, LevelTxt[level], file, line, function); 66 | vfprintf(stream, fmt, ap); 67 | break; 68 | } 69 | va_end(ap); 70 | } 71 | 72 | void DPS_LogBytes(DPS_LogLevel level, const char* file, int line, const char *function, const uint8_t *bytes, size_t n) 73 | { 74 | size_t i; 75 | for (i = 0; i < n; ++i) { 76 | if ((i % 16) == 0) { 77 | fprintf(stream, "%s%09u %-7s %s@%d: ", i ? "\n" : "", DPS_DBG_TIME, LevelTxt[level], file, line); 78 | } 79 | fprintf(stream, "%02x ", bytes[i]); 80 | } 81 | fprintf(stream, "\n"); 82 | } 83 | -------------------------------------------------------------------------------- /dps-micro/src/win32/malloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | 27 | void* DPS_Malloc(size_t len, DPS_AllocPool pool) 28 | { 29 | return malloc(len); 30 | } 31 | 32 | void* DPS_Calloc(size_t len, DPS_AllocPool pool) 33 | { 34 | return calloc(1, len); 35 | } 36 | 37 | void DPS_Free(void* mem, DPS_AllocPool pool) 38 | { 39 | free(mem); 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /dps-micro/src/win32/timer.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2019 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | struct _DPS_Timer { 27 | HANDLE handle; 28 | DPS_TimeoutCallback cb; 29 | void* data; 30 | }; 31 | 32 | static void CALLBACK TimerCB(_In_ PVOID lpParam, _In_ BOOLEAN timedOut) 33 | { 34 | DPS_Timer* timer = (DPS_Timer*)lpParam; 35 | 36 | if (timedOut) { 37 | timer->cb(timer, timer->data); 38 | } 39 | } 40 | 41 | DPS_Timer* DPS_TimerSet(uint16_t timeout, DPS_TimeoutCallback cb, void* data) 42 | { 43 | DPS_Timer* timer = malloc(sizeof(DPS_Timer)); 44 | 45 | timer->cb = cb; 46 | timer->data = data; 47 | if (CreateTimerQueueTimer(&timer->handle, NULL, TimerCB, timer, timeout, 0, 0)) { 48 | return timer; 49 | } else { 50 | free(timer); 51 | return NULL; 52 | } 53 | } 54 | 55 | DPS_Status DPS_TimerReset(DPS_Timer* timer, uint16_t timeout) 56 | { 57 | if (!timer) { 58 | return DPS_ERR_NULL; 59 | } 60 | DeleteTimerQueueTimer(NULL, timer->handle, NULL); 61 | CreateTimerQueueTimer(&timer->handle, NULL, TimerCB, timer, timeout, 0, 0); 62 | return DPS_OK; 63 | } 64 | 65 | DPS_Status DPS_TimerCancel(DPS_Timer* timer) 66 | { 67 | if (!timer) { 68 | return DPS_ERR_NULL; 69 | } 70 | DeleteTimerQueueTimer(NULL, timer->handle, NULL); 71 | free(timer); 72 | return DPS_OK; 73 | } 74 | -------------------------------------------------------------------------------- /dps-micro/src/zephyr/dbg.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | int DPS_Debug = 1; 29 | 30 | /* TODO - platform dependent timestamp */ 31 | #define DPS_DBG_TIME 0 32 | 33 | static const char* LevelTxt[] = { "ERROR", "WARNING", "" /* PRINT */, "" /* PRINTT */, "TRACE", "DEBUG" }; 34 | 35 | static char buf[1024]; 36 | 37 | void DPS_Log(DPS_LogLevel level, const char* file, int line, const char *function, const char *fmt, ...) 38 | { 39 | int len = 0; 40 | va_list ap; 41 | va_start(ap, fmt); 42 | switch (level) { 43 | case DPS_LOG_ERROR: 44 | case DPS_LOG_WARNING: 45 | case DPS_LOG_DBGPRINT: 46 | len = sprintf(buf, "%09u %-7s %s@%d: ", DPS_DBG_TIME, LevelTxt[level], file, line); 47 | vsprintf(buf + len, fmt, ap); 48 | break; 49 | case DPS_LOG_PRINTT: 50 | len = sprintf(buf, "%09u ", DPS_DBG_TIME); 51 | /* FALLTHROUGH */ 52 | case DPS_LOG_PRINT: 53 | vsprintf(buf + len, fmt, ap); 54 | break; 55 | case DPS_LOG_DBGTRACE: 56 | len = sprintf(buf, "%09u %-7s %s@%d: %s() ", DPS_DBG_TIME, LevelTxt[level], file, line, function); 57 | vsprintf(buf + len, fmt, ap); 58 | break; 59 | default: 60 | buf[0] = 0; 61 | } 62 | printk("%s\r", buf); 63 | va_end(ap); 64 | } 65 | 66 | void DPS_LogBytes(DPS_LogLevel level, const char* file, int line, const char *function, const uint8_t *bytes, size_t n) 67 | { 68 | } 69 | -------------------------------------------------------------------------------- /dps-micro/src/zephyr/entropy.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Network layer macros and functions 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2018 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "mbedtls/entropy.h" 34 | #include 35 | #include 36 | 37 | /* 38 | * Debug control for this module 39 | */ 40 | DPS_DEBUG_CONTROL(DPS_DEBUG_ON); 41 | 42 | int mbedtls_hardware_poll(void* data, unsigned char* output, size_t len, size_t* olen) 43 | { 44 | struct device *dev = device_get_binding(CONFIG_ENTROPY_NAME); 45 | int ret; 46 | 47 | if (!dev) { 48 | DPS_ERRPRINT("Could not get entropy device\n"); 49 | return 1; 50 | } 51 | ret = entropy_get_entropy(dev, output, len); 52 | if (ret) { 53 | DPS_ERRPRINT("Could not get entropy\n"); 54 | return 1; 55 | } 56 | *olen = len; 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /dps-micro/src/zephyr/malloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | K_MEM_POOL_DEFINE(briefPool, 64, 2048, 2, 4); 28 | K_MEM_POOL_DEFINE(longtermPool, 64, 1024, 6, 4); 29 | K_MEM_POOL_DEFINE(permanentPool, 64, 4096, 4, 4); 30 | 31 | void* DPS_Malloc(size_t len, DPS_AllocPool pool) 32 | { 33 | switch (pool) { 34 | case DPS_ALLOC_BRIEF: 35 | return k_mem_pool_malloc(&briefPool, len); 36 | case DPS_ALLOC_LONG_TERM: 37 | return k_mem_pool_malloc(&longtermPool, len); 38 | case DPS_ALLOC_PERMANENT: 39 | return k_mem_pool_malloc(&permanentPool, len); 40 | } 41 | return NULL; 42 | } 43 | 44 | void* DPS_Calloc(size_t len, DPS_AllocPool pool) 45 | { 46 | void* mem = DPS_Malloc(len, pool); 47 | if (mem) { 48 | memset(mem, 0, len); 49 | } 50 | return mem; 51 | } 52 | 53 | void DPS_Free(void* mem, DPS_AllocPool pool) 54 | { 55 | k_free(mem); 56 | } 57 | 58 | void* DPS_CallocCrypto(size_t num, size_t len) 59 | { 60 | return DPS_Calloc(num * len, DPS_ALLOC_LONG_TERM); 61 | } 62 | 63 | void DPS_FreeCrypto(void* mem) 64 | { 65 | DPS_Free(mem, DPS_ALLOC_LONG_TERM); 66 | } 67 | -------------------------------------------------------------------------------- /dps-micro/test/keys.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _KEYS_H 24 | #define _KEYS_H 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #ifdef __cplusplus 31 | extern "C" { 32 | #endif 33 | 34 | /* 35 | * Preshared keys and certificates for testing only - DO NOT USE THESE KEYS IN A REAL APPLICATION!!!! 36 | */ 37 | 38 | extern const DPS_KeyId NetworkKeyId; 39 | extern const DPS_Key NetworkKey; 40 | 41 | #define NUM_KEYS 2 42 | 43 | extern const DPS_KeyId PskId[NUM_KEYS]; 44 | extern const DPS_Key Psk[NUM_KEYS]; 45 | 46 | extern const char TrustedCAs[]; 47 | 48 | typedef struct _Id { 49 | DPS_KeyId keyId; 50 | const char* cert; 51 | const char* privateKey; 52 | const char* password; 53 | } Id; 54 | 55 | extern const Id Ids[]; 56 | 57 | #define PUB_ID 4 58 | #define SUB_ID 5 59 | 60 | #ifdef __cplusplus 61 | } 62 | #endif 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /dps-micro/test/mcast_unit_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | #include "test.h" 23 | #include 24 | #include 25 | #include 26 | 27 | 28 | static DPS_Node* node; 29 | 30 | static DPS_Status OnReceive(DPS_Node* node, DPS_NodeAddress* addr, int mcast, DPS_RxBuffer* rxBuf, DPS_Status status) 31 | { 32 | DPS_PRINT("Received %d bytes\n%s\n", DPS_RxBufferAvail(rxBuf), rxBuf->base); 33 | return DPS_OK; 34 | } 35 | 36 | static char testString[] = "This is a test string"; 37 | 38 | static DPS_TxBuffer txBuf; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | DPS_Status status; 43 | int i; 44 | char** arg = argv + 1; 45 | 46 | DPS_Debug = DPS_FALSE; 47 | while (--argc) { 48 | if (strcmp(*arg, "-d") == 0) { 49 | ++arg; 50 | DPS_Debug = DPS_TRUE; 51 | continue; 52 | } 53 | goto Usage; 54 | } 55 | 56 | node = DPS_CreateNode("/"); 57 | status = DPS_NetworkInit(node); 58 | CHECK(status == DPS_OK); 59 | 60 | status = DPS_NetworkStart(node, OnReceive); 61 | CHECK(status == DPS_OK); 62 | 63 | DPS_TxBufferReserve(node, &txBuf, strlen(testString) + 1, DPS_TX_POOL); 64 | DPS_TxBufferAppend(&txBuf, testString, strlen(testString) + 1); 65 | DPS_TxBufferCommit(&txBuf); 66 | 67 | for (i = 0; i < 100; ++i) { 68 | SLEEP(5000); 69 | DPS_MCastSend(node, NULL, NULL); 70 | } 71 | 72 | return 0; 73 | 74 | failed: 75 | DPS_PRINT("FAILED (%s) near line %d\r\n", __FILE__, atLine - 1); 76 | return 1; 77 | 78 | Usage: 79 | DPS_PRINT("Usage %s: [-d]\n", argv[0]); 80 | return 1; 81 | } 82 | -------------------------------------------------------------------------------- /dps-micro/test/serialize.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int main() 5 | { 6 | } 7 | -------------------------------------------------------------------------------- /dps-micro/test/test.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2017 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _TEST_H 24 | #define _TEST_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #if DPS_TARGET == DPS_TARGET_WINDOWS 40 | #define SLEEP(t) Sleep(t) 41 | #elif DPS_TARGET == DPS_TARGET_LINUX 42 | #include 43 | #define SLEEP(t) usleep((t) * 1000) 44 | #elif DPS_TARGET == DPS_TARGET_ZEPHYR 45 | #define SLEEP(t) k_sleep(t) 46 | #endif 47 | 48 | #define ASSERT(cond) do { assert(cond); if (!(cond)) exit(EXIT_FAILURE); } while (0) 49 | 50 | static int atLine; 51 | #define CHECK(cond) if (!(cond)) { atLine = __LINE__; goto failed; } 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /dps-micro/zephyr/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.8.2) 2 | 3 | include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) 4 | project(dps_app) 5 | 6 | include(ExternalProject) 7 | find_package(Git REQUIRED) 8 | 9 | set(ext_dir ${CMAKE_CURRENT_SOURCE_DIR}/../ext) 10 | set(mbedtls_dir ${ext_dir}/mbedtls) 11 | 12 | if(NOT EXISTS ${mbedtls_dir}) 13 | execute_process(COMMAND ${GIT_EXECUTABLE} clone https://github.com/ARMmbed/mbedtls.git ${mbedtls_dir}) 14 | execute_process(COMMAND ${GIT_EXECUTABLE} -C ${mbedtls_dir} checkout tags/mbedtls-2.8.0) 15 | endif() 16 | 17 | add_compile_definitions(MBEDTLS_USER_CONFIG_FILE="${ext_dir}/mbedtls_config_zephyr.h") 18 | 19 | include_directories("../include") 20 | include_directories("${mbedtls_dir}/include") 21 | 22 | add_compile_definitions(DPS_DEBUG=1) 23 | add_compile_definitions(DPS_TARGET=DPS_TARGET_ZEPHYR) 24 | 25 | set(mbedtls_sources 26 | ${mbedtls_dir}/library/aes.c 27 | ${mbedtls_dir}/library/aesni.c 28 | ${mbedtls_dir}/library/asn1write.c 29 | ${mbedtls_dir}/library/asn1parse.c 30 | ${mbedtls_dir}/library/base64.c 31 | ${mbedtls_dir}/library/bignum.c 32 | ${mbedtls_dir}/library/cipher.c 33 | ${mbedtls_dir}/library/cipher_wrap.c 34 | ${mbedtls_dir}/library/ctr_drbg.c 35 | ${mbedtls_dir}/library/debug.c 36 | ${mbedtls_dir}/library/ecdh.c 37 | ${mbedtls_dir}/library/ecdsa.c 38 | ${mbedtls_dir}/library/ecp.c 39 | ${mbedtls_dir}/library/ecp_curves.c 40 | ${mbedtls_dir}/library/entropy.c 41 | ${mbedtls_dir}/library/entropy_poll.c 42 | ${mbedtls_dir}/library/error.c 43 | ${mbedtls_dir}/library/gcm.c 44 | ${mbedtls_dir}/library/hmac_drbg.c 45 | ${mbedtls_dir}/library/md.c 46 | ${mbedtls_dir}/library/md_wrap.c 47 | ${mbedtls_dir}/library/md5.c 48 | ${mbedtls_dir}/library/oid.c 49 | ${mbedtls_dir}/library/pem.c 50 | ${mbedtls_dir}/library/pk.c 51 | ${mbedtls_dir}/library/pk_wrap.c 52 | ${mbedtls_dir}/library/pkparse.c 53 | ${mbedtls_dir}/library/platform.c 54 | ${mbedtls_dir}/library/sha256.c 55 | ${mbedtls_dir}/library/sha512.c 56 | ${mbedtls_dir}/library/timing.c 57 | ${mbedtls_dir}/library/x509.c 58 | ${mbedtls_dir}/library/x509_crt.c 59 | ${mbedtls_dir}/library/ssl_cache.c 60 | ${mbedtls_dir}/library/ssl_ciphersuites.c 61 | ${mbedtls_dir}/library/ssl_cli.c 62 | ${mbedtls_dir}/library/ssl_cookie.c 63 | ${mbedtls_dir}/library/ssl_srv.c 64 | ${mbedtls_dir}/library/ssl_tls.c 65 | ) 66 | 67 | FILE(GLOB dps_sources "../src/*.c") 68 | 69 | target_sources(app PRIVATE "../src/zephyr/network.c") 70 | target_sources(app PRIVATE "../src/zephyr/dbg.c") 71 | target_sources(app PRIVATE "../src/zephyr/entropy.c") 72 | target_sources(app PRIVATE "../src/zephyr/malloc.c") 73 | target_sources(app PRIVATE ${dps_sources}) 74 | target_sources(app PRIVATE ${mbedtls_sources}) 75 | 76 | # The application to build 77 | include_directories("../test") 78 | target_sources(app PRIVATE "../test/keys.c") 79 | target_sources(app PRIVATE "../test/sub_unit_test.c") 80 | -------------------------------------------------------------------------------- /dps-micro/zephyr/config_stm.bat: -------------------------------------------------------------------------------- 1 | set ZEPHYR_TOOLCHAIN_VARIANT=gnuarmemb 2 | set GNUARMEMB_TOOLCHAIN_PATH=c:\gnu_arm_tools 3 | cmake -Bbuild -DBOARD=stm32f746g_disco -GNinja . 4 | -------------------------------------------------------------------------------- /dps-micro/zephyr/prj.conf: -------------------------------------------------------------------------------- 1 | # Generic networking options 2 | CONFIG_NETWORKING=y 3 | CONFIG_NET_UDP=y 4 | CONFIG_NET_TCP=y 5 | CONFIG_NET_IPV6=y 6 | CONFIG_NET_IPV4=y 7 | 8 | # Kernel options 9 | CONFIG_MAIN_STACK_SIZE=5192 10 | CONFIG_ENTROPY_GENERATOR=y 11 | CONFIG_INIT_STACKS=y 12 | 13 | # Debug 14 | CONFIG_DEBUG=y 15 | CONFIG_STACK_SENTINEL=y 16 | 17 | # Logging 18 | CONFIG_NET_LOG=y 19 | CONFIG_LOG=y 20 | CONFIG_NET_STATISTICS=y 21 | CONFIG_PRINTK=y 22 | 23 | # Network buffers 24 | CONFIG_NET_PKT_RX_COUNT=16 25 | CONFIG_NET_PKT_TX_COUNT=16 26 | CONFIG_NET_BUF_RX_COUNT=80 27 | CONFIG_NET_BUF_TX_COUNT=80 28 | CONFIG_NET_CONTEXT_NET_PKT_POOL=y 29 | CONFIG_NET_RX_STACK_SIZE=4096 30 | 31 | # IP address options 32 | CONFIG_NET_CONFIG_SETTINGS=y 33 | CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=5 34 | CONFIG_NET_MAX_CONTEXTS=4 35 | 36 | # Drivers 37 | CONFIG_NET_L2_ETHERNET=y 38 | 39 | -------------------------------------------------------------------------------- /dps-micro/zephyr/sample.yaml: -------------------------------------------------------------------------------- 1 | sample: 2 | description: Zephyr port of DPS 3 | name: dps_app 4 | common: 5 | tags: DPS 6 | harness: console 7 | harness_config: 8 | type: one_line 9 | regex: 10 | - "Hello World! (.*)" 11 | tests: 12 | sample.helloworld: 13 | tags: DPS 14 | -------------------------------------------------------------------------------- /dps_ns3.pc.in: -------------------------------------------------------------------------------- 1 | # Package Information for pkg-config 2 | 3 | prefix=@PREFIX@ 4 | exec_prefix=${prefix} 5 | libdir=${prefix}/build/dist/lib 6 | includedir=${prefix}/inc 7 | 8 | Name: dps_ns3 9 | Description: Distributed Publish & Subscribe for IoT 10 | Version: @VERSION@ 11 | Requires: 12 | Libs: -L${libdir} -ldps_ns3 13 | Cflags: -I${includedir} -I${prefix}/ext/safestring/include 14 | -------------------------------------------------------------------------------- /dps_shared.def: -------------------------------------------------------------------------------- 1 | LIBRARY dps_shared 2 | 3 | EXPORTS 4 | 5 | DPS_AckGetSenderKeyId 6 | DPS_AckGetSequenceNum 7 | DPS_AckPublication 8 | DPS_AckPublicationBufs 9 | DPS_CBOR2JSON 10 | DPS_CopyAddress 11 | DPS_CopyPublication 12 | DPS_CreateAddress 13 | DPS_CreateDiscoveryService 14 | DPS_CreateDispatcher 15 | DPS_CreateEvent 16 | DPS_CreateKeyStore 17 | DPS_CreateMemoryKeyStore 18 | DPS_CreateNode 19 | DPS_CreatePublication 20 | DPS_CreateRegistrationList 21 | DPS_CreateSubscription 22 | DPS_Debug 23 | DPS_DestroyAddress 24 | DPS_DestroyDiscoveryService 25 | DPS_DestroyDispatcher 26 | DPS_DestroyEvent 27 | DPS_DestroyKeyStore 28 | DPS_DestroyMemoryKeyStore 29 | DPS_DestroyNode 30 | DPS_DestroyPublication 31 | DPS_DestroyRegistrationList 32 | DPS_DestroySubscription 33 | DPS_DiscoveryPublish 34 | DPS_Dispatch 35 | DPS_ErrTxt 36 | DPS_GenerateUUID 37 | DPS_GetDiscoveryServiceData 38 | DPS_GetEventData 39 | DPS_GetKeyStoreData 40 | DPS_GetListenAddress 41 | DPS_GetListenAddressString 42 | DPS_GetNodeData 43 | DPS_GetPublicationData 44 | DPS_GetSubscriptionData 45 | DPS_InitPublication 46 | DPS_InitUUID 47 | DPS_JSON2CBOR 48 | DPS_KeyStoreHandle 49 | DPS_Link 50 | DPS_LinkTo 51 | DPS_Log 52 | DPS_LogBytes 53 | DPS_MemoryKeyStoreHandle 54 | DPS_NodeAddrToString 55 | DPS_PublicationAddSubId 56 | DPS_PublicationGetNode 57 | DPS_PublicationGetNumTopics 58 | DPS_PublicationGetSenderKeyId 59 | DPS_PublicationGetSequenceNum 60 | DPS_PublicationGetTopic 61 | DPS_PublicationGetTTL 62 | DPS_PublicationGetUUID 63 | DPS_PublicationIsAckRequested 64 | DPS_PublicationRemoveSubId 65 | DPS_Publish 66 | DPS_PublishBufs 67 | DPS_Registration_Get 68 | DPS_Registration_GetSyn 69 | DPS_Registration_LinkTo 70 | DPS_Registration_LinkToSyn 71 | DPS_Registration_Put 72 | DPS_Registration_PutSyn 73 | DPS_RegistryTopicString 74 | DPS_ResolveAddress 75 | DPS_ScheduleCall 76 | DPS_SetAddress 77 | DPS_SetCA 78 | DPS_SetCertificate 79 | DPS_SetContentKey 80 | DPS_SetDiscoveryServiceData 81 | DPS_SetEventData 82 | DPS_SetKey 83 | DPS_SetKeyAndId 84 | DPS_SetKeyStoreData 85 | DPS_SetLinkLossCallback 86 | DPS_SetNetworkKey 87 | DPS_SetNodeData 88 | DPS_SetNodeLinkLossTimeout 89 | DPS_SetNodeSubscriptionUpdateDelay 90 | DPS_SetPublicationData 91 | DPS_SetSubscriptionData 92 | DPS_SetTrustedCA 93 | DPS_ShutdownNode 94 | DPS_SignalEvent 95 | DPS_StartNode 96 | DPS_Subscribe 97 | DPS_SubscribeExpired 98 | DPS_SubscriptionGetNode 99 | DPS_SubscriptionGetNumTopics 100 | DPS_SubscriptionGetTopic 101 | DPS_TimedWaitForEvent 102 | DPS_Unlink 103 | DPS_UnlinkFrom 104 | DPS_UUIDCompare 105 | DPS_UUIDToString 106 | DPS_WaitForEvent 107 | -------------------------------------------------------------------------------- /examples/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _COMMON_H 24 | #define _COMMON_H 25 | 26 | #include 27 | 28 | #if defined(_MSC_VER) 29 | #define strdup _strdup 30 | #endif 31 | 32 | #ifdef __cplusplus 33 | extern "C" { 34 | #endif 35 | 36 | #define MAX_LINKS 16 37 | 38 | int IntArg(char* opt, char*** argp, int* argcp, int* val, int min, int max); 39 | int ListenArg(char*** argp, int* argcp, DPS_NodeAddress** addr); 40 | int LinkArg(char*** argp, int* argcp, char** addrText, int* numAddrText); 41 | int UnlinkArg(char*** argp, int* argcp, char** addrText); 42 | DPS_Status Link(DPS_Node* node, char** addrText, DPS_NodeAddress** addr, int numAddr); 43 | void Unlink(DPS_Node* node, DPS_NodeAddress** addr, int numAddr); 44 | void DestroyLinkArg(char **addrText, DPS_NodeAddress** addr, int numAddr); 45 | 46 | #ifdef __cplusplus 47 | } 48 | #endif 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /examples/keys.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _KEYS_H 24 | #define _KEYS_H 25 | 26 | #include 27 | #include 28 | 29 | #ifdef __cplusplus 30 | extern "C" { 31 | #endif 32 | 33 | /* 34 | * Preshared keys and certificates for testing only - DO NOT USE THESE KEYS IN A REAL APPLICATION!!!! 35 | */ 36 | 37 | extern const DPS_KeyId NetworkKeyId; 38 | extern const DPS_Key NetworkKey; 39 | 40 | #define NUM_KEYS 2 41 | 42 | extern const DPS_KeyId PskId[NUM_KEYS]; 43 | extern const DPS_Key Psk[NUM_KEYS]; 44 | 45 | extern const char TrustedCAs[]; 46 | 47 | extern const DPS_KeyId PublisherId; 48 | extern const char PublisherCert[]; 49 | extern const char PublisherPrivateKey[]; 50 | extern const char PublisherPassword[]; 51 | 52 | extern const DPS_KeyId SubscriberId; 53 | extern const char SubscriberCert[]; 54 | extern const char SubscriberPrivateKey[]; 55 | extern const char SubscriberPassword[]; 56 | 57 | const char* KeyIdToString(const DPS_KeyId* keyId); 58 | 59 | #ifdef __cplusplus 60 | } 61 | #endif 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /ext/0001-DPS.patch: -------------------------------------------------------------------------------- 1 | From a80a12c6a4c72a4209c94614e77c79d7bdf2bd42 Mon Sep 17 00:00:00 2001 2 | From: Todd Malsbary 3 | Date: Tue, 8 Jan 2019 15:17:16 -0800 4 | Subject: [PATCH] DPS 5 | 6 | --- 7 | include/safe_lib.h | 11 +++++++++++ 8 | 1 file changed, 11 insertions(+) 9 | 10 | diff --git a/include/safe_lib.h b/include/safe_lib.h 11 | index 8e02899..0b0f601 100644 12 | --- a/include/safe_lib.h 13 | +++ b/include/safe_lib.h 14 | @@ -33,6 +33,17 @@ 15 | #ifndef __SAFE_LIB_H__ 16 | #define __SAFE_LIB_H__ 17 | 18 | +/* 19 | + * MinGW includes slightly different (and for strtok_s, conflicting) 20 | + * prototypes of the safe APIs. 21 | + */ 22 | +#ifdef __MINGW64__ 23 | +#include <_mingw.h> 24 | +#ifdef MINGW_HAS_SECURE_API 25 | +#undef MINGW_HAS_SECURE_API 26 | +#endif 27 | +#endif 28 | + 29 | #include "safe_types.h" 30 | #include "safe_lib_errno.h" 31 | 32 | -- 33 | 2.17.0.windows.1 34 | 35 | -------------------------------------------------------------------------------- /ext/SConscript.intel-ipsec-mb: -------------------------------------------------------------------------------- 1 | import os 2 | Import(['env']) 3 | 4 | # Pull down intel-ipsec-mb from github and build the library 5 | 6 | # optimized sha512 requires nasm and x86_64 7 | if env['TARGET_ARCH'] != 'x86' and env.Detect('nasm') != None: 8 | mbenv = env.Clone(tools=['nasm']) 9 | 10 | git = mbenv.Command('./intel-ipsec-mb/.git', None, 11 | ['git clone -q -n https://github.com/intel/intel-ipsec-mb.git ext/intel-ipsec-mb']) 12 | 13 | dep = mbenv.Command('./intel-ipsec-mb/README', git, 14 | ['git fetch -q', 'git checkout -q master'], 15 | chdir = 'ext/intel-ipsec-mb') 16 | 17 | sources = [ 18 | './intel-ipsec-mb/lib/sse/sha512_one_block_sse.asm', 19 | './intel-ipsec-mb/lib/avx/sha512_one_block_avx.asm' 20 | ] 21 | 22 | if mbenv['PLATFORM'] == 'win32': 23 | mbenv['ASFLAGS'] = [ 24 | '-fwin64', 25 | '-Xvc', 26 | '-DWIN_ABI', 27 | '-I./ext/intel-ipsec-mb/lib/' 28 | ] 29 | else: 30 | mbenv['ASFLAGS'] = [ 31 | '-felf64', 32 | '-Xgnu', 33 | '-gdwarf', 34 | '-DLINUX', 35 | '-D__linux__', 36 | '-I./ext/intel-ipsec-mb/lib/' 37 | ] 38 | 39 | objs = mbenv.Object(sources) 40 | shobjs = mbenv.SharedObject(sources) 41 | 42 | Depends(sources, dep) 43 | 44 | else: 45 | objs = [] 46 | shobjs = [] 47 | 48 | Return('objs shobjs') 49 | -------------------------------------------------------------------------------- /ext/SConscript.mbedtls: -------------------------------------------------------------------------------- 1 | import os 2 | Import(['env']) 3 | 4 | # Pull down mbedtls from github and build the library 5 | 6 | mtenv = env.Clone() 7 | 8 | # mbedtls uses gmtime_s, so we need the secure lib here 9 | try: 10 | mtenv['CPPDEFINES'].remove('__STDC_WANT_SECURE_LIB__=0') 11 | except ValueError: 12 | pass 13 | 14 | git = mtenv.Command('./mbedtls/.git', None, 15 | ['git clone -q -n https://github.com/ARMmbed/mbedtls ext/mbedtls']) 16 | 17 | dep = mtenv.Command('./mbedtls/Makefile', git, 18 | ['git fetch -q', 'git checkout -q tags/mbedtls-2.16.0'], 19 | chdir = 'ext/mbedtls') 20 | 21 | mtenv.Append(CPPPATH = ['.', './mbedtls/include/',]) 22 | mtenv.Append(CPPDEFINES = ['MBEDTLS_USER_CONFIG_FILE=\\"mbedtls_config.h\\"',]) 23 | # optimized sha512 requires nasm and x86_64 24 | if env['TARGET_ARCH'] != 'x86' and env.Detect('nasm') != None: 25 | mtenv.Append(CPPDEFINES = ['DPS_USE_NASM']) 26 | 27 | sources = [ 28 | './mbedtls/library/aes.c', 29 | './mbedtls/library/aesni.c', 30 | './mbedtls/library/asn1write.c', 31 | './mbedtls/library/asn1parse.c', 32 | './mbedtls/library/base64.c', 33 | './mbedtls/library/bignum.c', 34 | './mbedtls/library/cipher.c', 35 | './mbedtls/library/cipher_wrap.c', 36 | './mbedtls/library/ctr_drbg.c', 37 | './mbedtls/library/debug.c', 38 | './mbedtls/library/ecdh.c', 39 | './mbedtls/library/ecdsa.c', 40 | './mbedtls/library/ecp.c', 41 | './mbedtls/library/ecp_curves.c', 42 | './mbedtls/library/entropy.c', 43 | './mbedtls/library/entropy_poll.c', 44 | './mbedtls/library/error.c', 45 | './mbedtls/library/gcm.c', 46 | './mbedtls/library/hkdf.c', 47 | './mbedtls/library/hmac_drbg.c', 48 | './mbedtls/library/md.c', 49 | './mbedtls/library/md_wrap.c', 50 | './mbedtls/library/md5.c', 51 | './mbedtls/library/nist_kw.c', 52 | './mbedtls/library/oid.c', 53 | './mbedtls/library/padlock.c', 54 | './mbedtls/library/pem.c', 55 | './mbedtls/library/pk.c', 56 | './mbedtls/library/pk_wrap.c', 57 | './mbedtls/library/pkparse.c', 58 | './mbedtls/library/platform.c', 59 | './mbedtls/library/platform_util.c', 60 | './mbedtls/library/sha256.c', 61 | './mbedtls/library/sha512.c', 62 | './mbedtls/library/timing.c', 63 | './mbedtls/library/x509.c', 64 | './mbedtls/library/x509_crt.c' 65 | ] 66 | 67 | sources += [ 68 | './mbedtls/library/ssl_cache.c', 69 | './mbedtls/library/ssl_ciphersuites.c', 70 | './mbedtls/library/ssl_cli.c', 71 | './mbedtls/library/ssl_cookie.c', 72 | './mbedtls/library/ssl_srv.c', 73 | './mbedtls/library/ssl_tls.c', 74 | ] 75 | 76 | sources += [ 77 | './mbedtls_sha512_process_alt.c' 78 | ] 79 | 80 | objs = mtenv.Object(sources) 81 | shobjs = mtenv.SharedObject(sources) 82 | 83 | Depends(sources, dep) 84 | Depends(objs, './mbedtls_config.h') 85 | Depends(shobjs, './mbedtls_config.h') 86 | 87 | Return('objs shobjs') 88 | -------------------------------------------------------------------------------- /ext/SConscript.safestring: -------------------------------------------------------------------------------- 1 | import os 2 | Import(['env']) 3 | 4 | # Pull down safestringlib from github and build the library 5 | 6 | scenv = env.Clone() 7 | 8 | scgit = scenv.Command('./safestring/.git', None, 9 | ['git clone -q -n https://github.com/intel/safestringlib.git ext/safestring']) 10 | screl = scenv.Command('./safestring/makefile', scgit, 11 | ['git fetch -q', 'git checkout -q 77b772849eda2321fb0dca56a321e3939930d7b9', 12 | 'git am -q ../0001-DPS.patch'], 13 | chdir = 'ext/safestring') 14 | 15 | sources = [ 16 | './safestring/safeclib/ignore_handler_s.c', 17 | './safestring/safeclib/safe_mem_constraint.c', 18 | './safestring/safeclib/safe_str_constraint.c', 19 | './safestring/safeclib/memset_s.c', 20 | './safestring/safeclib/memzero_s.c', 21 | './safestring/safeclib/strcat_s.c', 22 | './safestring/safeclib/strcmp_s.c', 23 | './safestring/safeclib/strnlen_s.c', 24 | './safestring/safeclib/mem_primitives_lib.c' 25 | ] 26 | 27 | if scenv['PLATFORM'] == 'posix' or scenv['CC'] == 'cl': 28 | sources += [ 29 | './safestring/safeclib/memcpy_s.c', 30 | './safestring/safeclib/memmove_s.c', 31 | './safestring/safeclib/strncpy_s.c' 32 | ] 33 | 34 | scenv['CPPPATH'] = './safestring/include' 35 | 36 | objs = scenv.Object(sources) 37 | shobjs = scenv.SharedObject(sources) 38 | 39 | Depends(sources, screl) 40 | 41 | Return('objs shobjs') 42 | -------------------------------------------------------------------------------- /ext/mbedtls_config.h: -------------------------------------------------------------------------------- 1 | /* Use config file, to replace mbed defaults. It is set during 2 | * compilation with MBEDTLS_USER_CONFIG_FILE environment variable. */ 3 | 4 | #define MBEDTLS_DEPRECATED_REMOVED 5 | #define MBEDTLS_NIST_KW_C 6 | #if defined(DPS_USE_NASM) && (defined(__AVX2__) || defined(__AVX__) || defined(__SSE__) || defined(_M_X64) || defined(_M_AMD64)) 7 | #define MBEDTLS_SHA512_PROCESS_ALT 8 | #endif 9 | 10 | #undef MBEDTLS_ARC4_C 11 | #undef MBEDTLS_BLOWFISH_C 12 | #undef MBEDTLS_CAMELLIA_C 13 | #undef MBEDTLS_CCM_C 14 | #undef MBEDTLS_CHACHA20_C 15 | #undef MBEDTLS_CHACHAPOLY_C 16 | #undef MBEDTLS_CIPHER_MODE_OFB 17 | #undef MBEDTLS_CIPHER_MODE_XTS 18 | #undef MBEDTLS_DES_C 19 | #undef MBEDTLS_DHM_C 20 | #undef MBEDTLS_ECP_DP_BP256R1_ENABLED 21 | #undef MBEDTLS_ECP_DP_BP384R1_ENABLED 22 | #undef MBEDTLS_ECP_DP_BP512R1_ENABLED 23 | #undef MBEDTLS_ECP_DP_CURVE25519_ENABLED 24 | #undef MBEDTLS_ECP_DP_CURVE448_ENABLED 25 | #undef MBEDTLS_ECP_DP_SECP192K1_ENABLED 26 | #undef MBEDTLS_ECP_DP_SECP192R1_ENABLED 27 | #undef MBEDTLS_ECP_DP_SECP224K1_ENABLED 28 | #undef MBEDTLS_ECP_DP_SECP224R1_ENABLED 29 | #undef MBEDTLS_ECP_DP_SECP256K1_ENABLED 30 | #undef MBEDTLS_ECP_DP_SECP256R1_ENABLED 31 | #undef MBEDTLS_FS_IO 32 | #undef MBEDTLS_GENPRIME 33 | #undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED 34 | #undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED 35 | #undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED 36 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED 37 | #undef MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED 38 | #undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED 39 | #undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED 40 | #undef MBEDTLS_NET_C 41 | #undef MBEDTLS_PEM_WRITE_C 42 | #undef MBEDTLS_PKCS12_C 43 | #undef MBEDTLS_PKCS5_C 44 | #undef MBEDTLS_PK_RSA_ALT_SUPPORT 45 | #undef MBEDTLS_POLY1305_C 46 | #undef MBEDTLS_RIPEMD160_C 47 | #undef MBEDTLS_RSA_C 48 | #undef MBEDTLS_SELF_TEST 49 | #undef MBEDTLS_SHA1_C 50 | #undef MBEDTLS_SSL_CBC_RECORD_SPLITTING 51 | #undef MBEDTLS_SSL_PROTO_TLS1 52 | #undef MBEDTLS_SSL_PROTO_TLS1_1 53 | #undef MBEDTLS_X509_RSASSA_PSS_SUPPORT 54 | -------------------------------------------------------------------------------- /ext/mbedtls_sha512_process_alt.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2019 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | 25 | #if defined(DPS_USE_NASM) 26 | 27 | #if defined(__AVX2__) || defined(__AVX__) 28 | 29 | extern void sha512_block_avx( const void *, 30 | void * ); 31 | 32 | int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, 33 | const unsigned char data[128] ) 34 | { 35 | sha512_block_avx( data, ctx->state ); 36 | return ( 0 ); 37 | } 38 | 39 | #elif defined(__SSE__) || defined(_M_X64) || defined(_M_AMD64) 40 | 41 | extern void sha512_block_sse( const void *, 42 | void * ); 43 | 44 | int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, 45 | const unsigned char data[128] ) 46 | { 47 | sha512_block_sse( data, ctx->state ); 48 | return ( 0 ); 49 | } 50 | 51 | #endif 52 | 53 | #endif /* DPS_USE_NASM */ 54 | -------------------------------------------------------------------------------- /go/README.md: -------------------------------------------------------------------------------- 1 | ## Running 2 | 3 | ### Linux 4 | 5 | ``` shell 6 | cd $DPS_FOR_IOT/build/dist/go 7 | ./simple_pub 8 | ``` 9 | 10 | ### Windows 11 | Note that DPS must be built with the MinGW toolchain for use with Go. 12 | ``` shell 13 | scons --tool=mingw bindings=go 14 | ``` 15 | 16 | ``` shell 17 | cd %DPS_FOR_IOT%\build\dist\go 18 | simple_pub 19 | ``` 20 | -------------------------------------------------------------------------------- /go/examples/simple_pub/simple_pub.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "dps" 5 | "dps/examples/keys" 6 | "fmt" 7 | "os" 8 | "strconv" 9 | "time" 10 | ) 11 | 12 | func main() { 13 | dps.SetDebug(0) 14 | encryption := 1 15 | for i := 0; i < len(os.Args); i++ { 16 | if os.Args[i] == "-x" { 17 | i++ 18 | encryption, _ = strconv.Atoi(os.Args[i]) 19 | } else if os.Args[i] == "-d" { 20 | dps.SetDebug(1) 21 | } 22 | } 23 | 24 | var nodeId, pubKeyId []byte 25 | keyStore := dps.CreateMemoryKeyStore() 26 | dps.SetNetworkKey(keyStore, keys.NetworkKeyId, keys.NetworkKey) 27 | if encryption == 0 { 28 | nodeId = nil 29 | pubKeyId = nil 30 | } else if encryption == 1 { 31 | for i := 0; i < len(keys.KeyId); i++ { 32 | dps.SetContentKey(keyStore, keys.KeyId[i], keys.KeyData[i]) 33 | } 34 | nodeId = nil 35 | pubKeyId = keys.KeyId[0] 36 | } else if encryption == 2 { 37 | dps.SetTrustedCA(keyStore, keys.CA) 38 | dps.SetCertificate(keyStore, keys.PublisherCert, &keys.PublisherPrivateKey, &keys.PublisherPassword) 39 | dps.SetCertificate(keyStore, keys.SubscriberCert, nil, nil) 40 | nodeId = []byte(keys.PublisherId) 41 | pubKeyId = []byte(keys.SubscriberId) 42 | } 43 | 44 | node := dps.CreateNode("/", keyStore, nodeId) 45 | dps.StartNode(node, dps.MCAST_PUB_ENABLE_SEND, nil) 46 | fmt.Printf("Publisher is listening on %v\n", dps.GetListenAddressString(node)) 47 | 48 | pub := dps.CreatePublication(node) 49 | 50 | dps.InitPublication(pub, []string{"a/b/c"}, false, func(pub *dps.Publication, payload []byte) { 51 | fmt.Printf("Ack for pub UUID %v(%v)\n", dps.PublicationGetUUID(pub), dps.PublicationGetSequenceNum(pub)) 52 | fmt.Printf(" %v\n", string(payload)) 53 | }) 54 | dps.PublicationAddSubId(pub, pubKeyId) 55 | dps.Publish(pub, []byte("hello"), 0) 56 | fmt.Printf("Pub UUID %v(%v)\n", dps.PublicationGetUUID(pub), dps.PublicationGetSequenceNum(pub)) 57 | time.Sleep(100 * time.Millisecond) 58 | dps.Publish(pub, []byte("world"), 0) 59 | fmt.Printf("Pub UUID %v(%v)\n", dps.PublicationGetUUID(pub), dps.PublicationGetSequenceNum(pub)) 60 | time.Sleep(100 * time.Millisecond) 61 | 62 | dps.DestroyPublication(pub, func(pub *dps.Publication) {}) 63 | dps.DestroyNode(node, func(node *dps.Node) { 64 | dps.DestroyKeyStore(keyStore) 65 | }) 66 | } 67 | -------------------------------------------------------------------------------- /go/examples/simple_sub/simple_sub.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "dps" 5 | "dps/examples/keys" 6 | "fmt" 7 | "os" 8 | "strconv" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | func main() { 14 | dps.SetDebug(0) 15 | encryption := 1 16 | for i := 0; i < len(os.Args); i++ { 17 | if os.Args[i] == "-x" { 18 | i++ 19 | encryption, _ = strconv.Atoi(os.Args[i]) 20 | } else if os.Args[i] == "-d" { 21 | dps.SetDebug(1) 22 | } 23 | } 24 | 25 | var nodeId []byte 26 | keyStore := dps.CreateMemoryKeyStore() 27 | dps.SetNetworkKey(keyStore, keys.NetworkKeyId, keys.NetworkKey) 28 | if encryption == 0 { 29 | nodeId = nil 30 | } else if encryption == 1 { 31 | for i := 0; i < len(keys.KeyId); i++ { 32 | dps.SetContentKey(keyStore, keys.KeyId[i], keys.KeyData[i]) 33 | } 34 | nodeId = nil 35 | } else if encryption == 2 { 36 | dps.SetTrustedCA(keyStore, keys.CA) 37 | dps.SetCertificate(keyStore, keys.SubscriberCert, &keys.SubscriberPrivateKey, &keys.SubscriberPassword) 38 | dps.SetCertificate(keyStore, keys.PublisherCert, nil, nil) 39 | nodeId = []byte(keys.SubscriberId) 40 | } 41 | 42 | node := dps.CreateNode("/", keyStore, nodeId) 43 | dps.StartNode(node, dps.MCAST_PUB_ENABLE_RECV, nil) 44 | fmt.Printf("Subscriber is listening on %v\n", dps.GetListenAddressString(node)) 45 | 46 | sub := dps.CreateSubscription(node, []string{"a/b/c"}) 47 | dps.Subscribe(sub, func(sub *dps.Subscription, pub *dps.Publication, payload []byte) { 48 | fmt.Printf("Pub %v(%v) matches:\n", dps.PublicationGetUUID(pub), dps.PublicationGetSequenceNum(pub)) 49 | fmt.Printf(" pub %v\n", strings.Join(dps.PublicationGetTopics(pub), " | ")) 50 | fmt.Printf(" sub %v\n", strings.Join(dps.SubscriptionGetTopics(sub), " | ")) 51 | fmt.Printf("%v\n", string(payload)) 52 | if dps.PublicationIsAckRequested(pub) { 53 | ackMsg := fmt.Sprintf("This is an ACK from %v", dps.GetListenAddressString(node)) 54 | fmt.Printf("Sending ack for pub UUID %v(%v)\n", dps.PublicationGetUUID(pub), dps.PublicationGetSequenceNum(pub)) 55 | fmt.Printf(" %v\n", ackMsg) 56 | dps.AckPublication(pub, []byte(ackMsg)) 57 | } 58 | }) 59 | 60 | for { 61 | time.Sleep(1 * time.Second) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /go/test/perf_publisher/perf_publisher.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "dps" 5 | "flag" 6 | "fmt" 7 | "math" 8 | "log" 9 | "os" 10 | "runtime/pprof" 11 | "sync" 12 | "time" 13 | ) 14 | 15 | var ( 16 | debug = flag.Bool("d", false, "enable debug output if built for debug") 17 | linkText = flag.String("p", "", "address to link") 18 | payloadSize = flag.Int("s", 0, "size of PUB payload") 19 | numPubs = flag.Int("n", 1000, "number of publications to send") 20 | cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") 21 | rtTime time.Duration 22 | prev time.Time 23 | lock = sync.Mutex{} 24 | cond = sync.NewCond(&lock) 25 | ackReceived = false 26 | ) 27 | 28 | func elapsedTime() (elapsed time.Duration) { 29 | now := time.Now() 30 | elapsed = now.Sub(prev) 31 | prev = now 32 | return 33 | } 34 | 35 | func onAck(pub *dps.Publication, payload []byte) { 36 | rtTime = elapsedTime() 37 | lock.Lock() 38 | ackReceived = true 39 | cond.Signal() 40 | lock.Unlock() 41 | } 42 | 43 | func main() { 44 | flag.Parse() 45 | if *debug { 46 | dps.SetDebug(1) 47 | } else { 48 | dps.SetDebug(0) 49 | } 50 | if *cpuprofile != "" { 51 | f, err := os.Create(*cpuprofile) 52 | if err != nil { 53 | log.Fatal(err) 54 | } 55 | pprof.StartCPUProfile(f) 56 | defer pprof.StopCPUProfile() 57 | } 58 | 59 | mcast := dps.MCAST_PUB_ENABLE_SEND 60 | if *linkText != "" { 61 | mcast = dps.MCAST_PUB_DISALBED 62 | } 63 | 64 | node := dps.CreateNode("/", nil, nil) 65 | dps.StartNode(node, mcast, nil) 66 | 67 | if *linkText != "" { 68 | err := dps.LinkTo(node, *linkText, nil) 69 | if err != dps.OK { 70 | fmt.Printf("dps.LinkTo %v returned %s\n", *linkText, dps.ErrTxt(err)) 71 | return 72 | } 73 | } 74 | 75 | rtMin := time.Duration(math.MaxInt64) 76 | var rtMax, rtSum time.Duration 77 | 78 | pub := dps.CreatePublication(node) 79 | dps.InitPublication(pub, []string{"dps/roundtrip"}, false, onAck) 80 | var payload []byte 81 | if *payloadSize != 0 { 82 | payload = make([]byte, *payloadSize) 83 | } 84 | for i := 0; i < *numPubs; i++ { 85 | lock.Lock() 86 | ackReceived = false 87 | lock.Unlock() 88 | elapsedTime() // Initialize the round trip timer 89 | dps.Publish(pub, payload, 0) 90 | lock.Lock() 91 | for !ackReceived { 92 | cond.Wait() 93 | } 94 | lock.Unlock() 95 | if i != 0 { 96 | if rtTime > rtMax { 97 | rtMax = rtTime 98 | } 99 | if rtTime < rtMin { 100 | rtMin = rtTime 101 | } 102 | rtSum += rtTime 103 | } 104 | } 105 | 106 | fmt.Printf("Total pub sent = %v, payload size %v\n", *numPubs, *payloadSize) 107 | fmt.Printf("Min RT = %v, Max RT = %v, Avg RT %v\n", rtMin, rtMax, 108 | time.Duration(rtSum.Nanoseconds() / int64(*numPubs))) 109 | dps.DestroyPublication(pub, func(pub *dps.Publication) {}) 110 | dps.DestroyNode(node, func(node *dps.Node) {}) 111 | } 112 | -------------------------------------------------------------------------------- /go/test/perf_subscriber/perf_subscriber.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "dps" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "os" 9 | "runtime/pprof" 10 | "sync" 11 | ) 12 | 13 | var ( 14 | debug = flag.Bool("d", false, "enable debug output if built for debug") 15 | listenText = flag.Int("p", 0, "address to link") 16 | payloadSize = flag.Int("s", 0, "size of PUB payload") 17 | cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") 18 | lock = sync.Mutex{} 19 | cond = sync.NewCond(&lock) 20 | payload []byte 21 | ) 22 | 23 | func onPubMatch(sub *dps.Subscription, pub *dps.Publication, data []byte) { 24 | if dps.PublicationIsAckRequested(pub) { 25 | var ret int 26 | if *payloadSize < 0 { 27 | ret = dps.AckPublication(pub, data) 28 | } else { 29 | ret = dps.AckPublication(pub, payload) 30 | } 31 | if ret != dps.OK { 32 | fmt.Printf("Failed to ack pub %v\n", dps.ErrTxt(ret)) 33 | } 34 | } 35 | } 36 | 37 | func main() { 38 | flag.Parse() 39 | if *debug { 40 | dps.SetDebug(1) 41 | } else { 42 | dps.SetDebug(0) 43 | } 44 | if *cpuprofile != "" { 45 | f, err := os.Create(*cpuprofile) 46 | if err != nil { 47 | log.Fatal(err) 48 | } 49 | pprof.StartCPUProfile(f) 50 | defer pprof.StopCPUProfile() 51 | } 52 | 53 | node := dps.CreateNode("/", nil, nil) 54 | listenAddr := dps.CreateAddress() 55 | dps.SetAddress(listenAddr, fmt.Sprintf(":%v", *listenText)) 56 | dps.StartNode(node, dps.MCAST_PUB_ENABLE_RECV, listenAddr) 57 | fmt.Printf("Subscriber is listening on %v\n", dps.GetListenAddressString(node)) 58 | 59 | if *payloadSize > 0 { 60 | payload = make([]byte, *payloadSize) 61 | } 62 | 63 | sub := dps.CreateSubscription(node, []string{"dps/roundtrip"}) 64 | dps.Subscribe(sub, onPubMatch) 65 | 66 | lock.Lock() 67 | cond.Wait() 68 | lock.Unlock() 69 | 70 | dps.DestroySubscription(sub, func(pub *dps.Subscription) {}) 71 | dps.DestroyNode(node, func(node *dps.Node) {}) 72 | dps.DestroyAddress(listenAddr) 73 | } 74 | -------------------------------------------------------------------------------- /inc/dps/json.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * JSON <-> CBOR conversion 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2018 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_JSON_H 29 | #define _DPS_JSON_H 30 | 31 | #include 32 | #include 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * @defgroup json JSON 40 | * Convert between JSON and CBOR 41 | * @{ 42 | */ 43 | 44 | /** 45 | * Generate a CBOR encoded byte array from a JSON string. Note that if there are multiple 46 | * JSON elements in the input string only the first one is parsed and anything after the 47 | * fist element is ignored. 48 | * 49 | * @param json NUL terminated JSON string to convert 50 | * @param cbor Destination buffer for the conversion 51 | * @param cborSize The size of the cbor buffer 52 | * @param cborLen Returns the number of CBOR bytes written 53 | * 54 | * @return 55 | * - DPS_OK if the conversion was successful 56 | * - DPS_ERR_OVERFLOW if the cbor buffer was too small 57 | * - DPS_ERR_INVALID if the input was not valid JSON 58 | * - other error status codes 59 | */ 60 | DPS_Status DPS_JSON2CBOR(const char* json, uint8_t* cbor, size_t cborSize, size_t* cborLen); 61 | 62 | /** 63 | * Generate a JSON string from a CBOR encoded byte array. 64 | * 65 | * @param cbor CBOR encoded source data for the conversion 66 | * @param cborLen The length of the CBOR data 67 | * @param json Destination buffer for generated JSON string 68 | * @param jsonSize The length of the JSON string buffer 69 | * @param pretty If TRUE format the JSON using indentation and newlines, if FALSE 70 | * the output is compact with no newlines or whitespace is inserted. 71 | * 72 | * @return 73 | * - DPS_OK if the conversion was successful 74 | * - DPS_ERR_OVERFLOW if the json buffer was too small 75 | * - DPS_ERR_INVALID if the input was not valid CBOR 76 | * - other error status codes 77 | */ 78 | DPS_Status DPS_CBOR2JSON(const uint8_t* cbor, size_t cborLen, char* json, size_t jsonSize, int pretty); 79 | 80 | /** @} */ 81 | 82 | #ifdef __cplusplus 83 | } 84 | #endif 85 | 86 | #endif 87 | -------------------------------------------------------------------------------- /inc/dps/synchronous.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Synchronous helpers 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_SYNCHRONOUS_H 29 | #define _DPS_SYNCHRONOUS_H 30 | 31 | #include 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | /** 38 | * @addtogroup node 39 | * @{ 40 | */ 41 | 42 | /** 43 | * Synchronous helper that wraps DPS_Link(). 44 | * 45 | * @param node The local node to link from 46 | * @param addrText The text string of the address to link to 47 | * @param addr Returns the resolved address for the remote node 48 | * 49 | * @return 50 | * - DPS_OK if the link is successful, 51 | * - DPS_ERR_EXISTS if the address is already linked to, 52 | * - an error otherwise 53 | */ 54 | DPS_Status DPS_LinkTo(DPS_Node* node, const char* addrText, DPS_NodeAddress* addr); 55 | 56 | /** 57 | * Synchronous helper that wraps DPS_Unlink(). 58 | * 59 | * @param node The local node to unlink from 60 | * @param addr The address of the remote node to unlink 61 | * 62 | * @return DPS_OK if the unlink is successful, an error otherwise 63 | */ 64 | DPS_Status DPS_UnlinkFrom(DPS_Node* node, const DPS_NodeAddress* addr); 65 | 66 | /** @} */ 67 | 68 | #ifdef __cplusplus 69 | } 70 | #endif 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /inc/dps/uuid.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Create and compare UUIDs 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _DPS_UUID_H 29 | #define _DPS_UUID_H 30 | 31 | #include 32 | #include 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * @defgroup uuid UUID 40 | * Create and compare UUIDs. 41 | * @{ 42 | */ 43 | 44 | /** 45 | * Type definition for a UUID 46 | */ 47 | typedef struct _DPS_UUID { 48 | /**< The UUID value */ 49 | union { 50 | uint8_t val[16]; /**< The UUID as an array of 8-bit values */ 51 | uint32_t val32[4]; /**< The UUID as an array of 32-bit values */ 52 | uint64_t val64[2]; /**< The UUID as an array of 64-bit values */ 53 | }; 54 | } DPS_UUID; 55 | 56 | /** 57 | * One time initialization 58 | * 59 | * @return DPS_OK if initialization succeeds, an error otherwise 60 | */ 61 | DPS_Status DPS_InitUUID(void); 62 | 63 | /** 64 | * Non secure generation of a random UUID. 65 | * 66 | * @param uuid The generated UUID. 67 | */ 68 | void DPS_GenerateUUID(DPS_UUID* uuid); 69 | 70 | /** 71 | * Return a string representation of a UUID. 72 | * 73 | * @note This function uses a static string and is non-reentrant. 74 | * 75 | * @param uuid The UUID 76 | * 77 | * @return The string representation 78 | */ 79 | const char* DPS_UUIDToString(const DPS_UUID* uuid); 80 | 81 | /** 82 | * Numerical comparison of two UUIDs 83 | * 84 | * @param a One of the UUIDs to compare 85 | * @param b The other UUID to compare 86 | * 87 | * @return 88 | * - <0 if a less than b 89 | * - 0 if a equal to b 90 | * - >0 if a greater than b 91 | */ 92 | int DPS_UUIDCompare(const DPS_UUID* a, const DPS_UUID* b); 93 | 94 | /** @} */ 95 | 96 | #ifdef __cplusplus 97 | } 98 | #endif 99 | 100 | #endif 101 | -------------------------------------------------------------------------------- /js_scripts/README.md: -------------------------------------------------------------------------------- 1 | To run these scripts from this directory 2 | 3 | ``` shell 4 | NODE_PATH=../build/dist/js node -i 5 | > .load script.js 6 | ``` 7 | -------------------------------------------------------------------------------- /py_scripts/README.md: -------------------------------------------------------------------------------- 1 | To run these scripts from this directory 2 | 3 | ``` shell 4 | PYTHONPATH=../build/dist/py python -i script.py 5 | ``` 6 | 7 | -------------------------------------------------------------------------------- /py_scripts/late_sub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import dps 3 | import sys 4 | import time 5 | 6 | def on_pub(sub, pub, payload): 7 | print("Pub %s(%d) matches:" % (dps.publication_get_uuid(pub), dps.publication_get_sequence_num(pub))) 8 | print(" pub " + " | ".join(dps.publication_get_topics(pub))) 9 | print(" sub " + " | ".join(dps.subscription_get_topics(sub))) 10 | print(payload.tobytes()) 11 | if dps.publication_is_ack_requested(pub): 12 | ack_msg = "This is an ACK from %s" % (dps.get_listen_address(dps.publication_get_node(pub))) 13 | print("Sending ack for pub UUID %s(%d)" % (dps.publication_get_uuid(pub), dps.publication_get_sequence_num(pub))) 14 | print(" %s" % (ack_msg)) 15 | dps.ack_publication(pub, ack_msg); 16 | 17 | import argparse 18 | parser = argparse.ArgumentParser() 19 | parser.add_argument("-d", "--debug", action='store_true', 20 | help="Enable debug ouput if built for debug.") 21 | args = parser.parse_args() 22 | dps.cvar.debug = args.debug 23 | 24 | node = dps.create_node("/") 25 | dps.start_node(node, dps.MCAST_PUB_ENABLE_RECV + dps.MCAST_PUB_ENABLE_SEND, None) 26 | print("Subscriber is listening on %s" % (dps.get_listen_address(node))) 27 | sub = dps.create_subscription(node, ['a/b/c']); 28 | dps.subscribe(sub, on_pub) 29 | 30 | time.sleep(1) 31 | 32 | # Let publishers know we are here 33 | pub = dps.create_publication(node) 34 | dps.init_publication(pub, ['new_subscriber'], False) 35 | dps.publish(pub, "Hi") 36 | 37 | if not sys.flags.interactive: 38 | while True: 39 | time.sleep(1) 40 | -------------------------------------------------------------------------------- /py_scripts/retained_pub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import dps 3 | import time 4 | 5 | def on_pub(sub, new_sub_pub, payload): 6 | print("Pub %s(%d) matches:" % (dps.publication_get_uuid(new_sub_pub), dps.publication_get_sequence_num(new_sub_pub))) 7 | print(" pub " + " | ".join(dps.publication_get_topics(new_sub_pub))) 8 | print(" sub " + " | ".join(dps.subscription_get_topics(sub))) 9 | print(payload.tobytes()) 10 | if dps.publication_is_ack_requested(new_sub_pub): 11 | ack_msg = "This is an ACK from %s" % (dps.get_listen_address(dps.publication_get_node(new_sub_pub))) 12 | print("Sending ack for pub UUID %s(%d)" % (dps.publication_get_uuid(new_sub_pub), dps.publication_get_sequence_num(new_sub_pub))) 13 | print(" %s" % (ack_msg)) 14 | dps.ack_publication(new_sub_pub, ack_msg); 15 | dps.publish(pub, "hello") 16 | 17 | def on_destroy(node): 18 | print("Destroyed") 19 | 20 | import argparse 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument("-d", "--debug", action='store_true', 23 | help="Enable debug ouput if built for debug.") 24 | args = parser.parse_args() 25 | dps.cvar.debug = args.debug 26 | 27 | node = dps.create_node("/") 28 | dps.start_node(node, dps.MCAST_PUB_ENABLE_SEND + dps.MCAST_PUB_ENABLE_RECV, None) 29 | print("Publisher is listening on %s" % (dps.get_listen_address(node))) 30 | 31 | pub = dps.create_publication(node) 32 | dps.init_publication(pub, ['a/b/c'], False) 33 | dps.publish(pub, "hello", 200) 34 | 35 | # Subscription for responding to alerts from new subscribers 36 | sub = dps.create_subscription(node, ['new_subscriber']); 37 | dps.subscribe(sub, on_pub) 38 | 39 | time.sleep(60) 40 | 41 | dps.destroy_publication(pub) 42 | dps.destroy_node(node, on_destroy) 43 | -------------------------------------------------------------------------------- /site_scons/site_init.py: -------------------------------------------------------------------------------- 1 | def DPS(env): 2 | bld = Builder(action=build_function, 3 | emitter=modify_targets) 4 | env.Append(BUILDERS = {'SwigDox' : bld}) 5 | 6 | import swig_doc 7 | def build_function(target, source, env): 8 | for t in target: 9 | if "py" in str(t): 10 | swig_doc.generate("py", source[0].srcnode().path, t.path) 11 | elif "js" in str(t): 12 | swig_doc.generate("js", source[0].srcnode().path, t.path) 13 | return None 14 | 15 | def modify_targets(target, source, env): 16 | xml = [s for s in source if s.path.endswith(".xml")] 17 | return target, xml 18 | -------------------------------------------------------------------------------- /src/compat.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _COMPAT_H 24 | #define _COMPAT_H 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #ifdef __cplusplus 31 | extern "C" { 32 | #endif 33 | 34 | /* 35 | * Code required for platform compatibility 36 | */ 37 | 38 | #if defined(__GNUC__) || defined(__MINGW64__) 39 | #define THREAD __thread 40 | #define BSWAP_32(n) __builtin_bswap32(n) 41 | #define BSWAP_64(n) __builtin_bswap64(n) 42 | #elif defined(_MSC_VER) 43 | #define THREAD __declspec(thread) 44 | #define BSWAP_32(n) _byteswap_ulong(n) 45 | #define BSWAP_64(n) _byteswap_uint64(n) 46 | #endif 47 | 48 | #if defined(_WIN32) 49 | 50 | #include 51 | 52 | #define __LITTLE_ENDIAN 0 53 | #define __BIG_ENDIAN 1 54 | #define __BYTE_ORDER __LITTLE_ENDIAN 55 | 56 | static inline char* strndup(const char* str, size_t maxLen) 57 | { 58 | size_t len = strnlen_s(str, RSIZE_MAX_STR); 59 | if (len > maxLen) { 60 | len = maxLen; 61 | } 62 | char* c = malloc(len + 1); 63 | if (c) { 64 | memcpy_s(c, len, str, len); 65 | c[len] = '\0'; 66 | } 67 | return c; 68 | } 69 | 70 | #else /* posix */ 71 | 72 | #include 73 | 74 | #endif 75 | 76 | #ifdef __cplusplus 77 | } 78 | #endif 79 | 80 | #endif 81 | -------------------------------------------------------------------------------- /src/crypto.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Common cryptographic macros and functions 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _CRYPTO_H 29 | #define _CRYPTO_H 30 | 31 | #include 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | #define AES_256_KEY_LEN 32 /**< AES 256 key length, in bytes */ 38 | 39 | #define EC_MAX_COORD_LEN 66 /**< Maximum length of an EC coordinate (x, y, or d) */ 40 | 41 | /** 42 | * Opaque type of random byte generator 43 | */ 44 | typedef struct _DPS_RBG DPS_RBG; 45 | 46 | /** 47 | * Create an instance of a random byte generator 48 | * 49 | * @return the random byte generator 50 | */ 51 | DPS_RBG* DPS_CreateRBG(void); 52 | 53 | /** 54 | * Destroy a previously-created instance of a random byte generator 55 | * 56 | * @param rbg the random byte generator 57 | */ 58 | void DPS_DestroyRBG(DPS_RBG* rbg); 59 | 60 | /** 61 | * Generate random bytes 62 | * 63 | * @param rbg a random byte generator 64 | * @param bytes the generated bytes 65 | * @param len the requested number of bytes 66 | * 67 | * @return DPS_OK if generation is successful, an error otherwise 68 | */ 69 | DPS_Status DPS_RandomBytes(DPS_RBG *rbg, uint8_t* bytes, size_t len); 70 | 71 | /** 72 | * Create an ephemeral elliptic curve key 73 | * 74 | * @param rbg a random byte generator 75 | * @param curve a named curve 76 | * @param x the created key's x coordinate 77 | * @param y the created key's y coordinate 78 | * @param d the created key's d coordinate 79 | * 80 | * @return DPS_OK if creation is successful, an error otherwise 81 | */ 82 | DPS_Status DPS_EphemeralKey(DPS_RBG* rbg, DPS_ECCurve curve, 83 | uint8_t x[EC_MAX_COORD_LEN], uint8_t y[EC_MAX_COORD_LEN], 84 | uint8_t d[EC_MAX_COORD_LEN]); 85 | 86 | /** 87 | * Decode the common name (CN) attribute of an X.509 certificate. 88 | * 89 | * @param cert the X.509 certificate 90 | * 91 | * @return the CN value, must be freed by the caller. 92 | */ 93 | char* DPS_CertificateCN(const char* cert); 94 | 95 | #ifdef __cplusplus 96 | } 97 | #endif 98 | 99 | #endif 100 | -------------------------------------------------------------------------------- /src/err.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | #define ERR_CASE(_s) case _s: return # _s + 8 27 | 28 | const char* DPS_ErrTxt(DPS_Status s) 29 | { 30 | static char buf[8]; 31 | 32 | switch (s) { 33 | ERR_CASE(DPS_ERR_OK); 34 | ERR_CASE(DPS_ERR_FAILURE); 35 | ERR_CASE(DPS_ERR_NULL); 36 | ERR_CASE(DPS_ERR_ARGS); 37 | ERR_CASE(DPS_ERR_RESOURCES); 38 | ERR_CASE(DPS_ERR_READ); 39 | ERR_CASE(DPS_ERR_WRITE); 40 | ERR_CASE(DPS_ERR_TIMEOUT); 41 | ERR_CASE(DPS_ERR_EOD); 42 | ERR_CASE(DPS_ERR_OVERFLOW); 43 | ERR_CASE(DPS_ERR_NETWORK); 44 | ERR_CASE(DPS_ERR_INVALID); 45 | ERR_CASE(DPS_ERR_BUSY); 46 | ERR_CASE(DPS_ERR_EXISTS); 47 | ERR_CASE(DPS_ERR_MISSING); 48 | ERR_CASE(DPS_ERR_STALE); 49 | ERR_CASE(DPS_ERR_NO_ROUTE); 50 | ERR_CASE(DPS_ERR_NOT_STARTED); 51 | ERR_CASE(DPS_ERR_NOT_INITIALIZED); 52 | ERR_CASE(DPS_ERR_EXPIRED); 53 | ERR_CASE(DPS_ERR_UNRESOLVED); 54 | ERR_CASE(DPS_ERR_NODE_DESTROYED); 55 | ERR_CASE(DPS_ERR_EOF); 56 | ERR_CASE(DPS_ERR_NOT_IMPLEMENTED); 57 | ERR_CASE(DPS_ERR_SECURITY); 58 | ERR_CASE(DPS_ERR_NOT_ENCRYPTED); 59 | ERR_CASE(DPS_ERR_STOPPING); 60 | ERR_CASE(DPS_ERR_RANGE); 61 | ERR_CASE(DPS_ERR_LOST_PRECISION); 62 | ERR_CASE(DPS_ERR_NOT_COSE); 63 | ERR_CASE(DPS_ERR_NONCE_OVERFLOW); 64 | default: 65 | snprintf(buf, sizeof(buf), "ERR%d", s); 66 | return buf; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/hkdf.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2017 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include "mbedtls/hkdf.h" 27 | #include "hkdf.h" 28 | 29 | /* 30 | * Debug control for this module 31 | */ 32 | DPS_DEBUG_CONTROL(DPS_DEBUG_OFF); 33 | 34 | DPS_Status HKDF_SHA256(const uint8_t* secret, size_t secretLen, 35 | const uint8_t* context, size_t contextLen, 36 | uint8_t key[AES_256_KEY_LEN]) 37 | { 38 | const mbedtls_md_info_t* info; 39 | int ret; 40 | 41 | info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); 42 | ret = mbedtls_hkdf(info, NULL, 0, secret, secretLen, context, contextLen, key, AES_256_KEY_LEN); 43 | if (ret == 0) { 44 | return DPS_OK; 45 | } else { 46 | return DPS_ERR_INVALID; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/hkdf.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * HMAC-based extract-and-expand Key Derivation Function 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _HKDF_H 29 | #define _HKDF_H 30 | 31 | #include 32 | #include "crypto.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * Applies an HMAC-based extract-and-expand Key Derivation Function to 40 | * generate a key. 41 | * 42 | * @param secret the secret 43 | * @param secretLen the size of the secret, in bytes 44 | * @param context the context for the hash function 45 | * @param contextLen the size of the hash context, in bytes 46 | * @param key returns the generated key 47 | * 48 | * @return 49 | * - DPS_OK if the key is generated 50 | * - DPS_ERR_INVALID if the key cannot be generated 51 | */ 52 | DPS_Status HKDF_SHA256(const uint8_t* secret, size_t secretLen, 53 | const uint8_t* context, size_t contextLen, 54 | uint8_t key[AES_256_KEY_LEN]); 55 | 56 | #ifdef __cplusplus 57 | } 58 | #endif 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /src/keywrap.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2017 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include "mbedtls/nist_kw.h" 27 | #include "keywrap.h" 28 | 29 | /* 30 | * Debug control for this module 31 | */ 32 | DPS_DEBUG_CONTROL(DPS_DEBUG_OFF); 33 | 34 | DPS_Status KeyWrap(const uint8_t cek[AES_256_KEY_LEN], const uint8_t kek[AES_256_KEY_LEN], 35 | uint8_t cipherText[AES_256_KEY_WRAP_LEN]) 36 | { 37 | mbedtls_nist_kw_context kw; 38 | size_t n; 39 | int ret; 40 | 41 | mbedtls_nist_kw_init(&kw); 42 | ret = mbedtls_nist_kw_setkey(&kw, MBEDTLS_CIPHER_ID_AES, kek, AES_256_KEY_LEN * 8, 1); 43 | if (ret != 0) { 44 | goto Exit; 45 | } 46 | ret = mbedtls_nist_kw_wrap(&kw, MBEDTLS_KW_MODE_KW, cek, AES_256_KEY_LEN, 47 | cipherText, &n, AES_256_KEY_WRAP_LEN); 48 | if (ret != 0) { 49 | goto Exit; 50 | } 51 | if (n != AES_256_KEY_WRAP_LEN) { 52 | ret = -1; 53 | goto Exit; 54 | } 55 | 56 | Exit: 57 | mbedtls_nist_kw_free(&kw); 58 | if (ret == 0) { 59 | return DPS_OK; 60 | } else { 61 | return DPS_ERR_INVALID; 62 | } 63 | } 64 | 65 | DPS_Status KeyUnwrap(const uint8_t cipherText[AES_256_KEY_WRAP_LEN], const uint8_t kek[AES_256_KEY_LEN], 66 | uint8_t cek[AES_256_KEY_LEN]) 67 | { 68 | mbedtls_nist_kw_context kw; 69 | size_t n; 70 | int ret; 71 | 72 | mbedtls_nist_kw_init(&kw); 73 | ret = mbedtls_nist_kw_setkey(&kw, MBEDTLS_CIPHER_ID_AES, kek, AES_256_KEY_LEN * 8, 0); 74 | if (ret != 0) { 75 | goto Exit; 76 | } 77 | ret = mbedtls_nist_kw_unwrap(&kw, MBEDTLS_KW_MODE_KW, cipherText, AES_256_KEY_WRAP_LEN, 78 | cek, &n, AES_256_KEY_LEN); 79 | if (ret != 0) { 80 | goto Exit; 81 | } 82 | if (n != AES_256_KEY_LEN) { 83 | ret = -1; 84 | goto Exit; 85 | } 86 | 87 | Exit: 88 | mbedtls_nist_kw_free(&kw); 89 | if (ret == 0) { 90 | return DPS_OK; 91 | } else { 92 | return DPS_ERR_INVALID; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/keywrap.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * AES key wrap algorithm 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _KEYWRAP_H 29 | #define _KEYWRAP_H 30 | 31 | #include 32 | #include "crypto.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | #define AES_256_KEY_WRAP_LEN 40 /**< The length of the wrapped AES-256 key in bytes */ 39 | 40 | /** 41 | * Wrap a key per the algorithm specified in RFC 3394. 42 | * 43 | * @param cek the content encryption key (aka the plaintext) 44 | * @param kek the key encryption key 45 | * @param cipherText returns the wrapped content encryption key 46 | * 47 | * @return DPS_OK if wrapped, an error otherwise 48 | */ 49 | DPS_Status KeyWrap(const uint8_t cek[AES_256_KEY_LEN], const uint8_t kek[AES_256_KEY_LEN], 50 | uint8_t cipherText[AES_256_KEY_WRAP_LEN]); 51 | 52 | /** 53 | * Unwrap a key per the algorithm specified in RFC 3394. 54 | * 55 | * @param cipherText the wrapped content encryption key 56 | * @param kek the key encryption key 57 | * @param cek returns the content encryption key (aka the plaintext) 58 | * 59 | * @return DPS_OK if unwrapped, an error otherwise 60 | */ 61 | DPS_Status KeyUnwrap(const uint8_t cipherText[AES_256_KEY_WRAP_LEN], const uint8_t kek[AES_256_KEY_LEN], 62 | uint8_t cek[AES_256_KEY_LEN]); 63 | 64 | #ifdef __cplusplus 65 | } 66 | #endif 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /src/mbedtls.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Common mbedTLS functions 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _MBEDTLS_H 29 | #define _MBEDTLS_H 30 | 31 | #include "mbedtls/ecdh.h" 32 | #include "mbedtls/x509_crt.h" 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | /** 39 | * The text string representation of the mbedTLS status code. 40 | * 41 | * @param ret the status code 42 | * 43 | * @return the text string representation 44 | */ 45 | const char *TLSErrTxt(int ret); 46 | 47 | /** 48 | * Get the mbedTLS elliptic curve parameters 49 | * 50 | * @param curve the elliptic curve ID 51 | * @param id the mbedtls elliptic curve ID 52 | * @param len the size of a coordinate, in bytes 53 | * 54 | * @return 0 on success, an mbedTLS error code otherwise 55 | */ 56 | int TLSGetCurveParams(DPS_ECCurve curve, mbedtls_ecp_group_id* id, size_t* len); 57 | 58 | /** 59 | * Decode the common name (CN) attribute of an X.509 certificate. 60 | * 61 | * @param crt the X.509 certificate 62 | * 63 | * @return the CN value, must be freed by the caller. 64 | */ 65 | const mbedtls_x509_name* TLSCertificateCN(const mbedtls_x509_crt* crt); 66 | 67 | #ifdef __cplusplus 68 | } 69 | #endif 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /src/queue.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2019 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | #include "queue.h" 23 | 24 | void DPS_QueueInit(DPS_Queue* queue) 25 | { 26 | queue->prev = queue; 27 | queue->next = queue; 28 | } 29 | 30 | int DPS_QueueEmpty(const DPS_Queue* queue) 31 | { 32 | return queue == queue->next; 33 | } 34 | 35 | DPS_Queue* DPS_QueueFront(const DPS_Queue* queue) 36 | { 37 | return queue->next; 38 | } 39 | 40 | DPS_Queue* DPS_QueueBack(const DPS_Queue* queue) 41 | { 42 | return queue->prev; 43 | } 44 | 45 | void DPS_QueuePushBack(DPS_Queue* queue, DPS_Queue* item) 46 | { 47 | item->next = queue; 48 | item->prev = queue->prev; 49 | ((DPS_Queue*)item->prev)->next = item; 50 | queue->prev = item; 51 | } 52 | 53 | void DPS_QueueRemove(DPS_Queue* item) 54 | { 55 | ((DPS_Queue*)item->prev)->next = item->next; 56 | ((DPS_Queue*)item->next)->prev = item->prev; 57 | } 58 | -------------------------------------------------------------------------------- /src/queue.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Generic queue 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2019 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _QUEUE_H 29 | #define _QUEUE_H 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | 35 | /** 36 | * Generic queue 37 | */ 38 | typedef struct _DPS_Queue { 39 | void* prev; /**< Previous queue item */ 40 | void* next; /**< Next queue item */ 41 | } DPS_Queue; 42 | 43 | /** 44 | * Initializes a queue 45 | * 46 | * @param queue the queue 47 | */ 48 | void DPS_QueueInit(DPS_Queue* queue); 49 | 50 | /** 51 | * Returns whether the queue is empty or not. 52 | * 53 | * @param queue the queue 54 | * 55 | * @return DPS_TRUE if empty, DPS_FALSE otherwise 56 | */ 57 | int DPS_QueueEmpty(const DPS_Queue* queue); 58 | 59 | /** 60 | * Returns the item at the front of the queue. 61 | * 62 | * @param queue the queue 63 | * 64 | * @return the item at the front of the queue 65 | */ 66 | DPS_Queue* DPS_QueueFront(const DPS_Queue* queue); 67 | 68 | /** 69 | * Returns the item at the back of the queue. 70 | * 71 | * @param queue the queue 72 | * 73 | * @return the item at the back of the queue 74 | */ 75 | DPS_Queue* DPS_QueueBack(const DPS_Queue* queue); 76 | 77 | /** 78 | * Pushes an item onto the back of the queue 79 | * 80 | * @param queue the queue 81 | * @param item the item 82 | */ 83 | void DPS_QueuePushBack(DPS_Queue* queue, DPS_Queue* item); 84 | 85 | /** 86 | * Removes an item from the queue it is in. 87 | * 88 | * @param item the item 89 | */ 90 | void DPS_QueueRemove(DPS_Queue* item); 91 | 92 | #ifdef __cplusplus 93 | } 94 | #endif 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /src/resolver.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * Network address resolution 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2017 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _RESOLVER_H 29 | #define _RESOLVER_H 30 | 31 | #include 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | /** 38 | * Kick off address resolution. 39 | * 40 | * @param async The uv async signal 41 | */ 42 | void DPS_AsyncResolveAddress(uv_async_t* async); 43 | 44 | #ifdef __cplusplus 45 | } 46 | #endif 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /src/sha2.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include "sha2.h" 26 | #include "mbedtls/md.h" 27 | 28 | void DPS_Sha2(uint8_t digest[DPS_SHA2_DIGEST_LEN], const uint8_t* data, size_t len) 29 | { 30 | const mbedtls_md_info_t* info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); 31 | mbedtls_md(info, data, len, digest); 32 | } 33 | -------------------------------------------------------------------------------- /src/sha2.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * SHA-256 algorithm 4 | */ 5 | 6 | /* 7 | ******************************************************************* 8 | * 9 | * Copyright 2016 Intel Corporation All rights reserved. 10 | * 11 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 26 | */ 27 | 28 | #ifndef _SHA2_H 29 | #define _SHA2_H 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | #ifdef __cplusplus 36 | extern "C" { 37 | #endif 38 | 39 | #define DPS_SHA2_DIGEST_LEN 32 /**< Size of SHA-256 hash in bytes */ 40 | 41 | /** 42 | * Compute the SHA2 hash of some data 43 | * 44 | * @param digest The result 45 | * @param data The data to hash 46 | * @param len The length of the data to hash 47 | */ 48 | void DPS_Sha2(uint8_t digest[DPS_SHA2_DIGEST_LEN], const uint8_t* data, size_t len); 49 | 50 | #ifdef __cplusplus 51 | } 52 | #endif 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /src/synchronous.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | /* 31 | * Debug control for this module 32 | */ 33 | DPS_DEBUG_CONTROL(DPS_DEBUG_OFF); 34 | 35 | static void OnLinked(DPS_Node* node, const DPS_NodeAddress* addr, DPS_Status status, void* data) 36 | { 37 | DPS_Event* event = (DPS_Event*)data; 38 | 39 | if (status == DPS_OK) { 40 | DPS_NodeAddress* outAddr = (DPS_NodeAddress*)DPS_GetEventData(event); 41 | DPS_CopyAddress(outAddr, addr); 42 | } 43 | DPS_SignalEvent(event, status); 44 | } 45 | 46 | DPS_Status DPS_LinkTo(DPS_Node* node, const char* addrText, DPS_NodeAddress* addr) 47 | { 48 | DPS_Event* event = NULL; 49 | DPS_Status ret; 50 | 51 | DPS_DBGTRACE(); 52 | 53 | event = DPS_CreateEvent(); 54 | if (!event) { 55 | return DPS_ERR_RESOURCES; 56 | } 57 | DPS_SetEventData(event, addr); 58 | ret = DPS_Link(node, addrText, OnLinked, event); 59 | if (ret == DPS_OK) { 60 | ret = DPS_WaitForEvent(event); 61 | } 62 | DPS_DestroyEvent(event); 63 | return ret; 64 | } 65 | 66 | static void OnUnlinked(DPS_Node* node, const DPS_NodeAddress* addr, void* data) 67 | { 68 | DPS_Event* event = (DPS_Event*)data; 69 | DPS_SignalEvent(event, DPS_OK); 70 | } 71 | 72 | DPS_Status DPS_UnlinkFrom(DPS_Node* node, const DPS_NodeAddress* addr) 73 | { 74 | DPS_Status ret; 75 | DPS_Event* event = DPS_CreateEvent(); 76 | 77 | DPS_DBGTRACE(); 78 | 79 | if (!event) { 80 | return DPS_ERR_RESOURCES; 81 | } 82 | ret = DPS_Unlink(node, addr, OnUnlinked, event); 83 | if (ret == DPS_OK) { 84 | ret = DPS_WaitForEvent(event); 85 | } 86 | DPS_DestroyEvent(event); 87 | return ret; 88 | } 89 | -------------------------------------------------------------------------------- /src/uv_extra.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include "uv_extra.h" 24 | 25 | #ifdef _WIN32 26 | #else 27 | #include 28 | #endif 29 | 30 | int uv_thread_detach(uv_thread_t* tid) 31 | { 32 | int r; 33 | #ifdef _WIN32 34 | r = CloseHandle(*tid) ? 0 : UV_EINVAL; 35 | #else 36 | r = -pthread_detach(*tid); 37 | #endif 38 | *tid = 0; 39 | return r; 40 | } 41 | -------------------------------------------------------------------------------- /src/uv_extra.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _UV_EXTRA_H 24 | #define _UV_EXTRA_H 25 | 26 | #include 27 | #include 28 | 29 | #ifdef __cplusplus 30 | extern "C" { 31 | #endif 32 | 33 | int uv_thread_detach(uv_thread_t* tid); 34 | 35 | #ifdef __cplusplus 36 | } 37 | #endif 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /test/keys.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _KEYS_H 24 | #define _KEYS_H 25 | 26 | #include 27 | 28 | #ifdef __cplusplus 29 | extern "C" { 30 | #endif 31 | 32 | /* 33 | * Preshared keys and certificates for testing only - DO NOT USE THESE KEYS IN A REAL APPLICATION!!!! 34 | */ 35 | 36 | extern const DPS_KeyId NetworkKeyId; 37 | extern const DPS_Key NetworkKey; 38 | 39 | #define NUM_KEYS 2 40 | 41 | extern const DPS_KeyId PskId[NUM_KEYS]; 42 | extern const DPS_Key Psk[NUM_KEYS]; 43 | 44 | extern const char TrustedCAs[]; 45 | 46 | typedef struct _Id { 47 | DPS_KeyId keyId; 48 | const char* cert; 49 | const char* privateKey; 50 | const char* password; 51 | } Id; 52 | 53 | extern const Id Ids[]; 54 | 55 | extern const char AltCA[]; 56 | extern const Id AltId; 57 | 58 | #ifdef __cplusplus 59 | } 60 | #endif 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /test/ll_unit.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2019 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include "test.h" 24 | #include "dps/private/network.h" 25 | 26 | static const char addr1[] = "[::ffff:192.168.181.130]:49911"; 27 | static const char addr2[] = "192.168.181.130:49911"; 28 | 29 | 30 | int main(int argc, char** argv) 31 | { 32 | DPS_NodeAddress a1; 33 | DPS_NodeAddress a2; 34 | const char* check; 35 | int i; 36 | 37 | DPS_Debug = DPS_FALSE; 38 | for (i = 1; i < argc; ++i) { 39 | if (!strcmp(argv[i], "-d")) { 40 | DPS_Debug = DPS_TRUE; 41 | } 42 | } 43 | 44 | DPS_SetAddress(&a1, addr1); 45 | check = DPS_NetAddrText((struct sockaddr*)&a1.u.inaddr); 46 | if (strcmp(check, addr1) != 0) { 47 | DPS_PRINT("Failed %s != %s\n", check, addr1); 48 | } 49 | 50 | DPS_SetAddress(&a2, addr2); 51 | check = DPS_NetAddrText((struct sockaddr*)&a2.u.inaddr); 52 | if (strcmp(check, addr2) != 0) { 53 | DPS_PRINT("Failed %s != %s\n", check, addr2); 54 | } 55 | 56 | if (!DPS_SameAddr(&a1, &a2)) { 57 | char str1[64]; 58 | char str2[64]; 59 | strcpy(str1, DPS_NetAddrText((struct sockaddr*)&a1.u.inaddr)); 60 | strcpy(str2, DPS_NetAddrText((struct sockaddr*)&a2.u.inaddr)); 61 | DPS_PRINT("Failed %s != %s\n", str1, str2); 62 | } 63 | return EXIT_SUCCESS; 64 | } 65 | -------------------------------------------------------------------------------- /test/meshes/box.txt: -------------------------------------------------------------------------------- 1 | 0 1 2 | 2 3 3 | 0 2 4 | 1 3 5 | 0 3 6 | 1 2 7 | -------------------------------------------------------------------------------- /test/meshes/double.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 2 3 3 | 3 4 4 | 4 5 5 | 5 6 6 | 6 1 7 | 2 5 8 | -------------------------------------------------------------------------------- /test/meshes/dumbell.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 2 3 3 | 3 4 4 | 4 1 5 | 5 6 6 | 6 7 7 | 7 8 8 | 8 9 9 | 8 5 10 | 10 11 11 | 11 12 12 | 12 13 13 | 13 14 14 | 14 15 15 | 10 1 16 | 15 5 17 | -------------------------------------------------------------------------------- /test/meshes/hot_mesh.txt: -------------------------------------------------------------------------------- 1 | 0 1 2 | 0 2 3 | 0 3 4 | 0 4 5 | 1 11 6 | 1 12 7 | 1 13 8 | 11 15 9 | 11 16 10 | 11 17 11 | 15 20 12 | 15 21 13 | 15 22 14 | 20 25 15 | 20 26 16 | 20 27 17 | 25 30 18 | 25 31 19 | 25 32 20 | 30 2 21 | 30 35 22 | 30 4 23 | 2 12 24 | 2 38 25 | 12 16 26 | 12 40 27 | 16 21 28 | 16 43 29 | 21 26 30 | 21 47 31 | 26 31 32 | 26 49 33 | 31 35 34 | 31 56 35 | 35 38 36 | 35 58 37 | 38 40 38 | 38 61 39 | 40 43 40 | 40 66 41 | 43 47 42 | 43 72 43 | 47 49 44 | 47 76 45 | 49 56 46 | 49 78 47 | 56 58 48 | 56 81 49 | 58 61 50 | 58 84 51 | 61 66 52 | 61 89 53 | 66 72 54 | 66 91 55 | 72 76 56 | 72 94 57 | 76 78 58 | 76 98 59 | 78 81 60 | 78 103 61 | 81 84 62 | 81 109 63 | 84 89 64 | 84 111 65 | 89 91 66 | 89 116 67 | 91 94 68 | 91 118 69 | 94 98 70 | 94 121 71 | 98 103 72 | 98 125 73 | 103 109 74 | 103 130 75 | 109 111 76 | 109 132 77 | 111 116 78 | 111 135 79 | 116 118 80 | 116 3 81 | 118 121 82 | 118 13 83 | 121 125 84 | 121 17 85 | 125 130 86 | 125 22 87 | 130 132 88 | 130 27 89 | 132 135 90 | 132 32 91 | 135 3 92 | 135 4 93 | 3 13 94 | 13 17 95 | 17 22 96 | 22 27 97 | 27 32 98 | 32 4 99 | -------------------------------------------------------------------------------- /test/meshes/loop10.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 2 3 3 | 3 4 4 | 4 5 5 | 5 6 6 | 6 7 7 | 7 8 8 | 8 9 9 | 9 0 10 | 0 1 11 | -------------------------------------------------------------------------------- /test/meshes/maxmesh16.txt: -------------------------------------------------------------------------------- 1 | 0 1 2 | 1 2 3 | 2 3 4 | 3 4 5 | 4 5 6 | 5 6 7 | 6 7 8 | 7 8 9 | 8 9 10 | 9 10 11 | 10 11 12 | 11 12 13 | 12 13 14 | 13 14 15 | 14 15 16 | 15 0 17 | 0 2 18 | 1 3 19 | 2 4 20 | 3 5 21 | 4 6 22 | 5 6 23 | 6 8 24 | 7 9 25 | 8 10 26 | 9 11 27 | 10 12 28 | 11 13 29 | 12 14 30 | 13 15 31 | 14 0 32 | 15 1 33 | 0 3 34 | 1 4 35 | 2 5 36 | 3 6 37 | 4 7 38 | 5 8 39 | 6 9 40 | 7 10 41 | 8 11 42 | 9 12 43 | 10 13 44 | 11 14 45 | 12 15 46 | 13 0 47 | 14 1 48 | 15 2 49 | 0 4 50 | 1 5 51 | 2 6 52 | 3 7 53 | 4 8 54 | 5 9 55 | 6 10 56 | 7 11 57 | 8 12 58 | 9 13 59 | 10 14 60 | 11 15 61 | 12 0 62 | 13 1 63 | 14 2 64 | 15 3 65 | 0 5 66 | 1 6 67 | 2 7 68 | 3 8 69 | 4 9 70 | 5 10 71 | 6 11 72 | 7 12 73 | 8 13 74 | 9 14 75 | 10 15 76 | 11 0 77 | 12 1 78 | 13 2 79 | 14 3 80 | 15 4 81 | 0 6 82 | 1 7 83 | 2 8 84 | 3 9 85 | 4 10 86 | 5 11 87 | 6 12 88 | 7 13 89 | 8 14 90 | 9 15 91 | 10 0 92 | 11 1 93 | 12 2 94 | 13 3 95 | 14 4 96 | 15 5 97 | 0 7 98 | 1 8 99 | 2 9 100 | 3 10 101 | 4 11 102 | 5 12 103 | 6 13 104 | 7 14 105 | 8 15 106 | 9 0 107 | 10 1 108 | 11 2 109 | 12 3 110 | 13 4 111 | 14 5 112 | 15 6 113 | 0 8 114 | 1 9 115 | 2 10 116 | 3 11 117 | 4 12 118 | 5 13 119 | 6 14 120 | 7 15 121 | 8 0 122 | 9 1 123 | 10 2 124 | 11 3 125 | 12 4 126 | 13 5 127 | 14 6 128 | 15 7 129 | -------------------------------------------------------------------------------- /test/meshes/self.txt: -------------------------------------------------------------------------------- 1 | 1 2 2 | 2 1 3 | -------------------------------------------------------------------------------- /test/meshes/simple.txt: -------------------------------------------------------------------------------- 1 | 0 1 2 | 0 2 3 | 0 3 4 | 2 4 5 | 5 2 6 | 5 6 7 | 6 0 8 | -------------------------------------------------------------------------------- /test/test.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2018 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include "test.h" 24 | 25 | int IntArg(char* opt, char*** argp, int* argcp, int* val, int min, int max) 26 | { 27 | char* p; 28 | char** arg = *argp; 29 | int argc = *argcp; 30 | 31 | if (strcmp(*arg++, opt) != 0) { 32 | return 0; 33 | } 34 | if (!--argc) { 35 | return 0; 36 | } 37 | *val = strtol(*arg++, &p, 10); 38 | if (*p) { 39 | return 0; 40 | } 41 | if (*val < min || *val > max) { 42 | DPS_PRINT("Value for option %s must be in range %d..%d\n", opt, min, max); 43 | return 0; 44 | } 45 | *argp = arg; 46 | *argcp = argc; 47 | return 1; 48 | } 49 | 50 | int AddressArg(char* opt, char*** argp, int* argcp, DPS_NodeAddress** addr) 51 | { 52 | char** arg = *argp; 53 | int argc = *argcp; 54 | int port = 0; 55 | char str[256]; 56 | 57 | strcpy(str, "[::]:0"); 58 | 59 | if (IntArg(opt, &arg, &argc, &port, 1000, UINT16_MAX)) { 60 | snprintf(str, sizeof(str), "[::]:%d", port); 61 | } else if (strcmp(*arg, opt) == 0) { 62 | ++arg; 63 | if (!--argc) { 64 | return DPS_FALSE; 65 | } 66 | strncpy(str, *arg++, sizeof(str) - 1); 67 | } else { 68 | return DPS_FALSE; 69 | } 70 | *addr = DPS_CreateAddress(); 71 | if (!*addr) { 72 | return DPS_FALSE; 73 | } 74 | if (!DPS_SetAddress(*addr, str)) { 75 | DPS_DestroyAddress(*addr); 76 | *addr = NULL; 77 | return DPS_FALSE; 78 | } 79 | *argp = arg; 80 | *argcp = argc; 81 | return DPS_TRUE; 82 | } 83 | -------------------------------------------------------------------------------- /test/test.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2017 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #ifndef _TEST_H 24 | #define _TEST_H 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | 41 | #include 42 | #include 43 | 44 | #ifdef _WIN32 45 | #define SLEEP(t) Sleep(t) 46 | #else 47 | #include 48 | #define SLEEP(t) usleep((t) * 1000) 49 | #endif 50 | 51 | #define ASSERT(cond) do { assert(cond); if (!(cond)) exit(EXIT_FAILURE); } while (0) 52 | 53 | int IntArg(char* opt, char*** argp, int* argcp, int* val, int min, int max); 54 | int AddressArg(char* opt, char*** argp, int* argcp, DPS_NodeAddress** addr); 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /test/uuid.c: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************* 3 | * 4 | * Copyright 2016 Intel Corporation All rights reserved. 5 | * 6 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * 20 | *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 21 | */ 22 | 23 | #include "test.h" 24 | 25 | static int ln; 26 | 27 | #define CHECK(r) if ((r) != DPS_OK) { ln = __LINE__; goto Failed; } 28 | 29 | /* 30 | * UUID bytes are in little-endian order 31 | */ 32 | static DPS_UUID a = { 0x1a, 0x2c, 0xba, 0xd4, 0xa0, 0xee, 0x52, 0xe2, 33 | 0xe8, 0xa1, 0x29, 0x36, 0xe8, 0x10, 0x27, 0x53 }; 34 | static DPS_UUID b = { 0x02, 0xf8, 0x40, 0x55, 0x96, 0x38, 0xc7, 0xc5, 35 | 0x1f, 0x63, 0x52, 0xdb, 0xe4, 0x96, 0x5f, 0xc2 }; 36 | 37 | static DPS_Status TestToString(void) 38 | { 39 | if (strcmp("532710e8-3629-a1e8-e252-eea0d4ba2c1a", DPS_UUIDToString(&a)) || 40 | strcmp("c25f96e4-db52-631f-c5c7-38965540f802", DPS_UUIDToString(&b))) { 41 | return DPS_ERR_FAILURE; 42 | } else { 43 | return DPS_OK; 44 | } 45 | } 46 | 47 | static DPS_Status TestCompare(void) 48 | { 49 | if (DPS_UUIDCompare(&a, &b) < 0) { 50 | return DPS_OK; 51 | } else { 52 | return DPS_ERR_FAILURE; 53 | } 54 | } 55 | 56 | int main(int argc, char** argv) 57 | { 58 | int i; 59 | DPS_Status ret; 60 | 61 | DPS_Debug = DPS_FALSE; 62 | for (i = 1; i < argc; ++i) { 63 | if (!strcmp(argv[i], "-d")) { 64 | DPS_Debug = DPS_TRUE; 65 | } 66 | } 67 | 68 | ret = TestToString(); 69 | CHECK(ret); 70 | ret = TestCompare(); 71 | CHECK(ret); 72 | 73 | printf("Passed\n"); 74 | return EXIT_SUCCESS; 75 | 76 | Failed: 77 | 78 | printf("Failed at line %d %s\n", ln, DPS_ErrTxt(ret)); 79 | return EXIT_FAILURE; 80 | } 81 | -------------------------------------------------------------------------------- /test_scripts/auth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | # 9 | # Participants 10 | # - Alice :: authorized to publish data on topic T 11 | # - Bob :: authorized to subscribe to data on topic T 12 | # - Eve :: eavesdropper who is not authorized to subscribe 13 | # - Trudy :: intruder who is not authorized to publish or acknowledge 14 | # 15 | 16 | # 17 | # Unauthorized subscription 18 | # - To protect against Eve, Alice must encrypt for Bob to prevent Eve from eavesdropping. 19 | # 20 | reset_logs() 21 | 22 | node1 = node('-u bob -s T') 23 | node2 = node('-u eve -s T') 24 | node3 = node('-u alice -p T') 25 | 26 | expect_pub_received(node1, 'T') 27 | expect_pub_not_received(node2, 'T', allow_error=True) 28 | 29 | # 30 | # Unauthorized publication 31 | # - To protect against Trudy, Bob must know that Alice is not the originator. 32 | # 33 | reset_logs() 34 | 35 | node1 = node('-u bob -s T') 36 | node2 = node('-u trudy -p T') 37 | 38 | expect_error(node1, 'Unauthorized pub') 39 | 40 | # 41 | # Unauthorized acknowledgement 42 | # - To protect against Trudy, Alice must know that Bob is not the originator. 43 | # 44 | reset_logs() 45 | 46 | node1 = node('-u bob -s T') 47 | node2 = node('-u trudy -s T') 48 | node3 = node('-u alice -p T') 49 | 50 | expect_pub_received([node1, node2], 'T', allow_error=True) 51 | expect_error(node3, 'Unauthorized ack') 52 | -------------------------------------------------------------------------------- /test_scripts/chain_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = sub('-m 1.1') 9 | sub2 = sub('-p {} 2.1'.format(sub1.port)) 10 | sub3 = sub('-p {} 3.1'.format(sub2.port)) 11 | sub4 = sub('-p {} +.1'.format(sub3.port)); 12 | 13 | pub1 = pub('1.1 2.1 3.1 4.1') 14 | 15 | expect_pub_received([sub1, sub2, sub3, sub4], '1.1 2.1 3.1 4.1') 16 | -------------------------------------------------------------------------------- /test_scripts/discover.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Example: 4 | # $ ./test_scripts/discover.py 5 | # $ ./tools/graph_nodes.pl out/* | neato -Tpng | display 6 | # 7 | # neato and sfdp appear to provide the nicest results. 8 | # 9 | from common import * 10 | import atexit 11 | import glob 12 | import random 13 | import time 14 | 15 | atexit.register(cleanup) 16 | 17 | seed=1 18 | num_nodes = 100 19 | topics = list(range(ord('A'), ord('A') + 12)) 20 | 21 | random.seed(seed) 22 | 23 | def n_sub(n): 24 | ns = [] 25 | choices = [] 26 | for i in range(n): 27 | topic = random.choice(topics) 28 | choices.append(topic) 29 | ns.append(discover('-s %c' % (topic))) 30 | for i in range(n, num_nodes): 31 | ns.append(discover('-p %c' % (random.choice(choices)))) 32 | return ns 33 | 34 | def n_pub(n): 35 | ns = [] 36 | choices = [] 37 | for i in range(n): 38 | topic = random.choice(topics) 39 | choices.append(topic) 40 | ns.append(discover('-p %c' % (topic))) 41 | for i in range(n, num_nodes): 42 | ns.append(discover('-s %c' % (random.choice(choices)))) 43 | return ns 44 | 45 | def n_pub_one_topic(n): 46 | ns = [] 47 | choices = [] 48 | for i in range(n): 49 | ns.append(discover('-p A')) 50 | for i in range(n, num_nodes): 51 | ns.append(discover('-s A')) 52 | return ns 53 | 54 | def pub_or_sub(): 55 | ns = [] 56 | for i in range(num_nodes): 57 | choices = ['-p ' + chr(topic) for topic in topics] 58 | choices.extend(['-s ' + chr(topic) for topic in topics]) 59 | ns.append(discover(random.choice(choices))) 60 | return ns 61 | 62 | # Select a topology: 63 | #ns = n_sub(1) 64 | #ns = n_pub(2) 65 | #ns = n_pub_one_topic(2) 66 | ns = pub_or_sub() 67 | 68 | # Wait a bit for discovery to settle 69 | time.sleep(20 + 2 * num_nodes) 70 | 71 | for n in ns: 72 | n.kill(signal.SIGUSR1) 73 | 74 | time.sleep(1) 75 | for n in ns: 76 | n.kill(signal.SIGTERM) 77 | try: 78 | n.expect('ERROR') 79 | raise RuntimeError('ERROR') 80 | except pexpect.EOF: 81 | pass 82 | -------------------------------------------------------------------------------- /test_scripts/e2esec.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | def expect_signed_pub_received(subs, pattern, signed_count): 9 | ss = [] 10 | expect_pub_received(subs, pattern, signers=ss) 11 | if sum(s == 'DPS Test Publisher' for s in ss) != signed_count: 12 | sys.exit(1) 13 | 14 | def expect_signed_ack_received(pubs, signed_count): 15 | ss = [] 16 | expect_ack_received(pubs, signers=ss) 17 | if sum(s == 'DPS Test Subscriber' for s in ss) != signed_count: 18 | sys.exit(1) 19 | 20 | for S in range(0, 4): 21 | reset_logs() 22 | sub1 = sub('-x {} {}'.format(S, S)) 23 | pub1 = pub('-x 0 -a {}'.format(S)) 24 | pub2 = pub('-x 1 -a {}'.format(S)) 25 | pub3 = pub('-x 2 -a {}'.format(S)) 26 | pub4 = pub('-x 3 -a {}'.format(S)) 27 | if S == 0: 28 | expect_signed_pub_received(sub1, ['{}'.format(S)] * 2, 0) 29 | expect_signed_ack_received([pub1, pub4], 0) 30 | elif S == 1: 31 | expect_signed_pub_received(sub1, ['{}'.format(S)] * 3, 0) 32 | expect_ack_received([pub1, pub2, pub4], 0) 33 | elif S == 2: 34 | expect_signed_pub_received(sub1, ['{}'.format(S)] * 3, 2) 35 | expect_signed_ack_received([pub1, pub3, pub4], 2) 36 | elif S == 3: 37 | expect_signed_pub_received(sub1, ['{}'.format(S)] * 2, 1) 38 | expect_ack_received([pub1, pub4], 1) 39 | -------------------------------------------------------------------------------- /test_scripts/fanout.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = sub('-w 1 -s X -s A') 9 | sub2 = sub('-w 1 -p {} -s X -s B'.format(sub1.port)) 10 | sub3 = sub('-w 1 -p {} -s X -s C'.format(sub2.port)) 11 | sub4 = sub('-w 1 -p {} -s X -s D'.format(sub3.port)) 12 | sub5 = sub('-w 1 -p {} -s X -s E'.format(sub4.port)) 13 | sub6 = sub('-w 1 -p {} -s X -s F'.format(sub5.port)) 14 | sub7 = sub('-w 1 -p {} -s X -s G'.format(sub6.port)) 15 | sub8 = sub('-w 1 -p {} -s X -s H'.format(sub7.port)) 16 | sub9 = sub('-w 1 -p {} -s X -s I'.format(sub8.port)) 17 | sub10 = sub('-w 1 -p {} -s X -s J'.format(sub9.port)) 18 | sub11 = sub('-w 1 -p {} -s X -s K'.format(sub10.port)) 19 | 20 | # Link to all nodes in chain 21 | sub12 = sub('-w 2 -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -s X -s L'.format( 22 | sub1.port, sub2.port, sub3.port, sub4.port, sub5.port, sub6.port, sub7.port, sub8.port, sub9.port, sub10.port, sub11.port)) 23 | sub13 = sub('-w 2 -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -s X -s M'.format( 24 | sub11.port, sub10.port, sub9.port, sub8.port, sub7.port, sub6.port, sub5.port, sub4.port, sub3.port, sub2.port, sub1.port)) 25 | sub14 = sub('-w 2 -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -p {} -s X -s N'.format( 26 | sub9.port, sub8.port, sub5.port, sub7.port, sub11.port, sub1.port, sub3.port, sub10.port, sub6.port, sub4.port, sub2.port)) 27 | 28 | subs = [ 29 | sub1, sub2, sub3, sub4, sub5, sub6, sub7, sub8, sub9, sub10, sub11, sub12, sub13, sub14 30 | ] 31 | 32 | pubs = [ 33 | pub('-p {} A B C D E F G H I J K L M N'.format(sub1.port)), 34 | pub('-p {} A B C D E F G H I J K L M N'.format(sub2.port)), 35 | pub('-p {} A B C D E F G H I J K L M N'.format(sub3.port)), 36 | pub('-p {} A B C D E F G H I J K L M N'.format(sub4.port)), 37 | pub('-p {} A B C D E F G H I J K L M N'.format(sub5.port)), 38 | pub('-p {} A B C D E F G H I J K L M N'.format(sub6.port)), 39 | pub('-p {} A B C D E F G H I J K L M N'.format(sub7.port)), 40 | pub('-p {} A B C D E F G H I J K L M N'.format(sub8.port)), 41 | pub('-p {} A B C D E F G H I J K L M N'.format(sub9.port)), 42 | pub('-p {} A B C D E F G H I J K L M N'.format(sub10.port)), 43 | pub('-p {} A B C D E F G H I J K L M N'.format(sub11.port)), 44 | pub('-p {} A B C D E F G H I J K L M N'.format(sub12.port)), 45 | pub('-p {} A B C D E F G H I J K L M N'.format(sub13.port)), 46 | pub('-p {} A B C D E F G H I J K L M N'.format(sub14.port)) 47 | ] 48 | 49 | expect_pub_received(subs, ['A B C D E F G H I J K L M N'] * len(pubs)) 50 | 51 | # Reachability check 52 | 53 | pub('-p {} X'.format(sub6.port)) 54 | 55 | expect_pub_received(subs, 'X') 56 | -------------------------------------------------------------------------------- /test_scripts/fuzzer_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | import glob 6 | 7 | atexit.register(cleanup) 8 | 9 | def _fuzzer_check(fuzzer, corpus): 10 | while corpus: 11 | # Work around max argument length by slicing 12 | bin(fuzzer + corpus[:1024]) 13 | del corpus[:1024] 14 | 15 | if os.environ['USE_DTLS'] == '0': 16 | _fuzzer_check([os.path.join('build', 'test', 'bin', 'cbor_fuzzer')], 17 | glob.glob('test/corpus/cbor/*')) 18 | _fuzzer_check([os.path.join('build', 'test', 'bin', 'multicast_receive_fuzzer')], 19 | glob.glob('test/corpus/multicast_receive/*')) 20 | _fuzzer_check([os.path.join('build', 'test', 'bin', 'net_receive_fuzzer')], 21 | glob.glob('test/corpus/unicast_receive/*')) 22 | else: 23 | for step in range(7): 24 | _fuzzer_check([os.path.join('build', 'test', 'bin', 'dtls_fuzzer'), 'server', '{}'.format(step)], 25 | glob.glob('test/corpus/dtls_server_{}/*'.format(step))) 26 | for step in range(8): 27 | _fuzzer_check([os.path.join('build', 'test', 'bin', 'dtls_fuzzer'), 'client', '{}'.format(step)], 28 | glob.glob('test/corpus/dtls_client_{}/*'.format(step))) 29 | 30 | 31 | -------------------------------------------------------------------------------- /test_scripts/link_drop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | reps = 4 9 | dropper = drop('-w 5 -t 1 -r {}'.format(reps)) 10 | subscriber = sub('-f 1 --') 11 | 12 | link(subscriber, dropper.port) 13 | 14 | expect_dropped(dropper, reps) 15 | -------------------------------------------------------------------------------- /test_scripts/loop25.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | # loop 9 | 10 | subs = [ 11 | sub('--'), 12 | sub('--'), 13 | sub('--'), 14 | sub('--'), 15 | sub('--'), 16 | sub('A --'), 17 | sub('--'), 18 | sub('--'), 19 | sub('--'), 20 | sub('B --'), 21 | sub('--'), 22 | sub('--'), 23 | sub('--'), 24 | sub('--'), 25 | sub('--'), 26 | sub('--'), 27 | sub('--'), 28 | sub('--'), 29 | sub('--'), 30 | sub('--'), 31 | sub('--'), 32 | sub('--'), 33 | sub('--'), 34 | sub('--'), 35 | sub('--') 36 | ] 37 | 38 | for i in range(len(subs)): 39 | j = (i + len(subs) - 1) % len(subs) 40 | link(subs[i], subs[j].port) 41 | 42 | for i in range(len(subs)): 43 | j = (i + len(subs) - 1) % len(subs) 44 | expect_linked(subs[i], subs[j].port) 45 | -------------------------------------------------------------------------------- /test_scripts/loop3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | subs = [ 9 | sub('A --'), 10 | sub('B --'), 11 | sub('C --') 12 | ] 13 | 14 | for i in range(len(subs)): 15 | j = (i + 1) % len(subs) 16 | link(subs[i], subs[j].port) 17 | 18 | for i in range(len(subs)): 19 | j = (i + 1) % len(subs) 20 | expect_linked(subs[i], subs[j].port) 21 | -------------------------------------------------------------------------------- /test_scripts/mesh_stress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | import glob 6 | import time 7 | 8 | atexit.register(cleanup) 9 | 10 | ms = [] 11 | meshes = glob.glob('test/meshes/*.txt') 12 | for m in meshes: 13 | ms.append(mesh_stress(m)) 14 | 15 | # Watch for errors for ~10 minutes 16 | for i in range(10): 17 | time.sleep(60) 18 | for m in ms: 19 | try: 20 | # timeout=0 doesn't catch errors for some reason 21 | m.expect('ERROR', timeout=1) 22 | raise RuntimeError('ERROR') 23 | except pexpect.TIMEOUT: 24 | print('TIMEOUT') 25 | pass 26 | 27 | for m in ms: 28 | m.kill(signal.SIGTERM) 29 | try: 30 | m.expect('ERROR') 31 | raise RuntimeError('ERROR') 32 | except pexpect.EOF: 33 | pass 34 | -------------------------------------------------------------------------------- /test_scripts/pub100.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | subs = [ 9 | sub('1.1.#'), 10 | sub('1.1.#'), 11 | sub('1.1.#') 12 | ] 13 | 14 | for i in range(100): 15 | pub('1.1.{}'.format(i)) 16 | 17 | expect_pub_received(subs, ['1.1.\d+'] * 100) 18 | -------------------------------------------------------------------------------- /test_scripts/reg1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | import time 6 | 7 | atexit.register(cleanup) 8 | 9 | # Start the registry service 10 | reg1 = reg() 11 | 12 | # Start some subscribers 13 | 14 | # Delay the starts so that we ensure a fully connected graph. 15 | sub1 = reg_subs('-p {} -c 1 a/b/c'.format(reg1.port)) 16 | sub2 = reg_subs('-p {} -c 1 a/b/c'.format(reg1.port)) 17 | expect_reg_linked([sub1, sub2]) 18 | sub3 = reg_subs('-p {} -c 2 a/b/c'.format(reg1.port)) 19 | expect_reg_linked(sub3) 20 | sub4 = reg_subs('-p {} -c 3 a/b/c'.format(reg1.port)) 21 | expect_reg_linked(sub4) 22 | sub5 = reg_subs('-p {} -c 4 a/b/c'.format(reg1.port)) 23 | expect_reg_linked(sub5) 24 | sub6 = reg_subs('-p {} -c 5 a/b/c'.format(reg1.port)) 25 | expect_reg_linked(sub6) 26 | sub7 = reg_subs('-p {} -c 6 a/b/c'.format(reg1.port)) 27 | expect_reg_linked(sub7) 28 | sub8 = reg_subs('-p {} -c 7 a/b/c'.format(reg1.port)) 29 | expect_reg_linked(sub8) 30 | sub9 = reg_subs('-p {} -c 8 a/b/c'.format(reg1.port)) 31 | expect_reg_linked(sub9) 32 | sub10 = reg_subs('-p {} -c 9 a/b/c'.format(reg1.port)) 33 | expect_reg_linked(sub10) 34 | sub11 = reg_subs('-p {} -c 10 a/b/c'.format(reg1.port)) 35 | expect_reg_linked(sub11) 36 | sub12 = reg_subs('-p {} -c 11 a/b/c'.format(reg1.port)) 37 | expect_reg_linked(sub12) 38 | sub13 = reg_subs('-p {} -c 12 a/b/c'.format(reg1.port)) 39 | expect_reg_linked(sub13) 40 | sub14 = reg_subs('-p {} -c 13 a/b/c'.format(reg1.port)) 41 | expect_reg_linked(sub14) 42 | sub15 = reg_subs('-p {} -c 14 a/b/c'.format(reg1.port)) 43 | expect_reg_linked(sub15) 44 | sub16 = reg_subs('-p {} -c 15 1/2/3'.format(reg1.port)) 45 | expect_reg_linked(sub16) 46 | sub17 = reg_subs('-p {} -c 16 +/+/#'.format(reg1.port)) 47 | expect_reg_linked(sub17) 48 | 49 | # Give time for the subscriptions to propogate 50 | time.sleep(15) 51 | 52 | # Start some publishers 53 | reg_pubs('-p {} a/b/c -m hello'.format(reg1.port)) 54 | reg_pubs('-p {} 1/2/3 -m world'.format(reg1.port)) 55 | 56 | expect_pub_received([sub1, sub2, sub3, sub4, sub5, sub6, sub7, sub8, sub9, sub10, sub11, sub12, 57 | sub13, sub14, sub15], 'a/b/c') 58 | expect_pub_received([sub16], '1/2/3') 59 | expect_pub_received([sub17], ['a/b/c', '1/2/3']) 60 | -------------------------------------------------------------------------------- /test_scripts/retained_py.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | py_retained_pub() 9 | sub1 = py_late_sub() 10 | 11 | expect_pub_received(sub1, 'a/b/c') 12 | -------------------------------------------------------------------------------- /test_scripts/simple_go_ks_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = go_sub_ks() 9 | go_pub_ks() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and go pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | go_pub_ks() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | go_pub_ks('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between go pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = go_sub_ks() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = go_sub_ks('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_go_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = go_sub() 9 | go_pub() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and go pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | go_pub() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | go_pub('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between go pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = go_sub() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = go_sub('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_js_ks_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = js_sub_ks() 9 | js_pub_ks() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and javascript pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | js_pub_ks() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | js_pub_ks('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between javascript pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = js_sub_ks() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = js_sub_ks('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_js_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = js_sub() 9 | js_pub() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and javascript pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | js_pub() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | js_pub('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between javascript pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = js_sub() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = js_sub('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_py_ks_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = py_sub_ks() 9 | py_pub_ks() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and python pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | py_pub_ks() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | py_pub_ks('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between python pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = py_sub_ks() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = py_sub_ks('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_py_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = py_sub() 9 | py_pub() 10 | 11 | expect_pub_received(sub1, ['a/b/c'] * 2) 12 | 13 | # 14 | # Verify interop between C sub and python pub 15 | # 16 | reset_logs() 17 | 18 | sub1 = sub('a/b/c') 19 | py_pub() 20 | 21 | expect_pub_received(sub1, ['a/b/c'] * 2) 22 | 23 | reset_logs() 24 | 25 | sub1 = sub('-x 2 a/b/c') 26 | py_pub('-x 2') 27 | 28 | expect_pub_received(sub1, ['a/b/c'] * 2) 29 | 30 | # 31 | # Verify interop between python pub and C sub 32 | # 33 | reset_logs() 34 | 35 | sub1 = py_sub() 36 | pub('a/b/c') 37 | 38 | expect_pub_received(sub1, 'a/b/c') 39 | 40 | reset_logs() 41 | 42 | sub1 = py_sub('-x 2') 43 | pub('-x 2 a/b/c') 44 | 45 | expect_pub_received(sub1, 'a/b/c') 46 | -------------------------------------------------------------------------------- /test_scripts/simple_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = sub('1/1/1') 9 | sub2 = sub('+/+/1') 10 | sub3 = sub('1/1/1 1/1/2') 11 | sub4 = sub('1/1/1 1/1/2 1/1/3') 12 | sub5 = sub('1/1/#') 13 | sub6 = sub('2/#') 14 | sub7 = sub('3/# 2/# 1/#') 15 | 16 | pub('1/1/1 1/1/2 1/1/3') 17 | pub('2/1/1 1/1/4') 18 | pub('2/1/1 3/1/1') 19 | pub('2/1/1 1/1/4 3/1/1') 20 | pub('3/2 2/3') 21 | 22 | expect_pub_received([sub1, sub2, sub3, sub4, sub5], '1/1/1 1/1/2 1/1/3') 23 | expect_pub_received([sub2, sub5, sub6], '2/1/1 1/1/4') 24 | expect_pub_received([sub2, sub6], '2/1/1 3/1/1') 25 | expect_pub_received([sub2, sub5, sub6, sub7], '2/1/1 1/1/4 3/1/1') 26 | expect_pub_received([sub6], '3/2 2/3') 27 | -------------------------------------------------------------------------------- /test_scripts/topic_match.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | topic_match('No match', '-p 1/2/3 -s a/b/c') 9 | topic_match('Match', '-p a/b/c -s a/b/c') 10 | topic_match('Match', '-p a/b/c -p 1/2/3 -s a/b/c') 11 | topic_match('No match', '-p a/b/c -p 1/2/3 -s +/+') 12 | topic_match('Match', '-p a/b/c -p 1/2/3 -s +/#') 13 | topic_match('No match', '-p a/b/c -s x/y/#') 14 | topic_match('No match', '-p a/b/c -s +/y/#') 15 | topic_match('Match', '-p a/b/c -s +/+/#') 16 | topic_match('Match', '-p a/b/c -s +/+/+') 17 | topic_match('No match', '-p a/b/c -s +/+/+/#') 18 | -------------------------------------------------------------------------------- /test_scripts/tree0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | sub1 = sub('-w 1 T') 9 | sub2 = sub('-w 1 -p {} A'.format(sub1.port)) 10 | sub3 = sub('-w 1 -p {} B'.format(sub2.port)) 11 | 12 | pub('-w 2 -p {} A'.format(sub3.port)) 13 | pub('-w 2 -p {} B'.format(sub2.port)) 14 | 15 | expect_pub_received(sub2, 'A') 16 | expect_pub_received(sub3, 'B') 17 | -------------------------------------------------------------------------------- /test_scripts/tree1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | # 9 | # a/b/c ----\ /---- 1/2/3 10 | # \ / 11 | # d/e/f ------> A/A -------> B/B <------- C/C <------ 4/5/6 12 | # / \ 13 | # g/h/i ----/ \---- 7/8/9 14 | # 15 | 16 | sub1 = sub('B/B') 17 | sub2 = sub('-p {} A/A'.format(sub1.port)) 18 | sub3 = sub('-p {} C/C'.format(sub1.port)) 19 | 20 | sub4 = sub('-p {} a/b/c'.format(sub2.port)) 21 | sub5 = sub('-p {} d/e/f'.format(sub2.port)) 22 | sub6 = sub('-p {} g/h/i'.format(sub2.port)) 23 | 24 | sub7 = sub('-p {} 1/2/3'.format(sub3.port)) 25 | sub8 = sub('-p {} 4/5/6'.format(sub3.port)) 26 | sub9 = sub('-p {} 7/8/9'.format(sub3.port)) 27 | 28 | pub1 = pub('-p {} a/b/c 4/5/6'.format(sub1.port)) 29 | pub2 = pub('-p {} d/e/f'.format(sub2.port)) 30 | pub3 = pub('-p {} 1/2/3'.format(sub4.port)) 31 | pub4 = pub('-p {} g/h/i'.format(sub3.port)) 32 | 33 | expect_pub_received([sub4, sub8], 'a/b/c 4/5/6') 34 | expect_pub_received(sub5, 'd/e/f') 35 | expect_pub_received(sub7, '1/2/3') 36 | expect_pub_received(sub6, 'g/h/i') 37 | 38 | # Now some retained pubs 39 | # 40 | # a/b/c ----\ /---- 1/2/3 <----- +/# 41 | # \ / 42 | # d/e/f ------> A/A -------> B/B <------- C/C <------ 4/5/6 43 | # / \ 44 | # g/h/i ----/ \---- 7/8/9 45 | # 46 | # 47 | sub10 = sub('-p {} +/#'.format(sub7.port)) 48 | 49 | pub5 = pub('-t 20 -p {} X/X'.format(sub4.port)) 50 | pub6 = pub('-t 20 -p {} Y/Y'.format(sub7.port)) 51 | pub7 = pub('-t 20 -p {} Z/Z'.format(sub2.port)) 52 | 53 | expect_pub_received(sub10, ['X/X', 'Y/Y', 'Z/Z']) 54 | 55 | # a/b/c ----\ /---- 1/2/3 <----- +/# 56 | # \ / 57 | # d/e/f ------> A/A -------> B/B <------- C/C <------ 4/5/6 58 | # / ^ \ 59 | # g/h/i ----/ | \---- 7/8/9 60 | # | 61 | # 62 | 63 | sub11 = sub('-p {} +/#'.format(sub1.port)) 64 | 65 | expect_pub_received(sub11, ['X/X', 'Y/Y', 'Z/Z']) 66 | -------------------------------------------------------------------------------- /test_scripts/tree2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | 6 | atexit.register(cleanup) 7 | 8 | # 9 | # /---> B ----\ 10 | # / \ 11 | # / \ 12 | # A ------> C -------> E 13 | # \ / 14 | # \ / 15 | # \---> D-----/ 16 | # 17 | # 18 | 19 | sub1 = sub('E') 20 | 21 | sub2 = sub('-p {} B'.format(sub1.port)) 22 | sub3 = sub('-p {} C'.format(sub1.port)) 23 | sub4 = sub('-p {} D'.format(sub1.port)) 24 | 25 | sub5 = sub('-p {} -p {} -p {} A'.format(sub2.port, sub3.port, sub4.port)) 26 | -------------------------------------------------------------------------------- /test_scripts/versioning.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from common import * 4 | import atexit 5 | import os 6 | 7 | atexit.register(cleanup) 8 | 9 | # 10 | # Verify that all 4 packet types are sent/received with version property 11 | # 12 | 13 | # Multicast 14 | sub1 = sub('A') 15 | pub1 = pub('-a A') 16 | 17 | expect_pub_received(sub1, 'A') 18 | expect(pub1, 'Ack for pub') 19 | 20 | # Unicast 21 | sub2 = sub('-p {} A'.format(sub1.port)) 22 | pub2 = pub('-p {} -a A'.format(sub1.port)) 23 | 24 | expect_pub_received([sub1, sub2], 'A') 25 | expect(pub2, ['Ack for pub'] * 2) 26 | 27 | # 28 | # Verify that unsupported version is dropped 29 | # 30 | # Multicast 31 | reset_logs() 32 | 33 | sub1 = sub('A') 34 | ver('-v 2') 35 | 36 | expect_error(sub1, 'Expected message version 1, received 2') 37 | 38 | # Unicast 39 | reset_logs() 40 | 41 | sub1 = sub('A') 42 | ver('-p {} -v 2'.format(sub1.port)) 43 | 44 | expect_error(sub1, 'Expected message version 1, received 2') 45 | 46 | # 47 | # Verify that unsupported message type is dropped 48 | # 49 | # Multicast 50 | reset_logs() 51 | 52 | sub1 = sub('A') 53 | ver('-v 1 -t 5') 54 | 55 | expect_error(sub1, 'Invalid message type') 56 | 57 | # Unicast 58 | reset_logs() 59 | 60 | sub1 = sub('A') 61 | ver('-p {} -v 1 -t 5'.format(sub1.port)) 62 | 63 | expect_error(sub1, 'Invalid message type') 64 | -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | # A repository for useful tools 2 | 3 | ## asan_addr2line 4 | 5 | Applies addr2line to a fuzzer crash log. 6 | 7 | `./build/test/bin/cbor_fuzzer ./crash-f15bb0b64b75838dc982cef11b0c3b9ea08fcec6 2>&1 | ./tools/asan_addr2line` 8 | 9 | ## corpus_pcap 10 | 11 | Create a seed corpus for fuzzing from a tcpdump capture. 12 | 13 | `corpus_pcap --dir ./corpus dps.pcapng` 14 | 15 | Capture packets from a run of the tests: 16 | ``` 17 | $ tcpdump -i any -p -s 0 -w dps.tcpdump 18 | $ ./test_scripts/run.py 19 | ``` 20 | Filter multicast DPS packets: 21 | ``` 22 | $ tshark -r dps.tcpdump -w dps_multicast.pcapng 'coap' 23 | ``` 24 | 25 | Filter unicast DPS packets: 26 | ``` 27 | $ tshark -r dps.tcpdump -w dps_unicast.pcapng 'udp[8:2]==85:01 and not icmp' 28 | ``` 29 | 30 | ## docs_upload 31 | 32 | Generates Doxygen API documentation and uploads it to the upstream 33 | gh_pages branch. 34 | 35 | `docs_upload` 36 | 37 | ## dps_graph.pl 38 | 39 | Generates an input file to dot that graphs the TCP connections beween 40 | instances of the reg_subs example program. 41 | 42 | Run `test_scripts/reg1.py` or similar to create a network of connected 43 | nodes. 44 | 45 | `dps_graph.pl | dot -Tpng -o graph.png` 46 | 47 | Generates a .png file for the connections. 48 | 49 | ## dtls_fuzzer 50 | 51 | Runs the dtls_fuzzer for all server and client steps in parallel. 52 | 53 | `dtls_fuzzer` 54 | 55 | ## exports 56 | 57 | Scans the header files for symbols that need to be included in 58 | dps_shared.def. 59 | 60 | `exports > dps_shared.def` 61 | 62 | ## fuzzer_cov 63 | 64 | Runs all existing corpus with coverage and generate report in 65 | fuzzer_cov directory. 66 | 67 | `fuzzer_cov` 68 | 69 | Example: 70 | ``` 71 | $ rm *.profraw 72 | $ scons ... transport=fuzzer cov=yes 73 | $ ./fuzzer_cov 74 | $ scons ... transport=dtls cov=yes 75 | $ USE_DTLS=1 ./fuzzer_cov 76 | ``` 77 | 78 | ## fuzzer_run 79 | 80 | Runs all the fuzzers to generate more test cases. 81 | 82 | `fuzzer_run` 83 | 84 | Example: 85 | ``` 86 | $ scons ... transport=fuzzer 87 | $ ./fuzzer_run 88 | $ scons ... transport=dtls 89 | $ USE_DTLS=1 ./fuzzer_run 90 | ``` 91 | 92 | ## showmesh 93 | 94 | Runs the make_mesh test on an input file and displays the resultant 95 | graphs. 96 | 97 | `tools/showmesh [-d] [-o ] [-l ] [-k count] [-s ] [-e ] ` 98 | 99 | Requires graphviz and imagemagick (or some other png viewer) 100 | 101 | -d -- debug 102 | -e -- graphviz engine (default is fdp) 103 | -o -- Capture the png output file 104 | -l -- Capture the log file from make_mesh 105 | -s -- Maximum number of subscriptions to register (default=1) 106 | -k -- Maximum number of nodes to kill (default=0) 107 | 108 | There are some sample meshes in the ./meshes subdir. 109 | 110 | Active arcs are shown solid, muted arcs (if not hidden) are dotted. 111 | -------------------------------------------------------------------------------- /tools/asan_addr2line: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # ./build/test/bin/fuzzer ./crash-f15bb0b64b75838dc982cef11b0c3b9ea08fcec6 2>&1 | ./tools/asan_addr2line 4 | # 5 | 6 | while (<>) { 7 | if (/(.*#[0-9]+ 0x[0-9a-f]+ )\((.*)\+(0x[0-9a-f]+)\)/) { 8 | $name = $2; 9 | $addr = $3; 10 | $line = `addr2line -e $name $addr`; 11 | chomp($line); 12 | if ($line eq "??:?") { 13 | print $_; 14 | } else { 15 | print "$1($line)\n"; 16 | } 17 | } else { 18 | print $_; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tools/corpus_pcap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # ./corpus_pcap --dir ./corpus dps.pcapng 4 | # 5 | # dps.pcapng should contain only DPS packets. For example: 6 | # 7 | # Capture packets from a run of the tests: 8 | # $ tcpdump -i any -p -s 0 -w dps.tcpdump 9 | # $ ./test_scripts/run.py 10 | # 11 | # Filter multicast DPS packets: 12 | # $ tshark -r dps.tcpdump -w dps_multicast.pcapng 'coap' 13 | # 14 | # Filter unicast DPS packets: 15 | # $ tshark -r dps.tcpdump -w dps_unicast.pcapng 'udp[8:2]==85:01 and not icmp' 16 | # 17 | 18 | import argparse 19 | import os 20 | import tempfile 21 | from scapy.all import * 22 | 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('-d', '--dir', default='.', help='Output directory') 25 | parser.add_argument('pcapng', default='dps.pcapng', help='Input pcapng file') 26 | args = parser.parse_args() 27 | 28 | pcapng = rdpcap(args.pcapng) 29 | for packet in pcapng: 30 | with tempfile.NamedTemporaryFile(suffix='.dat', prefix='dps_msg_', dir=args.dir, delete=False) as file: 31 | file.write(bytes(packet[UDP].payload)) 32 | -------------------------------------------------------------------------------- /tools/coverity_scan: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | export COV_PATH=../../coverity/bin 4 | export PATH=$PATH:$COV_PATH 5 | 6 | scons $@ --clean 7 | cov-build --dir cov scons $@ 8 | 9 | cov-analyze --dir cov --concurrency --security --rule --enable-constraint-fpp --enable-fnptr --enable-virtual --strip-path `dirname $PWD` 10 | 11 | rm -rf cov_errors 12 | cov-format-errors --dir cov --html-output cov_errors --filesort --strip-path `dirname $PWD` --title "Distributed Publish & Subscribe" 13 | 14 | firefox cov_errors/index.html & 15 | -------------------------------------------------------------------------------- /tools/docs_upload: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Usage: ./tools/docs_upload 4 | # 5 | 6 | DPS_HOME=`pwd` 7 | COMMIT=`git rev-parse HEAD` 8 | 9 | rm -rf code_docs 10 | mkdir code_docs 11 | cd code_docs 12 | git clone -b gh-pages git@github.com:intel/dps-for-iot.git 13 | cd dps-for-iot 14 | rm -rf * 15 | echo "" > .nojekyll 16 | 17 | ( cat $DPS_HOME/doc/Doxyfile ; echo "OUTPUT_DIRECTORY=."; echo "INPUT=$DPS_HOME/doc/Introduction.dox $DPS_HOME/doc/Topic-Strings.dox $DPS_HOME/doc/Mesh-Network.dox $DPS_HOME/doc/Message-Types-and-Flows.dox $DPS_HOME/doc/Data-Series.dox $DPS_HOME/doc/Retained-Publications.dox $DPS_HOME/doc/Security.dox $DPS_HOME/doc/Building-and-Running.dox $DPS_HOME/doc/Tutorials.dox $DPS_HOME/doc/tutorial/hello_world.dox $DPS_HOME/doc/tutorial/link.dox $DPS_HOME/doc/tutorial/security.dox $DPS_HOME/doc/../inc" ; echo "EXAMPLE_PATH=$DPS_HOME/examples $DPS_HOME/doc/tutorial" ; echo "EXCLUDE=$DPS_HOME/inc/dps/private" ; echo "HTML_OUTPUT=." ; echo "HTML_FOOTER=$DPS_HOME/doc/html/footer.html" ; echo "IMAGE_PATH = $DPS_HOME/doc/images" ) | doxygen - 2>&1 | tee doxygen.log 18 | 19 | git add --all 20 | git commit -m 'Deploy docs to GitHub Pages' -m "Commit: $COMMIT" 21 | git push --force 22 | -------------------------------------------------------------------------------- /tools/dps_graph.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | open(SS, "ss -p -a |"); 4 | 5 | while ( ) 6 | { 7 | if (/ESTAB.*reg_subs/ || /ESTAB.*subscriber/) { 8 | my @elem = split(/ +/); 9 | my ($addr, $localPort) = @elem[4] =~ /([0-9,a-f,A-F,:]+):([0-9]+)$/; 10 | my ($addr, $peerPort) = @elem[5] =~ /([0-9,a-f,A-F,:]+):([0-9]+)$/; 11 | my ($pre, $pid, $post) = @elem[6] =~ /(.*pid=)([0-9]+)(.*)/; 12 | push(@{$links{$pid}}, $peerPort); 13 | } 14 | if (/LISTEN.*reg_subs/ || /LISTEN.*subscriber/) { 15 | my @elem = split(/ +/); 16 | my ($addr, $listenPort) = @elem[4] =~ /([0-9,a-f,A-F,:]+):([0-9]+)$/; 17 | my ($pre, $pid, $post) = @elem[6] =~ /(.*pid=)([0-9]+)(.*)/; 18 | $nodes{$listenPort} = $pid; 19 | push(@{$listener{$pid}}, $listenPort); 20 | } 21 | } 22 | 23 | print "digraph G {\n"; 24 | foreach $pid (keys %links) 25 | { 26 | foreach $port (@{$links{$pid}}) { 27 | if (exists($nodes{$port})) { 28 | $label = "@{$listener{$pid}}"; 29 | if ($label == "") { 30 | $label = "N/A"; 31 | } 32 | print " $pid [label=\"$label\"];\n"; 33 | print " $pid -> $nodes{$port}"; 34 | } 35 | } 36 | print "\n"; 37 | } 38 | print "}\n"; 39 | -------------------------------------------------------------------------------- /tools/dtls_fuzzer: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # run dtls_fuzzer for all server and client steps in parallel 4 | # 5 | 6 | function cleanup { 7 | kill $(jobs -rp) 8 | } 9 | trap cleanup EXIT 10 | 11 | for step in {0..6}; do 12 | ./build/test/bin/dtls_fuzzer server $step test/corpus_dtls_server_$step test/seed_corpus/dtls_server_$step & 13 | done 14 | for step in {0..7}; do 15 | ./build/test/bin/dtls_fuzzer client $step test/corpus_dtls_client_$step test/seed_corpus/dtls_client_$step & 16 | done 17 | 18 | wait $(jobs -rp) 2>/dev/null 19 | -------------------------------------------------------------------------------- /tools/exports: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Usage: ./tools/exports > dps_shared.def 4 | # 5 | 6 | echo LIBRARY dps_shared 7 | echo 8 | echo EXPORTS 9 | echo 10 | grep -hv '^$' inc/dps/*.h | grep -v '^ ?*' | grep -v '^/' | grep -v '^#' | grep -v '^typedef' | grep -v '^}' | grep -v '^struct' | grep -v 'extern "C"' | cut -d'(' -f1 | sed 's/^.* DPS_/DPS_/' | sed -e 's/;//' | sort 11 | -------------------------------------------------------------------------------- /tools/exports_gcc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Usage: ./tools/exports_gcc > libdps_shared.map 4 | # 5 | 6 | echo '{' 7 | echo ' global:' 8 | grep -hv '^$' inc/dps/*.h | grep -v '^ ?*' | grep -v '^/' | grep -v '^#' | grep -v '^typedef' | grep -v '^}' | grep -v '^struct' | grep -v 'extern "C"' | cut -d'(' -f1 | sed 's/^.* DPS_/DPS_/' | sed -e 's/;//' | awk '{print " " $1 ";"}' | sort 9 | echo '' 10 | echo ' local:' 11 | echo ' *;' 12 | echo '};' 13 | -------------------------------------------------------------------------------- /tools/fuzzer_cov: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # run all existing corpus with coverage and generate report in fuzzer_cov directory 4 | # 5 | # example: 6 | # $ rm *.profraw 7 | # $ scons ... transport=fuzzer cov=yes 8 | # $ ./fuzzer_cov 9 | # $ scons ... transport=dtls cov=yes 10 | # $ USE_DTLS=1 ./fuzzer_cov 11 | # 12 | 13 | USE_DTLS=${USE_DTLS:-0} 14 | 15 | export LLVM_PROFILE_FILE="%p.profraw" 16 | 17 | if [ $USE_DTLS -eq 0 ]; then 18 | find test/corpus/cbor -type f | xargs ./build/test/bin/cbor_fuzzer & 19 | find test/corpus/multicast_receive -type f | xargs ./build/test/bin/multicast_receive_fuzzer & 20 | find test/corpus/unicast_receive -type f | xargs ./build/test/bin/net_receive_fuzzer & 21 | fi 22 | 23 | if [ $USE_DTLS -ne 0 ]; then 24 | for step in {0..6}; do 25 | find test/corpus/dtls_server_$step -type f | xargs ./build/test/bin/dtls_fuzzer server $step & 26 | done 27 | for step in {0..7}; do 28 | find test/corpus/dtls_client_$step -type f | xargs ./build/test/bin/dtls_fuzzer client $step & 29 | done 30 | fi 31 | 32 | wait 33 | 34 | llvm-profdata merge -sparse *.profraw -o fuzzer.profdata 35 | llvm-cov show ./build/dist/lib/libdps_shared.so -instr-profile=fuzzer.profdata --format=html --output-dir=fuzzer_cov --show-instantiation-summary --show-region-summary --stats 36 | -------------------------------------------------------------------------------- /tools/fuzzer_run: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # run all the fuzzers to generate more test cases 4 | # 5 | # example: 6 | # $ scons ... transport=fuzzer 7 | # $ ./fuzzer_run 8 | # $ scons ... transport=dtls 9 | # $ USE_DTLS=1 ./fuzzer_run 10 | # 11 | 12 | USE_DTLS=${USE_DTLS:-0} 13 | 14 | if [ $USE_DTLS -eq 0 ]; then 15 | mkdir -p test/corpus/cbor 16 | ./build/test/bin/cbor_fuzzer test/corpus/cbor & 17 | mkdir -p test/corpus/multicast_receive 18 | ./build/test/bin/multicast_receive_fuzzer test/corpus/multicast_receive test/seed_corpus/multicast_receive & 19 | mkdir -p test/corpus/unicast_receive 20 | ./build/test/bin/net_receive_fuzzer test/corpus/unicast_receive test/seed_corpus/unicast_receive & 21 | fi 22 | 23 | if [ $USE_DTLS -ne 0 ]; then 24 | for step in {0..6}; do 25 | mkdir -p test/corpus/dtls_server_$step 26 | ./build/test/bin/dtls_fuzzer server $step test/corpus/dtls_server_$step test/seed_corpus/dtls_server_$step & 27 | done 28 | for step in {0..7}; do 29 | mkdir -p test/corpus/dtls_client_$step 30 | ./build/test/bin/dtls_fuzzer client $step test/corpus/dtls_client_$step test/seed_corpus/dtls_client_$step & 31 | done 32 | fi 33 | 34 | wait 35 | -------------------------------------------------------------------------------- /tools/graph_nodes.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use strict; 4 | use warnings; 5 | use Data::Dumper qw(Dumper); 6 | 7 | my (@nodes, %live, %mute) = ((), (), ()); 8 | 9 | foreach my $filename (@ARGV) { 10 | my ($n); 11 | open(my $fh, '<', $filename) or die "Could not open file '$filename' $!"; 12 | while (my $line = <$fh>) { 13 | chomp($line); 14 | if ($line =~ /node .*:(\d+)$/) { 15 | $n = $1; 16 | push(@nodes, $n) 17 | } elsif ($line =~ /.* [DEBUG|TRACE|ERROR|INFO]/) { 18 | # Ignore debug output 19 | } elsif ($line =~ / .*:(\d+) state=([^,]+)/) { 20 | my ($a, $b, $state) = ($n, $1, $2); 21 | # Keep all arcs going the same way 22 | if (exists($live{"$b -- $a"}) or exists($mute{"$b -- $a"})) { 23 | ($a, $b) = ($b, $a); 24 | } 25 | if ($state ne "MUTED") { 26 | if (exists($live{"$a -- $b"})) { 27 | $live{"$a -- $b"} += 1; 28 | } else { 29 | $live{"$a -- $b"} = 1; 30 | } 31 | } else { 32 | if (exists($mute{"$a -- $b"})) { 33 | $mute{"$a -- $b"} += 1; 34 | } else { 35 | $mute{"$a -- $b"} = 1; 36 | } 37 | } 38 | } 39 | } 40 | close($fh); 41 | } 42 | 43 | my ($nnodes, $narcs, $nmuted, $show_muted) = (scalar(@nodes), scalar(%live), scalar(%mute), 0); 44 | $narcs += $nmuted; 45 | 46 | print "graph {\n"; 47 | print " node[shape=circle, fontsize=10, margin=\"0.01,0.01\", fixedsize=true];\n"; 48 | print " overlap=false;\n"; 49 | print " splines=true;\n"; 50 | print " subgraph cluster_1 {\n"; 51 | print " style=invis;\n"; 52 | print " 1000[shape=none, width=1, style=bold, height=1, fontsize=12, label=\"nodes=$nnodes\\narcs=$narcs\\nmuted=$nmuted\"];\n"; 53 | print " subgraph cluster1 {\n"; 54 | print " node[style=filled, fillcolor=palegreen3];\n"; 55 | foreach my $arc (keys(%live)) { 56 | if ($live{$arc} == 2) { 57 | print " $arc [len=1];\n"; 58 | } else { 59 | print " $arc [len=1, style=dotted];\n"; 60 | } 61 | } 62 | if ($show_muted) { 63 | foreach my $arc (keys(%mute)) { 64 | if (not exists($live{$arc})) { 65 | print " $arc [len=1, color=red, style=dotted];\n"; 66 | } 67 | } 68 | } 69 | print " }\n"; 70 | print " }\n"; 71 | print "}\n"; 72 | -------------------------------------------------------------------------------- /tools/showmesh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | OPTIND=1 4 | 5 | engine="neato" 6 | outfile='' 7 | logfile="log" 8 | num_subs=1 9 | num_kills=0 10 | debug='' 11 | noMuted='' 12 | 13 | while getopts "de:hk:l:mo:s:" opt; do 14 | case "$opt" in 15 | d) debug="-d" 16 | ;; 17 | e) engine=$OPTARG 18 | ;; 19 | h) echo "[-d] [-m] [-o ] [-l ] [-k count] [-s ] [-e ] " 20 | exit 0 21 | ;; 22 | k) num_kills=$OPTARG 23 | ;; 24 | l) logfile=$OPTARG 25 | ;; 26 | m) noMuted="-m" 27 | ;; 28 | o) outfile=$OPTARG 29 | ;; 30 | s) num_subs=$OPTARG 31 | ;; 32 | esac 33 | done 34 | 35 | shift $((OPTIND-1)) 36 | 37 | killall -q display 38 | 39 | tmpfile=$(mktemp /tmp/showmesh.XXXXXX) 40 | if [[ $outfile != '' ]]; then 41 | build/test/bin/make_mesh $noMuted $debug -s $num_subs -k $num_kills -f $@ -o $tmpfile 42 | $engine -Tpng $tmpfile > $outfile 43 | display $outfile& 44 | rm $tmpfile 45 | else 46 | build/test/bin/make_mesh $noMuted $debug -s $num_subs -k $num_kills -f $@ -o $tmpfile 47 | $engine -Tpng $tmpfile | display 48 | rm $tmpfile 49 | fi 50 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py37 3 | skipsdist = True 4 | [testenv] 5 | deps = 6 | cryptography 7 | pexpect 8 | whitelist_externals = 9 | scons 10 | run.py 11 | commands = 12 | scons 13 | ./test_scripts/run.py 14 | -------------------------------------------------------------------------------- /yocto/recipes-connectivity/dps/dps_git.bb: -------------------------------------------------------------------------------- 1 | SUMMARY = "distributed pub/sub" 2 | DESCRIPTION = "distributed pub/sub examples and lib." 3 | 4 | LICENSE = "Apache-2.0" 5 | LIC_FILES_CHKSUM = "file://LICENSE.md;md5=048191255019d4e1ee70aef53dbbec10" 6 | 7 | S = "${WORKDIR}/git" 8 | SRCREV_dps = "59a3c33d64f2b3fc16cc5c52b5f4a7bec47640a7" 9 | SRCREV_safestring = "db404a9bba3a58d06adfdab4021e7b91265ac0f0" 10 | PV = "0.1+git${SRCPV}" 11 | PR = "r0" 12 | 13 | SRCREV_FORMAT = "dps" 14 | SRC_URI = "git://github.com/01org/dps-for-iot.git;name=dps \ 15 | git://github.com/01org/safestringlib.git;protocol=https;name=safestring;destsuffix=git/ext/safestring \ 16 | " 17 | inherit scons 18 | 19 | DEPENDS = "libuv nodejs python-scons-native python" 20 | 21 | INSANE_SKIP_${PN} += " ldflags" 22 | INSANE_SKIP_${PN}-dev += "ldflags" 23 | INSANE_SKIP_${PN}-dbg += "ldflags" 24 | 25 | ERROR_QA_remove = "ldflags" 26 | WARN_QA_append = " ldflags" 27 | 28 | EXTRA_OESCONS = " \ 29 | sysroot=${STAGING_DIR_TARGET} \ 30 | " 31 | 32 | do_compile_prepend() { 33 | export PKG_CONFIG_PATH="${PKG_CONFIG_PATH}" 34 | export PKG_CONFIG="PKG_CONFIG_SYSROOT_DIR=\"${PKG_CONFIG_SYSROOT_DIR}\" pkg-config" 35 | export STAGING_PREFIX="${STAGING_DIR_HOST}/${prefix}" 36 | export LINKFLAGS="${LDFLAGS}" 37 | export SYSROOT="${STAGING_DIR_TARGET}" 38 | } 39 | scons_do_compile() { 40 | ${STAGING_BINDIR_NATIVE}/scons target=yocto ${PARALLEL_MAKE} ${EXTRA_OESCONS} || \ 41 | die "scons build execution failed." 42 | } 43 | 44 | do_install() { 45 | install -d ${D}${libdir}/dps 46 | install -m 0755 ${WORKDIR}/git/build/dist/lib/libdps_shared.so ${D}${libdir}/dps/libdps_shared.so 47 | install -m 0755 ${WORKDIR}/git/build/dist/lib/libdps.a ${D}${libdir}/dps/libdps.a 48 | 49 | install -d ${D}/${libdir}/dps/bin 50 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/publisher ${D}/${libdir}/dps/bin/publisher 51 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/pub_many ${D}/${libdir}/dps/bin/pub_many 52 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/registry ${D}/${libdir}/dps/bin/registry 53 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/reg_pubs ${D}/${libdir}/dps/bin/reg_pubs 54 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/reg_subs ${D}/${libdir}/dps/bin/reg_subs 55 | install -c -m 0755 ${WORKDIR}/git/build/dist/bin/subscriber ${D}/${libdir}/dps/bin/subscriber 56 | } 57 | 58 | PACKAGES =+ "${PN}-tests" 59 | 60 | RDEPENDS_${PN} += "libuv" 61 | ALLOW_EMPTY_${PN}-staticdev = "1" 62 | 63 | FILES_${PN} += "${libdir}/dps/libdps_shared.so" 64 | 65 | FILES_${PN}-staticdev += "${libdir}/dps/libdps.a" 66 | 67 | FILES_${PN}-tests += "${libdir}/dps/bin/publisher \ 68 | ${libdir}/dps/bin/pub_many \ 69 | ${libdir}/dps/bin/registry \ 70 | ${libdir}/dps/bin/reg_pubs \ 71 | ${libdir}/dps/bin/reg_subs \ 72 | ${libdir}/dps/bin/subscriber" 73 | --------------------------------------------------------------------------------