Skip to contentSkip to conversation

Bluetooth Mesh Daemon

PATCH Superseded Brian Gix 1 participant 10 messages Apr 25, 2018

Subsystems (2)

v2 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Brian Gix

author
#0 lore raw

v2 cover Bluetooth Mesh Daemon

v2 of patch-set to address maximum patch size limits

This is our starting point for creating a stand-alone Mesh Daemon.

The Mesh Daemon (meshd) is intended to eventually co-exist beside the Bluetooth Daemon (bluetoothd), and either daemon may exist without the other. The Mesh Daemon will need full control/ownership of a BT Controller that supports at least Core Spec revision 4.0 or greater. It works strictly over the Advertising bearer, but we have plans to extend it to support Mesh Proxy Server over GATT, at which point it will require support from bluetoothd.

The current meshd, and it's companion Non-Background Command-line version btmesh, exists fully within user-space, but requires an HCI_USER socket to the kernel controler, and currently requires root privledges.

This first revision is intended to operate as a standard (non-provisioner) node. It includes the Configuration Server model, and if it cannot find it's Mesh Configuration, will look for it's Composition data, and start up as unprovisioned, and accept an incoming PB-ADV provisioning session.

Two of us (Inga and Brian) have been working on this, and will be the initial supporters and maintainers, and we gladly invite other interested parties to participate.

Brian Gix (4):
meshd: Shared private meshd interfaces
meshd: Infrastructure for Mesh daemon
meshd: Provisioning logic for mesh
meshd: Upper and Lower mesh transport

Inga Stotland (7):
meshd: Header files for mesh access layer and utilities
meshd: Source files for mesh access layer and utilities
meshd: Source code for handling access layer mux/demux
meshd: Mesh config server model
meshd: Read and write mesh configuration in JSON format
meshd: Sample device composition in JSON fromat Makefile for meshd and configure.ac

 Makefile.am                   |    1 +
 Makefile.meshd                |   44 +
 configure.ac                  |    2 +-
 meshd/common/agent.c          |  229 +++
 meshd/common/agent.h          |   42 +
 meshd/common/mesh-defs.h      |   84 +
 meshd/common/util.c           |   71 +
 meshd/common/util.h           |   25 +
 meshd/config/composition.json |   44 +
 meshd/mesh-json/mesh-db.c     | 1360 +++++++++++++
 meshd/mesh-json/mesh-db.h     |  144 ++
 meshd/src/appkey.c            |  538 ++++++
 meshd/src/appkey.h            |   43 +
 meshd/src/btmesh.c            |  176 ++
 meshd/src/cfgmod-server.c     | 1194 ++++++++++++
 meshd/src/cfgmod.h            |   98 +
 meshd/src/crypto.c            | 1607 ++++++++++++++++
 meshd/src/crypto.h            |  164 ++
 meshd/src/display.c           |   67 +
 meshd/src/display.h           |   29 +
 meshd/src/friend.c            | 1116 +++++++++++
 meshd/src/friend.h            |   57 +
 meshd/src/hci.c               |  699 +++++++
 meshd/src/hci.h               |   56 +
 meshd/src/main.c              |  174 ++
 meshd/src/mesh-io-api.h       |   58 +
 meshd/src/mesh-io-generic.c   |  660 +++++++
 meshd/src/mesh-io-generic.h   |   20 +
 meshd/src/mesh-io.c           |  187 ++
 meshd/src/mesh-io.h           |   99 +
 meshd/src/mesh.c              |  184 ++
 meshd/src/mesh.h              |   32 +
 meshd/src/model.c             | 1274 +++++++++++++
 meshd/src/model.h             |  146 ++
 meshd/src/net.c               | 4188 +++++++++++++++++++++++++++++++++++++++++
 meshd/src/net.h               |  392 ++++
 meshd/src/node.c              |  851 +++++++++
 meshd/src/node.h              |   80 +
 meshd/src/prov.c              |  722 +++++++
 meshd/src/prov.h              |  162 ++
 meshd/src/provision.c         | 1159 ++++++++++++
 meshd/src/provision.h         |   30 +
 meshd/src/storage.c           |  673 +++++++
 meshd/src/storage.h           |   51 +
 44 files changed, 19031 insertions(+), 1 deletion(-)
 create mode 100644 Makefile.meshd
 create mode 100644 meshd/common/agent.c
 create mode 100644 meshd/common/agent.h
 create mode 100644 meshd/common/mesh-defs.h
 create mode 100644 meshd/common/util.c
 create mode 100644 meshd/common/util.h
 create mode 100644 meshd/config/composition.json
 create mode 100644 meshd/mesh-json/mesh-db.c
 create mode 100644 meshd/mesh-json/mesh-db.h
 create mode 100644 meshd/src/appkey.c
 create mode 100644 meshd/src/appkey.h
 create mode 100644 meshd/src/btmesh.c
 create mode 100644 meshd/src/cfgmod-server.c
 create mode 100644 meshd/src/cfgmod.h
 create mode 100644 meshd/src/crypto.c
 create mode 100644 meshd/src/crypto.h
 create mode 100644 meshd/src/display.c
 create mode 100644 meshd/src/display.h
 create mode 100644 meshd/src/friend.c
 create mode 100644 meshd/src/friend.h
 create mode 100644 meshd/src/hci.c
 create mode 100644 meshd/src/hci.h
 create mode 100644 meshd/src/main.c
 create mode 100644 meshd/src/mesh-io-api.h
 create mode 100644 meshd/src/mesh-io-generic.c
 create mode 100644 meshd/src/mesh-io-generic.h
 create mode 100644 meshd/src/mesh-io.c
 create mode 100644 meshd/src/mesh-io.h
 create mode 100644 meshd/src/mesh.c
 create mode 100644 meshd/src/mesh.h
 create mode 100644 meshd/src/model.c
 create mode 100644 meshd/src/model.h
 create mode 100644 meshd/src/net.c
 create mode 100644 meshd/src/net.h
 create mode 100644 meshd/src/node.c
 create mode 100644 meshd/src/node.h
 create mode 100644 meshd/src/prov.c
 create mode 100644 meshd/src/prov.h
 create mode 100644 meshd/src/provision.c
 create mode 100644 meshd/src/provision.h
 create mode 100644 meshd/src/storage.c
 create mode 100644 meshd/src/storage.h
Signature · 1 line
2.14.3
author
#1 lore raw

PATCH v2 1/11 meshd: Shared private meshd interfaces

---
 meshd/src/crypto.h          | 164 ++++++++++++++++++
 meshd/src/display.h         |  29 ++++
 meshd/src/friend.h          |  57 +++++++
 meshd/src/hci.h             |  56 +++++++
 meshd/src/mesh-io-api.h     |  58 +++++++
 meshd/src/mesh-io-generic.h |  20 +++
 meshd/src/mesh-io.h         |  99 +++++++++++
 meshd/src/net.h             | 392 ++++++++++++++++++++++++++++++++++++++++++++
 meshd/src/prov.h            | 162 ++++++++++++++++++
 meshd/src/provision.h       |  30 ++++
 10 files changed, 1067 insertions(+)
 create mode 100644 meshd/src/crypto.h
 create mode 100644 meshd/src/display.h
 create mode 100644 meshd/src/friend.h
 create mode 100644 meshd/src/hci.h
 create mode 100644 meshd/src/mesh-io-api.h
 create mode 100644 meshd/src/mesh-io-generic.h
 create mode 100644 meshd/src/mesh-io.h
 create mode 100644 meshd/src/net.h
 create mode 100644 meshd/src/prov.h
 create mode 100644 meshd/src/provision.h
meshd/src/crypto.h new file +164 -0
new file mode 100644
index 000000000..251b2cc7f
@@ -0,0 +1,164 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ */
+
+#include <stdbool.h>
+#include <stdint.h>
+
+bool mesh_crypto_aes_ccm_encrypt(const uint8_t nonce[13], const uint8_t key[16],
+					const uint8_t *aad, uint16_t aad_len,
+					const uint8_t *msg, uint16_t msg_len,
+					uint8_t *out_msg,
+					void *out_mic, size_t mic_size);
+bool mesh_crypto_aes_ccm_decrypt(const uint8_t nonce[13], const uint8_t key[16],
+				const uint8_t *aad, uint16_t aad_len,
+				const uint8_t *enc_msg, uint16_t enc_msg_len,
+				uint8_t *out_msg,
+				void *out_mic, size_t mic_size);
+bool mesh_aes_ecb_one(const uint8_t key[16],
+			const uint8_t plaintext[16], uint8_t encrypted[16]);
+bool mesh_crypto_nkik(const uint8_t network_key[16], uint8_t identity_key[16]);
+bool mesh_crypto_nkbk(const uint8_t network_key[16], uint8_t beacon_key[16]);
+bool mesh_crypto_nkpk(const uint8_t network_key[16], uint8_t proxy_key[16]);
+bool mesh_crypto_identity(const uint8_t net_key[16], uint16_t addr,
+							uint8_t id[16]);
+bool mesh_crypto_beacon_cmac(const uint8_t encryption_key[16],
+				const uint8_t network_id[16],
+				uint32_t iv_index, bool kr,
+				bool iu, uint64_t *cmac);
+bool mesh_crypto_network_nonce(bool frnd, uint8_t ttl, uint32_t seq,
+				uint16_t src, uint32_t iv_index,
+				uint8_t nonce[13]);
+bool mesh_crypto_network_encrypt(bool ctl, uint8_t ttl,
+				uint32_t seq, uint16_t src,
+				uint32_t iv_index,
+				const uint8_t net_key[16],
+				const uint8_t *enc_msg, uint8_t enc_msg_len,
+				uint8_t *out, void *net_mic);
+bool mesh_crypto_network_decrypt(bool frnd, uint8_t ttl,
+				uint32_t seq, uint16_t src,
+				uint32_t iv_index,
+				const uint8_t net_key[16],
+				const uint8_t *enc_msg, uint8_t enc_msg_len,
+				uint8_t *out, void *net_mic, size_t mic_size);
+bool mesh_crypto_application_nonce(uint32_t seq, uint16_t src,
+				uint16_t dst, uint32_t iv_index,
+				bool aszmic, uint8_t nonce[13]);
+bool mesh_crypto_device_nonce(uint32_t seq, uint16_t src,
+				uint16_t dst, uint32_t iv_index,
+				bool aszmic, uint8_t nonce[13]);
+bool mesh_crypto_application_encrypt(uint8_t akf, uint32_t seq, uint16_t src,
+					uint16_t dst, uint32_t iv_index,
+					const uint8_t app_key[16],
+					const uint8_t *aad, uint8_t aad_len,
+					const uint8_t *msg, uint8_t msg_len,
+					uint8_t *out,
+					void *app_mic, size_t mic_size);
+bool mesh_crypto_application_decrypt(uint8_t akf, uint32_t seq, uint16_t src,
+				uint16_t dst, uint32_t iv_index,
+				const uint8_t app_key[16],
+				const uint8_t *aad, uint8_t aad_len,
+				const uint8_t *enc_msg, uint8_t enc_msg_len,
+				uint8_t *out, void *app_mic, size_t mic_size);
+bool mesh_crypto_device_key(const uint8_t secret[32],
+						const uint8_t salt[16],
+						uint8_t device_key[16]);
+bool mesh_crypto_virtual_addr(const uint8_t virtual_label[16],
+						uint16_t *v_addr);
+bool mesh_crypto_nonce(const uint8_t secret[32],
+					const uint8_t salt[16],
+					uint8_t nonce[13]);
+bool mesh_crypto_k1(const uint8_t ikm[16], const uint8_t salt[16],
+		const void *info, size_t info_len, uint8_t okm[16]);
+bool mesh_crypto_k2(const uint8_t n[16], const uint8_t *p, size_t p_len,
+							uint8_t net_id[1],
+							uint8_t enc_key[16],
+							uint8_t priv_key[16]);
+bool mesh_crypto_k3(const uint8_t n[16], uint8_t out64[8]);
+bool mesh_crypto_k4(const uint8_t a[16], uint8_t out5[1]);
+bool mesh_crypto_s1(const void *info, size_t len, uint8_t salt[16]);
+bool mesh_crypto_prov_prov_salt(const uint8_t conf_salt[16],
+					const uint8_t prov_rand[16],
+					const uint8_t dev_rand[16],
+					uint8_t prov_salt[16]);
+bool mesh_crypto_prov_conf_key(const uint8_t secret[32],
+					const uint8_t salt[16],
+					uint8_t conf_key[16]);
+bool mesh_crypto_session_key(const uint8_t secret[32],
+					const uint8_t salt[16],
+					uint8_t session_key[16]);
+bool mesh_crypto_privacy_counter(uint32_t iv_index,
+						const uint8_t *payload,
+						uint8_t privacy_counter[16]);
+bool mesh_crypto_network_obfuscate(const uint8_t privacy_key[16],
+					const uint8_t privacy_counter[16],
+					bool ctl, uint8_t ttl, uint32_t seq,
+					uint16_t src, uint8_t *out);
+bool mesh_crypto_network_clarify(const uint8_t privacy_key[16],
+				const uint8_t privacy_counter[16],
+				const uint8_t net_hdr[6],
+				bool *ctl, uint8_t *ttl,
+				uint32_t *seq, uint16_t *src);
+
+bool mesh_crypto_packet_build(bool ctl, uint8_t ttl,
+				uint32_t seq,
+				uint16_t src, uint16_t dst,
+				uint8_t opcode,
+				bool segmented, uint8_t key_id,
+				bool szmic, bool relay, uint16_t seqZero,
+				uint8_t segO, uint8_t segN,
+				const uint8_t *payload, uint8_t payload_len,
+				uint8_t *packet, uint8_t *packet_len);
+bool mesh_crypto_packet_parse(const uint8_t *packet, uint8_t packet_len,
+				bool *ctl, uint8_t *ttl, uint32_t *seq,
+				uint16_t *src, uint16_t *dst,
+				uint32_t *cookie, uint8_t *opcode,
+				bool *segmented, uint8_t *key_id,
+				bool *szmic, bool *relay, uint16_t *seqZero,
+				uint8_t *segO, uint8_t *segN,
+				const uint8_t **payload, uint8_t *payload_len);
+bool mesh_crypto_payload_encrypt(uint8_t *aad, const uint8_t *payload,
+				uint8_t *out, uint16_t payload_len,
+				uint16_t src, uint16_t dst, uint8_t key_id,
+				uint32_t seq_num, uint32_t iv_index,
+				bool aszmic,
+				const uint8_t application_key[16]);
+bool mesh_crypto_payload_decrypt(uint8_t *aad, uint16_t aad_len,
+				const uint8_t *payload, uint16_t payload_len,
+				bool szmict,
+				uint16_t src, uint16_t dst, uint8_t key_id,
+				uint32_t seq_num, uint32_t iv_index,
+				uint8_t *out,
+				const uint8_t application_key[16]);
+bool mesh_crypto_packet_encode(uint8_t *packet, uint8_t packet_len,
+				const uint8_t network_key[16],
+				uint32_t iv_index,
+				const uint8_t privacy_key[16]);
+bool mesh_crypto_packet_decode(const uint8_t *packet, uint8_t packet_len,
+				bool proxy, uint8_t *out, uint32_t iv_index,
+				const uint8_t network_key[16],
+				const uint8_t privacy_key[16]);
+bool mesh_crypto_packet_label(uint8_t *packet, uint8_t packet_len,
+				uint16_t iv_index, uint8_t network_id);
+
+uint8_t mesh_crypto_compute_fcs(const uint8_t *packet, uint8_t packet_len);
+bool mesh_crypto_check_fcs(const uint8_t *packet, uint8_t packet_len,
+							uint8_t received_fcs);
+bool mesh_crypto_aes_cmac(const uint8_t key[16], const uint8_t *msg,
+					size_t msg_len, uint8_t res[16]);
+
meshd/src/display.h new file +29 -0
new file mode 100644
index 000000000..d43292741
@@ -0,0 +1,29 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ */
+
+#define COLOR_OFF	"\x1B[0m"
+#define COLOR_RED	"\x1B[0;91m"
+#define COLOR_GREEN	"\x1B[0;92m"
+#define COLOR_YELLOW	"\x1B[0;93m"
+#define COLOR_BLUE	"\x1B[0;94m"
+
+unsigned int num_columns(void);
+
+void print_packet(const char *label, const void *data, uint16_t size);
+
meshd/src/friend.h new file +57 -0

57 lines not on this page · raw message

meshd/src/hci.h new file +56 -0

56 lines not on this page · raw message

meshd/src/mesh-io-api.h new file +58 -0

58 lines not on this page · raw message

meshd/src/mesh-io-generic.h new file +20 -0
new file mode 100644
index 000000000..4bf4d5cb7
@@ -0,0 +1,20 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ */
+
+extern const struct mesh_io_api mesh_io_generic;
meshd/src/mesh-io.h new file +99 -0

99 lines not on this page · raw message

meshd/src/net.h new file +392 -0

392 lines not on this page · raw message

meshd/src/prov.h new file +162 -0

162 lines not on this page · raw message

meshd/src/provision.h new file +30 -0
new file mode 100644
index 000000000..0c59bf037
@@ -0,0 +1,30 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ */
+
+struct mesh_prov;
+struct l_queue;
+
+void initiator_prov_open(struct mesh_prov *prov);
+void initiator_prov_close(struct mesh_prov *prov, uint8_t reason);
+void initiator_prov_receive(const void *pkt, uint16_t size,
+							struct mesh_prov *prov);
+void acceptor_prov_open(struct mesh_prov *prov);
+void acceptor_prov_close(struct mesh_prov *prov, uint8_t reason);
+void acceptor_prov_receive(const void *pkt, uint16_t size,
+							struct mesh_prov *prov);
Signature · 1 line
2.14.3
author
#2 lore raw

PATCH v2 3/11 meshd: Provisioning logic for mesh

In reply to Brian Gix
---
 meshd/src/prov.c      |  722 ++++++++++++++++++++++++++++++
 meshd/src/provision.c | 1159 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1881 insertions(+)
 create mode 100644 meshd/src/prov.c
 create mode 100644 meshd/src/provision.c
