1 /*
2 * Copyright (c) 2017 Intel Corporation
3 * Copyright (c) 2021 Lingao Meng
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8 #include <zephyr/kernel.h>
9 #include <zephyr/sys/byteorder.h>
10 #include <zephyr/sys/iterable_sections.h>
11 #include <zephyr/net/buf.h>
12 #include <zephyr/bluetooth/bluetooth.h>
13 #include <zephyr/bluetooth/conn.h>
14 #include <zephyr/bluetooth/gatt.h>
15 #include <zephyr/bluetooth/mesh.h>
16 #include <zephyr/sys/util.h>
17
18 #include <zephyr/bluetooth/hci.h>
19
20 #include "common/bt_str.h"
21
22 #include "mesh.h"
23 #include "net.h"
24 #include "rpl.h"
25 #include "transport.h"
26 #include "prov.h"
27 #include "beacon.h"
28 #include "foundation.h"
29 #include "access.h"
30 #include "proxy.h"
31 #include "proxy_msg.h"
32 #include "crypto.h"
33
34 #define LOG_LEVEL CONFIG_BT_MESH_PROXY_LOG_LEVEL
35 #include <zephyr/logging/log.h>
36 LOG_MODULE_REGISTER(bt_mesh_gatt);
37
38 #define PROXY_SVC_INIT_TIMEOUT K_MSEC(10)
39 #define PROXY_SVC_REG_ATTEMPTS 5
40
41 /* Interval to update random value in (10 minutes).
42 *
43 * Defined in the Bluetooth Mesh Specification v1.1, Section 7.2.2.2.4.
44 */
45 #define PROXY_RANDOM_UPDATE_INTERVAL (10 * 60 * MSEC_PER_SEC)
46
47 #define ADV_OPT_ADDR(private) (IS_ENABLED(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR) ? \
48 BT_LE_ADV_OPT_USE_IDENTITY : (private) ? BT_LE_ADV_OPT_USE_NRPA : 0)
49
50 #define ADV_OPT_PROXY(private) \
51 (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_SCANNABLE | ADV_OPT_ADDR(private) | \
52 BT_LE_ADV_OPT_ONE_TIME)
53
54 static void proxy_send_beacons(struct k_work *work);
55 static int proxy_send(struct bt_conn *conn,
56 const void *data, uint16_t len,
57 bt_gatt_complete_func_t end, void *user_data);
58
59 static struct bt_mesh_proxy_client {
60 struct bt_mesh_proxy_role *cli;
61 uint16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE];
62 enum __packed {
63 NONE,
64 ACCEPT,
65 REJECT,
66 } filter_type;
67 struct k_work send_beacons;
68 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
69 bool privacy;
70 #endif
71 } clients[CONFIG_BT_MAX_CONN] = {
72 [0 ... (CONFIG_BT_MAX_CONN - 1)] = {
73 .send_beacons = Z_WORK_INITIALIZER(proxy_send_beacons),
74 },
75 };
76
77 static bool service_registered;
78
find_client(struct bt_conn * conn)79 static struct bt_mesh_proxy_client *find_client(struct bt_conn *conn)
80 {
81 return &clients[bt_conn_index(conn)];
82 }
83
gatt_recv(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)84 static ssize_t gatt_recv(struct bt_conn *conn,
85 const struct bt_gatt_attr *attr, const void *buf,
86 uint16_t len, uint16_t offset, uint8_t flags)
87 {
88 const uint8_t *data = buf;
89
90 if (len < 1) {
91 LOG_WRN("Too small Proxy PDU");
92 return -EINVAL;
93 }
94
95 if (PDU_TYPE(data) == BT_MESH_PROXY_PROV) {
96 LOG_WRN("Proxy PDU type doesn't match GATT service");
97 return -EINVAL;
98 }
99
100 return bt_mesh_proxy_msg_recv(conn, buf, len);
101 }
102
103 /* Next subnet in queue to be advertised */
104 static struct bt_mesh_subnet *beacon_sub;
105
filter_set(struct bt_mesh_proxy_client * client,struct net_buf_simple * buf)106 static int filter_set(struct bt_mesh_proxy_client *client,
107 struct net_buf_simple *buf)
108 {
109 uint8_t type;
110
111 if (buf->len < 1) {
112 LOG_WRN("Too short Filter Set message");
113 return -EINVAL;
114 }
115
116 type = net_buf_simple_pull_u8(buf);
117 LOG_DBG("type 0x%02x", type);
118
119 switch (type) {
120 case 0x00:
121 (void)memset(client->filter, 0, sizeof(client->filter));
122 client->filter_type = ACCEPT;
123 break;
124 case 0x01:
125 (void)memset(client->filter, 0, sizeof(client->filter));
126 client->filter_type = REJECT;
127 break;
128 default:
129 LOG_WRN("Prohibited Filter Type 0x%02x", type);
130 return -EINVAL;
131 }
132
133 return 0;
134 }
135
filter_add(struct bt_mesh_proxy_client * client,uint16_t addr)136 static void filter_add(struct bt_mesh_proxy_client *client, uint16_t addr)
137 {
138 int i;
139
140 LOG_DBG("addr 0x%04x", addr);
141
142 if (addr == BT_MESH_ADDR_UNASSIGNED) {
143 return;
144 }
145
146 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
147 if (client->filter[i] == addr) {
148 return;
149 }
150 }
151
152 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
153 if (client->filter[i] == BT_MESH_ADDR_UNASSIGNED) {
154 client->filter[i] = addr;
155 return;
156 }
157 }
158 }
159
filter_remove(struct bt_mesh_proxy_client * client,uint16_t addr)160 static void filter_remove(struct bt_mesh_proxy_client *client, uint16_t addr)
161 {
162 int i;
163
164 LOG_DBG("addr 0x%04x", addr);
165
166 if (addr == BT_MESH_ADDR_UNASSIGNED) {
167 return;
168 }
169
170 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
171 if (client->filter[i] == addr) {
172 client->filter[i] = BT_MESH_ADDR_UNASSIGNED;
173 return;
174 }
175 }
176 }
177
send_filter_status(struct bt_mesh_proxy_client * client,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)178 static void send_filter_status(struct bt_mesh_proxy_client *client,
179 struct bt_mesh_net_rx *rx,
180 struct net_buf_simple *buf)
181 {
182 struct bt_mesh_net_tx tx = {
183 .sub = rx->sub,
184 .ctx = &rx->ctx,
185 .src = bt_mesh_primary_addr(),
186 };
187 uint16_t filter_size;
188 int i, err;
189
190 /* Configuration messages always have dst unassigned */
191 tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED;
192
193 net_buf_simple_reset(buf);
194 net_buf_simple_reserve(buf, 10);
195
196 net_buf_simple_add_u8(buf, CFG_FILTER_STATUS);
197
198 if (client->filter_type == ACCEPT) {
199 net_buf_simple_add_u8(buf, 0x00);
200 } else {
201 net_buf_simple_add_u8(buf, 0x01);
202 }
203
204 for (filter_size = 0U, i = 0; i < ARRAY_SIZE(client->filter); i++) {
205 if (client->filter[i] != BT_MESH_ADDR_UNASSIGNED) {
206 filter_size++;
207 }
208 }
209
210 net_buf_simple_add_be16(buf, filter_size);
211
212 LOG_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
213
214 err = bt_mesh_net_encode(&tx, buf, BT_MESH_NONCE_PROXY);
215 if (err) {
216 LOG_ERR("Encoding Proxy cfg message failed (err %d)", err);
217 return;
218 }
219
220 err = bt_mesh_proxy_msg_send(client->cli->conn, BT_MESH_PROXY_CONFIG,
221 buf, NULL, NULL);
222 if (err) {
223 LOG_ERR("Failed to send proxy cfg message (err %d)", err);
224 }
225 }
226
proxy_filter_recv(struct bt_conn * conn,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)227 static void proxy_filter_recv(struct bt_conn *conn,
228 struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
229 {
230 struct bt_mesh_proxy_client *client;
231 uint8_t opcode;
232
233 client = find_client(conn);
234
235 opcode = net_buf_simple_pull_u8(buf);
236 switch (opcode) {
237 case CFG_FILTER_SET:
238 filter_set(client, buf);
239 send_filter_status(client, rx, buf);
240 break;
241 case CFG_FILTER_ADD:
242 while (buf->len >= 2) {
243 uint16_t addr;
244
245 addr = net_buf_simple_pull_be16(buf);
246 filter_add(client, addr);
247 }
248 send_filter_status(client, rx, buf);
249 break;
250 case CFG_FILTER_REMOVE:
251 while (buf->len >= 2) {
252 uint16_t addr;
253
254 addr = net_buf_simple_pull_be16(buf);
255 filter_remove(client, addr);
256 }
257 send_filter_status(client, rx, buf);
258 break;
259 default:
260 LOG_WRN("Unhandled configuration OpCode 0x%02x", opcode);
261 break;
262 }
263 }
264
proxy_cfg(struct bt_mesh_proxy_role * role)265 static void proxy_cfg(struct bt_mesh_proxy_role *role)
266 {
267 NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
268 struct bt_mesh_net_rx rx;
269 int err;
270
271 err = bt_mesh_net_decode(&role->buf, BT_MESH_NET_IF_PROXY_CFG,
272 &rx, &buf);
273 if (err) {
274 LOG_ERR("Failed to decode Proxy Configuration (err %d)", err);
275 return;
276 }
277
278 rx.local_match = 1U;
279
280 if (bt_mesh_rpl_check(&rx, NULL)) {
281 LOG_WRN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", rx.ctx.addr, rx.ctx.recv_dst,
282 rx.seq);
283 return;
284 }
285
286 /* Remove network headers */
287 net_buf_simple_pull(&buf, BT_MESH_NET_HDR_LEN);
288
289 LOG_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len));
290
291 if (buf.len < 1) {
292 LOG_WRN("Too short proxy configuration PDU");
293 return;
294 }
295
296 proxy_filter_recv(role->conn, &rx, &buf);
297 }
298
proxy_msg_recv(struct bt_mesh_proxy_role * role)299 static void proxy_msg_recv(struct bt_mesh_proxy_role *role)
300 {
301 switch (role->msg_type) {
302 case BT_MESH_PROXY_NET_PDU:
303 LOG_DBG("Mesh Network PDU");
304 bt_mesh_net_recv(&role->buf, 0, BT_MESH_NET_IF_PROXY);
305 break;
306 case BT_MESH_PROXY_BEACON:
307 LOG_DBG("Mesh Beacon PDU");
308 bt_mesh_beacon_recv(&role->buf);
309 break;
310 case BT_MESH_PROXY_CONFIG:
311 LOG_DBG("Mesh Configuration PDU");
312 proxy_cfg(role);
313 break;
314 default:
315 LOG_WRN("Unhandled Message Type 0x%02x", role->msg_type);
316 break;
317 }
318 }
319
beacon_send(struct bt_mesh_proxy_client * client,struct bt_mesh_subnet * sub)320 static int beacon_send(struct bt_mesh_proxy_client *client,
321 struct bt_mesh_subnet *sub)
322 {
323 int err;
324
325 NET_BUF_SIMPLE_DEFINE(buf, 28);
326
327 net_buf_simple_reserve(&buf, 1);
328
329 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
330 err = bt_mesh_beacon_create(sub, &buf, client->privacy);
331 #else
332 err = bt_mesh_beacon_create(sub, &buf, false);
333 #endif
334 if (err) {
335 return err;
336 }
337
338 return bt_mesh_proxy_msg_send(client->cli->conn, BT_MESH_PROXY_BEACON,
339 &buf, NULL, NULL);
340 }
341
send_beacon_cb(struct bt_mesh_subnet * sub,void * cb_data)342 static bool send_beacon_cb(struct bt_mesh_subnet *sub, void *cb_data)
343 {
344 struct bt_mesh_proxy_client *client = cb_data;
345
346 return beacon_send(client, sub) != 0;
347 }
348
proxy_send_beacons(struct k_work * work)349 static void proxy_send_beacons(struct k_work *work)
350 {
351 struct bt_mesh_proxy_client *client;
352
353 client = CONTAINER_OF(work, struct bt_mesh_proxy_client, send_beacons);
354
355 (void)bt_mesh_subnet_find(send_beacon_cb, client);
356 }
357
bt_mesh_proxy_beacon_send(struct bt_mesh_subnet * sub)358 void bt_mesh_proxy_beacon_send(struct bt_mesh_subnet *sub)
359 {
360 int i;
361
362 if (!sub) {
363 /* NULL means we send on all subnets */
364 bt_mesh_subnet_foreach(bt_mesh_proxy_beacon_send);
365 return;
366 }
367
368 for (i = 0; i < ARRAY_SIZE(clients); i++) {
369 if (clients[i].cli) {
370 beacon_send(&clients[i], sub);
371 }
372 }
373 }
374
identity_enabled(struct bt_mesh_subnet * sub)375 static void identity_enabled(struct bt_mesh_subnet *sub)
376 {
377 sub->node_id = BT_MESH_NODE_IDENTITY_RUNNING;
378 sub->node_id_start = k_uptime_get_32();
379
380 STRUCT_SECTION_FOREACH(bt_mesh_proxy_cb, cb) {
381 if (cb->identity_enabled) {
382 cb->identity_enabled(sub->net_idx);
383 }
384 }
385 }
386
node_id_start(struct bt_mesh_subnet * sub)387 static void node_id_start(struct bt_mesh_subnet *sub)
388 {
389 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
390 sub->priv_beacon_ctx.node_id = false;
391 #endif
392
393 identity_enabled(sub);
394 }
395
private_node_id_start(struct bt_mesh_subnet * sub)396 static void private_node_id_start(struct bt_mesh_subnet *sub)
397 {
398 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
399 sub->priv_beacon_ctx.node_id = true;
400 #endif
401
402 identity_enabled(sub);
403 }
404
bt_mesh_proxy_identity_start(struct bt_mesh_subnet * sub,bool private)405 void bt_mesh_proxy_identity_start(struct bt_mesh_subnet *sub, bool private)
406 {
407 if (private) {
408 private_node_id_start(sub);
409 } else {
410 node_id_start(sub);
411 }
412
413 /* Prioritize the recently enabled subnet */
414 beacon_sub = sub;
415 }
416
bt_mesh_proxy_identity_stop(struct bt_mesh_subnet * sub)417 void bt_mesh_proxy_identity_stop(struct bt_mesh_subnet *sub)
418 {
419 sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
420 sub->node_id_start = 0U;
421
422 STRUCT_SECTION_FOREACH(bt_mesh_proxy_cb, cb) {
423 if (cb->identity_disabled) {
424 cb->identity_disabled(sub->net_idx);
425 }
426 }
427 }
428
bt_mesh_proxy_identity_enable(void)429 int bt_mesh_proxy_identity_enable(void)
430 {
431 LOG_DBG("");
432
433 if (!bt_mesh_is_provisioned()) {
434 return -EAGAIN;
435 }
436
437 if (bt_mesh_subnet_foreach(node_id_start)) {
438 bt_mesh_adv_gatt_update();
439 }
440
441 return 0;
442 }
443
bt_mesh_proxy_private_identity_enable(void)444 int bt_mesh_proxy_private_identity_enable(void)
445 {
446 LOG_DBG("");
447
448 if (!IS_ENABLED(CONFIG_BT_MESH_PRIV_BEACONS)) {
449 return -ENOTSUP;
450 }
451
452 if (!bt_mesh_is_provisioned()) {
453 return -EAGAIN;
454 }
455
456 if (bt_mesh_subnet_foreach(private_node_id_start)) {
457 bt_mesh_adv_gatt_update();
458 }
459
460 return 0;
461 }
462
463 #define ENC_ID_LEN 19
464 #define NET_ID_LEN 11
465
466 #define NODE_ID_TIMEOUT (CONFIG_BT_MESH_NODE_ID_TIMEOUT * MSEC_PER_SEC)
467
468 static uint8_t proxy_svc_data[ENC_ID_LEN] = {
469 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL),
470 };
471
472 static const struct bt_data enc_id_ad[] = {
473 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
474 BT_DATA_BYTES(BT_DATA_UUID16_ALL,
475 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL)),
476 BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, ENC_ID_LEN),
477 };
478
479 static const struct bt_data net_id_ad[] = {
480 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
481 BT_DATA_BYTES(BT_DATA_UUID16_ALL,
482 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL)),
483 BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NET_ID_LEN),
484 };
485
486 static const struct bt_data sd[] = {
487 #if defined(CONFIG_BT_MESH_PROXY_USE_DEVICE_NAME)
488 BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
489 #endif
490 };
491
randomize_bt_addr(void)492 static int randomize_bt_addr(void)
493 {
494 /* TODO: There appears to be no way to force an RPA/NRPA refresh. */
495 return 0;
496 }
497
enc_id_adv(struct bt_mesh_subnet * sub,uint8_t type,uint8_t hash[16],int32_t duration)498 static int enc_id_adv(struct bt_mesh_subnet *sub, uint8_t type,
499 uint8_t hash[16], int32_t duration)
500 {
501 struct bt_le_adv_param slow_adv_param = {
502 .id = BT_ID_DEFAULT,
503 .options = ADV_OPT_PROXY(type == BT_MESH_ID_TYPE_PRIV_NET ||
504 type == BT_MESH_ID_TYPE_PRIV_NODE),
505 ADV_SLOW_INT,
506 };
507 struct bt_le_adv_param fast_adv_param = {
508 .id = BT_ID_DEFAULT,
509 .options = ADV_OPT_PROXY(type == BT_MESH_ID_TYPE_PRIV_NET ||
510 type == BT_MESH_ID_TYPE_PRIV_NODE),
511 ADV_FAST_INT,
512 };
513 int err;
514
515 err = bt_mesh_encrypt(&sub->keys[SUBNET_KEY_TX_IDX(sub)].identity, hash, hash);
516 if (err) {
517 return err;
518 }
519
520 /* MshPRTv1.1: 7.2.2.2.4: The AdvA field shall be regenerated whenever the Random field is
521 * regenerated.
522 */
523 err = randomize_bt_addr();
524 if (err) {
525 LOG_ERR("AdvA refresh failed: %d", err);
526 return err;
527 }
528
529 proxy_svc_data[2] = type;
530 memcpy(&proxy_svc_data[3], &hash[8], 8);
531
532 err = bt_mesh_adv_gatt_start(
533 type == BT_MESH_ID_TYPE_PRIV_NET ? &slow_adv_param : &fast_adv_param,
534 duration, enc_id_ad, ARRAY_SIZE(enc_id_ad), sd, ARRAY_SIZE(sd));
535 if (err) {
536 LOG_WRN("Failed to advertise using type 0x%02x (err %d)", type, err);
537 return err;
538 }
539
540 return 0;
541 }
542
node_id_adv(struct bt_mesh_subnet * sub,int32_t duration)543 static int node_id_adv(struct bt_mesh_subnet *sub, int32_t duration)
544 {
545 uint8_t *random = &proxy_svc_data[11];
546 uint8_t tmp[16];
547 int err;
548
549 LOG_DBG("0x%03x", sub->net_idx);
550
551 err = bt_rand(random, 8);
552 if (err) {
553 return err;
554 }
555
556 memset(&tmp[0], 0x00, 6);
557 memcpy(&tmp[6], random, 8);
558 sys_put_be16(bt_mesh_primary_addr(), &tmp[14]);
559
560 return enc_id_adv(sub, BT_MESH_ID_TYPE_NODE, tmp, duration);
561 }
562
priv_node_id_adv(struct bt_mesh_subnet * sub,int32_t duration)563 static int priv_node_id_adv(struct bt_mesh_subnet *sub, int32_t duration)
564 {
565 uint8_t *random = &proxy_svc_data[11];
566 uint8_t tmp[16];
567 int err;
568
569 LOG_DBG("0x%03x", sub->net_idx);
570
571 err = bt_rand(random, 8);
572 if (err) {
573 return err;
574 }
575
576 memset(&tmp[0], 0x00, 5);
577 tmp[5] = 0x03;
578 memcpy(&tmp[6], random, 8);
579 sys_put_be16(bt_mesh_primary_addr(), &tmp[14]);
580
581 return enc_id_adv(sub, BT_MESH_ID_TYPE_PRIV_NODE, tmp, duration);
582 }
583
priv_net_id_adv(struct bt_mesh_subnet * sub,int32_t duration)584 static int priv_net_id_adv(struct bt_mesh_subnet *sub, int32_t duration)
585 {
586 uint8_t *random = &proxy_svc_data[11];
587 uint8_t tmp[16];
588 int err;
589
590 LOG_DBG("0x%03x", sub->net_idx);
591
592 err = bt_rand(random, 8);
593 if (err) {
594 return err;
595 }
596
597 memcpy(&tmp[0], sub->keys[SUBNET_KEY_TX_IDX(sub)].net_id, 8);
598 memcpy(&tmp[8], random, 8);
599
600 return enc_id_adv(sub, BT_MESH_ID_TYPE_PRIV_NET, tmp, duration);
601 }
602
net_id_adv(struct bt_mesh_subnet * sub,int32_t duration)603 static int net_id_adv(struct bt_mesh_subnet *sub, int32_t duration)
604 {
605 struct bt_le_adv_param slow_adv_param = {
606 .id = BT_ID_DEFAULT,
607 .options = ADV_OPT_PROXY(false),
608 ADV_SLOW_INT,
609 };
610 int err;
611
612 proxy_svc_data[2] = BT_MESH_ID_TYPE_NET;
613
614 LOG_DBG("Advertising with NetId %s", bt_hex(sub->keys[SUBNET_KEY_TX_IDX(sub)].net_id, 8));
615
616 memcpy(proxy_svc_data + 3, sub->keys[SUBNET_KEY_TX_IDX(sub)].net_id, 8);
617
618 err = bt_mesh_adv_gatt_start(&slow_adv_param, duration, net_id_ad,
619 ARRAY_SIZE(net_id_ad), sd, ARRAY_SIZE(sd));
620 if (err) {
621 LOG_WRN("Failed to advertise using Network ID (err %d)", err);
622 return err;
623 }
624
625 return 0;
626 }
627
is_sub_proxy_active(struct bt_mesh_subnet * sub)628 static bool is_sub_proxy_active(struct bt_mesh_subnet *sub)
629 {
630 if (sub->net_idx == BT_MESH_KEY_UNUSED) {
631 return false;
632 }
633
634 return (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING ||
635 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
636 (bt_mesh_od_priv_proxy_get() > 0 && sub->solicited) ||
637 #endif
638 bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED ||
639 bt_mesh_priv_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED);
640 }
641
active_proxy_sub_cnt_cb(struct bt_mesh_subnet * sub,void * cb_data)642 static bool active_proxy_sub_cnt_cb(struct bt_mesh_subnet *sub, void *cb_data)
643 {
644 int *cnt = cb_data;
645
646 if (is_sub_proxy_active(sub)) {
647 (*cnt)++;
648 }
649
650 /* Don't stop until we've visited all subnets.
651 * We're only using the "find" variant of the subnet iteration to get a context parameter.
652 */
653 return false;
654 }
655
active_proxy_sub_cnt_get(void)656 static int active_proxy_sub_cnt_get(void)
657 {
658 int cnt = 0;
659
660 (void)bt_mesh_subnet_find(active_proxy_sub_cnt_cb, &cnt);
661
662 return cnt;
663 }
664
proxy_adv_timeout_eval(struct bt_mesh_subnet * sub)665 static void proxy_adv_timeout_eval(struct bt_mesh_subnet *sub)
666 {
667 int32_t time_passed;
668
669 if (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING) {
670 time_passed = k_uptime_get_32() - sub->node_id_start;
671 if (time_passed > (NODE_ID_TIMEOUT - MSEC_PER_SEC)) {
672 bt_mesh_proxy_identity_stop(sub);
673 LOG_DBG("Node ID stopped for subnet %d after %dms", sub->net_idx,
674 time_passed);
675 }
676 }
677
678 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
679 if (bt_mesh_od_priv_proxy_get() > 0 && sub->solicited && sub->priv_net_id_sent) {
680 time_passed = k_uptime_get_32() - sub->priv_net_id_sent;
681 if (time_passed > ((MSEC_PER_SEC * bt_mesh_od_priv_proxy_get()) - MSEC_PER_SEC)) {
682 sub->priv_net_id_sent = 0;
683 sub->solicited = false;
684 LOG_DBG("Private Network ID stopped for subnet %d after %dms on "
685 "solicitation",
686 sub->net_idx, time_passed);
687 }
688 }
689 #endif
690 }
691
692 enum proxy_adv_evt {
693 NET_ID,
694 PRIV_NET_ID,
695 NODE_ID,
696 PRIV_NODE_ID,
697 OD_PRIV_NET_ID,
698 };
699
700 struct proxy_adv_request {
701 int32_t duration;
702 enum proxy_adv_evt evt;
703 };
704
proxy_adv_request_get(struct bt_mesh_subnet * sub,struct proxy_adv_request * request)705 static bool proxy_adv_request_get(struct bt_mesh_subnet *sub, struct proxy_adv_request *request)
706 {
707 if (!sub) {
708 return false;
709 }
710
711 if (sub->net_idx == BT_MESH_KEY_UNUSED) {
712 return false;
713 }
714
715 /** The priority for proxy adv is first solicitation, then Node Identity,
716 * and lastly Network ID. Network ID is prioritized last since, in many
717 * cases, another device can fulfill the same demand. Solicitation is
718 * prioritized first since legacy devices are dependent on this to
719 * connect to the network.
720 */
721
722 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
723 if (bt_mesh_od_priv_proxy_get() > 0 && sub->solicited) {
724 int32_t timeout = MSEC_PER_SEC * (int32_t)bt_mesh_od_priv_proxy_get();
725
726 request->evt = OD_PRIV_NET_ID;
727 request->duration = !sub->priv_net_id_sent
728 ? timeout
729 : timeout - (k_uptime_get_32() - sub->priv_net_id_sent);
730 return true;
731 }
732 #endif
733
734 if (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING) {
735 request->duration = NODE_ID_TIMEOUT - (k_uptime_get_32() - sub->node_id_start);
736 request->evt =
737 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
738 sub->priv_beacon_ctx.node_id ? PRIV_NODE_ID :
739 #endif
740 NODE_ID;
741
742 return true;
743 }
744
745 if (bt_mesh_priv_gatt_proxy_get() == BT_MESH_FEATURE_ENABLED) {
746 request->evt = PRIV_NET_ID;
747 request->duration = PROXY_RANDOM_UPDATE_INTERVAL;
748 return true;
749 }
750
751 if (bt_mesh_gatt_proxy_get() == BT_MESH_FEATURE_ENABLED) {
752 request->evt = NET_ID;
753 request->duration = SYS_FOREVER_MS;
754 return true;
755 }
756
757 return false;
758 }
759
adv_sub_get_next(struct bt_mesh_subnet * sub_start,struct proxy_adv_request * request)760 static struct bt_mesh_subnet *adv_sub_get_next(struct bt_mesh_subnet *sub_start,
761 struct proxy_adv_request *request)
762 {
763 struct bt_mesh_subnet *sub_temp = bt_mesh_subnet_next(sub_start);
764
765 do {
766 if (proxy_adv_request_get(sub_temp, request)) {
767 return sub_temp;
768 }
769
770 sub_temp = bt_mesh_subnet_next(sub_temp);
771 } while (sub_temp != sub_start);
772
773 return NULL;
774 }
775
776 static struct {
777 int32_t start;
778 struct bt_mesh_subnet *sub;
779 struct proxy_adv_request request;
780 } sub_adv;
781
gatt_proxy_advertise(void)782 static int gatt_proxy_advertise(void)
783 {
784 int err;
785
786 int32_t max_adv_duration;
787 int cnt;
788 struct bt_mesh_subnet *sub;
789 struct proxy_adv_request request;
790
791 LOG_DBG("");
792
793 /* Close proxy activity that has timed out on all subnets */
794 bt_mesh_subnet_foreach(proxy_adv_timeout_eval);
795
796 if (!bt_mesh_proxy_has_avail_conn()) {
797 LOG_DBG("Connectable advertising deferred (max connections)");
798 return -ENOMEM;
799 }
800
801 cnt = active_proxy_sub_cnt_get();
802 if (!cnt) {
803 LOG_DBG("No subnets to advertise proxy on");
804 return -ENOENT;
805 } else if (cnt > 1) {
806 /** There is more than one subnet that requires proxy adv,
807 * and the adv resources must be shared.
808 */
809
810 /* We use NODE_ID_TIMEOUT as a starting point since it may
811 * be less than 60 seconds. Divide this period into at least
812 * 6 slices, but make sure that a slice is more than one
813 * second long (to avoid excessive rotation).
814 */
815 max_adv_duration = NODE_ID_TIMEOUT / MAX(cnt, 6);
816 max_adv_duration = MAX(max_adv_duration, MSEC_PER_SEC + 20);
817
818 /* Check if the previous subnet finished its allocated timeslot */
819 if ((sub_adv.request.duration != SYS_FOREVER_MS) &&
820 proxy_adv_request_get(sub_adv.sub, &request) &&
821 (sub_adv.request.evt == request.evt)) {
822 int32_t time_passed = k_uptime_get_32() - sub_adv.start;
823
824 if (time_passed < sub_adv.request.duration &&
825 ((sub_adv.request.duration - time_passed) >= MSEC_PER_SEC)) {
826 sub = sub_adv.sub;
827 request.duration = sub_adv.request.duration - time_passed;
828 goto end;
829 }
830 }
831 }
832
833 sub = adv_sub_get_next(sub_adv.sub, &request);
834 if (!sub) {
835 LOG_ERR("Could not find subnet to advertise");
836 return -ENOENT;
837 }
838 end:
839 if (cnt > 1) {
840 request.duration = (request.duration == SYS_FOREVER_MS)
841 ? max_adv_duration
842 : MIN(request.duration, max_adv_duration);
843 }
844
845 /* Save current state for next iteration */
846 sub_adv.start = k_uptime_get_32();
847 sub_adv.sub = sub;
848 sub_adv.request = request;
849
850 switch (request.evt) {
851 case NET_ID:
852 err = net_id_adv(sub, request.duration);
853 break;
854 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
855 case OD_PRIV_NET_ID:
856 if (!sub->priv_net_id_sent) {
857 sub->priv_net_id_sent = k_uptime_get();
858 }
859 /* Fall through */
860 #endif
861 case PRIV_NET_ID:
862 err = priv_net_id_adv(sub, request.duration);
863 break;
864 case NODE_ID:
865 err = node_id_adv(sub, request.duration);
866 break;
867 case PRIV_NODE_ID:
868 err = priv_node_id_adv(sub, request.duration);
869 break;
870 default:
871 LOG_ERR("Unexpected proxy adv evt: %d", request.evt);
872 return -ENODEV;
873 }
874
875 if (err) {
876 LOG_ERR("Advertising proxy failed (err: %d)", err);
877 return err;
878 }
879
880 LOG_DBG("Advertising %d ms for net_idx 0x%04x", request.duration, sub->net_idx);
881 return err;
882 }
883
subnet_evt(struct bt_mesh_subnet * sub,enum bt_mesh_key_evt evt)884 static void subnet_evt(struct bt_mesh_subnet *sub, enum bt_mesh_key_evt evt)
885 {
886 if (evt == BT_MESH_KEY_DELETED) {
887 if (sub == beacon_sub) {
888 beacon_sub = NULL;
889 }
890 } else {
891 bt_mesh_proxy_beacon_send(sub);
892 bt_mesh_adv_gatt_update();
893 }
894 }
895
896 BT_MESH_SUBNET_CB_DEFINE(gatt_services) = {
897 .evt_handler = subnet_evt,
898 };
899
proxy_ccc_changed(const struct bt_gatt_attr * attr,uint16_t value)900 static void proxy_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
901 {
902 LOG_DBG("value 0x%04x", value);
903 }
904
proxy_ccc_write(struct bt_conn * conn,const struct bt_gatt_attr * attr,uint16_t value)905 static ssize_t proxy_ccc_write(struct bt_conn *conn,
906 const struct bt_gatt_attr *attr, uint16_t value)
907 {
908 struct bt_mesh_proxy_client *client;
909
910 LOG_DBG("value: 0x%04x", value);
911
912 if (value != BT_GATT_CCC_NOTIFY) {
913 LOG_WRN("Client wrote 0x%04x instead enabling notify", value);
914 return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
915 }
916
917 client = find_client(conn);
918 if (client->filter_type == NONE) {
919 client->filter_type = ACCEPT;
920 k_work_submit(&client->send_beacons);
921 }
922
923 return sizeof(value);
924 }
925
926 /* Mesh Proxy Service Declaration */
927 static struct _bt_gatt_ccc proxy_ccc =
928 BT_GATT_CCC_INITIALIZER(proxy_ccc_changed, proxy_ccc_write, NULL);
929
930 static struct bt_gatt_attr proxy_attrs[] = {
931 BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROXY),
932
933 BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_IN,
934 BT_GATT_CHRC_WRITE_WITHOUT_RESP,
935 BT_GATT_PERM_WRITE,
936 NULL, gatt_recv, NULL),
937
938 BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_OUT,
939 BT_GATT_CHRC_NOTIFY,
940 BT_GATT_PERM_NONE,
941 NULL, NULL, NULL),
942 BT_GATT_CCC_MANAGED(&proxy_ccc,
943 BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
944 };
945
946 static struct bt_gatt_service proxy_svc = BT_GATT_SERVICE(proxy_attrs);
947 static void svc_reg_work_handler(struct k_work *work);
948 static struct k_work_delayable svc_reg_work = Z_WORK_DELAYABLE_INITIALIZER(svc_reg_work_handler);
949 static uint32_t svc_reg_attempts;
950
svc_reg_work_handler(struct k_work * work)951 static void svc_reg_work_handler(struct k_work *work)
952 {
953 int err;
954
955 err = bt_gatt_service_register(&proxy_svc);
956 if ((err == -EINVAL) && ((--svc_reg_attempts) > 0)) {
957 /* settings_load() didn't finish yet. Try again. */
958 (void)k_work_schedule(&svc_reg_work, PROXY_SVC_INIT_TIMEOUT);
959 return;
960 } else if (err) {
961 LOG_ERR("Unable to register Mesh Proxy Service (err %d)", err);
962 return;
963 }
964
965 service_registered = true;
966
967 for (int i = 0; i < ARRAY_SIZE(clients); i++) {
968 if (clients[i].cli) {
969 clients[i].filter_type = ACCEPT;
970 }
971 }
972
973 bt_mesh_adv_gatt_update();
974 }
975
bt_mesh_proxy_gatt_enable(void)976 int bt_mesh_proxy_gatt_enable(void)
977 {
978 int err;
979
980 LOG_DBG("");
981
982 if (!bt_mesh_is_provisioned()) {
983 return -ENOTSUP;
984 }
985
986 if (service_registered) {
987 return -EBUSY;
988 }
989
990 svc_reg_attempts = PROXY_SVC_REG_ATTEMPTS;
991 err = k_work_schedule(&svc_reg_work, PROXY_SVC_INIT_TIMEOUT);
992 if (err < 0) {
993 LOG_ERR("Enabling GATT proxy failed (err %d)", err);
994 return err;
995 }
996
997 return 0;
998 }
999
bt_mesh_proxy_gatt_disconnect(void)1000 void bt_mesh_proxy_gatt_disconnect(void)
1001 {
1002 int i;
1003
1004 LOG_DBG("");
1005
1006 for (i = 0; i < ARRAY_SIZE(clients); i++) {
1007 struct bt_mesh_proxy_client *client = &clients[i];
1008
1009 if (client->cli && (client->filter_type == ACCEPT ||
1010 client->filter_type == REJECT)) {
1011 client->filter_type = NONE;
1012 bt_conn_disconnect(client->cli->conn,
1013 BT_HCI_ERR_REMOTE_USER_TERM_CONN);
1014 }
1015 }
1016 }
1017
bt_mesh_proxy_gatt_disable(void)1018 int bt_mesh_proxy_gatt_disable(void)
1019 {
1020 LOG_DBG("");
1021
1022 if (!service_registered) {
1023 return -EALREADY;
1024 }
1025
1026 bt_mesh_proxy_gatt_disconnect();
1027
1028 bt_gatt_service_unregister(&proxy_svc);
1029 service_registered = false;
1030
1031 return 0;
1032 }
1033
bt_mesh_proxy_addr_add(struct net_buf_simple * buf,uint16_t addr)1034 void bt_mesh_proxy_addr_add(struct net_buf_simple *buf, uint16_t addr)
1035 {
1036 struct bt_mesh_proxy_client *client;
1037 struct bt_mesh_proxy_role *cli =
1038 CONTAINER_OF(buf, struct bt_mesh_proxy_role, buf);
1039
1040 client = find_client(cli->conn);
1041
1042 LOG_DBG("filter_type %u addr 0x%04x", client->filter_type, addr);
1043
1044 if (client->filter_type == ACCEPT) {
1045 filter_add(client, addr);
1046 } else if (client->filter_type == REJECT) {
1047 filter_remove(client, addr);
1048 }
1049 }
1050
client_filter_match(struct bt_mesh_proxy_client * client,uint16_t addr)1051 static bool client_filter_match(struct bt_mesh_proxy_client *client,
1052 uint16_t addr)
1053 {
1054 int i;
1055
1056 LOG_DBG("filter_type %u addr 0x%04x", client->filter_type, addr);
1057
1058 if (client->filter_type == REJECT) {
1059 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
1060 if (client->filter[i] == addr) {
1061 return false;
1062 }
1063 }
1064
1065 return true;
1066 }
1067
1068 if (addr == BT_MESH_ADDR_ALL_NODES) {
1069 return true;
1070 }
1071
1072 if (client->filter_type == ACCEPT) {
1073 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
1074 if (client->filter[i] == addr) {
1075 return true;
1076 }
1077 }
1078 }
1079
1080 return false;
1081 }
1082
bt_mesh_proxy_relay(struct bt_mesh_adv * adv,uint16_t dst)1083 bool bt_mesh_proxy_relay(struct bt_mesh_adv *adv, uint16_t dst)
1084 {
1085 bool relayed = false;
1086 int i;
1087
1088 LOG_DBG("%u bytes to dst 0x%04x", adv->b.len, dst);
1089
1090 for (i = 0; i < ARRAY_SIZE(clients); i++) {
1091 struct bt_mesh_proxy_client *client = &clients[i];
1092
1093 if (!client->cli) {
1094 continue;
1095 }
1096
1097 if (!client_filter_match(client, dst)) {
1098 continue;
1099 }
1100
1101 if (bt_mesh_proxy_relay_send(client->cli->conn, adv)) {
1102 continue;
1103 }
1104
1105 relayed = true;
1106 }
1107
1108 return relayed;
1109 }
1110
solicitation_reset(struct bt_mesh_subnet * sub)1111 static void solicitation_reset(struct bt_mesh_subnet *sub)
1112 {
1113 #if defined(CONFIG_BT_MESH_OD_PRIV_PROXY_SRV)
1114 sub->solicited = false;
1115 sub->priv_net_id_sent = 0;
1116 #endif
1117 }
1118
gatt_connected(struct bt_conn * conn,uint8_t conn_err)1119 static void gatt_connected(struct bt_conn *conn, uint8_t conn_err)
1120 {
1121 struct bt_mesh_proxy_client *client;
1122 struct bt_conn_info info;
1123 int err;
1124
1125 err = bt_conn_get_info(conn, &info);
1126 if (err || info.role != BT_CONN_ROLE_PERIPHERAL || !service_registered ||
1127 info.id != BT_ID_DEFAULT) {
1128 return;
1129 }
1130
1131 LOG_DBG("conn %p err 0x%02x", (void *)conn, conn_err);
1132
1133 client = find_client(conn);
1134
1135 client->filter_type = NONE;
1136 (void)memset(client->filter, 0, sizeof(client->filter));
1137 client->cli = bt_mesh_proxy_role_setup(conn, proxy_send,
1138 proxy_msg_recv);
1139
1140 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
1141 /* Binding from MshPRTv1.1: 7.2.2.2.6. */
1142 enum bt_mesh_subnets_node_id_state cur_node_id = bt_mesh_subnets_node_id_state_get();
1143
1144 if (bt_mesh_gatt_proxy_get() == BT_MESH_FEATURE_ENABLED ||
1145 cur_node_id == BT_MESH_SUBNETS_NODE_ID_STATE_ENABLED) {
1146 client->privacy = false;
1147 } else {
1148 client->privacy = (bt_mesh_priv_gatt_proxy_get() == BT_MESH_FEATURE_ENABLED) ||
1149 (cur_node_id == BT_MESH_SUBNETS_NODE_ID_STATE_ENABLED_PRIVATE);
1150 }
1151
1152 LOG_DBG("privacy: %d", client->privacy);
1153 #endif
1154
1155 /* If connection was formed after Proxy Solicitation we need to stop future
1156 * Private Network ID advertisements
1157 */
1158 bt_mesh_subnet_foreach(solicitation_reset);
1159
1160 /* Try to re-enable advertising in case it's possible */
1161 if (bt_mesh_proxy_has_avail_conn()) {
1162 bt_mesh_adv_gatt_update();
1163 }
1164 }
1165
gatt_disconnected(struct bt_conn * conn,uint8_t reason)1166 static void gatt_disconnected(struct bt_conn *conn, uint8_t reason)
1167 {
1168 struct bt_conn_info info;
1169 struct bt_mesh_proxy_client *client;
1170 int err;
1171
1172 err = bt_conn_get_info(conn, &info);
1173 if (err || info.role != BT_CONN_ROLE_PERIPHERAL || info.id != BT_ID_DEFAULT) {
1174 return;
1175 }
1176
1177 if (!service_registered && bt_mesh_is_provisioned()) {
1178 (void)bt_mesh_proxy_gatt_enable();
1179 return;
1180 }
1181
1182 client = find_client(conn);
1183 if (client->cli) {
1184 bt_mesh_proxy_role_cleanup(client->cli);
1185 client->cli = NULL;
1186 }
1187 }
1188
proxy_send(struct bt_conn * conn,const void * data,uint16_t len,bt_gatt_complete_func_t end,void * user_data)1189 static int proxy_send(struct bt_conn *conn,
1190 const void *data, uint16_t len,
1191 bt_gatt_complete_func_t end, void *user_data)
1192 {
1193 LOG_DBG("%u bytes: %s", len, bt_hex(data, len));
1194
1195 struct bt_gatt_notify_params params = {
1196 .data = data,
1197 .len = len,
1198 .attr = &proxy_attrs[3],
1199 .user_data = user_data,
1200 .func = end,
1201 };
1202
1203 return bt_gatt_notify_cb(conn, ¶ms);
1204 }
1205
bt_mesh_proxy_adv_start(void)1206 int bt_mesh_proxy_adv_start(void)
1207 {
1208 LOG_DBG("");
1209
1210 if (!service_registered || !bt_mesh_is_provisioned()) {
1211 return -ENOTSUP;
1212 }
1213
1214 return gatt_proxy_advertise();
1215 }
1216
1217 BT_CONN_CB_DEFINE(conn_callbacks) = {
1218 .connected = gatt_connected,
1219 .disconnected = gatt_disconnected,
1220 };
1221
bt_mesh_proxy_srv_connected_cnt(void)1222 uint8_t bt_mesh_proxy_srv_connected_cnt(void)
1223 {
1224 uint8_t cnt = 0;
1225
1226 for (int i = 0; i < ARRAY_SIZE(clients); i++) {
1227 if (clients[i].cli) {
1228 cnt++;
1229 }
1230 }
1231
1232 return cnt;
1233 }
1234