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 #if defined(CONFIG_BT_MESH_PROXY_USE_DEVICE_NAME)
48 #define ADV_OPT_USE_NAME BT_LE_ADV_OPT_USE_NAME
49 #else
50 #define ADV_OPT_USE_NAME 0
51 #endif
52
53 #define ADV_OPT_ADDR(private) (IS_ENABLED(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR) ? \
54 BT_LE_ADV_OPT_USE_IDENTITY : (private) ? BT_LE_ADV_OPT_USE_NRPA : 0)
55
56 #define ADV_OPT_PROXY(private) \
57 (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_SCANNABLE | ADV_OPT_ADDR(private) | \
58 BT_LE_ADV_OPT_ONE_TIME | ADV_OPT_USE_NAME)
59
60 static void proxy_send_beacons(struct k_work *work);
61 static int proxy_send(struct bt_conn *conn,
62 const void *data, uint16_t len,
63 bt_gatt_complete_func_t end, void *user_data);
64
65 static struct bt_mesh_proxy_client {
66 struct bt_mesh_proxy_role *cli;
67 uint16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE];
68 enum __packed {
69 NONE,
70 ACCEPT,
71 REJECT,
72 } filter_type;
73 struct k_work send_beacons;
74 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
75 bool privacy;
76 #endif
77 } clients[CONFIG_BT_MAX_CONN] = {
78 [0 ... (CONFIG_BT_MAX_CONN - 1)] = {
79 .send_beacons = Z_WORK_INITIALIZER(proxy_send_beacons),
80 },
81 };
82
83 static bool service_registered;
84
find_client(struct bt_conn * conn)85 static struct bt_mesh_proxy_client *find_client(struct bt_conn *conn)
86 {
87 return &clients[bt_conn_index(conn)];
88 }
89
gatt_recv(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * buf,uint16_t len,uint16_t offset,uint8_t flags)90 static ssize_t gatt_recv(struct bt_conn *conn,
91 const struct bt_gatt_attr *attr, const void *buf,
92 uint16_t len, uint16_t offset, uint8_t flags)
93 {
94 const uint8_t *data = buf;
95
96 if (len < 1) {
97 LOG_WRN("Too small Proxy PDU");
98 return -EINVAL;
99 }
100
101 if (PDU_TYPE(data) == BT_MESH_PROXY_PROV) {
102 LOG_WRN("Proxy PDU type doesn't match GATT service");
103 return -EINVAL;
104 }
105
106 return bt_mesh_proxy_msg_recv(conn, buf, len);
107 }
108
109 /* Next subnet in queue to be advertised */
110 static struct bt_mesh_subnet *beacon_sub;
111
filter_set(struct bt_mesh_proxy_client * client,struct net_buf_simple * buf)112 static int filter_set(struct bt_mesh_proxy_client *client,
113 struct net_buf_simple *buf)
114 {
115 uint8_t type;
116
117 if (buf->len < 1) {
118 LOG_WRN("Too short Filter Set message");
119 return -EINVAL;
120 }
121
122 type = net_buf_simple_pull_u8(buf);
123 LOG_DBG("type 0x%02x", type);
124
125 switch (type) {
126 case 0x00:
127 (void)memset(client->filter, 0, sizeof(client->filter));
128 client->filter_type = ACCEPT;
129 break;
130 case 0x01:
131 (void)memset(client->filter, 0, sizeof(client->filter));
132 client->filter_type = REJECT;
133 break;
134 default:
135 LOG_WRN("Prohibited Filter Type 0x%02x", type);
136 return -EINVAL;
137 }
138
139 return 0;
140 }
141
filter_add(struct bt_mesh_proxy_client * client,uint16_t addr)142 static void filter_add(struct bt_mesh_proxy_client *client, uint16_t addr)
143 {
144 int i;
145
146 LOG_DBG("addr 0x%04x", addr);
147
148 if (addr == BT_MESH_ADDR_UNASSIGNED) {
149 return;
150 }
151
152 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
153 if (client->filter[i] == addr) {
154 return;
155 }
156 }
157
158 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
159 if (client->filter[i] == BT_MESH_ADDR_UNASSIGNED) {
160 client->filter[i] = addr;
161 return;
162 }
163 }
164 }
165
filter_remove(struct bt_mesh_proxy_client * client,uint16_t addr)166 static void filter_remove(struct bt_mesh_proxy_client *client, uint16_t addr)
167 {
168 int i;
169
170 LOG_DBG("addr 0x%04x", addr);
171
172 if (addr == BT_MESH_ADDR_UNASSIGNED) {
173 return;
174 }
175
176 for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
177 if (client->filter[i] == addr) {
178 client->filter[i] = BT_MESH_ADDR_UNASSIGNED;
179 return;
180 }
181 }
182 }
183
send_filter_status(struct bt_mesh_proxy_client * client,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)184 static void send_filter_status(struct bt_mesh_proxy_client *client,
185 struct bt_mesh_net_rx *rx,
186 struct net_buf_simple *buf)
187 {
188 struct bt_mesh_net_tx tx = {
189 .sub = rx->sub,
190 .ctx = &rx->ctx,
191 .src = bt_mesh_primary_addr(),
192 };
193 uint16_t filter_size;
194 int i, err;
195
196 /* Configuration messages always have dst unassigned */
197 tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED;
198
199 net_buf_simple_reset(buf);
200 net_buf_simple_reserve(buf, 10);
201
202 net_buf_simple_add_u8(buf, CFG_FILTER_STATUS);
203
204 if (client->filter_type == ACCEPT) {
205 net_buf_simple_add_u8(buf, 0x00);
206 } else {
207 net_buf_simple_add_u8(buf, 0x01);
208 }
209
210 for (filter_size = 0U, i = 0; i < ARRAY_SIZE(client->filter); i++) {
211 if (client->filter[i] != BT_MESH_ADDR_UNASSIGNED) {
212 filter_size++;
213 }
214 }
215
216 net_buf_simple_add_be16(buf, filter_size);
217
218 LOG_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
219
220 err = bt_mesh_net_encode(&tx, buf, BT_MESH_NONCE_PROXY);
221 if (err) {
222 LOG_ERR("Encoding Proxy cfg message failed (err %d)", err);
223 return;
224 }
225
226 err = bt_mesh_proxy_msg_send(client->cli->conn, BT_MESH_PROXY_CONFIG,
227 buf, NULL, NULL);
228 if (err) {
229 LOG_ERR("Failed to send proxy cfg message (err %d)", err);
230 }
231 }
232
proxy_filter_recv(struct bt_conn * conn,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)233 static void proxy_filter_recv(struct bt_conn *conn,
234 struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
235 {
236 struct bt_mesh_proxy_client *client;
237 uint8_t opcode;
238
239 client = find_client(conn);
240
241 opcode = net_buf_simple_pull_u8(buf);
242 switch (opcode) {
243 case CFG_FILTER_SET:
244 filter_set(client, buf);
245 send_filter_status(client, rx, buf);
246 break;
247 case CFG_FILTER_ADD:
248 while (buf->len >= 2) {
249 uint16_t addr;
250
251 addr = net_buf_simple_pull_be16(buf);
252 filter_add(client, addr);
253 }
254 send_filter_status(client, rx, buf);
255 break;
256 case CFG_FILTER_REMOVE:
257 while (buf->len >= 2) {
258 uint16_t addr;
259
260 addr = net_buf_simple_pull_be16(buf);
261 filter_remove(client, addr);
262 }
263 send_filter_status(client, rx, buf);
264 break;
265 default:
266 LOG_WRN("Unhandled configuration OpCode 0x%02x", opcode);
267 break;
268 }
269 }
270
proxy_cfg(struct bt_mesh_proxy_role * role)271 static void proxy_cfg(struct bt_mesh_proxy_role *role)
272 {
273 NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
274 struct bt_mesh_net_rx rx;
275 int err;
276
277 err = bt_mesh_net_decode(&role->buf, BT_MESH_NET_IF_PROXY_CFG,
278 &rx, &buf);
279 if (err) {
280 LOG_ERR("Failed to decode Proxy Configuration (err %d)", err);
281 return;
282 }
283
284 rx.local_match = 1U;
285
286 if (bt_mesh_rpl_check(&rx, NULL)) {
287 LOG_WRN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", rx.ctx.addr, rx.ctx.recv_dst,
288 rx.seq);
289 return;
290 }
291
292 /* Remove network headers */
293 net_buf_simple_pull(&buf, BT_MESH_NET_HDR_LEN);
294
295 LOG_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len));
296
297 if (buf.len < 1) {
298 LOG_WRN("Too short proxy configuration PDU");
299 return;
300 }
301
302 proxy_filter_recv(role->conn, &rx, &buf);
303 }
304
proxy_msg_recv(struct bt_mesh_proxy_role * role)305 static void proxy_msg_recv(struct bt_mesh_proxy_role *role)
306 {
307 switch (role->msg_type) {
308 case BT_MESH_PROXY_NET_PDU:
309 LOG_DBG("Mesh Network PDU");
310 bt_mesh_net_recv(&role->buf, 0, BT_MESH_NET_IF_PROXY);
311 break;
312 case BT_MESH_PROXY_BEACON:
313 LOG_DBG("Mesh Beacon PDU");
314 bt_mesh_beacon_recv(&role->buf);
315 break;
316 case BT_MESH_PROXY_CONFIG:
317 LOG_DBG("Mesh Configuration PDU");
318 proxy_cfg(role);
319 break;
320 default:
321 LOG_WRN("Unhandled Message Type 0x%02x", role->msg_type);
322 break;
323 }
324 }
325
beacon_send(struct bt_mesh_proxy_client * client,struct bt_mesh_subnet * sub)326 static int beacon_send(struct bt_mesh_proxy_client *client,
327 struct bt_mesh_subnet *sub)
328 {
329 int err;
330
331 NET_BUF_SIMPLE_DEFINE(buf, 28);
332
333 net_buf_simple_reserve(&buf, 1);
334
335 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
336 err = bt_mesh_beacon_create(sub, &buf, client->privacy);
337 #else
338 err = bt_mesh_beacon_create(sub, &buf, false);
339 #endif
340 if (err) {
341 return err;
342 }
343
344 return bt_mesh_proxy_msg_send(client->cli->conn, BT_MESH_PROXY_BEACON,
345 &buf, NULL, NULL);
346 }
347
send_beacon_cb(struct bt_mesh_subnet * sub,void * cb_data)348 static bool send_beacon_cb(struct bt_mesh_subnet *sub, void *cb_data)
349 {
350 struct bt_mesh_proxy_client *client = cb_data;
351
352 return beacon_send(client, sub) != 0;
353 }
354
proxy_send_beacons(struct k_work * work)355 static void proxy_send_beacons(struct k_work *work)
356 {
357 struct bt_mesh_proxy_client *client;
358
359 client = CONTAINER_OF(work, struct bt_mesh_proxy_client, send_beacons);
360
361 (void)bt_mesh_subnet_find(send_beacon_cb, client);
362 }
363
bt_mesh_proxy_beacon_send(struct bt_mesh_subnet * sub)364 void bt_mesh_proxy_beacon_send(struct bt_mesh_subnet *sub)
365 {
366 int i;
367
368 if (!sub) {
369 /* NULL means we send on all subnets */
370 bt_mesh_subnet_foreach(bt_mesh_proxy_beacon_send);
371 return;
372 }
373
374 for (i = 0; i < ARRAY_SIZE(clients); i++) {
375 if (clients[i].cli) {
376 beacon_send(&clients[i], sub);
377 }
378 }
379 }
380
identity_enabled(struct bt_mesh_subnet * sub)381 static void identity_enabled(struct bt_mesh_subnet *sub)
382 {
383 sub->node_id = BT_MESH_NODE_IDENTITY_RUNNING;
384 sub->node_id_start = k_uptime_get_32();
385
386 STRUCT_SECTION_FOREACH(bt_mesh_proxy_cb, cb) {
387 if (cb->identity_enabled) {
388 cb->identity_enabled(sub->net_idx);
389 }
390 }
391 }
392
node_id_start(struct bt_mesh_subnet * sub)393 static void node_id_start(struct bt_mesh_subnet *sub)
394 {
395 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
396 sub->priv_beacon_ctx.node_id = false;
397 #endif
398
399 identity_enabled(sub);
400 }
401
private_node_id_start(struct bt_mesh_subnet * sub)402 static void private_node_id_start(struct bt_mesh_subnet *sub)
403 {
404 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
405 sub->priv_beacon_ctx.node_id = true;
406 #endif
407
408 identity_enabled(sub);
409 }
410
bt_mesh_proxy_identity_start(struct bt_mesh_subnet * sub,bool private)411 void bt_mesh_proxy_identity_start(struct bt_mesh_subnet *sub, bool private)
412 {
413 if (private) {
414 private_node_id_start(sub);
415 } else {
416 node_id_start(sub);
417 }
418
419 /* Prioritize the recently enabled subnet */
420 beacon_sub = sub;
421 }
422
bt_mesh_proxy_identity_stop(struct bt_mesh_subnet * sub)423 void bt_mesh_proxy_identity_stop(struct bt_mesh_subnet *sub)
424 {
425 sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
426 sub->node_id_start = 0U;
427
428 STRUCT_SECTION_FOREACH(bt_mesh_proxy_cb, cb) {
429 if (cb->identity_disabled) {
430 cb->identity_disabled(sub->net_idx);
431 }
432 }
433 }
434
bt_mesh_proxy_identity_enable(void)435 int bt_mesh_proxy_identity_enable(void)
436 {
437 LOG_DBG("");
438
439 if (!bt_mesh_is_provisioned()) {
440 return -EAGAIN;
441 }
442
443 if (bt_mesh_subnet_foreach(node_id_start)) {
444 bt_mesh_adv_gatt_update();
445 }
446
447 return 0;
448 }
449
bt_mesh_proxy_private_identity_enable(void)450 int bt_mesh_proxy_private_identity_enable(void)
451 {
452 LOG_DBG("");
453
454 if (!IS_ENABLED(CONFIG_BT_MESH_PRIV_BEACONS)) {
455 return -ENOTSUP;
456 }
457
458 if (!bt_mesh_is_provisioned()) {
459 return -EAGAIN;
460 }
461
462 if (bt_mesh_subnet_foreach(private_node_id_start)) {
463 bt_mesh_adv_gatt_update();
464 }
465
466 return 0;
467 }
468
469 #define ENC_ID_LEN 19
470 #define NET_ID_LEN 11
471
472 #define NODE_ID_TIMEOUT (CONFIG_BT_MESH_NODE_ID_TIMEOUT * MSEC_PER_SEC)
473
474 static uint8_t proxy_svc_data[ENC_ID_LEN] = {
475 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL),
476 };
477
478 static const struct bt_data enc_id_ad[] = {
479 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
480 BT_DATA_BYTES(BT_DATA_UUID16_ALL,
481 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL)),
482 BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, ENC_ID_LEN),
483 };
484
485 static const struct bt_data net_id_ad[] = {
486 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
487 BT_DATA_BYTES(BT_DATA_UUID16_ALL,
488 BT_UUID_16_ENCODE(BT_UUID_MESH_PROXY_VAL)),
489 BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NET_ID_LEN),
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), NULL, 0);
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), NULL, 0);
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