meshd/src/prov.c new file +722 -0
new file mode 100644
index 000000000..d96f9f28b
@@ -0,0 +1,722 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/time.h>
+#include <ell/ell.h>
+
+#include "meshd/common/mesh-defs.h"
+
+#include "meshd/src/mesh-io.h"
+#include "meshd/src/display.h"
+#include "meshd/src/crypto.h"
+#include "meshd/src/net.h"
+#include "meshd/src/prov.h"
+
+#define PB_ADV_MTU	24
+
+#define DEFAULT_CONN_ID	0x00000000
+#define DEFAULT_PROV_MSG_NUM	0x00
+#define DEFAULT_DEV_MSG_NUM	0x80
+
+#define TX_TIMEOUT	30
+
+struct mesh_prov *mesh_prov_new(struct mesh_net *net, uint16_t remote)
+{
+	struct mesh_prov *prov;
+
+	prov = l_new(struct mesh_prov, 1);
+
+	prov->remote = remote;
+	prov->net = net;
+
+	return mesh_prov_ref(prov);
+}
+
+struct mesh_prov *mesh_prov_ref(struct mesh_prov *prov)
+{
+	if (!prov)
+		return NULL;
+
+	__sync_fetch_and_add(&prov->ref_count, 1);
+
+	return prov;
+}
+
+void mesh_prov_unref(struct mesh_prov *prov)
+{
+	struct mesh_io *io;
+	uint8_t type;
+
+	if (!prov)
+		return;
+
+	if (__sync_sub_and_fetch(&prov->ref_count, 1))
+		return;
+
+	io = mesh_net_get_io(prov->net);
+	type = MESH_AD_TYPE_BEACON;
+	mesh_io_send_cancel(io, &type, 1);
+	type = MESH_AD_TYPE_PROVISION;
+	mesh_io_send_cancel(io, &type, 1);
+	mesh_io_deregister_recv_cb(io, MESH_IO_FILTER_PROV);
+	mesh_io_deregister_recv_cb(io, MESH_IO_FILTER_BEACON);
+	l_timeout_remove(prov->tx_timeout);
+
+
+	l_info("Freed Prov Data");
+	l_free(prov);
+}
+
+static void packet_received(struct mesh_prov *prov, const void *data,
+						uint16_t size, uint8_t fcs)
+{
+	if (prov->receive_callback)
+		prov->receive_callback(data, size, prov);
+}
+
+static void send_open_req(struct mesh_prov *prov)
+{
+	struct mesh_io *io;
+	uint8_t open_req[23] = { MESH_AD_TYPE_PROVISION };
+	struct mesh_io_send_info info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 50,
+		.u.gen.cnt = 1,
+		.u.gen.min_delay = 0,
+		.u.gen.max_delay = 0,
+	};
+
+	if (!prov)
+		return;
+
+	io = mesh_net_get_io(prov->net);
+	if (!io)
+		return;
+
+	l_put_be32(prov->conn_id, open_req + 1);
+	open_req[1 + 4] = prov->local_msg_num = 0;
+	open_req[1 + 4 + 1] = 0x03; /* OPEN_REQ */
+	memcpy(open_req + 1 + 4 + 1 + 1, prov->uuid, 16);
+
+	/* print_packet("PB-TX", open_req + 1, sizeof(open_req) - 1); */
+	mesh_io_send_cancel(io, open_req, 1);
+	mesh_io_send(io, &info, open_req, sizeof(open_req));
+}
+
+static void send_open_cfm(struct mesh_prov *prov)
+{
+	struct mesh_io *io;
+	uint8_t open_cfm[7] = { MESH_AD_TYPE_PROVISION };
+	struct mesh_io_send_info info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 50,
+		.u.gen.cnt = 1,
+		.u.gen.min_delay = 0,
+		.u.gen.max_delay = 0,
+	};
+
+	if (!prov)
+		return;
+
+	io = mesh_net_get_io(prov->net);
+	if (!io)
+		return;
+
+	l_put_be32(prov->conn_id, open_cfm + 1);
+	open_cfm[1 + 4] = 0;
+	open_cfm[1 + 4 + 1] = 0x07; /* OPEN_CFM */
+
+	/* print_packet("PB-TX", open_cfm + 1, sizeof(open_cfm) - 1); */
+
+	mesh_io_send_cancel(io, open_cfm, 1);
+	mesh_io_send(io, &info, open_cfm, sizeof(open_cfm));
+}
+
+static void send_close_ind(struct mesh_prov *prov, uint8_t reason)
+{
+	uint8_t buf[8] = { MESH_AD_TYPE_PROVISION };
+	struct mesh_io *io;
+	struct mesh_io_send_info info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 50,
+		.u.gen.cnt = 3,
+		.u.gen.min_delay = 0,
+		.u.gen.max_delay = 0,
+	};
+
+	if (!prov)
+		return;
+
+	if (prov->bearer == MESH_BEARER_ADV) {
+		io = mesh_net_get_io(prov->net);
+		if (!io)
+			return;
+
+		l_put_be32(prov->conn_id, buf + 1);
+		buf[5] = 0;
+		buf[6] = 0x0B; /* CLOSE_IND */
+		buf[7] = reason;
+
+		/* print_packet("PB-TX", buf + 1, sizeof(buf) - 1); */
+
+		mesh_io_send_cancel(io, buf, 1);
+		mesh_io_send(io, &info, buf, sizeof(buf));
+	}
+
+	prov->bearer = MESH_BEARER_IDLE;
+}
+
+static void tx_timeout(struct l_timeout *timeout, void *user_data)
+{
+	struct mesh_prov *prov = user_data;
+	uint8_t cancel[] = { MESH_AD_TYPE_PROVISION };
+	struct mesh_io *io;
+
+	if (!prov)
+		return;
+
+	l_timeout_remove(prov->tx_timeout);
+	prov->tx_timeout = NULL;
+
+	io = mesh_net_get_io(prov->net);
+	if (!io)
+		return;
+
+	mesh_io_send_cancel(io, cancel, sizeof(cancel));
+
+	l_info("TX timeout");
+	mesh_prov_close(prov, 1);
+}
+
+static void send_adv_segs(struct mesh_prov *prov)
+{
+	struct mesh_io *io = mesh_net_get_io(prov->net);
+	struct mesh_io_send_info info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 50,
+		.u.gen.cnt = MESH_IO_TX_COUNT_UNLIMITED,
+		.u.gen.min_delay = 0,
+		.u.gen.max_delay = 0,
+	};
+	const void *data = prov->packet_buf;
+	uint16_t size = prov->packet_len;
+	uint16_t init_size;
+	uint8_t buf[1 + PB_ADV_MTU + 5] = { MESH_AD_TYPE_PROVISION };
+	uint8_t max_seg;
+	uint8_t consumed;
+	int i;
+
+	if (!size)
+		return;
+
+	mesh_io_send_cancel(io, buf, 1);
+
+	l_put_be32(prov->conn_id, buf + 1);
+	buf[1 + 4] = prov->local_msg_num;
+
+	if (size > PB_ADV_MTU - 4) {
+		max_seg = 1 +
+			(((size - (PB_ADV_MTU - 4)) - 1) / (PB_ADV_MTU - 1));
+		init_size = PB_ADV_MTU - 4;
+	} else {
+		max_seg = 0;
+		init_size = size;
+	}
+
+	/* print_packet("FULL-TX", data, size); */
+
+	l_debug("Sending %u fragments for %u octets", max_seg + 1, size);
+
+	buf[1 + 4 + 1] = max_seg << 2;
+	l_put_be16(size, buf + 1 + 4 + 1 + 1);
+	buf[9] = mesh_crypto_compute_fcs(data, size);
+	memcpy(buf + 1 + 4 + 1 + 1 + 2 + 1, data, init_size);
+
+	l_debug("max_seg: %2.2x", max_seg);
+	l_debug("size: %2.2x, CRC: %2.2x", size, buf[9]);
+
+	/* print_packet("PB-TX", buf + 1, init_size + 9); */
+	mesh_io_send(io, &info, buf, init_size + 10);
+
+	consumed = init_size;
+
+	for (i = 1; i <= max_seg; i++) {
+		uint8_t seg_size; /* Amount of payload data being sent */
+
+		if (size - consumed > PB_ADV_MTU - 1)
+			seg_size = PB_ADV_MTU - 1;
+		else
+			seg_size = size - consumed;
+
+		buf[6] = (i << 2) | 0x02;
+		memcpy(buf + 7, data + consumed, seg_size);
+
+		/* print_packet("PB-TX", buf + 1, seg_size + 6); */
+
+		mesh_io_send(io, &info, buf, seg_size + 7);
+
+		consumed += seg_size;
+	}
+}
+
+static void send_adv_msg(struct mesh_prov *prov, const void *data,
+								uint16_t size)
+{
+	l_timeout_remove(prov->tx_timeout);
+	prov->tx_timeout = l_timeout_create(TX_TIMEOUT, tx_timeout, prov, NULL);
+
+	memcpy(prov->packet_buf, data, size);
+	prov->packet_len = size;
+
+	send_adv_segs(prov);
+}
+
+static void send_ack(struct mesh_prov *prov)
+{
+	struct mesh_io *io = mesh_net_get_io(prov->net);
+	struct mesh_io_send_info info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 50,
+		.u.gen.cnt = 1,
+		.u.gen.min_delay = 0,
+		.u.gen.max_delay = 0,
+	};
+	uint8_t ack[7] = { MESH_AD_TYPE_PROVISION };
+
+	l_put_be32(prov->conn_id, ack + 1);
+	ack[1 + 4] = prov->last_peer_msg_num;
+	ack[1 + 4 + 1] = 0x01; /* ACK */
+
+	/* print_packet("ADV-ACK", ack + 1, sizeof(ack) - 1); */
+	mesh_io_send(io, &info, ack, sizeof(ack));
+}
+
+static void adv_data_pkt(uint8_t type, const void *pkt, uint8_t size,
+								void *user_data)
+{
+	const uint8_t *data = pkt;
+	struct mesh_prov *prov = user_data;
+	uint16_t offset = 0;
+
+	if ((type & 0x03) == 0x00) {
+		uint8_t last_seg = type >> 2;
+
+		prov->expected_len = l_get_be16(data);
+		prov->expected_fcs = l_get_u8(data + 2);
+
+		/* print_packet("Pkt", pkt, size); */
+		data += 3;
+		size -= 3;
+
+		prov->trans = MESH_TRANS_RX;
+
+		if (prov->expected_len > sizeof(prov->peer_buf)) {
+			l_info("Incoming pkt exceeds storage %d > %ld",
+				prov->expected_len, sizeof(prov->peer_buf));
+			return;
+		} else if (last_seg == 0)
+			prov->trans = MESH_TRANS_IDLE;
+
+		prov->expected_segs = 0xff >> (7 - last_seg);
+		prov->got_segs |= 1;
+		memcpy(prov->peer_buf, data, size);
+
+	} else if ((type & 0x03) == 0x02) {
+		offset = (PB_ADV_MTU - 4) + ((type >> 2) - 1) *
+							(PB_ADV_MTU - 1);
+
+		if (offset + size > prov->expected_len) {
+			l_info("Incoming pkt exceeds agreed len %d + %d > %d",
+					offset, size, prov->expected_len);
+			return;
+		}
+
+		prov->trans = MESH_TRANS_RX;
+
+		l_debug("Processing fragment %u", type & 0x3f);
+
+		prov->got_segs |= 1 << (type >> 2);
+		memcpy(prov->peer_buf + offset, data, size);
+
+	} else if (type == 0x01) {
+		if (prov->send_callback) {
+			void *data = prov->send_data;
+			mesh_prov_send_func_t cb = prov->send_callback;
+
+			prov->trans = MESH_TRANS_IDLE;
+			prov->send_callback = NULL;
+			prov->send_data = NULL;
+
+			cb(true, data);
+		}
+		return;
+	} else
+		return;
+
+	if (prov->got_segs != prov->expected_segs)
+		return;
+
+	/* Validate RXed packet and pass up to Provisioning */
+	if (!mesh_crypto_check_fcs(prov->peer_buf,
+				prov->expected_len,
+				prov->expected_fcs)) {
+		l_debug("Invalid FCS");
+		return;
+	}
+
+	prov->last_peer_msg_num = prov->peer_msg_num;
+	send_ack(prov);
+
+	prov->trans = MESH_TRANS_IDLE;
+
+	packet_received(prov, prov->peer_buf,
+			prov->expected_len, prov->expected_fcs);
+
+	/* Reset Re-Assembly for next packet */
+	prov->expected_len = sizeof(prov->peer_buf);
+	prov->expected_fcs = 0;
+	prov->expected_segs = 0;
+	prov->got_segs = 0;
+
+}
+
+static void adv_bearer_packet(void *user_data, struct mesh_io_recv_info *info,
+					const uint8_t *pkt, uint16_t len)
+{
+	struct mesh_prov *prov = user_data;
+	uint32_t conn_id;
+	uint8_t msg_num;
+	uint8_t type;
+
+	if (len < 6) {
+		l_info("  Too short packet");
+		return;
+	}
+
+	conn_id = l_get_be32(pkt + 1);
+	msg_num = l_get_u8(pkt + 1 + 4);
+	type = l_get_u8(pkt + 1 + 4 + 1);
+
+	/*if (prov->conn_id == conn_id) print_packet("ADV-RX", pkt, len); */
+
+	if (prov->conn_id != DEFAULT_CONN_ID) {
+		if (prov->conn_id != conn_id) {
+			l_debug("rxed unknown conn_id: %8.8x != %8.8x",
+							conn_id, prov->conn_id);
+			return;
+		}
+	} else if (type != 0x03)
+		return;
+
+	/* print_packet("PB-ADV-RX", pkt, len); */
+
+	/* Normalize pkt to start of PROV pkt payload */
+	pkt += 7;
+	len -= 7;
+
+	if (type == 0x07) { /* OPEN_CFM */
+		if (conn_id != prov->conn_id)
+			return;
+
+		if (msg_num != prov->local_msg_num)
+			return;
+
+		l_info("Link open confirmed");
+
+		prov->bearer = MESH_BEARER_ADV;
+		if (prov->open_callback)
+			prov->open_callback(prov->receive_data);
+	} else if (type == 0x01) {
+		if (conn_id != prov->conn_id)
+			return;
+
+		if (msg_num != prov->local_msg_num)
+			return;
+
+		l_debug("Got ACK %d", msg_num);
+		adv_data_pkt(type, pkt, len, user_data);
+	} else if (type == 0x03) {
+		/*
+		 * Ignore if:
+		 * 1. We are already provisioning
+		 * 2. We are not advertising that we are unprovisioned
+		 * 3. Open request not addressed to us
+		 */
+		if (prov->conn_id != DEFAULT_CONN_ID &&
+				prov->conn_id != conn_id)
+			return;
+
+		if (prov->local_msg_num != (DEFAULT_DEV_MSG_NUM - 1))
+			return;
+
+		if (memcmp(pkt, prov->uuid, 16))
+			return;
+
+		l_info("Link open request");
+
+		prov->last_peer_msg_num = 0xFF;
+		prov->bearer = MESH_BEARER_ADV;
+		if (prov->open_callback && prov->conn_id == DEFAULT_CONN_ID)
+			prov->open_callback(prov->receive_data);
+
+		prov->conn_id = conn_id;
+		prov->peer_msg_num = msg_num;
+		send_open_cfm(prov);
+	} else if (type == 0x0B) {
+		if (prov->conn_id != conn_id)
+			return;
+
+		prov->conn_id = DEFAULT_CONN_ID;
+		prov->local_msg_num = 0xFF;
+		prov->peer_msg_num = 0xFF;
+		prov->last_peer_msg_num = 0xFF;
+
+		l_timeout_remove(prov->tx_timeout);
+		prov->tx_timeout = NULL;
+
+		l_info("Link closed notification: %2.2x", pkt[0]);
+
+		if (prov->close_callback)
+			prov->close_callback(prov->receive_data, pkt[0]);
+	} else if ((type & 0x03) == 0x00) {
+		if (prov->conn_id != conn_id)
+			return;
+
+		if (msg_num == prov->last_peer_msg_num) {
+			send_ack(prov);
+			return;
+		}
+
+		prov->peer_msg_num = msg_num;
+
+		l_debug("Processing Data with %u fragments,%d octets",
+						type >> 2, l_get_be16(pkt));
+		adv_data_pkt(type, pkt, len, user_data);
+
+	} else if ((type & 0x03) == 0x02) {
+		if (prov->conn_id != conn_id)
+			return;
+
+		if (msg_num == prov->last_peer_msg_num) {
+			send_ack(prov);
+			return;
+		}
+
+		prov->peer_msg_num = msg_num;
+
+		l_debug("Processing fragment %u", type >> 2);
+		adv_data_pkt(type, pkt, len, user_data);
+	}
+}
+
+static void beacon_packet(void *user_data, struct mesh_io_recv_info *info,
+					const uint8_t *pkt, uint16_t len)
+{
+	struct mesh_prov *prov = user_data;
+	struct mesh_io *io;
+
+	pkt++;
+	len--;
+
+	if (len < 19)
+		return;
+
+	if (!pkt[0])
+		print_packet("UnProv-BEACON-RX", pkt, len);
+
+	/* Ignore devices not matching UUID */
+	if (pkt[0] || memcmp(pkt + 1, prov->uuid, 16))
+		return;
+
+	io = mesh_net_get_io(prov->net);
+	mesh_io_deregister_recv_cb(io, MESH_IO_FILTER_BEACON);
+
+	if ((prov->conn_id != DEFAULT_CONN_ID) ||
+			(prov->bearer != MESH_BEARER_IDLE)) {
+		l_info("PB-ADV: Already Provisioning");
+		return;
+	}
+
+	l_getrandom(&prov->conn_id, sizeof(prov->conn_id));
+	prov->bearer = MESH_BEARER_ADV;
+	send_open_req(prov);
+}
+
+static bool mesh_prov_enable(struct mesh_prov *prov, enum mesh_prov_mode mode,
+							uint8_t uuid[16])
+{
+	const uint8_t pb_adv_data[] = { MESH_AD_TYPE_BEACON, 0 };
+	uint8_t adv_data[62];
+	uint8_t adv_len, type;
+	struct mesh_io *io;
+	struct mesh_io_send_info tx_info = {
+		.type = MESH_IO_TIMING_TYPE_GENERAL,
+		.u.gen.interval = 1000,	/* ms */
+		.u.gen.cnt = 0,		/* 0 == Infinite */
+		.u.gen.min_delay = 0,	/* no delay */
+		.u.gen.max_delay = 0,	/* no delay */
+	};
+
+	if (!prov || !prov->net)
+		return false;
+
+
+	prov->mode = mode;
+	memcpy(prov->uuid, uuid, 16);
+	prov->conn_id = DEFAULT_CONN_ID;
+	io = mesh_net_get_io(prov->net);
+
+	switch (mode) {
+	case MESH_PROV_MODE_NONE:
+		break;
+	case MESH_PROV_MODE_INITIATOR:
+		print_packet("Searching for uuid", uuid, 16);
+		prov->local_msg_num = DEFAULT_PROV_MSG_NUM;
+		prov->peer_msg_num = DEFAULT_DEV_MSG_NUM;
+		mesh_io_register_recv_cb(io, MESH_IO_FILTER_PROV,
+						adv_bearer_packet, prov);
+		mesh_io_register_recv_cb(io, MESH_IO_FILTER_BEACON,
+						beacon_packet, prov);
+		break;
+
+	case MESH_PROV_MODE_ADV_ACCEPTOR:
+		prov->local_msg_num = DEFAULT_DEV_MSG_NUM - 1;
+		prov->peer_msg_num = DEFAULT_PROV_MSG_NUM;
+
+		print_packet("Beaconing as unProvisioned uuid", uuid, 16);
+		adv_len = sizeof(pb_adv_data);
+		memcpy(adv_data, pb_adv_data, adv_len);
+		memcpy(adv_data + adv_len, uuid, 16);
+		adv_len += 16;
+		adv_len += 2;
+		mesh_io_register_recv_cb(io, MESH_IO_FILTER_PROV,
+						adv_bearer_packet, prov);
+		type = MESH_AD_TYPE_BEACON;
+		mesh_io_send_cancel(io, &type, 1);
+		mesh_io_send(io, &tx_info, adv_data, adv_len);
+		break;
+
+	case MESH_PROV_MODE_GATT_CLIENT:
+	case MESH_PROV_MODE_MESH_GATT_CLIENT:
+	case MESH_PROV_MODE_GATT_ACCEPTOR:
+	case MESH_PROV_MODE_MESH_SERVER:
+	case MESH_PROV_MODE_MESH_CLIENT:
+	default:
+		l_error("Unimplemented Prov Mode: %d", mode);
+		break;
+	}
+
+	return true;
+}
+
+bool mesh_prov_listen(struct mesh_net *net, uint8_t uuid[16], uint8_t caps[12],
+					mesh_prov_open_func_t open_callback,
+					mesh_prov_close_func_t close_callback,
+					mesh_prov_receive_func_t recv_callback,
+					void *user_data)
+{
+	struct mesh_prov *prov = mesh_net_get_prov(net);
+
+	if (!prov) {
+		prov = mesh_prov_new(net, 0);
+		if (!prov)
+			return false;
+
+		mesh_net_set_prov(net, prov);
+	}
+
+	prov->open_callback = open_callback;
+	prov->close_callback = close_callback;
+	prov->receive_callback = recv_callback;
+	prov->receive_data = prov; /* TODO: retink the callback placement */
+	memcpy(prov->caps, caps, sizeof(prov->caps));
+
+	prov->trans = MESH_TRANS_IDLE;
+
+
+	return mesh_prov_enable(prov, MESH_PROV_MODE_ADV_ACCEPTOR, uuid);
+}
+
+unsigned int mesh_prov_send(struct mesh_prov *prov,
+					const void *ptr, uint16_t size,
+					mesh_prov_send_func_t send_callback,
+					void *user_data)
+{
+	const uint8_t *data = ptr;
+
+	if (!prov)
+		return 0;
+
+	if (prov->trans != MESH_TRANS_IDLE)
+		return 0;
+
+	if (prov->remote) {
+		/* TODO -- PB-Remote */
+	} else {
+		prov->send_callback = send_callback;
+		prov->send_data = user_data;
+		prov->trans = MESH_TRANS_TX;
+		prov->local_msg_num++;
+		send_adv_msg(prov, data, size);
+	}
+
+	return 1;
+}
+
+bool mesh_prov_close(struct mesh_prov *prov, uint8_t reason)
+{
+	if (!prov)
+		return false;
+
+	prov->local_msg_num = 0;
+	send_close_ind(prov, reason);
+
+	prov->conn_id = DEFAULT_CONN_ID;
+	prov->local_msg_num = 0xFF;
+	prov->peer_msg_num = 0xFF;
+	prov->last_peer_msg_num = 0xFF;
+
+	if (prov->tx_timeout) {
+		l_timeout_remove(prov->tx_timeout);
+
+		/* If timing out, give Close indication 1 second of
+		 * provisioning timing to get final Close indication out
+		 */
+		prov->tx_timeout = l_timeout_create(1, tx_timeout, prov, NULL);
+	}
+
+	if (prov->close_callback)
+		prov->close_callback(prov->receive_data, reason);
+
+	return false;
+}
+
+void mesh_prov_set_addr(struct mesh_prov *prov, uint16_t addr)
+{
+	prov->addr = addr;
+}
+
+uint16_t mesh_prov_get_idx(struct mesh_prov *prov)
+{
+	return prov->net_idx;
+}
meshd/src/provision.c new file +1159 -0

1,159 lines not on this page · raw message

Signature · 1 line
2.14.3
author
#3 lore raw

PATCH v2 5/11 meshd: Header files for mesh access layer and utilities

In reply to Brian Gix

From: Inga Stotland <[email protected]>

This adds initial implementation of Mesh access layer functionality

---
 meshd/common/agent.h     |  42 ++++++++++++++
 meshd/common/mesh-defs.h |  84 +++++++++++++++++++++++++++
 meshd/common/util.h      |  25 ++++++++
 meshd/src/appkey.h       |  43 ++++++++++++++
 meshd/src/cfgmod.h       |  98 +++++++++++++++++++++++++++++++
 meshd/src/mesh.h         |  32 +++++++++++
 meshd/src/model.h        | 146 +++++++++++++++++++++++++++++++++++++++++++++++
 meshd/src/node.h         |  80 ++++++++++++++++++++++++++
 meshd/src/storage.h      |  51 +++++++++++++++++
 9 files changed, 601 insertions(+)
 create mode 100644 meshd/common/agent.h
 create mode 100644 meshd/common/mesh-defs.h
 create mode 100644 meshd/common/util.h
 create mode 100644 meshd/src/appkey.h
 create mode 100644 meshd/src/cfgmod.h
 create mode 100644 meshd/src/mesh.h
 create mode 100644 meshd/src/model.h
 create mode 100644 meshd/src/node.h
 create mode 100644 meshd/src/storage.h
meshd/common/agent.h new file +42 -0
new file mode 100644
index 000000000..6fb475691
@@ -0,0 +1,42 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2017  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+#define MAX_HEXADECIMAL_OOB_LEN	128
+#define DECIMAL_OOB_LEN		4
+#define MAX_ASCII_OOB_LEN		16
+
+enum oob_type {
+	NONE,
+	HEXADECIMAL,
+	DECIMAL,
+	ASCII,
+	OUTPUT,
+} oob_type_t;
+
+typedef void (*agent_input_cb)(enum oob_type type, void *input, uint16_t len,
+							void *user_data);
+bool agent_input_request(enum oob_type type, uint16_t max_len,
+					agent_input_cb cb, void *user_data);
+
+bool agent_output_request(const char *str);
+void agent_output_request_cancel(void);
+bool agent_completion(void);
+bool agent_input(const char *input);
+void agent_release(void);
meshd/common/mesh-defs.h new file +84 -0

