1 /*  Bluetooth Mesh */
2 
3 /*
4  * SPDX-FileCopyrightText: 2017 Intel Corporation
5  * SPDX-FileContributor: 2018-2021 Espressif Systems (Shanghai) CO LTD
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 #include <stdint.h>
10 #include <stdbool.h>
11 #include <errno.h>
12 
13 #include "mesh.h"
14 #include "adv.h"
15 #include "transport.h"
16 #include "access.h"
17 #include "foundation.h"
18 #include "mesh_main.h"
19 #include "mesh_common.h"
20 #include "fast_prov.h"
21 #include "provisioner_main.h"
22 
23 #define BLE_MESH_SDU_MAX_LEN    384
24 
25 static const struct bt_mesh_comp *dev_comp;
26 static uint16_t dev_primary_addr;
27 
bt_mesh_model_foreach(void (* func)(struct bt_mesh_model * mod,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data),void * user_data)28 void bt_mesh_model_foreach(void (*func)(struct bt_mesh_model *mod,
29                                         struct bt_mesh_elem *elem,
30                                         bool vnd, bool primary,
31                                         void *user_data),
32                            void *user_data)
33 {
34     int i, j;
35 
36     if (dev_comp == NULL) {
37         BT_ERR("Invalid device composition");
38         return;
39     }
40 
41     for (i = 0; i < dev_comp->elem_count; i++) {
42         struct bt_mesh_elem *elem = &dev_comp->elem[i];
43 
44         for (j = 0; j < elem->model_count; j++) {
45             struct bt_mesh_model *model = &elem->models[j];
46 
47             func(model, elem, false, i == 0, user_data);
48         }
49 
50         for (j = 0; j < elem->vnd_model_count; j++) {
51             struct bt_mesh_model *model = &elem->vnd_models[j];
52 
53             func(model, elem, true, i == 0, user_data);
54         }
55     }
56 }
57 
bt_mesh_model_pub_period_get(struct bt_mesh_model * mod)58 int32_t bt_mesh_model_pub_period_get(struct bt_mesh_model *mod)
59 {
60     int period = 0;
61 
62     if (!mod->pub) {
63         BT_ERR("Model has no publication support");
64         return 0;
65     }
66 
67     switch (mod->pub->period >> 6) {
68     case 0x00:
69         /* 1 step is 100 ms */
70         period = K_MSEC((mod->pub->period & BIT_MASK(6)) * 100U);
71         break;
72     case 0x01:
73         /* 1 step is 1 second */
74         period = K_SECONDS(mod->pub->period & BIT_MASK(6));
75         break;
76     case 0x02:
77         /* 1 step is 10 seconds */
78         period = K_SECONDS((mod->pub->period & BIT_MASK(6)) * 10U);
79         break;
80     case 0x03:
81         /* 1 step is 10 minutes */
82         period = K_MINUTES((mod->pub->period & BIT_MASK(6)) * 10U);
83         break;
84     default:
85         BT_ERR("Unknown model publication period");
86         return 0;
87     }
88 
89     if (mod->pub->fast_period) {
90         return period >> mod->pub->period_div;
91     } else {
92         return period;
93     }
94 }
95 
next_period(struct bt_mesh_model * mod)96 static int32_t next_period(struct bt_mesh_model *mod)
97 {
98     struct bt_mesh_model_pub *pub = mod->pub;
99     uint32_t elapsed = 0U, period = 0U;
100 
101     if (!pub) {
102         BT_ERR("Model has no publication support");
103         return -ENOTSUP;
104     }
105 
106     period = bt_mesh_model_pub_period_get(mod);
107     if (!period) {
108         return 0;
109     }
110 
111     elapsed = k_uptime_get_32() - pub->period_start;
112 
113     BT_INFO("Publishing took %ums", elapsed);
114 
115     if (elapsed >= period) {
116         BT_WARN("Publication sending took longer than the period");
117         /* Return smallest positive number since 0 means disabled */
118         return K_MSEC(1);
119     }
120 
121     return period - elapsed;
122 }
123 
publish_sent(int err,void * user_data)124 static void publish_sent(int err, void *user_data)
125 {
126     struct bt_mesh_model *mod = user_data;
127     int32_t delay = 0;
128 
129     BT_DBG("err %d", err);
130 
131     if (!mod->pub) {
132         BT_ERR("Model has no publication support");
133         return;
134     }
135 
136     if (mod->pub->count) {
137         delay = BLE_MESH_PUB_TRANSMIT_INT(mod->pub->retransmit);
138     } else {
139         delay = next_period(mod);
140     }
141 
142     if (delay) {
143         BT_INFO("Publishing next time in %dms", delay);
144         k_delayed_work_submit(&mod->pub->timer, delay);
145     }
146 }
147 
publish_start(uint16_t duration,int err,void * user_data)148 static void publish_start(uint16_t duration, int err, void *user_data)
149 {
150     struct bt_mesh_model *mod = user_data;
151     struct bt_mesh_model_pub *pub = mod->pub;
152 
153     if (err) {
154         BT_ERR("Failed to publish: err %d", err);
155         return;
156     }
157 
158     /* Initialize the timestamp for the beginning of a new period */
159     if (pub->count == BLE_MESH_PUB_TRANSMIT_COUNT(pub->retransmit)) {
160         pub->period_start = k_uptime_get_32();
161     }
162 }
163 
164 static const struct bt_mesh_send_cb pub_sent_cb = {
165     .start = publish_start,
166     .end = publish_sent,
167 };
168 
publish_retransmit(struct bt_mesh_model * mod)169 static int publish_retransmit(struct bt_mesh_model *mod)
170 {
171     struct bt_mesh_model_pub *pub = mod->pub;
172     if (!pub) {
173         BT_ERR("Model has no publication support");
174         return -ENOTSUP;
175     }
176 
177     struct bt_mesh_app_key *key = NULL;
178     struct net_buf_simple *sdu = NULL;
179     struct bt_mesh_msg_ctx ctx = {
180         .addr = pub->addr,
181         .send_ttl = pub->ttl,
182         .model = mod,
183         .srv_send = (pub->dev_role == NODE ? true : false),
184     };
185     struct bt_mesh_net_tx tx = {
186         .ctx = &ctx,
187         .src = bt_mesh_model_elem(mod)->addr,
188         .xmit = bt_mesh_net_transmit_get(),
189         .friend_cred = pub->cred,
190     };
191     int err = 0;
192 
193     key = bt_mesh_tx_appkey_get(pub->dev_role, pub->key);
194     if (!key) {
195         BT_ERR("AppKey 0x%03x not exists", pub->key);
196         return -EADDRNOTAVAIL;
197     }
198 
199     tx.sub = bt_mesh_tx_netkey_get(pub->dev_role, key->net_idx);
200     if (!tx.sub) {
201         BT_ERR("Subnet 0x%04x not exists", key->net_idx);
202         return -EADDRNOTAVAIL;
203     }
204 
205     ctx.net_idx = key->net_idx;
206     ctx.app_idx = key->app_idx;
207 
208     sdu = bt_mesh_alloc_buf(pub->msg->len + BLE_MESH_MIC_SHORT);
209     if (!sdu) {
210         BT_ERR("%s, Out of memory", __func__);
211         return -ENOMEM;
212     }
213 
214     net_buf_simple_add_mem(sdu, pub->msg->data, pub->msg->len);
215 
216     pub->count--;
217 
218     err = bt_mesh_trans_send(&tx, sdu, &pub_sent_cb, mod);
219 
220     bt_mesh_free_buf(sdu);
221     return err;
222 }
223 
publish_retransmit_end(int err,struct bt_mesh_model_pub * pub)224 static void publish_retransmit_end(int err, struct bt_mesh_model_pub *pub)
225 {
226     /* Cancel all retransmits for this publish attempt */
227     pub->count = 0U;
228     /* Make sure the publish timer gets reset */
229     publish_sent(err, pub->mod);
230 }
231 
mod_publish(struct k_work * work)232 static void mod_publish(struct k_work *work)
233 {
234     struct bt_mesh_model_pub *pub = CONTAINER_OF(work,
235                                     struct bt_mesh_model_pub,
236                                     timer.work);
237     int32_t period_ms = 0;
238     int err = 0;
239 
240     BT_DBG("%s", __func__);
241 
242     period_ms = bt_mesh_model_pub_period_get(pub->mod);
243     BT_INFO("Publish period %u ms", period_ms);
244 
245     if (pub->count) {
246         err = publish_retransmit(pub->mod);
247         if (err) {
248             BT_ERR("Failed to retransmit (err %d)", err);
249 
250             pub->count = 0U;
251 
252             /* Continue with normal publication */
253             if (period_ms) {
254                 k_delayed_work_submit(&pub->timer, period_ms);
255             }
256         }
257 
258         return;
259     }
260 
261     if (!period_ms) {
262         return;
263     }
264 
265     /* Callback the model publish update event to the application layer.
266      * In the event, users can update the context of the publish message
267      * which will be published in the next period.
268      */
269     if (pub->update && pub->update(pub->mod)) {
270         /* Cancel this publish attempt. */
271         BT_ERR("Update failed, skipping publish (err %d)", err);
272         pub->period_start = k_uptime_get_32();
273         publish_retransmit_end(err, pub);
274         return;
275     }
276 
277     err = bt_mesh_model_publish(pub->mod);
278     if (err) {
279         BT_ERR("Publishing failed (err %d)", err);
280     }
281 }
282 
bt_mesh_model_elem(struct bt_mesh_model * mod)283 struct bt_mesh_elem *bt_mesh_model_elem(struct bt_mesh_model *mod)
284 {
285     return &dev_comp->elem[mod->elem_idx];
286 }
287 
bt_mesh_model_get(bool vnd,uint8_t elem_idx,uint8_t mod_idx)288 struct bt_mesh_model *bt_mesh_model_get(bool vnd, uint8_t elem_idx, uint8_t mod_idx)
289 {
290     struct bt_mesh_elem *elem = NULL;
291 
292     if (!dev_comp) {
293         BT_ERR("dev_comp not initialized");
294         return NULL;
295     }
296 
297     if (elem_idx >= dev_comp->elem_count) {
298         BT_ERR("Invalid element index %u", elem_idx);
299         return NULL;
300     }
301 
302     elem = &dev_comp->elem[elem_idx];
303 
304     if (vnd) {
305         if (mod_idx >= elem->vnd_model_count) {
306             BT_ERR("Invalid vendor model index %u", mod_idx);
307             return NULL;
308         }
309 
310         return &elem->vnd_models[mod_idx];
311     } else {
312         if (mod_idx >= elem->model_count) {
313             BT_ERR("Invalid SIG model index %u", mod_idx);
314             return NULL;
315         }
316 
317         return &elem->models[mod_idx];
318     }
319 }
320 
mod_init(struct bt_mesh_model * mod,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data)321 static void mod_init(struct bt_mesh_model *mod, struct bt_mesh_elem *elem,
322                      bool vnd, bool primary, void *user_data)
323 {
324     int *err = user_data;
325     int i;
326 
327     if (!user_data) {
328         BT_ERR("Invalid model init user data");
329         return;
330     }
331 
332     if (*err) {
333         BT_ERR("Model init failed (err %d)", *err);
334         return;
335     }
336 
337     mod->elem = elem;
338 
339     if (mod->pub) {
340         mod->pub->mod = mod;
341         k_delayed_work_init(&mod->pub->timer, mod_publish);
342     }
343 
344     for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
345         mod->keys[i] = BLE_MESH_KEY_UNUSED;
346     }
347 
348     mod->flags = 0;
349     mod->elem_idx = elem - dev_comp->elem;
350     if (vnd) {
351         mod->model_idx = mod - elem->vnd_models;
352     } else {
353         mod->model_idx = mod - elem->models;
354     }
355 
356     if (vnd) {
357         return;
358     }
359 
360     if (mod->cb && mod->cb->init) {
361         *err = mod->cb->init(mod);
362     }
363 }
364 
bt_mesh_comp_register(const struct bt_mesh_comp * comp)365 int bt_mesh_comp_register(const struct bt_mesh_comp *comp)
366 {
367     int err = 0;
368 
369     /* There must be at least one element */
370     if (!comp->elem_count) {
371         return -EINVAL;
372     }
373 
374     dev_comp = comp;
375 
376     bt_mesh_model_foreach(mod_init, &err);
377 
378     return err;
379 }
380 
381 #if CONFIG_BLE_MESH_DEINIT
mod_deinit(struct bt_mesh_model * mod,struct bt_mesh_elem * elem,bool vnd,bool primary,void * user_data)382 static void mod_deinit(struct bt_mesh_model *mod, struct bt_mesh_elem *elem,
383                        bool vnd, bool primary, void *user_data)
384 {
385     int *err = user_data;
386     int i;
387 
388     if (!user_data) {
389         BT_ERR("Invalid model deinit user data");
390         return;
391     }
392 
393     if (*err) {
394         BT_ERR("Model deinit failed (err %d)", *err);
395         return;
396     }
397 
398     mod->elem = NULL;
399 
400     if (mod->pub) {
401         mod->pub->mod = NULL;
402         k_delayed_work_free(&mod->pub->timer);
403     }
404 
405     for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
406         mod->keys[i] = BLE_MESH_KEY_UNUSED;
407     }
408 
409     mod->flags = 0U;
410     mod->elem_idx = 0U;
411     mod->model_idx = 0U;
412 
413     if (vnd) {
414         return;
415     }
416 
417     if (mod->cb && mod->cb->deinit) {
418         *err = mod->cb->deinit(mod);
419     }
420 }
421 
bt_mesh_comp_deregister(void)422 int bt_mesh_comp_deregister(void)
423 {
424     int err = 0;
425 
426     if (dev_comp == NULL) {
427         return -EINVAL;
428     }
429 
430     bt_mesh_model_foreach(mod_deinit, &err);
431 
432     dev_comp = NULL;
433 
434     return err;
435 }
436 #endif /* CONFIG_BLE_MESH_DEINIT */
437 
bt_mesh_comp_provision(uint16_t addr)438 void bt_mesh_comp_provision(uint16_t addr)
439 {
440     int i;
441 
442     dev_primary_addr = addr;
443 
444     BT_INFO("Primary address 0x%04x, element count %u", addr, dev_comp->elem_count);
445 
446     for (i = 0; i < dev_comp->elem_count; i++) {
447         struct bt_mesh_elem *elem = &dev_comp->elem[i];
448 
449         elem->addr = addr++;
450 
451         BT_DBG("addr 0x%04x mod_count %u vnd_mod_count %u",
452                elem->addr, elem->model_count, elem->vnd_model_count);
453     }
454 }
455 
bt_mesh_comp_unprovision(void)456 void bt_mesh_comp_unprovision(void)
457 {
458     BT_DBG("%s", __func__);
459 
460     dev_primary_addr = BLE_MESH_ADDR_UNASSIGNED;
461 }
462 
bt_mesh_primary_addr(void)463 uint16_t bt_mesh_primary_addr(void)
464 {
465     return dev_primary_addr;
466 }
467 
bt_mesh_model_find_group(struct bt_mesh_model * mod,uint16_t addr)468 uint16_t *bt_mesh_model_find_group(struct bt_mesh_model *mod, uint16_t addr)
469 {
470     int i;
471 
472     for (i = 0; i < ARRAY_SIZE(mod->groups); i++) {
473         if (mod->groups[i] == addr) {
474             return &mod->groups[i];
475         }
476     }
477 
478     return NULL;
479 }
480 
bt_mesh_elem_find_group(struct bt_mesh_elem * elem,uint16_t group_addr)481 static struct bt_mesh_model *bt_mesh_elem_find_group(struct bt_mesh_elem *elem,
482                                                      uint16_t group_addr)
483 {
484     struct bt_mesh_model *model = NULL;
485     uint16_t *match = NULL;
486     int i;
487 
488     for (i = 0; i < elem->model_count; i++) {
489         model = &elem->models[i];
490 
491         match = bt_mesh_model_find_group(model, group_addr);
492         if (match) {
493             return model;
494         }
495     }
496 
497     for (i = 0; i < elem->vnd_model_count; i++) {
498         model = &elem->vnd_models[i];
499 
500         match = bt_mesh_model_find_group(model, group_addr);
501         if (match) {
502             return model;
503         }
504     }
505 
506     return NULL;
507 }
508 
bt_mesh_elem_find(uint16_t addr)509 struct bt_mesh_elem *bt_mesh_elem_find(uint16_t addr)
510 {
511     uint16_t index = 0U;
512 
513     if (BLE_MESH_ADDR_IS_UNICAST(addr)) {
514         index = (addr - dev_comp->elem[0].addr);
515         if (index < dev_comp->elem_count) {
516             return &dev_comp->elem[index];
517         } else {
518             return NULL;
519         }
520     }
521 
522     for (index = 0; index < dev_comp->elem_count; index++) {
523         struct bt_mesh_elem *elem = &dev_comp->elem[index];
524 
525         if (bt_mesh_elem_find_group(elem, addr)) {
526             return elem;
527         }
528     }
529 
530     return NULL;
531 }
532 
bt_mesh_elem_count(void)533 uint8_t bt_mesh_elem_count(void)
534 {
535     return dev_comp->elem_count;
536 }
537 
model_has_key(struct bt_mesh_model * mod,uint16_t key)538 static bool model_has_key(struct bt_mesh_model *mod, uint16_t key)
539 {
540     int i;
541 
542     for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
543         if (mod->keys[i] == key) {
544             return true;
545         }
546     }
547 
548     return false;
549 }
550 
model_has_dst(struct bt_mesh_model * model,uint16_t dst)551 static bool model_has_dst(struct bt_mesh_model *model, uint16_t dst)
552 {
553     if (BLE_MESH_ADDR_IS_UNICAST(dst)) {
554         return (dev_comp->elem[model->elem_idx].addr == dst);
555     } else if (BLE_MESH_ADDR_IS_GROUP(dst) || BLE_MESH_ADDR_IS_VIRTUAL(dst)) {
556         return !!bt_mesh_model_find_group(model, dst);
557     }
558 
559     return (model->elem_idx == 0 && bt_mesh_fixed_group_match(dst));
560 }
561 
find_op(struct bt_mesh_model * models,uint8_t model_count,uint32_t opcode,struct bt_mesh_model ** model)562 static const struct bt_mesh_model_op *find_op(struct bt_mesh_model *models,
563                                               uint8_t model_count, uint32_t opcode,
564                                               struct bt_mesh_model **model)
565 {
566     int i;
567 
568     for (i = 0; i < model_count; i++) {
569         const struct bt_mesh_model_op *op;
570 
571         *model = &models[i];
572 
573         for (op = (*model)->op; op->func; op++) {
574             if (op->opcode == opcode) {
575                 return op;
576             }
577         }
578     }
579 
580     *model = NULL;
581     return NULL;
582 }
583 
get_opcode(struct net_buf_simple * buf,uint32_t * opcode)584 static int get_opcode(struct net_buf_simple *buf, uint32_t *opcode)
585 {
586     switch (buf->data[0] >> 6) {
587     case 0x00:
588     case 0x01:
589         if (buf->data[0] == 0x7f) {
590             BT_ERR("Ignoring RFU OpCode");
591             return -EINVAL;
592         }
593 
594         *opcode = net_buf_simple_pull_u8(buf);
595         return 0;
596     case 0x02:
597         if (buf->len < 2) {
598             BT_ERR("Too short payload for 2-octet OpCode");
599             return -EINVAL;
600         }
601 
602         *opcode = net_buf_simple_pull_be16(buf);
603         return 0;
604     case 0x03:
605         if (buf->len < 3) {
606             BT_ERR("Too short payload for 3-octet OpCode");
607             return -EINVAL;
608         }
609 
610         *opcode = net_buf_simple_pull_u8(buf) << 16;
611         /* Using LE for the CID since the model layer is defined as
612          * little-endian in the mesh spec and using BT_MESH_MODEL_OP_3
613          * will declare the opcode in this way.
614          */
615         *opcode |= net_buf_simple_pull_le16(buf);
616         return 0;
617     }
618 
619     return -EINVAL;
620 }
621 
bt_mesh_fixed_group_match(uint16_t addr)622 bool bt_mesh_fixed_group_match(uint16_t addr)
623 {
624     /* Check for fixed group addresses */
625     switch (addr) {
626     case BLE_MESH_ADDR_ALL_NODES:
627         return true;
628     case BLE_MESH_ADDR_PROXIES:
629         return (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED);
630     case BLE_MESH_ADDR_FRIENDS:
631         return (bt_mesh_friend_get() == BLE_MESH_FRIEND_ENABLED);
632     case BLE_MESH_ADDR_RELAYS:
633         return (bt_mesh_relay_get() == BLE_MESH_RELAY_ENABLED);
634     default:
635         return false;
636     }
637 }
638 
bt_mesh_model_recv(struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)639 void bt_mesh_model_recv(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
640 {
641     struct bt_mesh_model *models = NULL, *model = NULL;
642     const struct bt_mesh_model_op *op = NULL;
643     uint32_t opcode = 0U;
644     uint8_t count = 0U;
645     int i;
646 
647     BT_INFO("recv, app_idx 0x%04x src 0x%04x dst 0x%04x", rx->ctx.app_idx,
648            rx->ctx.addr, rx->ctx.recv_dst);
649     BT_INFO("recv, len %u: %s", buf->len, bt_hex(buf->data, buf->len));
650 
651     if (get_opcode(buf, &opcode) < 0) {
652         BT_WARN("Unable to decode OpCode");
653         return;
654     }
655 
656     BT_DBG("OpCode 0x%08x", opcode);
657 
658     for (i = 0; i < dev_comp->elem_count; i++) {
659         struct bt_mesh_elem *elem = &dev_comp->elem[i];
660         struct net_buf_simple_state state = {0};
661 
662         /* SIG models cannot contain 3-byte (vendor) OpCodes, and
663          * vendor models cannot contain SIG (1- or 2-byte) OpCodes, so
664          * we only need to do the lookup in one of the model lists.
665          */
666         if (BLE_MESH_MODEL_OP_LEN(opcode) < 3) {
667             models = elem->models;
668             count = elem->model_count;
669         } else {
670             models = elem->vnd_models;
671             count = elem->vnd_model_count;
672         }
673 
674         op = find_op(models, count, opcode, &model);
675         if (!op) {
676             BT_DBG("No OpCode 0x%08x for elem %d", opcode, i);
677             continue;
678         }
679 
680         if (!model_has_key(model, rx->ctx.app_idx)) {
681             continue;
682         }
683 
684         if (!model_has_dst(model, rx->ctx.recv_dst)) {
685             continue;
686         }
687 
688         if (buf->len < op->min_len) {
689             BT_ERR("Too short message for OpCode 0x%08x", opcode);
690             continue;
691         }
692 
693         /* The following three operations are added by Espressif.
694          * 1. Update the "recv_op" with the opcode got from the buf;
695          * 2. Update the model pointer with the found model;
696          * 3. Update the "srv_send" to be true when received a message.
697          *    This flag will be used when a server model sends a status
698          *    message, and has no impact on the client messages.
699          * Most of these info will be used by the application layer.
700          */
701         rx->ctx.recv_op = opcode;
702         rx->ctx.model = model;
703         rx->ctx.srv_send = true;
704 
705         /* The callback will likely parse the buffer, so store
706          * the parsing state in case multiple models receive
707          * the message.
708          */
709         net_buf_simple_save(buf, &state);
710         op->func(model, &rx->ctx, buf);
711         net_buf_simple_restore(buf, &state);
712     }
713 }
714 
bt_mesh_model_msg_init(struct net_buf_simple * msg,uint32_t opcode)715 void bt_mesh_model_msg_init(struct net_buf_simple *msg, uint32_t opcode)
716 {
717     net_buf_simple_init(msg, 0);
718 
719     switch (BLE_MESH_MODEL_OP_LEN(opcode)) {
720     case 1:
721         net_buf_simple_add_u8(msg, opcode);
722         break;
723     case 2:
724         net_buf_simple_add_be16(msg, opcode);
725         break;
726     case 3:
727         net_buf_simple_add_u8(msg, ((opcode >> 16) & 0xff));
728         /* Using LE for the CID since the model layer is defined as
729          * little-endian in the mesh spec and using BT_MESH_MODEL_OP_3
730          * will declare the opcode in this way.
731          */
732         net_buf_simple_add_le16(msg, opcode & 0xffff);
733         break;
734     default:
735         BT_WARN("Unknown opcode format");
736         break;
737     }
738 }
739 
ready_to_send(uint8_t role,uint16_t dst)740 static bool ready_to_send(uint8_t role, uint16_t dst)
741 {
742     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() && role == NODE) {
743         return true;
744     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en() && role == PROVISIONER) {
745         if (!bt_mesh_provisioner_check_msg_dst(dst)) {
746             BT_ERR("Failed to find DST 0x%04x", dst);
747             return false;
748         }
749         return true;
750     } else if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && bt_mesh_is_provisioned() && role == FAST_PROV) {
751         return true;
752     }
753 
754     return false;
755 }
756 
model_send(struct bt_mesh_model * model,struct bt_mesh_net_tx * tx,bool implicit_bind,struct net_buf_simple * msg,const struct bt_mesh_send_cb * cb,void * cb_data)757 static int model_send(struct bt_mesh_model *model,
758                       struct bt_mesh_net_tx *tx, bool implicit_bind,
759                       struct net_buf_simple *msg,
760                       const struct bt_mesh_send_cb *cb, void *cb_data)
761 {
762     uint8_t role = 0U;
763 
764     role = bt_mesh_get_device_role(model, tx->ctx->srv_send);
765     if (role == ROLE_NVAL) {
766         BT_ERR("Failed to get model role");
767         return -EINVAL;
768     }
769 
770     BT_INFO("send, app_idx 0x%04x src 0x%04x dst 0x%04x",
771         tx->ctx->app_idx, tx->src, tx->ctx->addr);
772     BT_INFO("send, len %u: %s", msg->len, bt_hex(msg->data, msg->len));
773 
774     if (!ready_to_send(role, tx->ctx->addr)) {
775         BT_ERR("Not ready to send");
776         return -EINVAL;
777     }
778 
779     if (net_buf_simple_tailroom(msg) < BLE_MESH_MIC_SHORT) {
780         BT_ERR("Not enough tailroom for TransMIC");
781         return -EINVAL;
782     }
783 
784     if (msg->len > MIN(BLE_MESH_TX_SDU_MAX, BLE_MESH_SDU_MAX_LEN) - BLE_MESH_MIC_SHORT) {
785         BT_ERR("Too big message (len %d)", msg->len);
786         return -EMSGSIZE;
787     }
788 
789     if (!implicit_bind && !model_has_key(model, tx->ctx->app_idx)) {
790         BT_ERR("Model not bound to AppKey 0x%04x", tx->ctx->app_idx);
791         return -EINVAL;
792     }
793 
794     return bt_mesh_trans_send(tx, msg, cb, cb_data);
795 }
796 
bt_mesh_model_send(struct bt_mesh_model * model,struct bt_mesh_msg_ctx * ctx,struct net_buf_simple * msg,const struct bt_mesh_send_cb * cb,void * cb_data)797 int bt_mesh_model_send(struct bt_mesh_model *model,
798                        struct bt_mesh_msg_ctx *ctx,
799                        struct net_buf_simple *msg,
800                        const struct bt_mesh_send_cb *cb, void *cb_data)
801 {
802     struct bt_mesh_subnet *sub = NULL;
803     uint8_t role = 0U;
804 
805     role = bt_mesh_get_device_role(model, ctx->srv_send);
806     if (role == ROLE_NVAL) {
807         BT_ERR("Failed to get model role");
808         return -EINVAL;
809     }
810 
811     sub = bt_mesh_tx_netkey_get(role, ctx->net_idx);
812     if (!sub) {
813         BT_ERR("Invalid NetKeyIndex 0x%04x", ctx->net_idx);
814         return -EINVAL;
815     }
816 
817     ctx->model = model;
818 
819     struct bt_mesh_net_tx tx = {
820         .sub = sub,
821         .ctx = ctx,
822         .src = bt_mesh_model_elem(model)->addr,
823         .xmit = bt_mesh_net_transmit_get(),
824         .friend_cred = 0,
825     };
826 
827     return model_send(model, &tx, false, msg, cb, cb_data);
828 }
829 
bt_mesh_model_publish(struct bt_mesh_model * model)830 int bt_mesh_model_publish(struct bt_mesh_model *model)
831 {
832     struct bt_mesh_model_pub *pub = model->pub;
833     struct bt_mesh_app_key *key = NULL;
834     struct net_buf_simple *sdu = NULL;
835     struct bt_mesh_msg_ctx ctx = {
836         .model = model,
837     };
838     struct bt_mesh_net_tx tx = {
839         .sub = NULL,
840         .ctx = &ctx,
841         .src = bt_mesh_model_elem(model)->addr,
842         .xmit = bt_mesh_net_transmit_get(),
843     };
844     int err = 0;
845 
846     BT_DBG("%s", __func__);
847 
848     if (!pub || !pub->msg) {
849         BT_ERR("Model has no publication support");
850         return -ENOTSUP;
851     }
852 
853     if (pub->addr == BLE_MESH_ADDR_UNASSIGNED) {
854         BT_WARN("Unassigned publish address");
855         return -EADDRNOTAVAIL;
856     }
857 
858     key = bt_mesh_tx_appkey_get(pub->dev_role, pub->key);
859     if (!key) {
860         BT_ERR("Invalid AppKeyIndex 0x%03x", pub->key);
861         return -EADDRNOTAVAIL;
862     }
863 
864     if (pub->msg->len + BLE_MESH_MIC_SHORT > MIN(BLE_MESH_TX_SDU_MAX, BLE_MESH_SDU_MAX_LEN)) {
865         BT_ERR("Message does not fit maximum SDU size");
866         return -EMSGSIZE;
867     }
868 
869     if (pub->count) {
870         BT_WARN("Clearing publish retransmit timer");
871         k_delayed_work_cancel(&pub->timer);
872     }
873 
874     ctx.addr = pub->addr;
875     ctx.send_rel = pub->send_rel;
876     ctx.send_ttl = pub->ttl;
877     ctx.net_idx = key->net_idx;
878     ctx.app_idx = key->app_idx;
879     ctx.srv_send = pub->dev_role == NODE ? true : false;
880 
881     tx.friend_cred = pub->cred;
882 
883     tx.sub = bt_mesh_tx_netkey_get(pub->dev_role, ctx.net_idx);
884     if (!tx.sub) {
885         BT_ERR("Invalid NetKeyIndex 0x%04x", ctx.net_idx);
886         return -EADDRNOTAVAIL;
887     }
888 
889     pub->count = BLE_MESH_PUB_TRANSMIT_COUNT(pub->retransmit);
890 
891     BT_INFO("Publish Retransmit Count %u Interval %ums", pub->count,
892            BLE_MESH_PUB_TRANSMIT_INT(pub->retransmit));
893 
894     sdu = bt_mesh_alloc_buf(pub->msg->len + BLE_MESH_MIC_SHORT);
895     if (!sdu) {
896         BT_ERR("%s, Out of memory", __func__);
897         return -ENOMEM;
898     }
899 
900     net_buf_simple_add_mem(sdu, pub->msg->data, pub->msg->len);
901 
902     err = model_send(model, &tx, true, sdu, &pub_sent_cb, model);
903     if (err) {
904         publish_retransmit_end(err, pub);
905     }
906 
907     bt_mesh_free_buf(sdu);
908     return err;
909 }
910 
bt_mesh_model_find_vnd(struct bt_mesh_elem * elem,uint16_t company,uint16_t id)911 struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem,
912                                              uint16_t company, uint16_t id)
913 {
914     int i;
915 
916     for (i = 0; i < elem->vnd_model_count; i++) {
917         if (elem->vnd_models[i].vnd.company == company &&
918                 elem->vnd_models[i].vnd.id == id) {
919             return &elem->vnd_models[i];
920         }
921     }
922 
923     return NULL;
924 }
925 
bt_mesh_model_find(struct bt_mesh_elem * elem,uint16_t id)926 struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem *elem, uint16_t id)
927 {
928     int i;
929 
930     for (i = 0; i < elem->model_count; i++) {
931         if (elem->models[i].id == id) {
932             return &elem->models[i];
933         }
934     }
935 
936     return NULL;
937 }
938 
bt_mesh_comp_get(void)939 const struct bt_mesh_comp *bt_mesh_comp_get(void)
940 {
941     return dev_comp;
942 }
943 
944 /* APIs used by messages encryption in upper transport layer & network layer */
bt_mesh_tx_netkey_get(uint8_t role,uint16_t net_idx)945 struct bt_mesh_subnet *bt_mesh_tx_netkey_get(uint8_t role, uint16_t net_idx)
946 {
947     struct bt_mesh_subnet *sub = NULL;
948 
949     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() && role == NODE) {
950         sub = bt_mesh_subnet_get(net_idx);
951     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en() && role == PROVISIONER) {
952         sub = bt_mesh_provisioner_subnet_get(net_idx);
953     } else if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && bt_mesh_is_provisioned() && role == FAST_PROV) {
954         sub = bt_mesh_fast_prov_subnet_get(net_idx);
955     }
956 
957     return sub;
958 }
959 
bt_mesh_tx_devkey_get(uint8_t role,uint16_t dst)960 const uint8_t *bt_mesh_tx_devkey_get(uint8_t role, uint16_t dst)
961 {
962     const uint8_t *key = NULL;
963 
964     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() && role == NODE) {
965         key = bt_mesh.dev_key;
966     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en() && role == PROVISIONER) {
967         key = bt_mesh_provisioner_dev_key_get(dst);
968     } else if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && bt_mesh_is_provisioned() && role == FAST_PROV) {
969         key = bt_mesh_fast_prov_dev_key_get(dst);
970     }
971 
972     return key;
973 }
974 
bt_mesh_tx_appkey_get(uint8_t role,uint16_t app_idx)975 struct bt_mesh_app_key *bt_mesh_tx_appkey_get(uint8_t role, uint16_t app_idx)
976 {
977     struct bt_mesh_app_key *key = NULL;
978 
979     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() && role == NODE) {
980         key = bt_mesh_app_key_find(app_idx);
981     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en() && role == PROVISIONER) {
982         key = bt_mesh_provisioner_app_key_find(app_idx);
983     } else if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && bt_mesh_is_provisioned() && role == FAST_PROV) {
984         key = bt_mesh_fast_prov_app_key_find(app_idx);
985     }
986 
987     return key;
988 }
989 
990 /* APIs used by messages decryption in network layer & upper transport layer */
bt_mesh_rx_netkey_size(void)991 size_t bt_mesh_rx_netkey_size(void)
992 {
993     size_t size = 0U;
994 
995 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
996     if (bt_mesh_is_provisioned()) {
997         size = ARRAY_SIZE(bt_mesh.sub);
998     }
999 #endif
1000 
1001 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1002     if (bt_mesh_is_provisioner_en()) {
1003         size = ARRAY_SIZE(bt_mesh.p_sub);
1004     }
1005 #endif
1006 
1007 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1008     size = ARRAY_SIZE(bt_mesh.sub);
1009     if (bt_mesh_is_provisioner_en()) {
1010         size += ARRAY_SIZE(bt_mesh.p_sub);
1011     }
1012 #endif
1013 
1014     return size;
1015 }
1016 
bt_mesh_rx_netkey_get(size_t index)1017 struct bt_mesh_subnet *bt_mesh_rx_netkey_get(size_t index)
1018 {
1019     struct bt_mesh_subnet *sub = NULL;
1020 
1021 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
1022     if (bt_mesh_is_provisioned()) {
1023         sub = &bt_mesh.sub[index];
1024     }
1025 #endif
1026 
1027 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1028     if (bt_mesh_is_provisioner_en()) {
1029         sub = bt_mesh.p_sub[index];
1030     }
1031 #endif
1032 
1033 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1034     if (index < ARRAY_SIZE(bt_mesh.sub)) {
1035         sub = &bt_mesh.sub[index];
1036     } else {
1037         sub = bt_mesh.p_sub[index - ARRAY_SIZE(bt_mesh.sub)];
1038     }
1039 #endif
1040 
1041     return sub;
1042 }
1043 
bt_mesh_rx_devkey_size(void)1044 size_t bt_mesh_rx_devkey_size(void)
1045 {
1046     size_t size = 0U;
1047 
1048 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
1049     if (bt_mesh_is_provisioned()) {
1050         size = 1;
1051     }
1052 #endif
1053 
1054 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1055     if (bt_mesh_is_provisioner_en()) {
1056         size = 1;
1057     }
1058 #endif
1059 
1060 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1061     size = 1;
1062     if (bt_mesh_is_provisioner_en()) {
1063         size += 1;
1064     }
1065 #endif
1066 
1067     return size;
1068 }
1069 
bt_mesh_rx_devkey_get(size_t index,uint16_t src)1070 const uint8_t *bt_mesh_rx_devkey_get(size_t index, uint16_t src)
1071 {
1072     const uint8_t *key = NULL;
1073 
1074 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
1075     if (bt_mesh_is_provisioned()) {
1076         key = bt_mesh.dev_key;
1077     }
1078 #endif
1079 
1080 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1081     if (bt_mesh_is_provisioner_en()) {
1082         key = bt_mesh_provisioner_dev_key_get(src);
1083     }
1084 #endif
1085 
1086 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1087     if (index < 1) {
1088         key = bt_mesh.dev_key;
1089     } else {
1090         key = bt_mesh_provisioner_dev_key_get(src);
1091     }
1092 #endif
1093 
1094     return key;
1095 }
1096 
bt_mesh_rx_appkey_size(void)1097 size_t bt_mesh_rx_appkey_size(void)
1098 {
1099     size_t size = 0U;
1100 
1101 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
1102     if (bt_mesh_is_provisioned()) {
1103         size = ARRAY_SIZE(bt_mesh.app_keys);
1104     }
1105 #endif
1106 
1107 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1108     if (bt_mesh_is_provisioner_en()) {
1109         size = ARRAY_SIZE(bt_mesh.p_app_keys);
1110     }
1111 #endif
1112 
1113 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1114     size = ARRAY_SIZE(bt_mesh.app_keys);
1115     if (bt_mesh_is_provisioner_en()) {
1116         size += ARRAY_SIZE(bt_mesh.p_app_keys);
1117     }
1118 #endif
1119 
1120     return size;
1121 }
1122 
bt_mesh_rx_appkey_get(size_t index)1123 struct bt_mesh_app_key *bt_mesh_rx_appkey_get(size_t index)
1124 {
1125     struct bt_mesh_app_key *key = NULL;
1126 
1127 #if CONFIG_BLE_MESH_NODE && !CONFIG_BLE_MESH_PROVISIONER
1128     if (bt_mesh_is_provisioned()) {
1129         key = &bt_mesh.app_keys[index];
1130     }
1131 #endif
1132 
1133 #if !CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1134     if (bt_mesh_is_provisioner_en()) {
1135         key = bt_mesh.p_app_keys[index];
1136     }
1137 #endif
1138 
1139 #if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PROVISIONER
1140     if (index < ARRAY_SIZE(bt_mesh.app_keys)) {
1141         key = &bt_mesh.app_keys[index];
1142     } else {
1143         key = bt_mesh.p_app_keys[index - ARRAY_SIZE(bt_mesh.app_keys)];
1144     }
1145 #endif
1146 
1147     return key;
1148 }
1149