84 lines not on this page · raw message

meshd/common/util.h new file +25 -0
new file mode 100644
index 000000000..ed880bce7
@@ -0,0 +1,25 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+uint32_t get_timestamp_secs(void);
+bool str2hex(const char *str, uint16_t in_len, uint8_t *out,
+							uint16_t out_len);
+size_t hex2str(uint8_t *in, size_t in_len, char *out, size_t out_len);
+
meshd/src/appkey.h new file +43 -0

43 lines not on this page · raw message

meshd/src/cfgmod.h new file +98 -0

98 lines not on this page · raw message

meshd/src/mesh.h new file +32 -0
new file mode 100644
index 000000000..7cd1e6158
@@ -0,0 +1,32 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+struct bt_mesh;
+struct mesh_net;
+
+struct bt_mesh *mesh_create(uint16_t index);
+struct bt_mesh *mesh_ref(struct bt_mesh *mesh);
+void mesh_unref(struct bt_mesh *mesh);
+bool mesh_load_config(struct bt_mesh *mesh, const char *in_config_name);
+bool mesh_set_output(struct bt_mesh *mesh, const char *out_config_name);
+const char *mesh_status_str(uint8_t err);
+
+/* Command line testing */
+struct mesh_net *mesh_get_net(struct bt_mesh *mesh);
meshd/src/model.h new file +146 -0

146 lines not on this page · raw message

meshd/src/node.h new file +80 -0

80 lines not on this page · raw message

meshd/src/storage.h new file +51 -0

51 lines not on this page · raw message

Signature · 1 line
2.14.3
author
#4 lore raw

PATCH v2 6/11 meshd: Source files for mesh access layer and utilities

In reply to Brian Gix

From: Inga Stotland <[email protected]>

This adds initial implementation of BT Mesh access layer functionality plus utilities.

---
 meshd/common/agent.c | 229 ++++++++++++++
 meshd/common/util.c  |  71 +++++
 meshd/src/appkey.c   | 538 ++++++++++++++++++++++++++++++++
 meshd/src/btmesh.c   | 176 +++++++++++
 meshd/src/main.c     | 174 +++++++++++
 meshd/src/mesh.c     | 184 +++++++++++
 meshd/src/node.c     | 851 +++++++++++++++++++++++++++++++++++++++++++++++++++
 meshd/src/storage.c  | 673 ++++++++++++++++++++++++++++++++++++++++
 8 files changed, 2896 insertions(+)
 create mode 100644 meshd/common/agent.c
 create mode 100644 meshd/common/util.c
 create mode 100644 meshd/src/appkey.c
 create mode 100644 meshd/src/btmesh.c
 create mode 100644 meshd/src/main.c
 create mode 100644 meshd/src/mesh.c
 create mode 100644 meshd/src/node.c
 create mode 100644 meshd/src/storage.c
meshd/common/agent.c new file +229 -0
new file mode 100644
index 000000000..bbd916244
@@ -0,0 +1,229 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <inttypes.h>
+
+#include <ell/ell.h>
+
+#include "src/shared/shell.h"
+
+#include "meshd/common/util.h"
+#include "meshd/common/agent.h"
+
+struct input_request {
+	enum oob_type type;
+	uint16_t len;
+	agent_input_cb cb;
+	void *user_data;
+};
+
+static struct input_request pending_request = {NONE, 0, NULL, NULL};
+
+bool agent_completion(void)
+{
+	if (pending_request.type == NONE)
+		return false;
+
+	return true;
+}
+
+static void reset_input_request(void)
+{
+	pending_request.type = NONE;
+	pending_request.len = 0;
+	pending_request.cb = NULL;
+	pending_request.user_data = NULL;
+}
+
+static void try_again(void)
+{
+	static int try_count;
+	enum oob_type type = pending_request.type;
+
+	if (try_count == 2) {
+		reset_input_request();
+		try_count = 0;
+		return;
+	}
+
+	pending_request.type = NONE;
+	agent_input_request(type, pending_request.len, pending_request.cb,
+						pending_request.user_data);
+
+	try_count++;
+}
+
+static void response_hexadecimal(const char *input, void *user_data)
+{
+	uint8_t buf[MAX_HEXADECIMAL_OOB_LEN];
+
+	if (!str2hex(input, strlen(input), buf, pending_request.len)) {
+		bt_shell_printf("Incorrect input: expecting %d hex octets\n",
+							pending_request.len);
+		try_again();
+		return;
+	}
+
+	if (pending_request.cb)
+		pending_request.cb(HEXADECIMAL, buf, pending_request.len,
+					pending_request.user_data);
+
+	reset_input_request();
+}
+
+static void response_decimal(const char *input, void *user_data)
+{
+	uint8_t buf[DECIMAL_OOB_LEN];
+
+	if (strlen(input) > pending_request.len) {
+		bt_shell_printf("Bad input: expected no more than %d digits\n",
+						pending_request.len);
+		try_again();
+		return;
+	}
+
+	l_put_be32(atoi(input), buf);
+
+	if (pending_request.cb)
+		pending_request.cb(DECIMAL, buf, DECIMAL_OOB_LEN,
+					pending_request.user_data);
+
+	reset_input_request();
+}
+
+static void response_ascii(const char *input, void *user_data)
+{
+	if (pending_request.cb)
+		pending_request.cb(ASCII, (uint8_t *) input, strlen(input),
+					pending_request.user_data);
+
+	reset_input_request();
+}
+
+static bool request_hexadecimal(uint16_t len)
+{
+	if (len > MAX_HEXADECIMAL_OOB_LEN)
+		return false;
+
+	bt_shell_printf("Request hexadecimal key (hex %d octets)\n", len);
+	bt_shell_prompt_input("mesh", "Enter key (hex number):",
+						response_hexadecimal, NULL);
+
+	return true;
+}
+
+static uint32_t power_ten(uint8_t power)
+{
+	uint32_t ret = 1;
+
+	while (power--)
+		ret *= 10;
+
+	return ret;
+}
+
+static bool request_decimal(uint16_t len)
+{
+	bt_shell_printf("Request decimal key (0 - %d)\n", power_ten(len) - 1);
+	bt_shell_prompt_input("mesh", "Enter Numeric key:", response_decimal,
+									NULL);
+
+	return true;
+}
+
+static bool request_ascii(uint16_t len)
+{
+	if (len > MAX_ASCII_OOB_LEN)
+		return false;
+
+	bt_shell_printf("Request ASCII key (max characters %d)\n", len);
+	bt_shell_prompt_input("mesh", "Enter key (ascii string):",
+							response_ascii, NULL);
+
+	return true;
+}
+
+bool agent_input_request(enum oob_type type, uint16_t max_len,
+					agent_input_cb cb, void *user_data)
+{
+	bool result;
+
+	if (pending_request.type != NONE)
+		return false;
+
+	switch (type) {
+	case HEXADECIMAL:
+		result = request_hexadecimal(max_len);
+		break;
+	case DECIMAL:
+		result = request_decimal(max_len);
+		break;
+	case ASCII:
+		result = request_ascii(max_len);
+		break;
+	case NONE:
+	case OUTPUT:
+	default:
+		return false;
+	};
+
+	if (result) {
+		pending_request.type = type;
+		pending_request.len = max_len;
+		pending_request.cb = cb;
+		pending_request.user_data = user_data;
+
+		return true;
+	}
+
+	return false;
+}
+
+static void response_output(const char *input, void *user_data)
+{
+	reset_input_request();
+}
+
+bool agent_output_request(const char *str)
+{
+	if (pending_request.type != NONE)
+		return false;
+
+	pending_request.type = OUTPUT;
+	bt_shell_prompt_input("mesh", str, response_output, NULL);
+	return true;
+}
+
+void agent_output_request_cancel(void)
+{
+	if (pending_request.type != OUTPUT)
+		return;
+
+	pending_request.type = NONE;
+	bt_shell_release_prompt("");
+}
meshd/common/util.c new file +71 -0

71 lines not on this page · raw message

meshd/src/appkey.c new file +538 -0

538 lines not on this page · raw message

meshd/src/btmesh.c new file +176 -0

176 lines not on this page · raw message

meshd/src/main.c new file +174 -0

174 lines not on this page · raw message

meshd/src/mesh.c new file +184 -0

184 lines not on this page · raw message

meshd/src/node.c new file +851 -0

851 lines not on this page · raw message

meshd/src/storage.c new file +673 -0

673 lines not on this page · raw message

Signature · 1 line
2.14.3
author
#5 lore raw

PATCH v2 7/11 meshd: Source code for handling access layer mux/demux

In reply to Brian Gix

From: Inga Stotland <[email protected]>

---
 meshd/src/model.c | 1274 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 1274 insertions(+)
 create mode 100644 meshd/src/model.c
meshd/src/model.c new file +1274 -0
new file mode 100644
index 000000000..0b87312c0
@@ -0,0 +1,1274 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/time.h>
+#include <ell/ell.h>
+
+#include "meshd/common/mesh-defs.h"
+
+#include "meshd/src/mesh.h"
+#include "meshd/src/crypto.h"
+#include "meshd/src/node.h"
+#include "meshd/src/net.h"
+#include "meshd/src/appkey.h"
+#include "meshd/src/model.h"
+#include "meshd/src/display.h"
+#include "meshd/src/cfgmod.h"
+#include "meshd/src/storage.h"
+
+struct mesh_model {
+	const struct mesh_model_ops *cbs;
+	void *user_data;
+	struct l_queue *bindings;
+	struct l_queue *subs;
+	struct l_queue *virtuals;
+	struct mesh_model_pub *pub;
+	uint32_t id;
+	uint8_t ele_idx;
+};
+
+struct mesh_virtual {
+	uint32_t id; /*Identifier of internally stored addr, min val 0x10000 */
+	uint16_t ota;
+	uint16_t ref_cnt;
+	uint8_t addr[16];
+};
+
+/* These struct is used to pass lots of params to l_queue_foreach */
+struct mod_forward {
+	struct mesh_virtual *virt;
+	const uint8_t *data;
+	uint16_t src;
+	uint16_t dst;
+	uint16_t unicast;
+	uint16_t idx;
+	uint16_t size;
+	uint8_t ttl;
+	int8_t rssi;
+	bool szmict;
+	bool done;
+};
+
+static struct l_queue *mesh_virtuals;
+
+static uint32_t virt_id_next = VIRTUAL_BASE;
+static struct timeval tx_start;
+
+static void unref_virt(void *data)
+{
+	struct mesh_virtual *virt = data;
+
+	if (virt->ref_cnt > 0)
+		virt->ref_cnt--;
+
+	if (virt->ref_cnt)
+		return;
+
+	l_queue_remove(mesh_virtuals, virt);
+	l_free(virt);
+}
+
+static bool simple_match(const void *a, const void *b)
+{
+	return a == b;
+}
+
+static bool find_virt_by_id(const void *a, const void *b)
+{
+	const struct mesh_virtual *virt = a;
+	uint32_t id = L_PTR_TO_UINT(b);
+
+	return virt->id == id;
+}
+
+static bool find_virt_by_addr(const void *a, const void *b)
+{
+	const struct mesh_virtual *virt = a;
+	const uint8_t *addr = b;
+
+	return memcmp(virt->addr, addr, 16) == 0;
+}
+
+static struct mesh_model *find_model(struct mesh_net *net, uint16_t addr,
+						uint32_t mod_id, int *fail)
+{
+	int ele_idx;
+	struct mesh_node *node;
+
+	node = mesh_net_local_node_get(net);
+
+	ele_idx = node_get_element_idx(node, addr);
+
+	if (ele_idx < 0) {
+		if (fail)
+			*fail = MESH_STATUS_INVALID_ADDRESS;
+		return NULL;
+	}
+
+	return node_get_model(node, (uint8_t) ele_idx, mod_id, fail);
+}
+
+static void forward_model(void *a, void *b)
+{
+	struct mesh_model *mod = a;
+	struct mod_forward *fwd = b;
+	struct mesh_virtual *virt;
+	uint32_t dst;
+	bool has_dst = false;
+
+	if (!mod->cbs || !mod->cbs->recv)
+		return;
+
+	l_debug("model %8.8x with idx %3.3x", mod->id, fwd->idx);
+	if (fwd->idx != APP_IDX_DEV &&
+		!l_queue_find(mod->bindings, simple_match,
+						L_UINT_TO_PTR(fwd->idx)))
+		return;
+
+	dst = fwd->dst;
+	if (dst == fwd->unicast || IS_ALL_NODES(dst))
+		has_dst = true;
+	else if (fwd->virt) {
+		virt = l_queue_find(mod->virtuals, simple_match, fwd->virt);
+		if (virt) {
+			/*
+			 * Map Virtual addresses to a usable namespace that
+			 * prevents us for forwarding a false positive
+			 * (multiple Virtual Addresses that map to the same
+			 * u16 OTA addr)
+			 */
+			has_dst = true;
+			dst = virt->id;
+		}
+	} else {
+		if (l_queue_find(mod->subs, simple_match, L_UINT_TO_PTR(dst)))
+			has_dst = true;
+	}
+
+
+	if (!has_dst)
+		return;
+
+	/*
+	 * TODO: models shall be registered with a list of supported opcodes and
+	 * element address. Iterate through the list of opcodes to see if the
+	 * model is an addressee.
+	 * If this is an internal registered model, check for a "bind" callback.
+	 * For an external ("user") model, send D-Bus method (signal?) (TBD)
+	 */
+	if (mod->cbs->recv)
+		mod->cbs->recv(fwd->src, dst, fwd->unicast, fwd->idx,
+				fwd->data, fwd->size, fwd->ttl, mod->user_data);
+
+	if (dst == fwd->unicast)
+		fwd->done = true;
+}
+
+static int dev_packet_decrypt(struct mesh_net *net, const uint8_t *data,
+				uint16_t size, bool szmict, uint16_t src,
+				uint16_t dst, uint8_t key_id, uint32_t seq,
+				uint32_t iv_idx, uint8_t *out)
+{
+	struct mesh_node *node;
+	const uint8_t *dev_key;
+
+	node = mesh_net_local_node_get(net);
+	dev_key = node_get_device_key(node);
+	if (!dev_key)
+		return false;
+
+	if (mesh_crypto_payload_decrypt(NULL, 0, data, size, szmict, src,
+					dst, key_id, seq, iv_idx, out, dev_key))
+		return APP_IDX_DEV;
+
+	return -1;
+}
+
+static int virt_packet_decrypt(struct mesh_net *net, const uint8_t *data,
+				uint16_t size, bool szmict, uint16_t src,
+				uint16_t dst, uint8_t key_id, uint32_t seq,
+				uint32_t iv_idx, uint8_t *out,
+				struct mesh_virtual **decrypt_virt)
+{
+	const struct l_queue_entry *v;
+
+	for (v = l_queue_get_entries(mesh_virtuals); v; v = v->next) {
+		struct mesh_virtual *virt = v->data;
+		int decrypt_idx;
+
+		if (virt->ota != dst)
+			continue;
+
+		decrypt_idx = appkey_packet_decrypt(net, szmict, seq,
+							iv_idx, src, dst,
+							virt->addr, 16, key_id,
+							data, size, out);
+
+		if (decrypt_idx >= 0) {
+			*decrypt_virt = virt;
+			return decrypt_idx;
+		}
+	}
+
+	return -1;
+}
+
+static void cmplt(uint16_t remote, uint8_t status,
+					void *data, uint16_t size,
+					void *user_data)
+{
+	struct timeval tx_end;
+
+	if (status)
+		l_info("Tx-->%4.4x (%d octets) Failed (%d)",
+				remote, size, status);
+	else
+		l_info("Tx-->%4.4x (%d octets) Succeeded", remote, size);
+
+	/* print_packet("Sent Data", data, size); */
+
+	gettimeofday(&tx_end, NULL);
+	if (tx_end.tv_sec == tx_start.tv_sec) {
+		l_info("Duration 0.%zu seconds",
+				tx_end.tv_usec - tx_start.tv_usec);
+	} else {
+		if (tx_start.tv_usec > tx_end.tv_usec)
+			l_info("Duration %zu.%zu seconds",
+				tx_end.tv_sec - tx_start.tv_sec - 1,
+				tx_end.tv_usec + 1000000 - tx_start.tv_usec);
+		else
+			l_info("Duration %zu.%zu seconds",
+					tx_end.tv_sec - tx_start.tv_sec,
+					tx_end.tv_usec - tx_start.tv_usec);
+	}
+}
+
+static bool pub_frnd_cred(struct mesh_net *net, uint16_t src, uint32_t mod_id)
+{
+	struct mesh_model *mod = find_model(net, src, mod_id, NULL);
+
+	if (!mod || !mod->pub)
+		return false;
+
+	return (mod->pub->credential != 0);
+}
+
+static unsigned int msg_send(struct mesh_net *net, uint32_t mod_id,
+				uint16_t src, uint32_t dst,
+				uint8_t key_id, const uint8_t *key,
+				uint8_t *aad, uint8_t ttl,
+				const void *msg, uint16_t msg_len)
+{
+	unsigned int ret = 0;
+	uint32_t iv_index, seq_num;
+	uint8_t *out;
+	bool szmic = false;
+	uint16_t out_len = msg_len + sizeof(uint32_t);
+
+	/* Use large MIC if it doesn't affect segmentation */
+	if (msg_len > 11 && msg_len <= 376) {
+		if ((out_len / 12) == ((out_len + 4) / 12)) {
+			szmic = true;
+			out_len = msg_len + sizeof(uint64_t);
+		}
+	}
+
+	out = l_malloc(out_len);
+
+	iv_index = mesh_net_get_iv_index(net);
+
+	seq_num = mesh_net_get_seq_num(net);
+	if (!mesh_crypto_payload_encrypt(aad, msg, out, msg_len,
+				src, dst, key_id,
+				seq_num, iv_index,
+				szmic, key)) {
+		l_error("Failed to Encrypt Payload");
+		goto done;
+	}
+
+	/* print_packet("Encrypted with", key, 16); */
+
+	ret = mesh_net_app_send(net, pub_frnd_cred(net, src, mod_id),
+				src, dst, key_id, ttl,
+				seq_num, iv_index,
+				szmic,
+				out, out_len,
+				cmplt, NULL);
+done:
+	l_free(out);
+	return ret;
+}
+
+static void model_unbind_idx(void *a, void *b)
+{
+	struct mesh_model *mod = a;
+	uint16_t idx = L_PTR_TO_UINT(b);
+
+	if (idx == mod->pub->idx) {
+		mod->pub->addr = UNASSIGNED_ADDRESS;
+		/*
+		 * TODO: callback for internal model or
+		 * D-Bus signal/method "model publication changed" (TBD)
+		 */
+	}
+
+	l_queue_remove(mod->bindings, b);
+
+	if (mod->cbs->bind)
+		mod->cbs->bind(idx, ACTION_DELETE);
+}
+
+static int model_bind_idx(struct mesh_model *mod, uint16_t idx)
+{
+	if (l_queue_length(mod->bindings) >= MAX_BINDINGS)
+		return MESH_STATUS_INSUFF_RESOURCES;
+
+	if (!l_queue_push_tail(mod->bindings, L_UINT_TO_PTR(idx)))
+		return MESH_STATUS_INSUFF_RESOURCES;
+
+	if (mod->cbs->bind)
+		mod->cbs->bind(idx, ACTION_ADD);
+
+	return MESH_STATUS_SUCCESS;
+
+}
+
+static int update_binding(struct mesh_net *net, uint16_t addr, uint32_t id,
+				uint16_t app_idx, bool unbind)
+{
+	int fail;
+	struct mesh_model *mod;
+	int status;
+
+	mod = find_model(net, addr, id, &fail);
+	if (!mod) {
+		l_info("model not found");
+		return fail;
+	}
+
+	if (id == CONFIG_SRV_MODEL || id == CONFIG_CLI_MODEL)
+		return MESH_STATUS_INVALID_MODEL;
+
+	if (!l_queue_find(mod->bindings, simple_match, L_UINT_TO_PTR(app_idx)))
+		return MESH_STATUS_CANNOT_BIND;
+
+	if (!appkey_have_key(net, app_idx))
+		return MESH_STATUS_INVALID_APPKEY;
+
+	if (unbind) {
+		model_unbind_idx(mod, &app_idx);
+
+		if (!storage_model_bind(net, addr, id, app_idx, true))
+			return MESH_STATUS_STORAGE_FAIL;
+
+		return MESH_STATUS_SUCCESS;
+	}
+
+	status = model_bind_idx(mod, app_idx);
+	if (status != MESH_STATUS_SUCCESS)
+		return status;
+
+	if (!storage_model_bind(net, addr, id, app_idx, false)) {
+		model_unbind_idx(mod, &app_idx);
+		return MESH_STATUS_STORAGE_FAIL;
+	}
+
+	return MESH_STATUS_SUCCESS;
+
+}
+
+static int set_pub(struct mesh_model *mod, const uint8_t *mod_addr,
+			uint16_t idx, bool cred_flag, uint8_t ttl,
+			uint8_t period, uint8_t retransmit, bool b_virt,
+			uint16_t *dst)
+{
+	struct mesh_virtual *virt;
+	uint16_t grp;
+
+	if (dst) {
+		if (b_virt)
+			*dst = 0;
+		else
+			*dst = l_get_le16(mod_addr);
+	}
+
+	if (b_virt) {
+		if (!mesh_crypto_virtual_addr(mod_addr, &grp))
+			return MESH_STATUS_STORAGE_FAIL;
+	}
+
+	/* If old publication was Virtual, remove it */
+	if (mod->pub && mod->pub->addr >= VIRTUAL_BASE) {
+		virt = l_queue_find(mod->virtuals, find_virt_by_id,
+						L_UINT_TO_PTR(mod->pub->addr));
+		if (virt) {
+			l_queue_remove(mod->virtuals, virt);
+			unref_virt(virt);
+		}
+	}
+
+	if (b_virt) {
+		virt = l_queue_find(mesh_virtuals, find_virt_by_addr, mod_addr);
+		if (!virt) {
+			virt = l_new(struct mesh_virtual, 1);
+			virt->id = virt_id_next++;
+			virt->ota = grp;
+			memcpy(virt->addr, mod_addr, sizeof(virt->addr));
+			l_queue_push_head(mesh_virtuals, virt);
+		} else {
+			grp = virt->ota;
+		}
+		virt->ref_cnt++;
+		l_queue_push_head(mod->virtuals, virt);
+		mod->pub->addr = virt->id;
+	} else {
+		grp = l_get_le16(mod_addr);
+		mod->pub->addr = grp;
+	}
+
+	if (dst)
+		*dst = grp;
+
+	if (IS_UNASSIGNED(grp) && mod->pub) {
+		l_free(mod->pub);
+		mod->pub = NULL;
+		/* Remove publication if Pub Addr is 0x0000 */
+	} else {
+		if (!mod->pub)
+			mod->pub = l_new(struct mesh_model_pub, 1);
+		if (!mod->pub)
+			return MESH_STATUS_STORAGE_FAIL;
+
+		mod->pub->credential = cred_flag;
+		mod->pub->idx = idx;
+		mod->pub->ttl = ttl;
+		mod->pub->period = period;
+		mod->pub->retransmit = retransmit;
+	}
+
+	return MESH_STATUS_SUCCESS;
+}
+
+static int add_sub(struct mesh_net *net, struct mesh_model *mod,
+			const uint8_t *group, bool b_virt, uint16_t *dst)
+{
+	struct mesh_virtual *virt;
+	uint16_t grp;
+
+	if (b_virt) {
+		virt = l_queue_find(mesh_virtuals, find_virt_by_addr, group);
+		if (!virt) {
+			if (!mesh_crypto_virtual_addr(group, &grp))
+				return MESH_STATUS_STORAGE_FAIL;
+
+			virt = l_new(struct mesh_virtual, 1);
+			virt->id = virt_id_next++;
+			virt->ota = grp;
+			memcpy(virt->addr, group, sizeof(virt->addr));
+			if (!l_queue_push_head(mesh_virtuals, virt))
+				return MESH_STATUS_STORAGE_FAIL;
+		} else {
+			grp = virt->ota;
+		}
+		virt->ref_cnt++;
+		l_queue_push_head(mod->virtuals, virt);
+	} else {
+		grp = l_get_le16(group);
+	}
+
+	if (dst)
+		*dst = grp;
+
+	if (!mod->subs)
+		mod->subs = l_queue_new();
+	if (!mod->subs)
+		return MESH_STATUS_STORAGE_FAIL;
+
+	if (l_queue_find(mod->subs, simple_match, L_UINT_TO_PTR(grp)))
+		/* Group already exists */
+		return MESH_STATUS_SUCCESS;
+
+	l_queue_push_tail(mod->subs, L_UINT_TO_PTR(grp));
+
+	l_info("Added %4.4x", grp);
+	if (net)
+		mesh_net_dst_reg(net, grp);
+
+	return MESH_STATUS_SUCCESS;
+}
+
+bool mesh_model_rx(struct mesh_net *net, bool szmict, uint32_t seq0,
+			uint32_t seq, uint32_t iv_index, uint8_t ttl,
+			uint16_t src, uint16_t dst, uint8_t key_id,
+			const uint8_t *data, uint16_t size)
+{
+	uint8_t *clear_text;
+	struct mod_forward forward = {
+		.src = src,
+		.dst = dst,
+		.data = NULL,
+		.size = size - (szmict ? 8 : 4),
+		.ttl = ttl,
+		.virt = NULL,
+		.done = false,
+	};
+
+	struct mesh_node *node;
+	uint8_t num_ele;
+	int decrypt_idx, i, ele_idx;
+	uint16_t addr;
+	struct mesh_virtual *decrypt_virt = NULL;
+
+	l_debug("iv_index %8.8x key_id = %2.2x", iv_index, key_id);
+	if (!dst)
+		return false;
+
+	node = mesh_net_local_node_get(net);
+	if (!node)
+		return false;
+
+	ele_idx = node_get_element_idx(node, dst);
+
+	if (dst < 0x8000 && ele_idx < 0)
+		/* Unicast and not addressed to us */
+		return false;
+
+
+	clear_text = l_malloc(size);
+	if (!clear_text)
+		return false;
+
+	forward.data = clear_text;
+
+	/*
+	 * The packet needs to be decoded by the correct key which
+	 * is hinted by key_id, but is not necessarily definitive
+	 */
+	if (key_id == APP_ID_DEV || mesh_net_provisioner_mode_get(net))
+		decrypt_idx = dev_packet_decrypt(net, data, size, szmict, src,
+						dst, key_id, seq0, iv_index,
+						clear_text);
+	else if ((dst & 0xc000) == 0x8000)
+		decrypt_idx = virt_packet_decrypt(net, data, size, szmict, src,
+							dst, key_id, seq0,
+							iv_index, clear_text,
+							&decrypt_virt);
+	else
+		decrypt_idx = appkey_packet_decrypt(net, szmict, seq0,
+							iv_index, src, dst,
+							NULL, 0, key_id, data,
+							size, clear_text);
+
+	if (decrypt_idx < 0) {
+		l_error("model.c - Failed to decrypt application payload");
+		forward.done = false;
+		goto done;
+	}
+
+	/* print_packet("Clr Rx (pre-cache-check)", clear_text, size - 4); */
+
+	if (key_id != APP_ID_DEV) {
+		uint16_t crpl = mesh_net_get_crpl(net);
+
+		if (appkey_msg_in_replay_cache(net, (uint16_t) decrypt_idx, src,
+							crpl, seq, iv_index)) {
+			forward.done = true;
+			goto done;
+		}
+	}
+
+	print_packet("Clr Rx", clear_text, size - (szmict ? 8 : 4));
+
+	forward.virt = decrypt_virt;
+	forward.idx = decrypt_idx;
+	num_ele = node_get_num_elements(node);
+	addr = node_get_primary(node);
+
+	if (!num_ele || IS_UNASSIGNED(addr))
+		goto done;
+
+	for (i = 0; i < num_ele; i++) {
+		struct l_queue *models;
+
+		if (dst < 0x8000 && ele_idx != i)
+			continue;
+
+		forward.unicast = addr + i;
+		models = node_get_element_models(node, i, NULL);
+		l_queue_foreach(models, forward_model, &forward);
+
+		if (dst < 0x8000 && ele_idx == i)
+			break;
+	}
+done:
+	l_free(clear_text);
+	return forward.done;
+}
+
+unsigned int mesh_model_send(struct mesh_net *net, uint32_t mod_id,
+				uint16_t src, uint32_t target,
+				uint16_t app_idx, uint8_t ttl,
+				const void *msg, uint16_t msg_len)
+{
+	struct mesh_model *mod;
+	uint8_t *aad = NULL;
+	uint16_t dst;
+	uint8_t key_id;
+	const uint8_t *key;
+
+	/* print_packet("Mod Tx", msg, msg_len); */
+
+	if (!net || msg_len > 380)
+		return 0;
+
+	/* If SRC is 0, use the Primary Element */
+	if (src == 0)
+		src = mesh_net_get_address(net);
+
+	mod = find_model(net, src, mod_id, NULL);
+	if (!mod) {
+		l_info("model %x not found", mod_id);
+		return 0;
+	}
+
+	gettimeofday(&tx_start, NULL);
+
+	if (target == USE_PUB_VALUE) {
+		target = mod->pub->addr;
+		app_idx = mod->pub->idx;
+	}
+
+	if (IS_UNASSIGNED(target))
+		return 0;
+
+	if (target >= VIRTUAL_BASE) {
+		struct mesh_virtual *virt = l_queue_find(mesh_virtuals,
+				find_virt_by_id,
+				L_UINT_TO_PTR(target));
+
+		if (!virt)
+			return 0;
+
+		aad = virt->addr;
+		dst = virt->ota;
+	} else
+		dst = target;
+
+	l_debug("dst=%x", dst);
+	if (app_idx == APP_IDX_DEV && mesh_net_provisioner_mode_get(net)) {
+		key = node_get_device_key(mesh_net_local_node_get(net));
+	} else if (app_idx == APP_IDX_DEV) {
+		key = node_get_device_key(mesh_net_local_node_get(net));
+		if (!key)
+			return 0;
+
+		l_debug("(%x)", app_idx);
+		key_id = APP_ID_DEV;
+	} else {
+		key = appkey_get_key(net, app_idx, &key_id);
+		if (!key) {
+			l_debug("no app key for (%x)", app_idx);
+			return 0;
+		}
+
+		l_debug("(%x) %p", app_idx, key);
+		l_debug("key_id %x", key_id);
+	}
+
+	return msg_send(net, mod_id, src, dst, key_id, key, aad, ttl,
+			msg, msg_len);
+
+}
+
+int mesh_model_pub_set(struct mesh_net *net, uint16_t addr, uint32_t id,
+			const uint8_t *mod_addr, uint16_t idx, bool cred_flag,
+			uint8_t ttl, uint8_t period, uint8_t retransmit,
+			bool b_virt, uint16_t *dst)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	int ele_idx = -1;
+	struct mesh_model *mod;
+	struct mesh_node *node;
+
+	node = mesh_net_local_node_get(net);
+	if (node)
+		ele_idx = node_get_element_idx(node, addr);
+
+	if (!node || ele_idx < 0) {
+		fail = MESH_STATUS_INVALID_ADDRESS;
+		return false;
+	}
+
+	mod = node_get_model(node, (uint8_t) ele_idx, id, &fail);
+	if (!mod)
+		return fail;
+
+	if (id == CONFIG_SRV_MODEL || id == CONFIG_CLI_MODEL)
+		return MESH_STATUS_INVALID_PUB_PARAM;
+
+	if (!appkey_have_key(net, idx))
+		return MESH_STATUS_INVALID_APPKEY;
+
+	return set_pub(mod, mod_addr, idx, cred_flag, ttl, period, retransmit,
+								b_virt, dst);
+	/*
+	 * TODO: Add standardized Publication Change notification to model
+	 * definition
+	 */
+}
+
+struct mesh_model_pub *mesh_model_pub_get(struct mesh_net *net, uint8_t ele_idx,
+						uint32_t mod_id, int *status)
+{
+	struct mesh_model *mod;
+	struct mesh_node *node = mesh_net_local_node_get(net);
+
+	if (!node) {
+		*status = MESH_STATUS_INVALID_ADDRESS;
+		return NULL;
+	}
+
+	mod = node_get_model(node, ele_idx, mod_id, status);
+	if (!mod)
+		return NULL;
+
+	return mod->pub;
+}
+
+uint32_t mesh_model_get_model_id(const struct mesh_model *model)
+{
+	if (!model)
+		return 0xffffffff; /* TODO: use define */
+	return model->id;
+}
+
+void mesh_model_free(void *data)
+{
+	struct mesh_model *mod = data;
+
+	l_queue_destroy(mod->bindings, NULL);
+	l_queue_destroy(mod->subs, NULL);
+	l_queue_destroy(mod->virtuals, unref_virt);
+	l_free(mod->pub);
+	l_free(mod);
+}
+
+struct mesh_model *mesh_model_new(uint8_t ele_idx, uint32_t id, bool vendor)
+{
+	struct mesh_model *mod = l_new(struct mesh_model, 1);
+
+	if (!mod)
+		return NULL;
+
+	if (vendor)
+		id |= VENDOR_ID_MASK;
+
+	mod->id = id;
+	mod->ele_idx = ele_idx;
+	mod->virtuals = l_queue_new();
+	if (!mod->virtuals) {
+		l_free(mod);
+		return NULL;
+	}
+	return mod;
+}
+
+static void restore_model_state(void *data)
+{
+	struct mesh_model *mod = data;
+	const struct mesh_model_ops *cbs;
+	const struct l_queue_entry *b;
+
+	cbs = mod->cbs;
+
+	if (l_queue_isempty(mod->bindings) || !mod->cbs->bind) {
+		for (b = l_queue_get_entries(mod->bindings); b; b = b->next) {
+			if (cbs->bind(L_PTR_TO_UINT(b->data), ACTION_ADD) !=
+				MESH_STATUS_SUCCESS)
+				break;
+		}
+	}
+
+	if (mod->pub && cbs->pub)
+		cbs->pub(mod->pub);
+}
+
+bool mesh_model_vendor_register(struct mesh_net *net, uint8_t ele_idx,
+					uint32_t mod_id,
+					const struct mesh_model_ops *cbs,
+					void *user_data)
+{
+	struct mesh_model *mod;
+	struct mesh_node *node;
+
+	node = mesh_net_local_node_get(net);
+	if (!node)
+		return false;
+
+	mod = node_get_model(node, ele_idx, mod_id, NULL);
+	if (!mod)
+		return false;
+
+	mod->cbs = cbs;
+	mod->user_data = user_data;
+
+	l_idle_oneshot(restore_model_state, mod, NULL);
+
+	return true;
+}
+
+bool mesh_model_register(struct mesh_net *net, uint8_t ele_idx,
+					uint32_t mod_id,
+					const struct mesh_model_ops *cbs,
+					void *user_data)
+{
+	uint32_t id = VENDOR_ID_MASK | mod_id;
+
+	return mesh_model_vendor_register(net, ele_idx, id, cbs, user_data);
+}
+
+void mesh_model_app_key_delete(struct mesh_net *net, struct l_queue *models,
+							uint16_t app_idx)
+{
+	l_queue_foreach(models, model_unbind_idx, L_UINT_TO_PTR(app_idx));
+}
+
+int mesh_model_binding_del(struct mesh_net *net, uint16_t addr, uint32_t id,
+						uint16_t app_idx)
+{
+	l_debug("0x%x, 0x%x, %d", addr, id, app_idx);
+	return update_binding(net, addr, id, app_idx, true);
+}
+
+int mesh_model_binding_add(struct mesh_net *net, uint16_t addr, uint32_t id,
+						uint16_t app_idx)
+{
+	l_debug("0x%x, 0x%x, %d", addr, id, app_idx);
+	return update_binding(net, addr, id, app_idx, false);
+}
+
+int mesh_model_get_bindings(struct mesh_net *net, uint16_t addr, uint32_t id,
+				uint8_t *buf, uint16_t buf_size, uint16_t *size)
+{
+	int fail;
+	struct mesh_model *mod;
+	const struct l_queue_entry *entry;
+	uint16_t n;
+	uint32_t idx_pair;
+	int i;
+
+	mod = find_model(net, addr, id, &fail);
+
+	if (!mod) {
+		*size = 0;
+		return fail;
+	}
+
+	entry = l_queue_get_entries(mod->bindings);
+	n = 0;
+	i = 0;
+	idx_pair = 0;
+
+	for (; entry; entry = entry->next) {
+		uint16_t app_idx = (uint16_t) (L_PTR_TO_UINT(entry->data));
+
+		if (!(i & 0x1)) {
+			idx_pair = app_idx;
+		} else {
+			idx_pair <<= 12;
+			idx_pair += app_idx;
+			/* Unlikely, but check for overflow*/
+			if ((n + 3) > buf_size) {
+				l_warn("Binding list too large");
+				goto done;
+			}
+			l_put_le32(idx_pair, buf);
+			buf += 3;
+			n += 3;
+		}
+		i++;
+	}
+
+	/* Process the last app key if present */
+	if (i & 0x1 && ((n + 2) <= buf_size)) {
+		l_put_le16(idx_pair, buf);
+		n += 2;
+	}
+
+done:
+	*size = n;
+
+	return MESH_STATUS_SUCCESS;
+}
+
+int mesh_model_sub_get(struct mesh_net *net, uint16_t addr, uint32_t id,
+			uint8_t *buf, uint16_t buf_size, uint16_t *size)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	int16_t n;
+	struct mesh_model *mod;
+	const struct l_queue_entry *entry;
+
+	mod = find_model(net, addr, id, &fail);
+	if (!mod)
+		return fail;
+
+	entry = l_queue_get_entries(mod->subs);
+	*size = 0;
+	n = 0;
+
+	for (; entry; entry = entry->next) {
+		if ((n + 2) > buf_size)
+			return MESH_STATUS_UNSPECIFIED_ERROR;
+
+		l_put_le16((uint16_t) L_PTR_TO_UINT(entry->data), buf);
+		buf += 2;
+		n += 2;
+	}
+
+	*size = n;
+	return MESH_STATUS_SUCCESS;
+}
+
+int mesh_model_sub_add(struct mesh_net *net, uint16_t addr, uint32_t id,
+			const uint8_t *group, bool b_virt, uint16_t *dst)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	int ele_idx = -1;
+	struct mesh_model *mod;
+	struct mesh_node *node;
+
+	node = mesh_net_local_node_get(net);
+	if (node)
+		ele_idx = node_get_element_idx(node, addr);
+
+	if (!node || ele_idx < 0) {
+		fail = MESH_STATUS_INVALID_ADDRESS;
+		return false;
+	}
+
+	mod = node_get_model(node, (uint8_t) ele_idx, id, &fail);
+	if (!mod)
+		return fail;
+
+	return add_sub(net, mod, group, b_virt, dst);
+	/* TODO: communicate to registered models that sub has changed */
+}
+
+int mesh_model_sub_ovr(struct mesh_net *net, uint16_t addr, uint32_t id,
+			const uint8_t *group, bool b_virt, uint16_t *dst)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	struct l_queue *virtuals, *subs;
+	struct mesh_virtual *virt;
+	struct mesh_model *mod;
+
+	mod = find_model(net, addr, id, &fail);
+	if (!mod)
+		return fail;
+
+	subs = mod->subs;
+	virtuals = mod->virtuals;
+	mod->subs = l_queue_new();
+	mod->virtuals = l_queue_new();
+
+	if (!mod->subs || !mod->virtuals)
+		return MESH_STATUS_INSUFF_RESOURCES;
+
+	/*
+	 * When overwriting the Subscription List,
+	 * make sure any virtual Publication address is preserved
+	 */
+	if (mod->pub && mod->pub->addr >= VIRTUAL_BASE) {
+		virt = l_queue_find(virtuals, find_virt_by_id,
+				L_UINT_TO_PTR(mod->pub->addr));
+		if (virt) {
+			virt->ref_cnt++;
+			l_queue_push_head(mod->virtuals, virt);
+		}
+	}
+
+	fail = mesh_model_sub_add(net, addr, id, group, b_virt, dst);
+
+	if (fail) {
+		/* Adding new group failed, so revert to old list */
+		l_queue_destroy(mod->subs, NULL);
+		mod->subs = subs;
+		l_queue_destroy(mod->virtuals, unref_virt);
+		mod->virtuals = virtuals;
+	} else {
+		const struct l_queue_entry *entry;
+
+		entry = l_queue_get_entries(subs);
+		for (; entry; entry = entry->next)
+			mesh_net_dst_unreg(net,
+					(uint16_t) L_PTR_TO_UINT(entry->data));
+
+		l_queue_destroy(subs, NULL);
+		l_queue_destroy(virtuals, unref_virt);
+	}
+
+	return fail;
+}
+
+int mesh_model_sub_del(struct mesh_net *net, uint16_t addr, uint32_t id,
+			const uint8_t *group, bool b_virt, uint16_t *dst)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	uint16_t grp;
+	struct mesh_model *mod;
+
+	mod = find_model(net, addr, id, &fail);
+	if (!mod)
+		return fail;
+
+	if (b_virt) {
+		struct mesh_virtual *virt;
+
+		virt = l_queue_find(mod->virtuals, find_virt_by_addr, group);
+		if (virt) {
+			l_queue_remove(mod->virtuals, virt);
+			grp = virt->ota;
+			unref_virt(virt);
+		} else {
+			if (!mesh_crypto_virtual_addr(group, &grp))
+				return MESH_STATUS_STORAGE_FAIL;
+		}
+	} else {
+		grp = l_get_le16(group);
+	}
+
+	*dst = grp;
+
+	if (l_queue_remove(mod->subs, L_UINT_TO_PTR(grp)))
+		mesh_net_dst_unreg(net, grp);
+
+	return MESH_STATUS_SUCCESS;
+}
+
+int mesh_model_sub_del_all(struct mesh_net *net, uint16_t addr, uint32_t id)
+{
+	int fail = MESH_STATUS_SUCCESS;
+	struct mesh_model *mod;
+	const struct l_queue_entry *entry;
+
+	mod = find_model(net, addr, id, &fail);
+	if (!mod)
+		return fail;
+
+	entry = l_queue_get_entries(mod->subs);
+	for (; entry; entry = entry->next)
+		mesh_net_dst_unreg(net, (uint16_t) L_PTR_TO_UINT(entry->data));
+
+	l_queue_destroy(mod->subs, NULL);
+	l_queue_destroy(mod->virtuals, unref_virt);
+	mod->virtuals = l_queue_new();
+
+	return fail;
+}
+
+struct mesh_model *mesh_model_init(struct mesh_net *net, uint8_t ele_idx,
+						struct mesh_db_model *db_mod)
+{
+	struct mesh_model *mod;
+	uint32_t i;
+
+	mod = mesh_model_new(ele_idx, db_mod->id, db_mod->vendor);
+	if (!mod)
+		return NULL;
+
+	/* Implicitly bind config server model to device key */
+	if (db_mod->id == CONFIG_SRV_MODEL) {
+
+		if (ele_idx != PRIMARY_ELE_IDX)
+			return NULL;
+
+		l_queue_push_head(mod->bindings, L_UINT_TO_PTR(APP_IDX_DEV));
+		return mod;
+	}
+
+	if (db_mod->id == CONFIG_CLI_MODEL) {
+		l_queue_push_head(mod->bindings, L_UINT_TO_PTR(APP_IDX_DEV));
+		return mod;
+	}
+
+	/* Add application key bindings if present */
+	if (db_mod->bindings) {
+		mod->bindings = l_queue_new();
+
+		if (!mod->bindings) {
+			mesh_model_free(mod);
+			return NULL;
+		}
+
+		for (i = 0; i < db_mod->num_bindings; i++) {
+			if (!model_bind_idx(mod, db_mod->bindings[i])) {
+				mesh_model_free(mod);
+				return NULL;
+			}
+		}
+	}
+
+	/* Add publication if present */
+	if (db_mod->pub) {
+		uint16_t mod_addr;
+		uint8_t *dst;
+
+		l_put_le16(db_mod->pub->addr, &mod_addr);
+		dst = db_mod->pub->virt ? db_mod->pub->virt_addr :
+							(uint8_t *) &mod_addr;
+
+		if (set_pub(mod, dst, db_mod->pub->idx, db_mod->pub->credential,
+			db_mod->pub->ttl, db_mod->pub->period,
+			db_mod->pub->retransmit, db_mod->pub->virt, NULL) !=
+							MESH_STATUS_SUCCESS) {
+			mesh_model_free(mod);
+			return NULL;
+		}
+	}
+
+	/* Add subscriptions if present */
+	if (!db_mod->subs)
+		return mod;
+
+	for (i = 0; i < db_mod->num_subs; i++) {
+		uint16_t group;
+		uint8_t *src;
+
+		/*
+		 * To keep calculations for virtual label coherent,
+		 * convert to little endian.
+		 */
+		l_put_le16(db_mod->subs[i].src.addr, &group);
+		src = db_mod->subs[i].virt ? db_mod->subs[i].src.virt_addr :
+			(uint8_t *) &group;
+
+		if (add_sub(net, mod, src, db_mod->subs[i].virt, NULL) !=
+							MESH_STATUS_SUCCESS) {
+			mesh_model_free(mod);
+			return NULL;
+		}
+	}
+
+	return mod;
+}
+
+uint16_t mesh_model_opcode_set(uint32_t opcode, uint8_t *buf)
+{
+	if (opcode <= 0x7e) {
+		buf[0] = opcode;
+		return 1;
+	}
+
+	if (opcode >= 0x8000 && opcode <= 0xbfff) {
+		l_put_be16(opcode, buf);
+		return 2;
+	}
+
+	if (opcode >= 0xc00000 && opcode <= 0xffffff) {
+		buf[0] = (opcode >> 16) & 0xff;
+		l_put_be16(opcode, buf + 1);
+		return 3;
+	}
+
+	l_info("Illegal Opcode %x", opcode);
+	return 0;
+}
+
+bool mesh_model_opcode_get(const uint8_t *buf, uint16_t size,
+					uint32_t *opcode, uint16_t *n)
+{
+	if (!n || !opcode || size < 1)
+		return false;
+
+	switch (buf[0] & 0xc0) {
+	case 0x00:
+	case 0x40:
+		/* RFU */
+		if (buf[0] == 0x7f)
+			return false;
+
+		*n = 1;
+		*opcode = buf[0];
+		break;
+
+	case 0x80:
+		if (size < 2)
+			return false;
+
+		*n = 2;
+		*opcode = l_get_be16(buf);
+		break;
+
+	case 0xc0:
+		if (size < 3)
+			return false;
+
+		*n = 3;
+		*opcode = l_get_be16(buf + 1);
+		*opcode |= buf[0] << 16;
+		break;
+
+	default:
+		print_packet("Bad", buf, size);
+		return false;
+	}
+
+	return true;
+}
+
+void mesh_model_add_virtual(struct mesh_net *net, const uint8_t *v)
+{
+	struct mesh_virtual *virt = l_queue_find(mesh_virtuals,
+						find_virt_by_addr, v);
+
+	if (virt) {
+		virt->ref_cnt++;
+		return;
+	}
+
+	virt = l_new(struct mesh_virtual, 1);
+	if (!virt)
+		return;
+
+	if (!mesh_crypto_virtual_addr(v, &virt->ota)) {
+		l_free(virt);
+		return; /* Storage Failure */
+	}
+
+	memcpy(virt->addr, v, 16);
+	virt->ref_cnt++;
+	virt->id = virt_id_next++;
+	l_queue_push_head(mesh_virtuals, virt);
+}
+
+void mesh_model_del_virtual(struct mesh_net *net, uint32_t va24)
+{
+	struct mesh_virtual *virt = l_queue_remove_if(mesh_virtuals,
+						find_virt_by_id,
+						L_UINT_TO_PTR(va24));
+
+	if (virt)
+		unref_virt(virt);
+}
Signature · 1 line
2.14.3
author
#6 lore raw

PATCH v2 8/11 meshd: Mesh config server model

In reply to Brian Gix

From: Inga Stotland <[email protected]>

---
 meshd/src/cfgmod-server.c | 1194 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 1194 insertions(+)
 create mode 100644 meshd/src/cfgmod-server.c
meshd/src/cfgmod-server.c new file +1194 -0
new file mode 100644
index 000000000..de7c6fcff
@@ -0,0 +1,1194 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/time.h>
+#include <ell/ell.h>
+
+#include "meshd/common/mesh-defs.h"
+
+#include "meshd/src/mesh.h"
+#include "meshd/src/node.h"
+#include "meshd/src/net.h"
+#include "meshd/src/appkey.h"
+#include "meshd/src/model.h"
+#include "meshd/src/storage.h"
+
+#include "meshd/src/cfgmod.h"
+
+#define CFG_MAX_MSG_LEN 380
+
+static void send_pub_status(struct mesh_net *net, uint16_t src, uint16_t dst,
+			uint8_t status, uint16_t ele_addr, uint16_t pub_addr,
+			uint32_t mod_id, uint16_t idx, bool cred_flag,
+			uint8_t ttl, uint8_t period, uint8_t retransmit)
+{
+	uint8_t msg[16];
+	size_t n;
+
+	n = mesh_model_opcode_set(OP_CONFIG_MODEL_PUB_STATUS, msg);
+	msg[n++] = status;
+	l_put_le16(ele_addr, msg + n);
+	n += 2;
+	l_put_le16(pub_addr, msg + n);
+	n += 2;
+	idx |= cred_flag ? CREDFLAG_MASK : 0;
+	l_put_le16(idx, msg + n);
+	n += 2;
+	msg[n++] = ttl;
+	msg[n++] = period;
+	msg[n++] = retransmit;
+	if (mod_id < 0x10000) {
+		l_put_le16(mod_id, msg + n);
+		n += 2;
+	} else {
+		l_put_le16(mod_id >> 16, msg + n);
+		n += 2;
+		l_put_le16(mod_id, msg + n);
+		n += 2;
+	}
+
+	mesh_model_send(net, CONFIG_SRV_MODEL,
+			dst, src,
+			APP_IDX_DEV, DEFAULT_TTL, msg, n);
+}
+
+static bool config_pub_get(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size)
+{
+	uint32_t mod_id;
+	uint16_t ele_addr;
+	int ele_idx;
+	struct mesh_model_pub *pub;
+	int status;
+
+	if (size == 4)
+		mod_id = l_get_le16(pkt + 2);
+	else if (size == 6) {
+		mod_id = l_get_le16(pkt + 2) << 16;
+		mod_id |= l_get_le16(pkt + 4);
+	} else
+		return false;
+
+	ele_addr = l_get_le16(pkt);
+	ele_idx = node_get_element_idx(mesh_net_local_node_get(net), ele_addr);
+
+	if (ele_idx >= 0)
+		pub = mesh_model_pub_get(net, ele_idx, mod_id, &status);
+	else
+		status = MESH_STATUS_INVALID_ADDRESS;
+
+	if (pub && status == MESH_STATUS_SUCCESS)
+		send_pub_status(net, src, dst, status, ele_addr, pub->addr,
+				mod_id, pub->idx, pub->credential, pub->ttl,
+						pub->period, pub->retransmit);
+	else
+		send_pub_status(net, src, dst, status, ele_addr, 0, mod_id,
+								0, 0, 0, 0, 0);
+	return true;
+}
+
+static bool config_pub_set(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size,
+					bool unreliable)
+{
+	uint32_t mod_id;
+	uint16_t ele_addr, idx, ota = 0;
+	const uint8_t *pub_addr;
+	uint16_t test_addr;
+	uint8_t ttl, period;
+	uint8_t retransmit;
+	int status;
+	bool cred_flag, b_virt = false;
+
+	switch (size) {
+	default:
+		return false;
+
+	case 11:
+		idx = l_get_le16(pkt + 4);
+		ttl = pkt[6];
+		period = pkt[7];
+		retransmit = pkt[8];
+		mod_id = l_get_le16(pkt + 9);
+		break;
+
+	case 13:
+		idx = l_get_le16(pkt + 4);
+		ttl = pkt[6];
+		period = pkt[7];
+		retransmit = pkt[8];
+		mod_id = l_get_le16(pkt + 9) << 16;
+		mod_id |= l_get_le16(pkt + 11);
+		break;
+
+	case 25:
+		b_virt = true;
+		idx = l_get_le16(pkt + 18);
+		ttl = pkt[20];
+		period = pkt[21];
+		retransmit = pkt[22];
+		mod_id = l_get_le16(pkt + 23);
+		break;
+
+	case 27:
+		b_virt = true;
+		idx = l_get_le16(pkt + 18);
+		ttl = pkt[20];
+		period = pkt[21];
+		retransmit = pkt[22];
+		mod_id = l_get_le16(pkt + 23) << 16;
+		mod_id |= l_get_le16(pkt + 25);
+		break;
+	}
+	ele_addr = l_get_le16(pkt);
+	pub_addr = pkt + 2;
+
+	/* Doesn't accept out-of-range TTLs */
+	if (ttl > TTL_MASK && ttl != DEFAULT_TTL)
+		return false;
+
+	/* Get cred_flag */
+	cred_flag = !!(CREDFLAG_MASK & idx);
+
+	/* Ignore non-IDX bits */
+	idx &= APP_IDX_MASK;
+
+	/* Doesn't accept virtual seeming addresses */
+	test_addr = l_get_le16(pub_addr);
+	if (!b_virt && test_addr > 0x7fff && test_addr < 0xc000)
+		return false;
+
+	status = mesh_model_pub_set(net, ele_addr, mod_id, pub_addr, idx,
+					cred_flag, ttl, period, retransmit,
+					b_virt, &ota);
+
+	l_info("pub_set: status %d, ea %4.4x, ota: %4.4x, mod: %x, idx: %3.3x",
+					status, ele_addr, ota, mod_id, idx);
+
+	if (IS_UNASSIGNED(ota) && !b_virt)
+		ttl = period = idx = 0;
+
+	if (status >= 0 && !unreliable)
+		send_pub_status(net, src, dst, status, ele_addr, ota,
+				mod_id, idx, cred_flag, ttl, period,
+				retransmit);
+	return true;
+}
+
+static void send_sub_status(struct mesh_net *net, uint16_t src, uint16_t dst,
+					uint8_t status, uint16_t ele_addr,
+					uint16_t addr, uint32_t mod)
+{
+	uint8_t msg[12];
+	int n = mesh_model_opcode_set(OP_CONFIG_MODEL_SUB_STATUS, msg);
+
+	msg[n++] = status;
+	l_put_le16(ele_addr, msg + n);
+	n += 2;
+	l_put_le16(addr, msg + n);
+	n += 2;
+	if (mod >= 0x10000) {
+		l_put_le16(mod >> 16, msg + n);
+		l_put_le16(mod, msg + n + 2);
+		n += 4;
+	} else {
+		l_put_le16(mod, msg + n);
+		n += 2;
+	}
+
+	mesh_model_send(net, CONFIG_SRV_MODEL, dst, src, APP_IDX_DEV,
+							DEFAULT_TTL, msg, n);
+}
+
+static bool config_sub_get(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size)
+{
+	uint16_t ele_addr;
+	uint32_t mod_id;
+	uint16_t n = 0;
+	int ret = 0;
+	uint8_t *status;
+	uint16_t buf_size;
+	uint8_t msg[5 + sizeof(uint16_t) * MAX_GRP_PER_MOD];
+
+	/* Incoming message has already been size-checked */
+	ele_addr = l_get_le16(pkt);
+
+	switch (size) {
+	default:
+		l_debug("Bad Len Cfg_Pub_Set: %d", size);
+		return false;
+
+	case 4:
+		mod_id = l_get_le16(pkt + 2);
+		n = mesh_model_opcode_set(OP_CONFIG_MODEL_SUB_LIST, msg);
+		status = msg + n;
+		msg[n++] = 0;
+		l_put_le16(ele_addr, msg + n);
+		n += 2;
+		l_put_le16(mod_id, msg + n);
+		n += 2;
+		break;
+
+	case 6:
+		mod_id = l_get_le16(pkt + 2) << 16;
+		mod_id |= l_get_le16(pkt + 4);
+		n = mesh_model_opcode_set(OP_CONFIG_VEND_MODEL_SUB_LIST, msg);
+		status = msg + n;
+		msg[n++] = 0;
+		l_put_le16(ele_addr, msg + n);
+		n += 2;
+		l_put_le16(mod_id >> 16, msg + n);
+		n += 2;
+		l_put_le16(mod_id, msg + n);
+		n += 2;
+		break;
+	}
+
+	buf_size = sizeof(uint16_t) * MAX_GRP_PER_MOD;
+	ret = mesh_model_sub_get(net, ele_addr, mod_id, msg + n, buf_size,
+									&size);
+
+	if (!ret)
+		n += size;
+	else if (ret > 0)
+		*status = ret;
+
+	mesh_model_send(net, CONFIG_SRV_MODEL,
+			dst, src, APP_IDX_DEV,
+			DEFAULT_TTL, msg, n);
+	return true;
+}
+
+static void config_sub_set(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size,
+					bool virt, uint32_t opcode)
+{
+	uint16_t grp, ele_addr;
+	bool unreliable = !!(opcode & OP_UNRELIABLE);
+	uint32_t mod_id, func;
+	const uint8_t *addr = NULL;
+	int status = 0;
+
+	switch (size) {
+	default:
+		l_error("Bad Len Cfg_Sub_Set: %d", size);
+		return;
+	case 4:
+		if (opcode != OP_CONFIG_MODEL_SUB_DELETE_ALL)
+			return;
+		mod_id = l_get_le16(pkt + 2);
+		break;
+	case 6:
+		if (virt)
+			return;
+		if (opcode != OP_CONFIG_MODEL_SUB_DELETE_ALL)
+			mod_id = l_get_le16(pkt + 4);
+		else {
+			mod_id = l_get_le16(pkt + 2) << 16;
+			mod_id |= l_get_le16(pkt + 4);
+		}
+		break;
+	case 8:
+		if (virt)
+			return;
+		mod_id = l_get_le16(pkt + 4) << 16;
+		mod_id |= l_get_le16(pkt + 6);
+		break;
+	case 20:
+		if (!virt)
+			return;
+		mod_id = l_get_le16(pkt + 18);
+		break;
+	case 22:
+		if (!virt)
+			return;
+		mod_id = l_get_le16(pkt + 18) << 16;
+		mod_id |= l_get_le16(pkt + 20);
+		break;
+	}
+	ele_addr = l_get_le16(pkt);
+
+	if (opcode != OP_CONFIG_MODEL_SUB_DELETE_ALL) {
+		addr = pkt + 2;
+		grp = l_get_le16(addr);
+	} else
+		grp = UNASSIGNED_ADDRESS;
+
+	func = opcode & ~OP_UNRELIABLE;
+	switch (func) {
+	default:
+		l_info("Bad opcode: %x", func);
+		return;
+
+	case OP_CONFIG_MODEL_SUB_DELETE_ALL:
+		status = mesh_model_sub_del_all(net, ele_addr, mod_id);
+		break;
+
+	case OP_CONFIG_MODEL_SUB_VIRT_OVERWRITE:
+		grp = UNASSIGNED_ADDRESS;
+		/* Fall Through */
+	case OP_CONFIG_MODEL_SUB_OVERWRITE:
+		status = mesh_model_sub_ovr(net, ele_addr, mod_id,
+							addr, virt, &grp);
+		break;
+	case OP_CONFIG_MODEL_SUB_VIRT_ADD:
+		grp = UNASSIGNED_ADDRESS;
+		/* Fall Through */
+	case OP_CONFIG_MODEL_SUB_ADD:
+		status = mesh_model_sub_add(net, ele_addr, mod_id,
+							addr, virt, &grp);
+		break;
+	case OP_CONFIG_MODEL_SUB_VIRT_DELETE:
+		grp = UNASSIGNED_ADDRESS;
+		/* Fall Through */
+	case OP_CONFIG_MODEL_SUB_DELETE:
+		status = mesh_model_sub_del(net, ele_addr, mod_id,
+							addr, virt, &grp);
+		break;
+	}
+
+	if (!unreliable && status >= 0)
+		send_sub_status(net, src, dst, status, ele_addr, grp, mod_id);
+
+}
+
+static void send_model_app_status(struct mesh_net *net, uint16_t src,
+					uint16_t dst, uint8_t status,
+					uint16_t addr, uint32_t id,
+					uint16_t idx)
+{
+	uint8_t msg[12];
+	size_t n = mesh_model_opcode_set(OP_MODEL_APP_STATUS, msg);
+
+	msg[n++] = status;
+	l_put_le16(addr, msg + n);
+	n += 2;
+	l_put_le16(idx, msg + n);
+	n += 2;
+	if (id > 0xffff) {
+		l_put_le16(id >> 16, msg + n);
+		n += 2;
+	}
+	l_put_le16(id, msg + n);
+	n += 2;
+
+	mesh_model_send(net, CONFIG_SRV_MODEL, dst, src, APP_IDX_DEV,
+				DEFAULT_TTL, msg, n);
+}
+
+static void model_app_list(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size)
+{
+	uint16_t ele_addr;
+	uint32_t mod_id = 0xffff;
+	uint8_t *msg = NULL;
+	uint8_t *status;
+	uint16_t n, buf_size;
+	int result;
+
+	buf_size = MAX_BINDINGS * sizeof(uint16_t);
+	msg = l_malloc(7 + buf_size);
+	if (!msg)
+		return;
+
+	ele_addr = l_get_le16(pkt);
+
+	switch (size) {
+	default:
+		l_free(msg);
+		return;
+	case 4:
+		n = mesh_model_opcode_set(OP_MODEL_APP_LIST, msg);
+		status = msg + n;
+		mod_id = l_get_le16(pkt + 2);
+		l_put_le16(ele_addr, msg + 1 + n);
+		l_put_le16(mod_id, msg + 3 + n);
+		n += 5;
+		break;
+	case 6:
+		n = mesh_model_opcode_set(OP_VEND_MODEL_APP_LIST, msg);
+		status = msg + n;
+		mod_id = l_get_le16(pkt + 2) << 16;
+		mod_id |= l_get_le16(pkt + 4);
+
+		l_put_le16(ele_addr, msg + 1 + n);
+		l_put_le16(mod_id >> 16, msg + 3 + n);
+		l_put_le16(mod_id, msg + 5 + n);
+		n += 7;
+		break;
+	}
+
+
+	result = mesh_model_get_bindings(net, ele_addr, mod_id, msg + n,
+							buf_size, &size);
+	n += size;
+
+	if (result >= 0) {
+		*status = result;
+		mesh_model_send(net, CONFIG_SRV_MODEL, dst, src, APP_IDX_DEV,
+					DEFAULT_TTL, msg, n);
+	}
+
+	l_free(msg);
+}
+
+static bool model_app_bind(struct mesh_net *net, uint16_t src, uint16_t dst,
+					const uint8_t *pkt, uint16_t size,
+					bool unbind)
+{
+	uint16_t ele_addr;
+	uint32_t mod_id;
+	uint16_t idx;
+	int result;
+
+	switch (size) {
+	default:
+		return false;
+
+	case 6:
+		mod_id = l_get_le16(pkt + 4);
+		break;
+	case 8:
+		mod_id = l_get_le16(pkt + 4) << 16;
+		mod_id |= l_get_le16(pkt + 6);
+		break;
+	}
+
+	ele_addr = l_get_le16(pkt);
+	idx = l_get_le16(pkt + 2);
+
+	if (idx > 0xfff)
+		return false;
+
+	if (unbind)
+		result = mesh_model_binding_del(net, ele_addr, mod_id, idx);
+	else
+		result = mesh_model_binding_add(net, ele_addr, mod_id, idx);
+
+	send_model_app_status(net, src, dst, result, ele_addr, mod_id, idx);
+
+	return true;
+}
+
+static void hb_pub_timeout_func(struct l_timeout *timeout, void *user_data)
+{
+	struct mesh_net *net = user_data;
+	struct mesh_net_heartbeat *hb = mesh_net_heartbeat_get(net);
+
+	mesh_net_heartbeat_send(net);
+
+	if (hb->pub_count != 0xffff)
+		hb->pub_count--;
+	if (hb->pub_count > 0)
+		l_timeout_modify(hb->pub_timer, hb->pub_period);
+	else {
+		l_timeout_remove(hb->pub_timer);
+		hb->pub_timer = NULL;
+	}
+	l_debug("%d left", hb->pub_count);
+}
+
+static void update_hb_pub_timer(struct mesh_net *net,
+						struct mesh_net_heartbeat *hb)
+{
+	if (IS_UNASSIGNED(hb->pub_dst) || hb->pub_count == 0) {
+		l_timeout_remove(hb->pub_timer);
+		hb->pub_timer = NULL;
+		return;
+	}
+
+	if (!hb->pub_timer)
+		hb->pub_timer = l_timeout_create(hb->pub_period,
+					hb_pub_timeout_func, net, NULL);
+	else
+		l_timeout_modify(hb->pub_timer, hb->pub_period);
+}
+
+static void hb_sub_timeout_func(struct l_timeout *timeout, void *user_data)
+{
+	struct mesh_net *net = user_data;
+	struct mesh_net_heartbeat *hb = mesh_net_heartbeat_get(net);
+
+	l_info("HB Subscription Ended");
+	l_timeout_remove(hb->sub_timer);
+	hb->sub_timer = NULL;
+	hb->sub_enabled = false;
+}
+
+static uint8_t uint32_to_log(uint32_t value)
+{
+	uint32_t val = 1;
+	uint8_t ret = 1;
+
+	if (!value)
+		return 0;
+	else if (value > 0x10000)
+		return 0xff;
+
+	while (val < value) {
+		val <<= 1;
+		ret++;
+	}
+
+	return ret;
+}
+
+static uint32_t log_to_uint32(uint8_t log, uint8_t offset)
+{
+	if (!log)
+		return 0x0000;
+	else if (log > 0x11)
+		return 0xffff;
+	else
+		return (1 << (log - offset));
+}
+
+
+static int hb_subscription_set(struct mesh_net *net, uint16_t src,
+					uint16_t dst, uint8_t period_log)
+{
+	struct mesh_net_heartbeat *hb = mesh_net_heartbeat_get(net);
+	struct timeval time_now;
+
+	/* SRC must be Unicast, DST can be any legal address except Virtual */
+	if ((!IS_UNASSIGNED(src) && !IS_UNICAST(src)) || IS_VIRTUAL(dst))
+		return -1;
+
+	/* Check if the subscription should be disabled */
+	if (IS_UNASSIGNED(src) || IS_UNASSIGNED(dst)) {
+		if (IS_GROUP(hb->sub_dst))
+			mesh_net_dst_unreg(net, hb->sub_dst);
+
+		l_timeout_remove(hb->sub_timer);
+		hb->sub_timer = NULL;
+		hb->sub_enabled = false;
+		hb->sub_dst = UNASSIGNED_ADDRESS;
+		hb->sub_src = UNASSIGNED_ADDRESS;
+		hb->sub_count = 0;
+		hb->sub_period = 0;
+		hb->sub_min_hops = 0;
+		hb->sub_max_hops = 0;
+		return MESH_STATUS_SUCCESS;
+	} else if (!period_log && src == hb->sub_src && dst == hb->sub_dst) {
+		/* Preserve collected data, but disable */
+		l_timeout_remove(hb->sub_timer);
+		hb->sub_timer = NULL;
+		hb->sub_enabled = false;
+		hb->sub_period = 0;
+		return MESH_STATUS_SUCCESS;
+	}
+
+	if (hb->sub_dst != dst) {
+		if (IS_GROUP(hb->sub_dst))
+			mesh_net_dst_unreg(net, hb->sub_dst);
+		if (IS_GROUP(dst))
+			mesh_net_dst_reg(net, dst);
+	}
+
+	hb->sub_enabled = !!period_log;
+	hb->sub_src = src;
+	hb->sub_dst = dst;
+	hb->sub_count = 0;
+	hb->sub_period = log_to_uint32(period_log, 1);
+	hb->sub_min_hops = 0x00;
+	hb->sub_max_hops = 0x00;
+
+	gettimeofday(&time_now, NULL);
+	hb->sub_start = time_now.tv_sec;
+
+	if (!hb->sub_enabled) {
+		l_timeout_remove(hb->sub_timer);
+		hb->sub_timer = NULL;
+		return MESH_STATUS_SUCCESS;
+	}
+
+	hb->sub_min_hops = 0xff;
+
+	if (!hb->sub_timer)
+		hb->sub_timer = l_timeout_create(hb->sub_period,
+						hb_sub_timeout_func, net, NULL);
+	else
+		l_timeout_modify(hb->sub_timer, hb->sub_period);
+
+	return MESH_STATUS_SUCCESS;
+}
+
+static void node_reset(struct l_timeout *timeout, void *user_data)
+{
+	l_info("Node Reset");
+	l_timeout_remove(timeout);
+	l_main_quit();
+}
+
+static bool cfg_srv_pkt(uint16_t src, uint32_t dst,
+				uint16_t unicast, uint16_t idx,
+				const uint8_t *data, uint16_t size,
+				uint8_t ttl, const void *user_data)
+{
+	struct mesh_net *net = (struct mesh_net *) user_data;
+	const uint8_t *pkt = data;
+	struct timeval time_now;
+	uint32_t opcode, tmp32;
+	int b_res = MESH_STATUS_SUCCESS;
+	uint8_t msg[11];
+	uint8_t *long_msg = NULL;
+	struct mesh_net_heartbeat *hb;
+	uint16_t net_idx, app_idx;
+	uint8_t state, status;
+	uint8_t phase;
+	bool virt = false;
+	uint8_t count;
+	uint16_t interval;
+	struct mesh_node *node;
+	uint16_t n;
+
+	if (idx != APP_IDX_DEV)
+		return false;
+
+	if (mesh_model_opcode_get(pkt, size, &opcode, &n)) {
+		size -= n;
+		pkt += n;
+	} else
+		return false;
+
+	hb = mesh_net_heartbeat_get(net);
+	l_debug("CONFIG-SRV-opcode 0x%x size %u idx %3.3x", opcode, size, idx);
+
+	node = mesh_net_local_node_get(net);
+	n = 0;
+
+	switch (opcode) {
+	default:
+		return false;
+
+	case OP_DEV_COMP_GET:
+		if (size != 1)
+			return false;
+
+		/* Only page 0 is currently supported */
+		if (pkt[0] != 0) {
+			l_info("Unsupported page number %d", pkt[0]);
+			l_info("Returning page number 0");
+		}
+		long_msg = l_malloc(CFG_MAX_MSG_LEN);
+		n = mesh_model_opcode_set(OP_DEV_COMP_STATUS, long_msg);
+		long_msg[n++] = 0;
+		n += node_generate_comp(node, long_msg + n,
+							CFG_MAX_MSG_LEN - n);
+
+		break;
+
+	case OP_CONFIG_DEFAULT_TTL_SET:
+		if (size != 1 || pkt[0] > TTL_MASK || pkt[0] == 1)
+			return true;
+
+		if (pkt[0] <= TTL_MASK)
+			node_default_ttl_set(node, pkt[0]);
+		/* Fall Through */
+
+	case OP_CONFIG_DEFAULT_TTL_GET:
+		l_info("Get/Set Default TTL");
+
+		n = mesh_model_opcode_set(OP_CONFIG_DEFAULT_TTL_STATUS, msg);
+		msg[n++] = node_default_ttl_get(node);
+		break;
+
+	case OP_CONFIG_MODEL_PUB_VIRT_SET:
+		if (size != 25 && size != 27)
+			return true;
+
+		config_pub_set(net, src, unicast, pkt, size,
+				!!(opcode & OP_UNRELIABLE));
+		break;
+
+	case OP_CONFIG_MODEL_PUB_SET:
+		if (size != 11 && size != 13)
+			return true;
+
+		config_pub_set(net, src, unicast, pkt, size,
+				!!(opcode & OP_UNRELIABLE));
+		break;
+
+	case OP_CONFIG_MODEL_PUB_GET:
+		config_pub_get(net, src, unicast, pkt, size);
+		break;
+
+	case OP_CONFIG_VEND_MODEL_SUB_GET:
+		if (size != 6)
+			return true;
+		config_sub_get(net, src, unicast, pkt, size);
+		break;
+
+	case OP_CONFIG_MODEL_SUB_GET:
+		if (size != 4)
+			return true;
+		config_sub_get(net, src, unicast, pkt, size);
+		break;
+
+	case OP_CONFIG_MODEL_SUB_VIRT_OVERWRITE:
+	case OP_CONFIG_MODEL_SUB_VIRT_DELETE:
+	case OP_CONFIG_MODEL_SUB_VIRT_ADD:
+		virt = true;
+		/* Fall Through */
+	case OP_CONFIG_MODEL_SUB_OVERWRITE:
+	case OP_CONFIG_MODEL_SUB_DELETE:
+	case OP_CONFIG_MODEL_SUB_ADD:
+	case OP_CONFIG_MODEL_SUB_DELETE_ALL:
+		config_sub_set(net, src, unicast, pkt, size, virt, opcode);
+		break;
+
+	case OP_CONFIG_RELAY_SET:
+		if (size != 2 || pkt[0] > 0x01)
+			return true;
+
+		count = (pkt[1] >> 5) + 1;
+		interval = ((pkt[1] & 0x1f) + 1) * 10;
+		node_relay_mode_set(node, !!pkt[0], pkt[1]>>5,
+					pkt[1] & 0x1f);
+		/* Fall Through */
+
+	case OP_CONFIG_RELAY_GET:
+		n = mesh_model_opcode_set(OP_CONFIG_RELAY_STATUS, msg);
+
+		msg[n++] = node_relay_mode_get(node, &count, &interval);
+		msg[n++] = ((count - 1) << 5) + ((interval/10 - 1) & 0x1f);
+
+		l_info("Get/Set Relay Config (%d)", msg[n-1]);
+		break;
+
+	case OP_CONFIG_NETWORK_TRANSMIT_SET:
+		if (size != 1)
+			return true;
+
+		count = (pkt[0] >> 5) + 1;
+		interval = ((pkt[0] & 0x1f) + 1) * 10;
+		if (storage_local_set_transmit_params(net, count, interval))
+			mesh_net_transmit_params_set(net, count, interval);
+		/* Fall Through */
+
+	case OP_CONFIG_NETWORK_TRANSMIT_GET:
+		n = mesh_model_opcode_set(OP_CONFIG_NETWORK_TRANSMIT_STATUS,
+									msg);
+		mesh_net_transmit_params_get(net, &count, &interval);
+		msg[n++] = ((count - 1) << 5) + ((interval/10 - 1) & 0x1f);
+
+		l_info("Get/Set Network Transmit Config");
+		break;
+
+	case OP_CONFIG_PROXY_SET:
+		if (size != 1 || pkt[0] > 0x01)
+			return true;
+
+		node_proxy_mode_set(node, !!pkt[0]);
+		/* Fall Through */
+
+	case OP_CONFIG_PROXY_GET:
+		n = mesh_model_opcode_set(OP_CONFIG_PROXY_STATUS, msg);
+
+		msg[n++] = node_proxy_mode_get(node);
+		l_info("Get/Set Config Proxy (%d)", msg[n-1]);
+		break;
+
+	case OP_NODE_IDENTITY_SET:
+		if (size != 3 || pkt[2] > 0x01)
+			return true;
+
+		net_idx = l_get_le16(pkt);
+		if (net_idx > 0xfff)
+			return true;
+
+		/*
+		 * Currently no support for proxy: node identity not supported
+		 */
+
+		/* Fall Through */
+
+	case OP_NODE_IDENTITY_GET:
+		if (size < 2)
+			return true;
+
+		net_idx = l_get_le16(pkt);
+		if (net_idx > 0xfff)
+			return true;
+
+		n = mesh_model_opcode_set(OP_NODE_IDENTITY_STATUS, msg);
+
+		status = mesh_net_get_identity_mode(net, net_idx, &state);
+
+		msg[n++] = status;
+
+		l_put_le16(net_idx, msg + n);
+		n += 2;
+
+		msg[n++] = state;
+		l_info("Get/Set Config Identity (%d)", state);
+		break;
+
+	case OP_CONFIG_BEACON_SET:
+		if (size != 1 || pkt[0] > 0x01)
+			return true;
+
+		node_beacon_mode_set(node, !!pkt[0]);
+		/* Fall Through */
+
+	case OP_CONFIG_BEACON_GET:
+		n = mesh_model_opcode_set(OP_CONFIG_BEACON_STATUS, msg);
+
+		msg[n++] = node_beacon_mode_get(node);
+		l_info("Get/Set Config Beacon (%d)", msg[n-1]);
+		break;
+
+	case OP_CONFIG_FRIEND_SET:
+		if (size != 1 || pkt[0] > 0x01)
+			return true;
+
+		node_friend_mode_set(node, !!pkt[0]);
+		/* Fall Through */
+
+	case OP_CONFIG_FRIEND_GET:
+
+		n = mesh_model_opcode_set(OP_CONFIG_FRIEND_STATUS, msg);
+
+		msg[n++] = node_friend_mode_get(node);
+		l_info("Get/Set Friend (%d)", msg[n-1]);
+		break;
+
+	case OP_CONFIG_KEY_REFRESH_PHASE_SET:
+		if (size != 3 || pkt[2] > 0x03)
+			return true;
+
+		b_res = mesh_net_key_refresh_phase_set(net, l_get_le16(pkt),
+							pkt[2]);
+		size = 2;
+		/* Fall Through */
+
+	case OP_CONFIG_KEY_REFRESH_PHASE_GET:
+		if (size != 2)
+			return true;
+
+		net_idx = l_get_le16(pkt);
+
+		n = mesh_model_opcode_set(OP_CONFIG_KEY_REFRESH_PHASE_STATUS,
+						msg);
+
+		/* State: 0x00-0x03 phase of key refresh */
+		status = mesh_net_key_refresh_phase_get(net, net_idx,
+							&phase);
+		if (status != MESH_STATUS_SUCCESS) {
+			b_res = status;
+			phase = KEY_REFRESH_PHASE_NONE;
+		}
+
+		msg[n++] = b_res;
+		l_put_le16(net_idx, msg + n);
+		n += 2;
+		msg[n++] = phase;
+
+		l_info("Get/Set Key Refresh State (%d)", msg[n-1]);
+		break;
+
+	case OP_APPKEY_ADD:
+	case OP_APPKEY_UPDATE:
+		if (size != 19)
+			return true;
+
+		net_idx = l_get_le16(pkt) & 0xfff;
+		app_idx = l_get_le16(pkt + 1) >> 4;
+		b_res = appkey_key_add(net, net_idx, app_idx, pkt + 3,
+						opcode == OP_APPKEY_UPDATE);
+
+		l_info("Add/Update AppKey %s: Net_Idx %3.3x, App_Idx %3.3x",
+			(b_res == MESH_STATUS_SUCCESS) ? "success" : "fail",
+							net_idx, app_idx);
+
+
+		n = mesh_model_opcode_set(OP_APPKEY_STATUS, msg);
+
+		msg[n++] = b_res;
+		msg[n++] = pkt[0];
+		msg[n++] = pkt[1];
+		msg[n++] = pkt[2];
+		break;
+
+	case OP_APPKEY_DELETE:
+		if (size != 3)
+			return
+				true;
+
+		net_idx = l_get_le16(pkt) & 0xfff;
+		app_idx = l_get_le16(pkt + 1) >> 4;
+		b_res = appkey_key_delete(net, net_idx, app_idx);
+		if (b_res == MESH_STATUS_SUCCESS)
+			node_app_key_delete(net, dst, net_idx, app_idx);
+		l_info("Delete AppKey %s Net_Idx %3.3x to App_Idx %3.3x",
+			(b_res == MESH_STATUS_SUCCESS) ? "success" : "fail",
+							net_idx, app_idx);
+
+		n = mesh_model_opcode_set(OP_APPKEY_STATUS, msg);
+		msg[n++] = b_res;
+		msg[n++] = pkt[0];
+		msg[n++] = pkt[1];
+		msg[n++] = pkt[2];
+		break;
+
+	case OP_APPKEY_GET:
+		if (size != 2)
+			return true;
+		net_idx = l_get_le16(pkt);
+
+		long_msg = l_malloc(CFG_MAX_MSG_LEN);
+		n = mesh_model_opcode_set(OP_APPKEY_LIST, long_msg);
+
+		status = appkey_list(net, net_idx, long_msg + n + 3,
+						CFG_MAX_MSG_LEN - n - 3, &size);
+
+		long_msg[n] = status;
+		l_put_le16(net_idx, long_msg + n + 1);
+		n += (size + 3);
+		break;
+
+	case OP_NETKEY_ADD:
+	case OP_NETKEY_UPDATE:
+		if (size != 18)
+			return true;
+
+		b_res = mesh_net_add_key(net, opcode == OP_NETKEY_UPDATE,
+						l_get_le16(pkt), pkt + 2);
+
+		l_info("NetKey Add/Update %s",
+			(b_res == MESH_STATUS_SUCCESS) ? "success" : "fail");
+
+		n = mesh_model_opcode_set(OP_NETKEY_STATUS, msg);
+		msg[n++] = b_res;
+		l_put_le16(l_get_le16(pkt), msg + n);
+		n += 2;
+		break;
+
+	case OP_NETKEY_DELETE:
+		if (size != 2)
+			return true;
+
+		b_res = mesh_net_del_key(net, l_get_le16(pkt));
+
+		l_info("NetKey delete %s",
+			(b_res == MESH_STATUS_SUCCESS) ? "success" : "fail");
+
+		n = mesh_model_opcode_set(OP_NETKEY_STATUS, msg);
+		msg[n++] = b_res;
+		l_put_le16(l_get_le16(pkt), msg + n);
+		n += 2;
+		break;
+
+	case OP_NETKEY_GET:
+		long_msg = l_malloc(CFG_MAX_MSG_LEN);
+		n = mesh_model_opcode_set(OP_NETKEY_LIST, long_msg);
+		size = CFG_MAX_MSG_LEN - n;
+
+		if (mesh_net_key_list_get(net, long_msg + n, &size))
+			n += size;
+		else
+			n = 0;
+		break;
+
+	case OP_MODEL_APP_BIND:
+	case OP_MODEL_APP_UNBIND:
+		model_app_bind(net, src, unicast, pkt, size,
+				opcode != OP_MODEL_APP_BIND);
+		break;
+
+	case OP_VEND_MODEL_APP_GET:
+		if (size != 6)
+			return true;
+		model_app_list(net, src, unicast, pkt, size);
+		break;
+
+	case OP_MODEL_APP_GET:
+		if (size != 4)
+			return true;
+		model_app_list(net, src, unicast, pkt, size);
+		break;
+
+	case OP_CONFIG_HEARTBEAT_PUB_SET:
+		l_info("OP_CONFIG_HEARTBEAT_PUB_SET");
+		if (size != 9) {
+			l_info("bad size %d", size);
+			return true;
+		}
+		if (pkt[2] > 0x11 || pkt[3] > 0x10 || pkt[4] > 0x7f)
+			return true;
+		else if (IS_VIRTUAL(l_get_le16(pkt)))
+			b_res = MESH_STATUS_INVALID_ADDRESS;
+		else if (l_get_le16(pkt + 7) != mesh_net_get_primary_idx(net))
+			/* Future work: check for valid subnets */
+			b_res = MESH_STATUS_INVALID_NETKEY;
+
+		n = mesh_model_opcode_set(OP_CONFIG_HEARTBEAT_PUB_STATUS,
+						msg);
+		msg[n++] = b_res;
+
+		memcpy(&msg[n], pkt, 9);
+
+		/* Ignore RFU bits in features */
+		l_put_le16(l_get_le16(pkt + 5) & 0xf, &msg[n + 5]);
+
+		/* Add octet count to status */
+		n += 9;
+
+		if (b_res != MESH_STATUS_SUCCESS)
+			break;
+
+		hb->pub_dst = l_get_le16(pkt);
+		if (hb->pub_dst == UNASSIGNED_ADDRESS ||
+				pkt[2] == 0 || pkt[3] == 0) {
+			/*
+			 * We might still have a pub_dst here in case
+			 * we need it for State Change heartbeat
+			 */
+			hb->pub_count = 0;
+			hb->pub_period = 0;
+		} else {
+			hb->pub_count = (pkt[2] != 0xff) ?
+				log_to_uint32(pkt[2], 1) : 0xffff;
+			hb->pub_period = log_to_uint32(pkt[3], 1);
+		}
+
+		hb->pub_ttl = pkt[4];
+		hb->pub_features = l_get_le16(pkt + 5) & 0xf;
+		hb->pub_net_idx = l_get_le16(pkt + 7);
+		update_hb_pub_timer(net, hb);
+
+		break;
+
+	case OP_CONFIG_HEARTBEAT_PUB_GET:
+		n = mesh_model_opcode_set(OP_CONFIG_HEARTBEAT_PUB_STATUS, msg);
+		msg[n++] = b_res;
+		l_put_le16(hb->pub_dst, msg + n);
+		n += 2;
+		msg[n++] = uint32_to_log(hb->pub_count);
+		msg[n++] = uint32_to_log(hb->pub_period);
+		msg[n++] = hb->pub_ttl;
+		l_put_le16(hb->pub_features, msg + n);
+		n += 2;
+		l_put_le16(hb->pub_net_idx, msg + n);
+		n += 2;
+		break;
+
+	case OP_CONFIG_HEARTBEAT_SUB_SET:
+		if (size != 5)
+			return true;
+
+		l_info("Set Sub Period (Log %2.2x) %d sec",
+				pkt[4], log_to_uint32(pkt[4], 1));
+
+		b_res = hb_subscription_set(net, l_get_le16(pkt),
+						l_get_le16(pkt + 2),
+						pkt[4]);
+		if (b_res < 0)
+			return true;
+
+		/* Fall through */
+
+	case OP_CONFIG_HEARTBEAT_SUB_GET:
+		gettimeofday(&time_now, NULL);
+		time_now.tv_sec -= hb->sub_start;
+
+		if (time_now.tv_sec >= hb->sub_period)
+			time_now.tv_sec = 0;
+		else
+			time_now.tv_sec = hb->sub_period - time_now.tv_sec;
+
+		l_info("Sub Period (Log %2.2x) %d sec",
+				uint32_to_log(time_now.tv_sec),
+				(int) time_now.tv_sec);
+
+		n = mesh_model_opcode_set(OP_CONFIG_HEARTBEAT_SUB_STATUS, msg);
+		msg[n++] = b_res;
+		l_put_le16(hb->sub_src, msg + n);
+		n += 2;
+		l_put_le16(hb->sub_dst, msg + n);
+		n += 2;
+		msg[n++] = uint32_to_log(time_now.tv_sec);
+		msg[n++] = uint32_to_log(hb->sub_count);
+		msg[n++] = hb->sub_count ? hb->sub_min_hops : 0;
+		msg[n++] = hb->sub_max_hops;
+		break;
+
+	case OP_CONFIG_POLL_TIMEOUT_LIST:
+		if (size != 2 || l_get_le16(pkt) == 0 ||
+						l_get_le16(pkt) > 0x7fff)
+			return true;
+
+		n = mesh_model_opcode_set(OP_CONFIG_POLL_TIMEOUT_STATUS, msg);
+		l_put_le16(l_get_le16(pkt), msg + n);
+		n += 2;
+		tmp32 = mesh_net_friend_timeout(net, l_get_le16(pkt));
+		msg[n++] = tmp32;
+		msg[n++] = tmp32 >> 8;
+		msg[n++] = tmp32 >> 16;
+		break;
+
+	case OP_NODE_RESET:
+		n = mesh_model_opcode_set(OP_NODE_RESET_STATUS, msg);
+		l_timeout_create(1, node_reset, net, NULL);
+		break;
+	}
+
+	if (n) {
+		/* print_packet("App Tx", long_msg ? long_msg : msg, n); */
+		mesh_model_send(net, CONFIG_SRV_MODEL,
+				unicast, src,
+				APP_IDX_DEV, DEFAULT_TTL,
+				long_msg ? long_msg : msg, n);
+	}
+	l_free(long_msg);
+
+	return true;
+}
+
+static void cfgmod_srv_unregister(void *user_data)
+{
+	struct mesh_net *net = user_data;
+	struct mesh_net_heartbeat *hb = mesh_net_heartbeat_get(net);
+
+	l_timeout_remove(hb->pub_timer);
+	l_timeout_remove(hb->sub_timer);
+	hb->pub_timer = hb->sub_timer = NULL;
+}
+
+static const struct mesh_model_ops ops = {
+	.unregister = cfgmod_srv_unregister,
+	.recv = cfg_srv_pkt,
+	.bind = NULL,
+	.sub = NULL,
+	.pub = NULL
+};
+
+void mesh_config_srv_init(struct mesh_net *net, uint8_t ele_idx)
+{
+	l_debug("%2.2x", ele_idx);
+	mesh_model_register(net, ele_idx, CONFIG_SRV_MODEL, &ops, net);
+}
Signature · 1 line
2.14.3
author
#7 lore raw

PATCH v2 9/11 meshd: Read and write mesh configuration in JSON format

In reply to Brian Gix

From: Inga Stotland <[email protected]>

This adds implementation for parsing and writing Mesh configuration into JSON format. Alos, parse stored unprovisioned device composiotion.

---
 meshd/mesh-json/mesh-db.c | 1360 +++++++++++++++++++++++++++++++++++++++++++++
 meshd/mesh-json/mesh-db.h |  144 +++++
 2 files changed, 1504 insertions(+)
 create mode 100644 meshd/mesh-json/mesh-db.c
 create mode 100644 meshd/mesh-json/mesh-db.h
meshd/mesh-json/mesh-db.c new file +1360 -0
new file mode 100644
index 000000000..6d894a920
@@ -0,0 +1,1360 @@
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2018  Intel Corporation. All rights reserved.
+ *
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <ell/ell.h>
+
+#include "meshd/common/mesh-defs.h"
+#include "meshd/common/util.h"
+
+#include "meshd/mesh-json/mesh-db.h"
+
+#define CHECK_KEY_IDX_RANGE(x) (((x) >= 0) && ((x) <= 4095))
+
+static bool get_int(json_object *jobj, const char *keyword, int *value)
+{
+	json_object *jvalue;
+
+	if (!json_object_object_get_ex(jobj, keyword, &jvalue))
+		return false;
+
+	*value = json_object_get_int(jvalue);
+	if (errno == EINVAL)
+		return false;
+
+	return true;
+}
+
+static bool add_key(json_object *jobject, const char *desc,
+					const uint8_t key[16])
+{
+	json_object *jstring;
+	char hexstr[33];
+
+	hex2str((uint8_t *) key, 16, hexstr, 33);
+	jstring = json_object_new_string(hexstr);
+	if (!jstring)
+		return false;
+
+	json_object_object_add(jobject, desc, jstring);
+	return true;
+}
+
+static json_object *get_element_model(json_object *jnode, int ele_idx,
+						uint32_t mod_id, bool vendor)
+{
+	json_object *jelements, *jelement, *jmodels;
+	int i, num_mods;
+	size_t len;
+	char buf[9];
+
+	if (!vendor)
+		snprintf(buf, 5, "%4.4x", (uint16_t)mod_id);
+	else
+		snprintf(buf, 9, "%8.8x", mod_id);
+
+	json_object_object_get_ex(jnode, "elements", &jelements);
+	if (!jelements)
+		return NULL;
+
+	jelement = json_object_array_get_idx(jelements, ele_idx);
+	if (!jelement)
+		return NULL;
+
+	json_object_object_get_ex(jelement, "models", &jmodels);
+	if (!jmodels)
+		return NULL;
+
+	num_mods = json_object_array_length(jmodels);
+	if (!num_mods)
+		return NULL;
+
+	if (!vendor) {
+		snprintf(buf, 5, "%4.4x", mod_id);
+		len = 4;
+	} else {
+		snprintf(buf, 9, "%8.8x", mod_id);
+		len = 8;
+	}
+
+	for (i = 0; i < num_mods; ++i) {
+		json_object *jmodel, *jvalue;
+		char *str;
+
+		jmodel = json_object_array_get_idx(jmodels, i);
+		json_object_object_get_ex(jmodel, "modelId", &jvalue);
+		if (!jvalue)
+			return NULL;
+
+		str = (char *)json_object_get_string(jvalue);
+		if (!str)
+			return NULL;
+
+		if (!strncmp(str, buf, len))
+			return jmodel;
+	}
+
+	return NULL;
+}
+
+static bool jarray_has_string(json_object *jarray, char *str, size_t len)
+{
+	int i, sz = json_object_array_length(jarray);
+
+	for (i = 0; i < sz; ++i) {
+		json_object *jentry;
+		char *str_entry;
+
+		jentry = json_object_array_get_idx(jarray, i);
+		str_entry = (char *)json_object_get_string(jentry);
+		if (!str_entry)
+			continue;
+
+		if (!strncmp(str, str_entry, len))
+			return true;
+	}
+
+	return false;
+}
+
+static json_object *jarray_string_del(json_object *jarray, char *str,
+								size_t len)
+{
+	int i, sz = json_object_array_length(jarray);
+	json_object *jarray_new;
+
+	jarray_new = json_object_new_array();
+	if (!jarray_new)
+		return NULL;
+
+	for (i = 0; i < sz; ++i) {
+		json_object *jentry;
+		char *str_entry;
+
+		jentry = json_object_array_get_idx(jarray, i);
+		str_entry = (char *)json_object_get_string(jentry);
+		if (str_entry && !strncmp(str, str_entry, len))
+			continue;
+
+		json_object_array_add(jarray_new, jentry);
+	}
+
+	return jarray_new;
+}
+
+static json_object *get_key_object(json_object *jarray, uint16_t idx)
+{
+	int i, sz = json_object_array_length(jarray);
+
+	for (i = 0; i < sz; ++i) {
+		json_object *jentry, *jvalue;
+		uint32_t jidx;
+
+		jentry = json_object_array_get_idx(jarray, i);
+		if (!json_object_object_get_ex(jentry, "index", &jvalue))
+			return NULL;
+
+		jidx = json_object_get_int(jvalue);
+
+		if (jidx == idx)
+			return jentry;
+	}
+
+	return NULL;
+}
+
+static json_object *jarray_key_del(json_object *jarray, int16_t idx)
+{
+	json_object *jarray_new;
+	int i, sz = json_object_array_length(jarray);
+	char idx_str[5];
+
+	snprintf(idx_str, 5, "%4.4x", idx);
+
+	jarray_new = json_object_new_array();
+	if (!jarray_new)
+		return NULL;
+
+	for (i = 0; i < sz; ++i) {
+		json_object *jentry, *jvalue;
+		char *str;
+
+		jentry = json_object_array_get_idx(jarray, i);
+
+		if (json_object_object_get_ex(jentry, "index", &jvalue)) {
+			str = (char *)json_object_get_string(jvalue);
+			if (str && !strncmp(str, idx_str, 4))
+				continue;
+		}
+
+		json_object_array_add(jarray_new, jentry);
+	}
+
+	return jarray_new;
+}
+
+bool mesh_db_read_iv_index(json_object *jobj, uint32_t *idx, bool *update)
+{
+	int tmp;
+
+	/* IV index */
+	if (!get_int(jobj, "IVindex", &tmp))
+		return false;
+
+	*idx = (uint32_t) tmp;
+
+	if (!get_int(jobj, "IVupdate", &tmp))
+		return false;
+
+	*update = tmp ? true : false;
+
+	return true;
+}
+
+bool mesh_db_read_device_key(json_object *jobj, uint8_t key_buf[16])
+{
+	json_object *jvalue;
+	char *str;
+
+	if (!key_buf)
+		return false;
+
+	if (!json_object_object_get_ex(jobj, "deviceKey", &jvalue) ||
+								!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (!str2hex(str, strlen(str), key_buf, 16))
+		return false;
+
+	return true;
+}
+
+bool mesh_db_read_app_keys(json_object *jobj, mesh_db_app_key_cb cb,
+							void *user_data)
+{
+	json_object *jarray;
+	int len;
+	int i;
+
+	if (!cb)
+		return true;
+
+	json_object_object_get_ex(jobj, "appKeys", &jarray);
+	if (!jarray || (json_object_get_type(jarray) != json_type_array))
+		return false;
+
+	len = json_object_array_length(jarray);
+
+	for (i = 0; i < len; ++i) {
+		json_object *jtemp, *jvalue;
+		int app_idx, net_idx;
+		bool key_refresh = false;
+		char *str;
+		uint8_t key[16];
+		uint8_t new_key[16];
+
+		jtemp = json_object_array_get_idx(jarray, i);
+
+		if (!get_int(jtemp, "index", &app_idx))
+			return false;
+
+		if (!CHECK_KEY_IDX_RANGE(app_idx))
+			return false;
+
+		if (!get_int(jtemp, "boundNetKey", &net_idx))
+			return false;
+
+		if (!CHECK_KEY_IDX_RANGE(net_idx))
+			return false;
+
+		json_object_object_get_ex(jtemp, "oldKey", &jvalue);
+		if (jvalue) {
+			str = (char *)json_object_get_string(jvalue);
+			if (!str2hex(str, strlen(str), key, 16))
+				return false;
+			key_refresh = true;
+		}
+
+		json_object_object_get_ex(jtemp, "key", &jvalue);
+		if (!jvalue)
+			return false;
+
+		str = (char *)json_object_get_string(jvalue);
+		if (!str2hex(str, strlen(str), key_refresh ? new_key : key, 16))
+			return false;
+
+		if (!cb((uint16_t)net_idx, (uint16_t) app_idx, key,
+				key_refresh ? new_key : NULL, user_data))
+			return false;
+	}
+
+	return true;
+}
+
+bool mesh_db_read_net_keys(json_object *jobj, mesh_db_net_key_cb cb,
+								void *user_data)
+{
+	json_object *jarray;
+	int len;
+	int i;
+
+	if (!cb)
+		return true;
+
+	json_object_object_get_ex(jobj, "netKeys", &jarray);
+	if (!jarray || (json_object_get_type(jarray) != json_type_array))
+		return false;
+
+	len = json_object_array_length(jarray);
+
+	for (i = 0; i < len; ++i) {
+		json_object *jtemp, *jvalue;
+		int idx;
+		char *str;
+		bool key_refresh = false;
+		int phase;
+		uint8_t key[16];
+		uint8_t new_key[16];
+
+		jtemp = json_object_array_get_idx(jarray, i);
+
+		if (!get_int(jtemp, "index", &idx))
+			return false;
+
+		if (!CHECK_KEY_IDX_RANGE(idx))
+			return false;
+
+		json_object_object_get_ex(jtemp, "oldKey", &jvalue);
+		if (jvalue) {
+			str = (char *)json_object_get_string(jvalue);
+			if (!str2hex(str, strlen(str), key, 16))
+				return false;
+			key_refresh = true;
+		}
+
+		json_object_object_get_ex(jtemp, "key", &jvalue);
+		if (!jvalue)
+			return false;
+
+		str = (char *)json_object_get_string(jvalue);
+		if (!str2hex(str, strlen(str), key_refresh ? new_key : key, 16))
+			return false;
+
+		json_object_object_get_ex(jtemp, "keyRefresh", &jvalue);
+		if (!jvalue)
+			phase = KEY_REFRESH_PHASE_NONE;
+		else
+			phase = json_object_get_int(jvalue);
+
+
+		if (!cb((uint16_t)idx, key, key_refresh ? new_key : NULL, phase,
+								user_data))
+			return false;
+	}
+
+	return true;
+}
+
+bool mesh_db_net_key_add(json_object *jobj, uint16_t idx,
+					const uint8_t key[16], int phase)
+{
+	json_object *jarray, *jentry = NULL, *jstring;
+	char buf[5];
+
+	json_object_object_get_ex(jobj, "netKeys", &jarray);
+	if (!jarray && (phase != KEY_REFRESH_PHASE_NONE))
+		return false;
+
+	if (jarray)
+		jentry = get_key_object(jarray, idx);
+
+	/*
+	 * The key entry should exist if the key is updated
+	 * (i.e., Key Refresh is underway)
+	 */
+	if (!jentry && (phase != KEY_REFRESH_PHASE_NONE))
+		return false;
+
+	if (jentry) {
+		uint8_t buf[16];
+		json_object *jvalue;
+		char *str;
+
+		json_object_object_get_ex(jentry, "key", &jvalue);
+		if (!jvalue)
+			return false;
+
+		str = (char *)json_object_get_string(jvalue);
+		if (!str2hex(str, strlen(str), buf, sizeof(buf)))
+			return false;
+
+		/* If the same key, return success */
+		if (memcmp(key, buf, 16) == 0)
+			return true;
+
+		return false;
+	}
+
+	if (phase == KEY_REFRESH_PHASE_NONE) {
+		jentry = json_object_new_object();
+		if (!jentry)
+			goto fail;
+
+		snprintf(buf, 5, "%4.4x", idx);
+		jstring = json_object_new_string(buf);
+		if (!jstring)
+			goto fail;
+
+		json_object_object_add(jentry, "index", jstring);
+
+		snprintf(buf, 5, "%4.4x", idx);
+		jstring = json_object_new_string(buf);
+		if (!jstring)
+			goto fail;
+
+		if (!add_key(jentry, "key", key))
+			goto fail;
+
+		if (!jarray) {
+			jarray = json_object_new_array();
+			if (!jarray)
+				goto fail;
+			json_object_object_add(jobj, "netKeys", jarray);
+		}
+
+		json_object_array_add(jarray, jentry);
+
+	} else {
+
+		if (!json_object_object_get_ex(jentry, "key", &jstring))
+			return false;
+
+		json_object_object_add(jentry, "oldKey", jstring);
+		json_object_object_del(jentry, "key");
+
+		if (!add_key(jentry, "key", key))
+			return false;
+	}
+
+
+	json_object_object_add(jentry, "keyRefresh",
+					json_object_new_int(phase));
+
+	return true;
+fail:
+
+	if (jentry)
+		json_object_put(jentry);
+
+	return false;
+}
+
+bool mesh_db_net_key_del(json_object *jobj, uint16_t idx)
+{
+	json_object *jarray, *jarray_new;
+
+	json_object_object_get_ex(jobj, "netKeys", &jarray);
+	if (!jarray)
+		return true;
+
+	/* Check if matching entry exists */
+	if (!get_key_object(jarray, idx))
+		return true;
+
+	if (json_object_array_length(jarray) == 1) {
+		json_object_object_del(jobj, "netKeys");
+		return true;
+	}
+
+	/*
+	 * There is no easy way to delete a value from json array.
+	 * Create a new copy without specified element and
+	 * then remove old array.
+	 */
+	jarray_new = jarray_key_del(jarray, idx);
+	if (!jarray_new)
+		return false;
+
+	json_object_object_del(jobj, "netKeys");
+	json_object_object_add(jobj, "netKeys", jarray_new);
+
+	return true;
+}
+
+bool mesh_db_write_device_key(json_object *jnode, uint8_t *key)
+{
+	return add_key(jnode, "deviceKey", key);
+}
+
+bool mesh_db_app_key_add(json_object *jobj, uint16_t net_idx, uint16_t app_idx,
+			 const uint8_t key[16], bool update)
+{
+	json_object *jarray, *jentry = NULL, *jstring = NULL;
+	char buf[5];
+
+	json_object_object_get_ex(jobj, "appKeys", &jarray);
+	if (!jarray && update)
+		return false;
+
+	if (jarray)
+		jentry = get_key_object(jarray, app_idx);
+
+	/* The key entry should exist if the key is updated */
+	if (!jentry  && update)
+		return false;
+
+	if (jentry) {
+		uint8_t buf[16];
+		json_object *jvalue;
+		char *str;
+
+		json_object_object_get_ex(jentry, "key", &jvalue);
+		if (!jvalue)
+			return false;
+
+		str = (char *)json_object_get_string(jvalue);
+		if (!str2hex(str, strlen(str), buf, sizeof(buf)))
+			return false;
+
+		/* If the same key, return success */
+		if (memcmp(key, buf, 16) == 0)
+			return true;
+
+		return false;
+	}
+
+	if (!update) {
+		jentry = json_object_new_object();
+		if (!jentry)
+			goto fail;
+
+		snprintf(buf, 5, "%4.4x", app_idx);
+		jstring = json_object_new_string(buf);
+		if (!jstring)
+			goto fail;
+
+		json_object_object_add(jentry, "index", jstring);
+
+		snprintf(buf, 5, "%4.4x", net_idx);
+		jstring = json_object_new_string(buf);
+		if (!jstring)
+			goto fail;
+
+		json_object_object_add(jentry, "boundNetKey", jstring);
+
+		if (!add_key(jentry, "key", key))
+			goto fail;
+
+		if (!jarray) {
+			jarray = json_object_new_array();
+			if (!jarray)
+				goto fail;
+			json_object_object_add(jobj, "appKeys", jarray);
+		}
+
+		json_object_array_add(jarray, jentry);
+
+	} else {
+
+		if (!json_object_object_get_ex(jentry, "key", &jstring))
+			return false;
+
+		json_object_object_add(jentry, "oldKey", jstring);
+		json_object_object_del(jentry, "key");
+
+		if (!add_key(jentry, "key", key))
+			return false;
+	}
+
+	return true;
+fail:
+
+	if (jentry)
+		json_object_put(jentry);
+
+	return false;
+}
+
+bool mesh_db_app_key_del(json_object *jobj, uint16_t net_idx, uint16_t idx)
+{
+	json_object *jarray, *jarray_new;
+
+	json_object_object_get_ex(jobj, "appKeys", &jarray);
+	if (!jarray)
+		return true;
+
+	/* Check if matching entry exists */
+	if (!get_key_object(jarray, idx))
+		return true;
+
+	if (json_object_array_length(jarray) == 1) {
+		json_object_object_del(jobj, "appKeys");
+		return true;
+	}
+
+	/*
+	 * There is no easy way to delete a value from json array.
+	 * Create a new copy without specified element and
+	 * then remove old array.
+	 */
+	jarray_new = jarray_key_del(jarray, idx);
+	if (!jarray_new)
+		return false;
+
+	json_object_object_del(jobj, "appKeys");
+	json_object_object_add(jobj, "appKeys", jarray_new);
+
+	return true;
+}
+
+bool mesh_db_model_binding_add(json_object *jnode, uint8_t ele_idx, bool vendor,
+				uint32_t mod_id, uint16_t app_idx)
+{
+	json_object *jmodel, *jstring, *jarray;
+	char buf[5];
+
+	jmodel = get_element_model(jnode, ele_idx, mod_id, vendor);
+	if (!jmodel)
+		return false;
+
+	json_object_object_get_ex(jmodel, "bind", &jarray);
+
+	snprintf(buf, 5, "%4.4x", app_idx);
+
+	if (jarray && jarray_has_string(jarray, buf, 4))
+		return true;
+
+	jstring = json_object_new_string(buf);
+	if (!jstring)
+		return false;
+
+	if (!jarray) {
+		jarray = json_object_new_array();
+		if (!jarray) {
+			json_object_put(jstring);
+			return false;
+		}
+		json_object_object_add(jmodel, "bind", jarray);
+	}
+
+	json_object_array_add(jarray, jstring);
+
+	return true;
+}
+
+bool mesh_db_model_binding_del(json_object *jnode, uint8_t ele_idx, bool vendor,
+				uint32_t mod_id, uint16_t app_idx)
+{
+	json_object *jmodel, *jarray, *jarray_new;
+	char buf[5];
+
+	jmodel = get_element_model(jnode, ele_idx, mod_id, vendor);
+	if (!jmodel)
+		return false;
+
+	json_object_object_get_ex(jmodel, "bind", &jarray);
+
+	snprintf(buf, 5, "%4.4x", app_idx);
+
+	if (!jarray || !jarray_has_string(jarray, buf, 4))
+		return true;
+
+	if (json_object_array_length(jarray) == 1) {
+		json_object_object_del(jmodel, "bind");
+		return true;
+	}
+
+	/*
+	 * There is no easy way to delete a value from json array.
+	 * Create a new copy without specified element and
+	 * then remove old array.
+	 */
+	jarray_new = jarray_string_del(jarray, buf, 4);
+	if (!jarray_new)
+		return false;
+
+	json_object_object_del(jmodel, "bind");
+	json_object_object_add(jmodel, "bind", jarray_new);
+
+	return true;
+}
+
+static void free_model(void *data)
+{
+	struct mesh_db_model *mod = data;
+
+	l_free(mod->bindings);
+	l_free(mod->subs);
+	l_free(mod->pub);
+	l_free(mod);
+}
+
+static void free_element(void *data)
+{
+	struct mesh_db_element *ele = data;
+
+	l_queue_destroy(ele->models, free_model);
+	l_free(ele);
+}
+
+static bool parse_bindings(json_object *jbindings, struct mesh_db_model *mod)
+{
+	int cnt;
+	int i;
+
+	cnt = json_object_array_length(jbindings);
+	if (cnt > 0xffff)
+		return false;
+
+	mod->num_subs = cnt;
+
+	/* Allow empty bindings list */
+	if (!cnt)
+		return true;
+
+	mod->bindings = l_new(uint16_t, cnt);
+	if (!mod->bindings)
+		return false;
+
+	for (i = 0; i < cnt; ++i) {
+		int idx;
+		json_object *jvalue;
+
+		jvalue = json_object_array_get_idx(jbindings, i);
+		if (!jvalue)
+			return false;
+
+		idx = json_object_get_int(jvalue);
+		if (!CHECK_KEY_IDX_RANGE(idx))
+			return false;
+
+		mod->bindings[i] = (uint16_t) idx;
+	}
+
+	return true;
+}
+
+static bool parse_models(json_object *jmodels, struct mesh_db_element *ele)
+{
+	int i, num_models;
+
+	num_models = json_object_array_length(jmodels);
+	if (!num_models)
+		return true;
+
+	for (i = 0; i < num_models; ++i) {
+		json_object *jmodel, *jarray, *jvalue;
+		struct mesh_db_model *mod;
+		uint32_t id;
+		int len;
+		char *str;
+
+		jmodel = json_object_array_get_idx(jmodels, i);
+		if (!jmodel)
+			goto fail;
+
+		mod = l_new(struct mesh_db_model, 1);
+		if (!ele)
+			goto fail;
+
+		json_object_object_get_ex(jmodel, "modelId", &jvalue);
+		str = (char *)json_object_get_string(jvalue);
+
+		len = strlen(str);
+
+		if (len != 4 && len != 8)
+			goto fail;
+
+		if (len == 4) {
+			if (sscanf(str, "%04x", &id) != 1)
+				goto fail;
+
+			id |= VENDOR_ID_MASK;
+		} else if (len == 8) {
+			if (sscanf(str, "%08x", &id) != 1)
+				goto fail;
+		} else
+			goto fail;
+
+		mod->id = id;
+
+		if (len == 8)
+			mod->vendor = true;
+
+		json_object_object_get_ex(jmodel, "bind", &jarray);
+
+		if (jarray && (json_object_get_type(jmodels) != json_type_array
+					|| !parse_bindings(jarray, mod)))
+			goto fail;
+
+		/* TODO add pub/sub */
+		l_queue_push_tail(ele->models, mod);
+	}
+
+	return true;
+
+fail:
+	l_queue_destroy(ele->models, free_model);
+	return false;
+}
+
+static bool parse_elements(json_object *jelements, struct mesh_db_node *node)
+{
+	int i, num_ele;
+
+	num_ele = json_object_array_length(jelements);
+	if (!num_ele)
+		/* Allow "empty" nodes */
+		return true;
+
+	node->elements = l_queue_new();
+	if (!node->elements)
+		return false;
+
+	for (i = 0; i < num_ele; ++i) {
+		json_object *jelement;
+		json_object *jmodels;
+		json_object *jvalue;
+		struct mesh_db_element *ele;
+		int index;
+		char *str;
+
+		jelement = json_object_array_get_idx(jelements, i);
+		if (!jelement)
+			goto fail;
+
+		if (!get_int(jelement, "elementIndex", &index) ||
+								index > num_ele)
+			goto fail;
+
+		ele = l_new(struct mesh_db_element, 1);
+		if (!ele)
+			goto fail;
+
+		ele->index = index;
+		ele->models = l_queue_new();
+		if (!ele->models)
+			goto fail;
+
+		json_object_object_get_ex(jelement, "location", &jvalue);
+		str = (char *)json_object_get_string(jvalue);
+		if (sscanf(str, "%04hx", &(ele->location)) != 1)
+			goto fail;
+
+		json_object_object_get_ex(jelement, "models", &jmodels);
+
+		if (jmodels && (json_object_get_type(jmodels) != json_type_array
+				|| !parse_models(jmodels, ele)))
+			goto fail;
+
+		l_queue_push_tail(node->elements, ele);
+	}
+
+	return true;
+
+fail:
+	l_queue_destroy(node->elements, free_element);
+	node->elements = NULL;
+
+	return false;
+}
+
+static int get_mode(json_object *jvalue)
+{
+	const char *str;
+
+	str = json_object_get_string(jvalue);
+	if (!str)
+		return 0xffffffff;
+
+	if (!strncasecmp(str, "disabled", strlen("disabled")))
+		return MESH_MODE_DISABLED;
+
+	if (!strncasecmp(str, "enabled", strlen("enabled")))
+		return MESH_MODE_ENABLED;
+
+	if (!strncasecmp(str, "unsupported", strlen("unsupported")))
+		return MESH_MODE_UNSUPPORTED;
+
+	return 0xffffffff;
+}
+
+static void parse_features(json_object *jconfig, struct mesh_db_node *node)
+{
+	json_object *jvalue, *jrelay;
+	int mode, count;
+	uint16_t interval;
+
+	json_object_object_get_ex(jconfig, "proxy", &jvalue);
+	if (jvalue) {
+		mode = get_mode(jvalue);
+		if (mode <= MESH_MODE_UNSUPPORTED)
+			node->modes.proxy = mode;
+	}
+
+	json_object_object_get_ex(jconfig, "friend", &jvalue);
+	if (jvalue) {
+		mode = get_mode(jvalue);
+		if (mode <= MESH_MODE_UNSUPPORTED)
+			node->modes.friend = mode;
+	}
+
+	json_object_object_get_ex(jconfig, "lowPower", &jvalue);
+	if (jvalue) {
+		mode = get_mode(jvalue);
+		if (mode <= MESH_MODE_UNSUPPORTED)
+			node->modes.friend = mode;
+	}
+
+	json_object_object_get_ex(jconfig, "beacon", &jvalue);
+	if (jvalue) {
+		mode = get_mode(jvalue);
+		if (mode <= MESH_MODE_ENABLED)
+			node->modes.beacon = mode;
+	}
+
+	json_object_object_get_ex(jconfig, "relay", &jrelay);
+	if (!jrelay)
+		return;
+
+	json_object_object_get_ex(jrelay, "mode", &jvalue);
+	if (jvalue) {
+		mode = get_mode(jvalue);
+		if (mode <= MESH_MODE_UNSUPPORTED)
+			node->modes.relay.state = mode;
+		else
+			return;
+	} else
+		return;
+
+	json_object_object_get_ex(jrelay, "count", &jvalue);
+	if (!jvalue)
+		return;
+
+	/* TODO: check range */
+	count = json_object_get_int(jvalue);
+	node->modes.relay.cnt = count;
+
+	json_object_object_get_ex(jrelay, "interval", &jvalue);
+	if (!jvalue)
+		return;
+
+	/* TODO: check range */
+	interval = json_object_get_int(jvalue);
+	node->modes.relay.interval = interval;
+}
+
+static bool parse_composition(json_object *jcomp, struct mesh_db_node *node)
+{
+	json_object *jvalue;
+	char *str;
+
+	/* All the fields in node composition are mandatory */
+	json_object_object_get_ex(jcomp, "cid", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (sscanf(str, "%04hx", &node->cid) != 1)
+		return false;
+
+	json_object_object_get_ex(jcomp, "pid", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (sscanf(str, "%04hx", &node->pid) != 1)
+		return false;
+
+	json_object_object_get_ex(jcomp, "vid", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (sscanf(str, "%04hx", &node->vid) != 1)
+		return false;
+
+	json_object_object_get_ex(jcomp, "crpl", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (sscanf(str, "%04hx", &node->crpl) != 1)
+		return false;
+
+	return true;
+}
+
+static uint16_t get_prov_flags(json_object *jarray, uint16_t max_value)
+{
+	int i, cnt;
+	uint16_t result = 0;
+
+	cnt = json_object_array_length(jarray);
+	if (!cnt)
+		return 0;
+
+	for (i = 0; i < cnt; ++i) {
+		json_object *jvalue;
+		int value;
+
+		jvalue = json_object_array_get_idx(jarray, i);
+		value = json_object_get_int(jvalue);
+		if (value > 16)
+			continue;
+
+		if ((1 << value) > max_value)
+			continue;
+
+		result |= (1 << value);
+	}
+
+	return result;
+}
+
+bool mesh_db_read_node(json_object *jnode, mesh_db_node_cb cb, void *user_data)
+{
+	struct mesh_db_node node;
+	json_object *jvalue;
+	char *str;
+
+	if (!cb) {
+		l_info("Node read callback is required");
+		return false;
+	}
+
+	memset(&node, 0, sizeof(node));
+
+	if (!parse_composition(jnode, &node)) {
+		l_info("Failed to parse local node composition");
+		return false;
+	}
+
+	parse_features(jnode, &node);
+
+	json_object_object_get_ex(jnode, "unicastAddress", &jvalue);
+	if (!jvalue) {
+		l_info("Bad config: Unicast address must be present");
+		return false;
+	}
+
+	str = (char *)json_object_get_string(jvalue);
+	if (sscanf(str, "%04hx", &node.unicast) != 1)
+		return false;
+
+	json_object_object_get_ex(jnode, "defaultTTL", &jvalue);
+	if (jvalue) {
+		int ttl = json_object_get_int(jvalue);
+
+		if (ttl < 0 || ttl == 1 || ttl > DEFAULT_TTL)
+			return false;
+		node.ttl = (uint8_t) ttl;
+	}
+
+	json_object_object_get_ex(jnode, "sequenceNumber", &jvalue);
+	if (jvalue)
+		node.seq_number = json_object_get_int(jvalue);
+
+	json_object_object_get_ex(jnode, "elements", &jvalue);
+	if (jvalue && json_object_get_type(jvalue) == json_type_array) {
+		if (!parse_elements(jvalue, &node))
+			return false;
+	}
+
+	return cb(&node, user_data);
+}
+
+bool mesh_db_read_unprovisioned_device(json_object *jnode, mesh_db_node_cb cb,
+								void *user_data)
+{
+	struct mesh_db_node node;
+	json_object *jvalue;
+	char *str;
+
+	if (!cb) {
+		l_info("Device read callback is required");
+		return false;
+	}
+
+	memset(&node, 0, sizeof(node));
+
+	if (!parse_composition(jnode, &node)) {
+		l_info("Failed to parse local device composition");
+		return false;
+	}
+
+	parse_features(jnode, &node);
+
+	json_object_object_get_ex(jnode, "elements", &jvalue);
+	if (jvalue && json_object_get_type(jvalue) == json_type_array) {
+		if (!parse_elements(jvalue, &node))
+			return false;
+	}
+
+	json_object_object_get_ex(jnode, "UUID", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (!str2hex(str, strlen(str), node.uuid, 16))
+		return false;
+
+	return cb(&node, user_data);
+}
+
+bool mesh_db_read_prov_info(json_object *jnode, struct mesh_db_prov *prov)
+{
+	json_object *jprov, *jarray, *jvalue, *jobj;
+	int value;
+	char *str;
+
+	if (!prov)
+		return false;
+
+	json_object_object_get_ex(jnode, "provision", &jprov);
+	if (!jprov)
+		return false;
+
+	json_object_object_get_ex(jprov, "algorithms", &jarray);
+	if (!jarray || json_object_get_type(jarray) != json_type_array)
+		return false;
+
+	prov->algorithm = get_prov_flags(jarray, ALG_FIPS_256_ECC);
+	if (!prov->algorithm) {
+		l_info("At least one algorithm must be indicated");
+		return false;
+	}
+
+	json_object_object_get_ex(jprov, "outputOOB", &jobj);
+	json_object_object_get_ex(jobj, "size", &jvalue);
+	value = json_object_get_int(jvalue);
+	if (value > 8)
+		return false;
+
+	prov->output_oob.size = (uint8_t) value;
+	json_object_object_get_ex(jobj, "actions", &jarray);
+	if (!jarray || json_object_get_type(jarray) != json_type_array)
+		return false;
+
+	prov->output_oob.actions = get_prov_flags(jarray, OOB_OUT_ALPHA);
+
+	json_object_object_get_ex(jprov, "inputOOB", &jobj);
+	json_object_object_get_ex(jobj, "size", &jvalue);
+	value = json_object_get_int(jvalue);
+	if (value > 8)
+		return false;
+
+	prov->input_oob.size = (uint8_t) value;
+	json_object_object_get_ex(jobj, "actions", &jarray);
+	if (!jarray || json_object_get_type(jarray) != json_type_array)
+		return false;
+
+	prov->input_oob.actions = get_prov_flags(jarray, OOB_IN_ALPHA);
+
+	json_object_object_get_ex(jprov, "publicType", &jvalue);
+	prov->pub_type = (json_object_get_boolean(jvalue)) ? 1 : 0;
+
+	json_object_object_get_ex(jprov, "staticType", &jvalue);
+	prov->static_type = (json_object_get_boolean(jvalue)) ? 1 : 0;
+
+	json_object_object_get_ex(jprov, "privateKey", &jvalue);
+	if (!jvalue)
+		return false;
+
+	str = (char *)json_object_get_string(jvalue);
+	if (!str2hex(str, strlen(str), prov->priv_key, 32))
+		return false;
+
+	return true;
+}
+
+bool mesh_db_write_uint16_hex(json_object *jobj, const char *desc,
+								uint16_t value)
+{
+	json_object *jstring;
+	char buf[5];
+
+	snprintf(buf, 5, "%4.4x", value);
+	jstring = json_object_new_string(buf);
+	if (!jstring)
+		return false;
+
+	json_object_object_add(jobj, desc, jstring);
+	return true;
+}
+
+bool mesh_db_write_int(json_object *jobj, const char *keyword, int value)
+{
+	json_object *jvalue;
+
+	json_object_object_del(jobj, keyword);
+
+	jvalue = json_object_new_int(value);
+	if (!jvalue)
+		return false;
+
+	json_object_object_add(jobj, keyword, jvalue);
+	return true;
+}
+
+bool mesh_db_write_bool(json_object *jobj, const char *keyword, bool value)
+{
+	json_object *jvalue;
+
+	json_object_object_del(jobj, keyword);
+
+	jvalue = json_object_new_boolean(value);
+	if (!jvalue)
+		return false;
+
+	json_object_object_add(jobj, keyword, jvalue);
+	return true;
+}
+
+bool mesh_db_write_mode(json_object *jobj, const char *keyword, int value)
+{
+	json_object *jstring;
+
+	switch (value) {
+	case MESH_MODE_DISABLED:
+		jstring = json_object_new_string("disabled");
+		break;
+	case MESH_MODE_ENABLED:
+		jstring = json_object_new_string("enabled");
+		break;
+	case MESH_MODE_UNSUPPORTED:
+		jstring = json_object_new_string("unsupported");
+		break;
+	default:
+		return false;
+	};
+
+	if (!jstring)
+		return false;
+
+	json_object_object_add(jobj, keyword, jstring);
+
+	return true;
+}
+
+bool mesh_db_write_relay_mode(json_object *jnode, uint8_t mode, uint8_t count,
+							uint16_t interval)
+{
+	json_object *jrelay;
+
+	json_object_object_del(jnode, "relay");
+
+	jrelay = json_object_new_object();
+	if (jrelay)
+		return false;
+
+	if (!mesh_db_write_mode(jrelay, "mode", mode))
+		goto fail;
+
+	if (!mesh_db_write_int(jrelay, "count", count))
+		goto fail;
+
+	if (!mesh_db_write_int(jrelay, "interval", interval))
+		goto fail;
+
+	json_object_object_add(jnode, "relay", jrelay);
+
+	return true;
+fail:
+	json_object_put(jrelay);
+	return false;
+}
+
+bool mesh_db_read_net_transmit(json_object *jobj, uint8_t *cnt,
+							uint16_t *interval)
+{
+	json_object *jretransmit, *jvalue;
+
+	json_object_object_get_ex(jobj, "retransmit", &jretransmit);
+	if (!jretransmit)
+		return false;
+
+	json_object_object_get_ex(jretransmit, "count", &jvalue);
+	if (!jvalue)
+		return false;
+
+	*cnt = (uint8_t) json_object_get_int(jvalue);
+
+	json_object_object_get_ex(jretransmit, "interval", &jvalue);
+	if (!jvalue)
+		return false;
+
+	*interval = (uint16_t) json_object_get_int(jvalue);
+
+	return true;
+}
+
+bool mesh_db_write_net_transmit(json_object *jobj, uint8_t cnt,
+							uint16_t interval)
+{
+	json_object *jretransmit;
+
+	json_object_object_del(jobj, "retransmit");
+
+	jretransmit = json_object_new_object();
+	if (jretransmit)
+		return false;
+
+	if (!mesh_db_write_int(jretransmit, "count", cnt))
+		goto fail;
+
+	if (!mesh_db_write_int(jretransmit, "interval", interval))
+		goto fail;
+
+	json_object_object_add(jobj, "retransmit", jretransmit);
+
+	return true;
+fail:
+	json_object_put(jretransmit);
+	return false;
+
+}
+
+bool mesh_db_write_iv_index(json_object *jobj, uint32_t idx, bool update)
+{
+	int tmp = update ? 1 : 0;
+
+	if (!mesh_db_write_int(jobj, "IVindex", idx))
+		return false;
+
+	if (!mesh_db_write_int(jobj, "IVupdate", tmp))
+		return false;
+
+	return true;
+}
+
+void mesh_db_remove_property(json_object *jobj, const char *desc)
+{
+	json_object_object_del(jobj, desc);
+}
meshd/mesh-json/mesh-db.h new file +144 -0

144 lines not on this page · raw message

Signature · 1 line
2.14.3
author
#8 lore raw

PATCH v2 10/11 meshd: Sample device composition in JSON fromat

In reply to Brian Gix

From: Inga Stotland <[email protected]>

This is a sample unprovisioned device composition described in JSON format.

---
 meshd/config/composition.json | 44 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
 create mode 100644 meshd/config/composition.json
meshd/config/composition.json new file +44 -0
new file mode 100644
index 000000000..20c0d0c3a
@@ -0,0 +1,44 @@
+{
+  "$schema":"file:\/\/\/BlueZ\/MeshD\/local_schema\/mesh.jsonschema",
+  "meshName":"BT Mesh sample node",
+  "UUID":"E0ED0F0200000000203C100200000000",
+  "cid":"0002",
+  "pid":"0010",
+  "vid":"0001",
+  "crpl":"000a",
+  "proxy":"unsupported",
+  "friend":"disabled",
+  "lowPower":"disabled",
+  "relay":{
+    "mode":"enabled"
+  },
+  "elements":[
+    {
+      "elementIndex":0,
+      "location":"0001",
+      "models":[
+        {
+          "modelId":"0000"
+        },
+        {
+          "modelId":"1001"
+        }
+      ]
+    }
+  ],
+  "provision": {
+    "privateKey": "729aa0670d72cd6497502ed473502b037e8803b5c60829a5a3caa219505530ba",
+    "algorithms": [ 0 ],
+	"inputOOB": {
+       "size": 8,
+       "actions": [ 2, 3]
+    },
+    "outputOOB": {
+      "size": 8,
+      "actions": [ 3, 4]
+    },
+    "publicType": false,
+    "staticType": false
+  },
+   }
+}
Signature · 1 line
2.14.3
author
#9 lore raw

PATCH v2 11/11 Makefile for meshd and configure.ac

In reply to Brian Gix

From: Inga Stotland <[email protected]>

---
 Makefile.am    |  1 +
 Makefile.meshd | 44 ++++++++++++++++++++++++++++++++++++++++++++
 configure.ac   |  2 +-
 3 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 Makefile.meshd
Makefile.am +1 -0
index daf34b6ca..2a96fa1d3 100644
@@ -225,6 +225,7 @@ unit_tests =
 include Makefile.tools
 include Makefile.obexd
 include android/Makefile.am
+include Makefile.meshd
 
 if HID2HCI
 rulesdir = @UDEV_DIR@/rules.d
Makefile.meshd new file +44 -0

44 lines not on this page · raw message

configure.ac +1 -1
index 5132131f2..f6259c0fe 100644
@@ -248,7 +248,7 @@ AC_ARG_ENABLE(btpclient, AC_HELP_STRING([--enable-btpclient],
 		[enable BTP client]), [enable_btpclient=${enableval}])
 AM_CONDITIONAL(BTPCLIENT, test "${enable_btpclient}" = "yes")
 
-if (test "${enable_btpclient}" = "yes"); then
+if (test "${enable_btpclient}" = "yes" || test "${enable_mesh}" == "yes"); then
 	PKG_CHECK_MODULES(ELL, ell >= 0.3, dummy=yes,
 			  AC_MSG_ERROR(ell library >= 0.3 is required))
 	AC_SUBST(ELL_CFLAGS)
Signature · 1 line
2.14.3