1 /*
2  * SPDX-FileCopyrightText: 2017-2024 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <string.h>
8 #include <errno.h>
9 
10 #include "crypto.h"
11 #include "adv.h"
12 #include "scan.h"
13 #include "mesh.h"
14 #include "access.h"
15 #include "settings.h"
16 #include "fast_prov.h"
17 #include "mesh_common.h"
18 #include "proxy_client.h"
19 #include "provisioner_prov.h"
20 #include "provisioner_main.h"
21 
22 #define PROV_SVC_ADV_RX_CHECK(pre, cur)   ((cur) < (pre) ? ((cur) + (UINT32_MAX - (pre)) >= 200) : ((cur) - (pre) >= 200))
23 
24 #if CONFIG_BLE_MESH_PROVISIONER
25 
26 _Static_assert(BLE_MESH_MAX_CONN >= CONFIG_BLE_MESH_PBG_SAME_TIME,
27                "Too large BLE Mesh PB-GATT count");
28 
29 /* 3 transmissions, 20ms interval */
30 #define PROV_XMIT              BLE_MESH_TRANSMIT(2, 20)
31 
32 #define AUTH_METHOD_NO_OOB     0x00
33 #define AUTH_METHOD_STATIC     0x01
34 #define AUTH_METHOD_OUTPUT     0x02
35 #define AUTH_METHOD_INPUT      0x03
36 
37 #define OUTPUT_OOB_BLINK       0x00
38 #define OUTPUT_OOB_BEEP        0x01
39 #define OUTPUT_OOB_VIBRATE     0x02
40 #define OUTPUT_OOB_NUMBER      0x03
41 #define OUTPUT_OOB_STRING      0x04
42 
43 #define INPUT_OOB_PUSH         0x00
44 #define INPUT_OOB_TWIST        0x01
45 #define INPUT_OOB_NUMBER       0x02
46 #define INPUT_OOB_STRING       0x03
47 
48 #define PROV_ERR_NONE          0x00
49 #define PROV_ERR_NVAL_PDU      0x01
50 #define PROV_ERR_NVAL_FMT      0x02
51 #define PROV_ERR_UNEXP_PDU     0x03
52 #define PROV_ERR_CFM_FAILED    0x04
53 #define PROV_ERR_RESOURCES     0x05
54 #define PROV_ERR_DECRYPT       0x06
55 #define PROV_ERR_UNEXP_ERR     0x07
56 #define PROV_ERR_ADDR          0x08
57 
58 #define PROV_INVITE            0x00
59 #define PROV_CAPABILITIES      0x01
60 #define PROV_START             0x02
61 #define PROV_PUB_KEY           0x03
62 #define PROV_INPUT_COMPLETE    0x04
63 #define PROV_CONFIRM           0x05
64 #define PROV_RANDOM            0x06
65 #define PROV_DATA              0x07
66 #define PROV_COMPLETE          0x08
67 #define PROV_FAILED            0x09
68 
69 #define PROV_ALG_P256          0x00
70 
71 #define GPCF(gpc)              (gpc & 0x03)
72 #define GPC_START(last_seg)    (((last_seg) << 2) | 0x00)
73 #define GPC_ACK                0x01
74 #define GPC_CONT(seg_id)       (((seg_id) << 2) | 0x02)
75 #define GPC_CTL(op)            (((op) << 2) | 0x03)
76 
77 #define START_PAYLOAD_MAX      20
78 #define CONT_PAYLOAD_MAX       23
79 #define START_LAST_SEG_MAX     2
80 
81 #define START_LAST_SEG(gpc)    (gpc >> 2)
82 #define CONT_SEG_INDEX(gpc)    (gpc >> 2)
83 
84 #define BEARER_CTL(gpc)        (gpc >> 2)
85 #define LINK_OPEN              0x00
86 #define LINK_ACK               0x01
87 #define LINK_CLOSE             0x02
88 
89 #define CLOSE_REASON_SUCCESS   0x00
90 #define CLOSE_REASON_TIMEOUT   0x01
91 #define CLOSE_REASON_FAILED    0x02
92 
93 #define PROV_AUTH_VAL_SIZE     0x10
94 #define PROV_CONF_SALT_SIZE    0x10
95 #define PROV_CONF_KEY_SIZE     0x10
96 #define PROV_DH_KEY_SIZE       0x20
97 #define PROV_CONFIRM_SIZE      0x10
98 #define PROV_RANDOM_SIZE       0x10
99 #define PROV_PROV_SALT_SIZE    0x10
100 #define PROV_CONF_INPUTS_SIZE  0x91
101 
102 #define XACT_SEG_DATA(_idx, _seg) (&link[_idx].rx.buf->data[20 + ((_seg - 1) * 23)])
103 #define XACT_SEG_RECV(_idx, _seg) (link[_idx].rx.seg &= ~(1 << (_seg)))
104 
105 #define XACT_NVAL              0xff
106 
107 enum {
108     REMOTE_PUB_KEY,        /* Remote key has been received */
109     LOCAL_PUB_KEY,         /* Local public key is available */
110     LINK_ACTIVE,           /* Link has been opened */
111     WAIT_GEN_DHKEY,        /* Waiting for remote public key to generate DHKey */
112     HAVE_DHKEY,            /* DHKey has been calculated */
113     SEND_CONFIRM,          /* Waiting to send Confirm value */
114     WAIT_NUMBER,           /* Waiting for number input from user */
115     WAIT_STRING,           /* Waiting for string input from user */
116     TIMEOUT_START,         /* Provision timeout timer has started */
117     NUM_FLAGS,
118 };
119 
120 /** Provisioner link structure allocation
121  * |--------------------------------------------------------|
122  * |            Link(PB-ADV)            |   Link(PB-GATT)   |
123  * |--------------------------------------------------------|
124  * |<----------------------Total Link---------------------->|
125  */
126 struct prov_link {
127     BLE_MESH_ATOMIC_DEFINE(flags, NUM_FLAGS);
128     uint8_t  uuid[16];          /* check if device is being provisioned*/
129     uint16_t oob_info;          /* oob info of this device */
130     uint8_t  element_num;       /* element num of device */
131     uint8_t  ki_flags;          /* Key refresh flag and iv update flag */
132     uint32_t iv_index;          /* IV Index */
133     uint8_t  auth_method;       /* Choosen authentication method */
134     uint8_t  auth_action;       /* Choosen authentication action */
135     uint8_t  auth_size;         /* Choosen authentication size */
136     uint16_t assign_addr;       /* Application assigned address for the device */
137     uint16_t unicast_addr;      /* unicast address allocated for device */
138     bt_mesh_addr_t addr;        /* Device address */
139 #if defined(CONFIG_BLE_MESH_PB_GATT)
140     bool   connecting;          /* start connecting with device */
141     struct bt_mesh_conn *conn;  /* GATT connection */
142 #endif
143     uint8_t  expect;            /* Next expected PDU */
144 
145     uint8_t *dhkey;             /* Calculated DHKey */
146     uint8_t *auth;              /* Authentication Value */
147 
148     uint8_t *conf_salt;         /* ConfirmationSalt */
149     uint8_t *conf_key;          /* ConfirmationKey */
150     uint8_t *conf_inputs;       /* ConfirmationInputs */
151 
152     uint8_t *rand;              /* Local Random */
153     uint8_t *conf;              /* Remote Confirmation */
154     uint8_t *local_conf;        /* Local Confirmation */
155 
156     uint8_t *prov_salt;         /* Provisioning Salt */
157 
158 #if defined(CONFIG_BLE_MESH_PB_ADV)
159     bool     linking;           /* Linking is being establishing */
160     uint16_t send_link_close;   /* Link close is being sent flag */
161     uint32_t link_id;           /* Link ID */
162     uint8_t  pending_ack;       /* Decide which transaction id ack is pending */
163     uint8_t  expect_ack_for;    /* Transaction ACK expected for provisioning pdu */
164     uint8_t  tx_pdu_type;       /* The current transmitted Provisioning PDU type */
165 
166     struct {
167         uint8_t trans_id;       /* Transaction ID */
168         uint8_t prev_id;        /* Previous Transaction ID */
169         uint8_t seg;            /* Bit-field of unreceived segments */
170         uint8_t last_seg;       /* Last segment (to check length) */
171         uint8_t fcs;            /* Expected FCS value */
172         uint8_t adv_buf_id;     /* index of buf allocated in adv_buf_data */
173         struct net_buf_simple *buf;
174     } rx;
175 
176     struct {
177         /* Start timestamp of the transaction */
178         int64_t start;
179 
180         /* Transaction id*/
181         uint8_t trans_id;
182 
183         /* Pending outgoing buffer(s) */
184         struct net_buf *buf[3];
185 
186         /* Retransmit timer */
187         struct k_delayed_work retransmit;
188     } tx;
189 #endif
190 
191     /** Provision timeout timer. Spec P259 says: The provisioning protocol
192      *  shall have a minimum timeout of 60 seconds that is reset each time
193      *  a provisioning protocol PDU is sent or received.
194      */
195     struct k_delayed_work timeout;
196 };
197 
198 /* Number of devices can be provisioned at the same time equals to PB-ADV + PB-GATT */
199 #define BLE_MESH_PROV_SAME_TIME \
200     (CONFIG_BLE_MESH_PBA_SAME_TIME + CONFIG_BLE_MESH_PBG_SAME_TIME)
201 
202 #define PROV_MAX_ADDR_TO_ASSIGN    0x7FFF
203 
204 static struct prov_link link[BLE_MESH_PROV_SAME_TIME];
205 
206 struct prov_rx {
207     uint32_t link_id;
208     uint8_t  xact_id;
209     uint8_t  gpc;
210 };
211 
212 struct bt_mesh_prov_ctx {
213     /* Primary element address of Provisioner */
214     uint16_t primary_addr;
215 
216     /* Provisioning bearers used by Provisioner */
217     bt_mesh_prov_bearer_t bearers;
218 
219     /* Current number of PB-ADV provisioned devices simultaneously */
220     uint8_t  pba_count;
221 
222     /* Current number of PB-GATT provisioned devices simultaneously */
223     uint8_t  pbg_count;
224 
225     /* Current unicast address going to allocated */
226     uint16_t curr_alloc_addr;
227 
228     /* Current net_idx going to be used in provisioning data */
229     uint16_t curr_net_idx;
230 
231     /* Current flags going to be used in provisioning data */
232     uint8_t  curr_flags;
233 
234     /* Current iv_index going to be used in provisioning data */
235     uint16_t curr_iv_index;
236 
237     /* Length of Static OOB value */
238     uint8_t  static_oob_len;
239 
240     /* Static OOB value */
241     uint8_t  static_oob_val[16];
242 
243     /* Offset of the device uuid to be matched, based on zero */
244     uint8_t  match_offset;
245 
246     /* Length of the device uuid to be matched (start from the match_offset) */
247     uint8_t  match_length;
248 
249     /* Value of the device uuid to be matched */
250     uint8_t  match_value[16];
251 
252     /* Indicate when received uuid_match adv_pkts, can provision it at once */
253     bool prov_after_match;
254 
255 #if defined(CONFIG_BLE_MESH_PB_ADV)
256     /* Mutex used to protect the PB-ADV procedure */
257     bt_mesh_mutex_t pb_adv_lock;
258 
259     /* Mutex used to protect the adv buf during PB-ADV procedure */
260     bt_mesh_mutex_t pb_buf_lock;
261 #endif
262 
263 #if defined(CONFIG_BLE_MESH_PB_GATT)
264     /* Mutex used to protect the PB-GATT procedure */
265     bt_mesh_mutex_t pb_gatt_lock;
266 #endif
267 
268     /* Fast provisioning related information */
269     struct {
270         bool     enable;
271         uint16_t net_idx;
272         uint8_t  flags;
273         uint32_t iv_index;
274         uint16_t unicast_addr_min;
275         uint16_t unicast_addr_max;
276     } fast_prov;
277 };
278 
279 static struct bt_mesh_prov_ctx prov_ctx;
280 
281 #define FAST_PROV_ENABLE()  (prov_ctx.fast_prov.enable)
282 
283 struct unprov_dev_queue {
284     bt_mesh_addr_t addr;
285     uint8_t  uuid[16];
286     uint16_t oob_info;
287     uint8_t  bearer;
288     uint8_t  flags;
289 } __packed unprov_dev[CONFIG_BLE_MESH_WAIT_FOR_PROV_MAX_DEV_NUM] = {
290     [0 ... (CONFIG_BLE_MESH_WAIT_FOR_PROV_MAX_DEV_NUM - 1)] = {
291         .addr.type = 0xff,
292         .bearer    = 0,
293         .flags     = false,
294     },
295 };
296 
297 static unprov_adv_pkt_cb_t   notify_unprov_adv_pkt_cb;
298 
299 #define BUF_TIMEOUT          K_MSEC(400)
300 
301 #if defined(CONFIG_BLE_MESH_FAST_PROV)
302 #define RETRANSMIT_TIMEOUT   K_MSEC(360)
303 #define TRANSACTION_TIMEOUT  K_SECONDS(3)
304 #define PROVISION_TIMEOUT    K_SECONDS(6)
305 #else
306 #define RETRANSMIT_TIMEOUT   K_MSEC(500)
307 #define TRANSACTION_TIMEOUT  K_SECONDS(30)
308 #define PROVISION_TIMEOUT    K_SECONDS(60)
309 #endif /* CONFIG_BLE_MESH_FAST_PROV */
310 
311 #if defined(CONFIG_BLE_MESH_PB_GATT)
312 #define PROV_BUF_HEADROOM 5
313 #else
314 #define PROV_BUF_HEADROOM 0
315 #endif
316 
317 #define PROV_BUF(name, len) \
318     NET_BUF_SIMPLE_DEFINE(name, PROV_BUF_HEADROOM + len)
319 
320 static const struct bt_mesh_prov *prov;
321 
322 #if defined(CONFIG_BLE_MESH_PB_ADV)
323 static void send_link_open(const uint8_t idx);
324 #endif
325 
326 static void prov_gen_dh_key(const uint8_t idx);
327 
328 static void send_pub_key(const uint8_t idx, uint8_t oob);
329 
330 static void close_link(const uint8_t idx, uint8_t reason);
331 
332 #if defined(CONFIG_BLE_MESH_PB_ADV)
333 #define ADV_BUF_SIZE    65
334 
335 static struct prov_adv_buf {
336     struct net_buf_simple buf;
337 } adv_buf[CONFIG_BLE_MESH_PBA_SAME_TIME];
338 
339 static uint8_t adv_buf_data[ADV_BUF_SIZE * CONFIG_BLE_MESH_PBA_SAME_TIME];
340 #endif /* CONFIG_BLE_MESH_PB_ADV */
341 
342 #define PROV_FREE_MEM(_idx, member)     \
343 {                                       \
344     if (link[_idx].member) {            \
345         bt_mesh_free(link[_idx].member);    \
346         link[_idx].member = NULL;       \
347     }                                   \
348 }
349 
350 #if defined(CONFIG_BLE_MESH_PB_ADV)
bt_mesh_pb_adv_mutex_new(void)351 static inline void bt_mesh_pb_adv_mutex_new(void)
352 {
353     if (!prov_ctx.pb_adv_lock.mutex) {
354         bt_mesh_mutex_create(&prov_ctx.pb_adv_lock);
355     }
356 }
357 
358 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_pb_adv_mutex_free(void)359 static inline void bt_mesh_pb_adv_mutex_free(void)
360 {
361     bt_mesh_mutex_free(&prov_ctx.pb_adv_lock);
362 }
363 #endif /* CONFIG_BLE_MESH_DEINIT */
364 
bt_mesh_pb_adv_lock(void)365 static inline void bt_mesh_pb_adv_lock(void)
366 {
367     bt_mesh_mutex_lock(&prov_ctx.pb_adv_lock);
368 }
369 
bt_mesh_pb_adv_unlock(void)370 static inline void bt_mesh_pb_adv_unlock(void)
371 {
372     bt_mesh_mutex_unlock(&prov_ctx.pb_adv_lock);
373 }
374 
bt_mesh_pb_buf_mutex_new(void)375 static inline void bt_mesh_pb_buf_mutex_new(void)
376 {
377     if (!prov_ctx.pb_buf_lock.mutex) {
378         bt_mesh_mutex_create(&prov_ctx.pb_buf_lock);
379     }
380 }
381 
382 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_pb_buf_mutex_free(void)383 static inline void bt_mesh_pb_buf_mutex_free(void)
384 {
385     bt_mesh_mutex_free(&prov_ctx.pb_buf_lock);
386 }
387 #endif /* CONFIG_BLE_MESH_DEINIT */
388 
bt_mesh_pb_buf_lock(void)389 static inline void bt_mesh_pb_buf_lock(void)
390 {
391     bt_mesh_mutex_lock(&prov_ctx.pb_buf_lock);
392 }
393 
bt_mesh_pb_buf_unlock(void)394 static inline void bt_mesh_pb_buf_unlock(void)
395 {
396     bt_mesh_mutex_unlock(&prov_ctx.pb_buf_lock);
397 }
398 #endif /* CONFIG_BLE_MESH_PB_ADV */
399 
400 #if defined(CONFIG_BLE_MESH_PB_GATT)
bt_mesh_pb_gatt_mutex_new(void)401 static inline void bt_mesh_pb_gatt_mutex_new(void)
402 {
403     if (!prov_ctx.pb_gatt_lock.mutex) {
404         bt_mesh_mutex_create(&prov_ctx.pb_gatt_lock);
405     }
406 }
407 
408 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_pb_gatt_mutex_free(void)409 static inline void bt_mesh_pb_gatt_mutex_free(void)
410 {
411     bt_mesh_mutex_free(&prov_ctx.pb_gatt_lock);
412 }
413 #endif /* CONFIG_BLE_MESH_DEINIT */
414 
bt_mesh_pb_gatt_lock(void)415 static inline void bt_mesh_pb_gatt_lock(void)
416 {
417     bt_mesh_mutex_lock(&prov_ctx.pb_gatt_lock);
418 }
419 
bt_mesh_pb_gatt_unlock(void)420 static inline void bt_mesh_pb_gatt_unlock(void)
421 {
422     bt_mesh_mutex_unlock(&prov_ctx.pb_gatt_lock);
423 }
424 
bt_mesh_provisioner_pbg_count_dec(void)425 void bt_mesh_provisioner_pbg_count_dec(void)
426 {
427     if (prov_ctx.pbg_count) {
428         prov_ctx.pbg_count--;
429     }
430 }
431 
provisioner_pbg_count_inc(void)432 static inline void provisioner_pbg_count_inc(void)
433 {
434     prov_ctx.pbg_count++;
435 }
436 
bt_mesh_provisioner_clear_link_info(const uint8_t addr[6])437 void bt_mesh_provisioner_clear_link_info(const uint8_t addr[6])
438 {
439     int i;
440 
441     if (!addr) {
442         BT_ERR("%s, Invalid parameter", __func__);
443         return;
444     }
445 
446     BT_DBG("Clear device info, addr %s", bt_hex(addr, BLE_MESH_ADDR_LEN));
447 
448     for (i = CONFIG_BLE_MESH_PBA_SAME_TIME; i < BLE_MESH_PROV_SAME_TIME; i++) {
449         if (!memcmp(link[i].addr.val, addr, BLE_MESH_ADDR_LEN)) {
450             link[i].connecting = false;
451             link[i].conn = NULL;
452             link[i].oob_info = 0x0;
453             memset(link[i].uuid, 0, 16);
454             memset(&link[i].addr, 0, sizeof(bt_mesh_addr_t));
455             bt_mesh_atomic_test_and_clear_bit(link[i].flags, LINK_ACTIVE);
456             if (bt_mesh_atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
457                 k_delayed_work_cancel(&link[i].timeout);
458             }
459             return;
460         }
461     }
462 
463     BT_WARN("Device not found, addr %s", bt_hex(addr, BLE_MESH_ADDR_LEN));
464     return;
465 }
466 #endif /* CONFIG_BLE_MESH_PB_GATT */
467 
bt_mesh_provisioner_get_prov_info(void)468 const struct bt_mesh_prov *bt_mesh_provisioner_get_prov_info(void)
469 {
470     return prov;
471 }
472 
bt_mesh_provisioner_restore_prov_info(uint16_t primary_addr,uint16_t alloc_addr)473 void bt_mesh_provisioner_restore_prov_info(uint16_t primary_addr, uint16_t alloc_addr)
474 {
475     prov_ctx.primary_addr = primary_addr;
476     prov_ctx.curr_alloc_addr = alloc_addr;
477 }
478 
is_unprov_dev_being_provision(const uint8_t uuid[16])479 static bool is_unprov_dev_being_provision(const uint8_t uuid[16])
480 {
481     int i;
482 
483 #if defined(CONFIG_BLE_MESH_FAST_PROV)
484     /**
485      * During Fast Provisioning test, we found that if a device has already being
486      * provisioned, there is still a chance that the Provisioner can receive the
487      * Unprovisioned Device Beacon from the device (because the device will stop
488      * Unprovisioned Device Beacon when Transaction ACK for Provisioning Complete
489      * is received). So in Fast Provisioning the Provisioner should ignore this.
490      */
491     if (bt_mesh_provisioner_get_node_with_uuid(uuid)) {
492         BT_WARN("Device has already been provisioned");
493         return true;
494     }
495 #endif
496 
497     for (i = 0; i < BLE_MESH_PROV_SAME_TIME; i++) {
498 #if defined(CONFIG_BLE_MESH_PB_ADV) && defined(CONFIG_BLE_MESH_PB_GATT)
499         if (link[i].linking || link[i].connecting ||
500                 bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
501 #elif defined(CONFIG_BLE_MESH_PB_ADV) && !defined(CONFIG_BLE_MESH_PB_GATT)
502         if (link[i].linking || bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
503 #else
504         if (link[i].connecting || bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
505 #endif
506             if (!memcmp(link[i].uuid, uuid, 16)) {
507                 BT_DBG("Device is being provisioning");
508                 return true;
509             }
510         }
511     }
512 
513     return false;
514 }
515 
516 static bool is_unprov_dev_uuid_match(const uint8_t uuid[16])
517 {
518     if (prov_ctx.match_length) {
519         if (memcmp(uuid + prov_ctx.match_offset,
520                    prov_ctx.match_value, prov_ctx.match_length)) {
521             return false;
522         }
523     }
524 
525     return true;
526 }
527 
528 static int provisioner_check_unprov_dev_info(const uint8_t uuid[16], bt_mesh_prov_bearer_t bearer)
529 {
530     if (!uuid) {
531         BT_ERR("%s, Invalid parameter", __func__);
532         return -EINVAL;
533     }
534 
535     /* Check if the device uuid matches configured value */
536     if (is_unprov_dev_uuid_match(uuid) == false) {
537         BT_DBG("Device uuid mismatch");
538         return -EIO;
539     }
540 
541     /* Check if this device is currently being provisioned.
542      * According to Zephyr's device code, if we connect with
543      * one device and start to provision it, we may still can
544      * receive the connectable prov adv pkt from this device.
545      * Here we check both PB-GATT and PB-ADV link status.
546      */
547     if (is_unprov_dev_being_provision(uuid)) {
548         return -EALREADY;
549     }
550 
551     /* Check if the current PB-ADV link is full */
552     if (IS_ENABLED(CONFIG_BLE_MESH_PB_ADV) &&
553         (prov_ctx.bearers & BLE_MESH_PROV_ADV) &&
554         (bearer == BLE_MESH_PROV_ADV) &&
555         (prov_ctx.pba_count == CONFIG_BLE_MESH_PBA_SAME_TIME)) {
556         BT_INFO("Current PB-ADV links reach max limit");
557         return -ENOMEM;
558     }
559 
560     /* Check if the current PB-GATT link is full */
561     if (IS_ENABLED(CONFIG_BLE_MESH_PB_GATT) &&
562         (prov_ctx.bearers & BLE_MESH_PROV_GATT) &&
563         (bearer == BLE_MESH_PROV_GATT) &&
564         (prov_ctx.pbg_count == CONFIG_BLE_MESH_PBG_SAME_TIME)) {
565         BT_INFO("Current PB-GATT links reach max limit");
566         return -ENOMEM;
567     }
568 
569     /* Check if the device has already been provisioned */
570     if (bt_mesh_provisioner_get_node_with_uuid(uuid)) {
571         BT_INFO("Provisioned before, start to provision again");
572     }
573 
574     return 0;
575 }
576 
577 #if defined(CONFIG_BLE_MESH_PB_ADV)
578 static int provisioner_start_prov_pb_adv(const uint8_t uuid[16], const bt_mesh_addr_t *addr,
579                                          uint16_t oob_info, uint16_t assign_addr)
580 {
581     int i;
582 
583     if (uuid == NULL) {
584         BT_ERR("%s, Invalid parameter", __func__);
585         return -EINVAL;
586     }
587 
588     bt_mesh_pb_adv_lock();
589 
590     /* If the unicast address of the node is going to be allocated internally,
591      * then we need to check if there are addresses can be allocated.
592      */
593     if (assign_addr == BLE_MESH_ADDR_UNASSIGNED &&
594         prov_ctx.curr_alloc_addr == BLE_MESH_ADDR_UNASSIGNED) {
595         BT_ERR("No available unicast address to assign");
596         bt_mesh_pb_adv_unlock();
597         return -EIO;
598     }
599 
600     if (is_unprov_dev_being_provision(uuid)) {
601         bt_mesh_pb_adv_unlock();
602         return 0;
603     }
604 
605     for (i = 0; i < CONFIG_BLE_MESH_PBA_SAME_TIME; i++) {
606         if (!bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE) && !link[i].linking) {
607             memcpy(link[i].uuid, uuid, 16);
608             link[i].oob_info = oob_info;
609             if (addr) {
610                 link[i].addr.type = addr->type;
611                 memcpy(link[i].addr.val, addr->val, BLE_MESH_ADDR_LEN);
612             }
613 
614             send_link_open(i);
615 
616             /* If a specific unicast address is assigned for the device, then
617              * Provisioner will use this address in the Provisioning Data PDU.
618              */
619             if (BLE_MESH_ADDR_IS_UNICAST(assign_addr)) {
620                 link[i].assign_addr = assign_addr;
621             }
622 
623             /* Increase PB-ADV link count */
624             prov_ctx.pba_count++;
625 
626             bt_mesh_pb_adv_unlock();
627             return 0;
628         }
629     }
630 
631     BT_ERR("No PB-ADV link available");
632     bt_mesh_pb_adv_unlock();
633 
634     return -ENOMEM;
635 }
636 #endif /* CONFIG_BLE_MESH_PB_ADV */
637 
638 #if defined(CONFIG_BLE_MESH_PB_GATT)
639 static int provisioner_start_prov_pb_gatt(const uint8_t uuid[16], const bt_mesh_addr_t *addr,
640                                           uint16_t oob_info, uint16_t assign_addr)
641 {
642     int i;
643 
644     if (uuid == NULL || addr == NULL) {
645         BT_ERR("%s, Invalid parameter", __func__);
646         return -EINVAL;
647     }
648 
649     bt_mesh_pb_gatt_lock();
650 
651     /* If the unicast address of the node is going to be allocated internally,
652      * then we need to check if there are addresses can be allocated.
653      */
654     if (assign_addr == BLE_MESH_ADDR_UNASSIGNED &&
655             prov_ctx.curr_alloc_addr == BLE_MESH_ADDR_UNASSIGNED) {
656         BT_ERR("No available unicast address to assign");
657         bt_mesh_pb_gatt_unlock();
658         return -EIO;
659     }
660 
661     if (is_unprov_dev_being_provision(uuid)) {
662         bt_mesh_pb_gatt_unlock();
663         return 0;
664     }
665 
666     for (i = CONFIG_BLE_MESH_PBA_SAME_TIME; i < BLE_MESH_PROV_SAME_TIME; i++) {
667         if (!link[i].connecting && !bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
668             if (bt_mesh_gattc_conn_create(addr, BLE_MESH_UUID_MESH_PROV_VAL)) {
669                 bt_mesh_pb_gatt_unlock();
670                 return -EIO;
671             }
672 
673             memcpy(link[i].uuid, uuid, 16);
674             link[i].oob_info = oob_info;
675             link[i].addr.type = addr->type;
676             memcpy(link[i].addr.val, addr->val, BLE_MESH_ADDR_LEN);
677 
678             /* If the application layer assigned a specific unicast address for the device,
679              * then Provisioner will use this address in the Provisioning Data PDU.
680              */
681             if (BLE_MESH_ADDR_IS_UNICAST(assign_addr)) {
682                 link[i].assign_addr = assign_addr;
683             }
684 
685             /* If creating connection successfully, set connecting flag to 1 */
686             link[i].connecting = true;
687 
688             /* Increase PB-GATT link count */
689             provisioner_pbg_count_inc();
690 
691             bt_mesh_pb_gatt_unlock();
692             return 0;
693         }
694     }
695 
696     BT_ERR("No PB-GATT link available");
697     bt_mesh_pb_gatt_unlock();
698 
699     return -ENOMEM;
700 }
701 #endif /* CONFIG_BLE_MESH_PB_GATT */
702 
703 int bt_mesh_provisioner_add_unprov_dev(struct bt_mesh_unprov_dev_add *add_dev, uint8_t flags)
704 {
705     bt_mesh_addr_t add_addr = {0};
706     bool addr_valid = false;
707     uint8_t zero[16] = {0};
708     int err = 0;
709     int i;
710 
711     if (add_dev == NULL) {
712         BT_ERR("%s, Invalid parameter", __func__);
713         return -EINVAL;
714     }
715 
716     if (!memcmp(add_dev->uuid, zero, 16)) {
717         BT_ERR("Invalid device uuid to add");
718         return -EINVAL;
719     }
720 
721     if (!(add_dev->bearer & (BLE_MESH_PROV_ADV | BLE_MESH_PROV_GATT))) {
722         BT_ERR("Invalid bearer 0x%02x", add_dev->bearer);
723         return -EINVAL;
724     }
725 
726     if ((!IS_ENABLED(CONFIG_BLE_MESH_PB_GATT) ||
727         !(prov_ctx.bearers & BLE_MESH_PROV_GATT))
728         && (add_dev->bearer & BLE_MESH_PROV_GATT)) {
729         BT_ERR("Not support PB-GATT");
730         return -EINVAL;
731     }
732 
733     if ((!IS_ENABLED(CONFIG_BLE_MESH_PB_ADV) ||
734         !(prov_ctx.bearers & BLE_MESH_PROV_ADV))
735         && (add_dev->bearer & BLE_MESH_PROV_ADV)) {
736         BT_ERR("Not support PB-ADV");
737         return -EINVAL;
738     }
739 
740     if (memcmp(add_dev->addr, zero, BLE_MESH_ADDR_LEN)) {
741         addr_valid = true;
742 
743         add_addr.type = add_dev->addr_type;
744         memcpy(add_addr.val, add_dev->addr, BLE_MESH_ADDR_LEN);
745     }
746 
747     /* Pb-GATT needs device address to create connection */
748     if ((add_dev->bearer & BLE_MESH_PROV_GATT) && (addr_valid == false)) {
749         BT_ERR("Invalid device address for PB-GATT");
750         return -EINVAL;
751     }
752 
753     /* If start provisioning immediately, only one bearer can be used */
754     if ((flags & START_PROV_NOW) &&
755         (add_dev->bearer != BLE_MESH_PROV_ADV) &&
756         (add_dev->bearer != BLE_MESH_PROV_GATT)) {
757         BT_ERR("Can not start PB-ADV & PB-GATT simultaneously");
758         return -EINVAL;
759     }
760 
761     /* Check if the provisioned nodes array is full */
762     if (bt_mesh_provisioner_get_node_with_uuid(add_dev->uuid) == NULL) {
763         if (bt_mesh_provisioner_get_node_count() == CONFIG_BLE_MESH_MAX_PROV_NODES) {
764             BT_WARN("Current provisioned devices reach max limit");
765             return -ENOMEM;
766         }
767     }
768 
769     /* Check if the device already exists in queue */
770     for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
771         if (!memcmp(unprov_dev[i].uuid, add_dev->uuid, 16)) {
772             if (!(add_dev->bearer & unprov_dev[i].bearer)) {
773                 BT_WARN("Add device with only bearer updated");
774                 unprov_dev[i].bearer |= add_dev->bearer;
775             } else {
776                 BT_WARN("Device already exists in queue");
777             }
778             goto start;
779         }
780     }
781 
782     /* If not exists, try to add the device into queue */
783     for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
784         if (unprov_dev[i].bearer) {
785             continue;
786         }
787         if (addr_valid) {
788             unprov_dev[i].addr.type = add_dev->addr_type;
789             memcpy(unprov_dev[i].addr.val, add_dev->addr, BLE_MESH_ADDR_LEN);
790         }
791         memcpy(unprov_dev[i].uuid, add_dev->uuid, 16);
792         unprov_dev[i].bearer = add_dev->bearer & BIT_MASK(2);
793         unprov_dev[i].flags = flags & BIT_MASK(3);
794         goto start;
795     }
796 
797     /* If queue is full, find flushable device and replace it */
798     for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
799         if (unprov_dev[i].flags & FLUSHABLE_DEV) {
800             memset(&unprov_dev[i], 0, sizeof(struct unprov_dev_queue));
801             if (addr_valid) {
802                 unprov_dev[i].addr.type = add_dev->addr_type;
803                 memcpy(unprov_dev[i].addr.val, add_dev->addr, BLE_MESH_ADDR_LEN);
804             }
805             memcpy(unprov_dev[i].uuid, add_dev->uuid, 16);
806             unprov_dev[i].bearer = add_dev->bearer & BIT_MASK(2);
807             unprov_dev[i].flags  = flags & BIT_MASK(3);
808             goto start;
809         }
810     }
811 
812     BT_ERR("Unprovisioned device queue is full");
813     return -ENOMEM;
814 
815 start:
816     /* If not provisioning immediately, directly return here */
817     if (!(flags & START_PROV_NOW)) {
818         return 0;
819     }
820 
821     /* Check if current provisioned node count + active link reach max limit */
822     if (bt_mesh_provisioner_get_node_with_uuid(add_dev->uuid) == NULL) {
823         if (bt_mesh_provisioner_get_node_count() + prov_ctx.pba_count + \
824             prov_ctx.pbg_count >= CONFIG_BLE_MESH_MAX_PROV_NODES) {
825             BT_WARN("Node count + active link count reach max limit");
826             return -EIO;
827         }
828     }
829 
830     if ((err = provisioner_check_unprov_dev_info(add_dev->uuid, add_dev->bearer))) {
831         return err;
832     }
833 
834     if (add_dev->bearer == BLE_MESH_PROV_ADV) {
835 #if defined(CONFIG_BLE_MESH_PB_ADV)
836         if ((err = provisioner_start_prov_pb_adv(add_dev->uuid, addr_valid ? &add_addr : NULL,
837                                                  add_dev->oob_info, BLE_MESH_ADDR_UNASSIGNED))) {
838             return err;
839         }
840 #endif
841     } else if (add_dev->bearer == BLE_MESH_PROV_GATT) {
842 #if defined(CONFIG_BLE_MESH_PB_GATT)
843         if ((err = provisioner_start_prov_pb_gatt(add_dev->uuid, &add_addr, add_dev->oob_info,
844                                                   BLE_MESH_ADDR_UNASSIGNED))) {
845             return err;
846         }
847 #endif
848     }
849 
850     return 0;
851 }
852 
853 int bt_mesh_provisioner_prov_device_with_addr(const uint8_t uuid[16], const uint8_t addr[6],
854                                               uint8_t addr_type, bt_mesh_prov_bearer_t bearer,
855                                               uint16_t oob_info, uint16_t unicast_addr)
856 {
857     bt_mesh_addr_t dev_addr = {0};
858     int err = 0;
859 
860     if (uuid == NULL) {
861         BT_ERR("Invalid device uuid");
862         return -EINVAL;
863     }
864 
865     if (bearer != BLE_MESH_PROV_ADV && bearer != BLE_MESH_PROV_GATT) {
866         BT_ERR("Invalid provisioning bearer 0x%02x", bearer);
867         return -EINVAL;
868     }
869 
870     if ((!IS_ENABLED(CONFIG_BLE_MESH_PB_ADV) ||
871         !(prov_ctx.bearers & BLE_MESH_PROV_ADV)) &&
872         (bearer == BLE_MESH_PROV_ADV)) {
873         BT_ERR("Not support PB-ADV");
874         return -ENOTSUP;
875     }
876 
877     if ((!IS_ENABLED(CONFIG_BLE_MESH_PB_GATT) ||
878         !(prov_ctx.bearers & BLE_MESH_PROV_GATT)) &&
879         (bearer == BLE_MESH_PROV_GATT)) {
880         BT_ERR("Not support PB-GATT");
881         return -ENOTSUP;
882     }
883 
884     if (bearer == BLE_MESH_PROV_GATT && addr == NULL) {
885         BT_ERR("Invalid device address for PB-GATT");
886         return -EINVAL;
887     }
888 
889     if (!BLE_MESH_ADDR_IS_UNICAST(unicast_addr)) {
890         BT_ERR("Invalid unicast address 0x%04x", unicast_addr);
891         return -EINVAL;
892     }
893 
894     /* Here we will not check if the assigned unicast address is overlapped
895      * with the unicast addresses of other nodes or Provisioner, because:
896      * 1. At this moment, the element number of the device is unknown
897      * 2. If the node is a reprovisioned device, then the original allocated
898      *    unicast address will be used.
899      * 3. Some other devices may be just being provisioning, and currently we
900      *    can not know the exactly allocated addresses of them.
901      */
902 
903     if (bt_mesh_provisioner_get_node_with_uuid(uuid) == NULL) {
904         /* Check if the provisioned nodes array is full */
905         if (bt_mesh_provisioner_get_node_count() == CONFIG_BLE_MESH_MAX_PROV_NODES) {
906             BT_WARN("Current provisioned devices reach max limit");
907             return -ENOMEM;
908         }
909 
910         /* Check if current provisioned node count + active link reach max limit */
911         if (bt_mesh_provisioner_get_node_count() + prov_ctx.pba_count + \
912                 prov_ctx.pbg_count >= CONFIG_BLE_MESH_MAX_PROV_NODES) {
913             BT_WARN("Node count + active link count reach max limit");
914             return -EIO;
915         }
916     }
917 
918     if ((err = provisioner_check_unprov_dev_info(uuid, bearer))) {
919         return err;
920     }
921 
922     if (addr) {
923         dev_addr.type = addr_type;
924         memcpy(dev_addr.val, addr, BLE_MESH_ADDR_LEN);
925     }
926 
927     if (bearer == BLE_MESH_PROV_ADV) {
928 #if defined(CONFIG_BLE_MESH_PB_ADV)
929         if ((err = provisioner_start_prov_pb_adv(uuid, addr ? &dev_addr : NULL, oob_info, unicast_addr))) {
930             return err;
931         }
932 #endif
933     } else if (bearer == BLE_MESH_PROV_GATT) {
934 #if defined(CONFIG_BLE_MESH_PB_GATT)
935         if ((err = provisioner_start_prov_pb_gatt(uuid, &dev_addr, oob_info, unicast_addr))) {
936             return err;
937         }
938 #endif
939     }
940 
941     return 0;
942 }
943 
944 int bt_mesh_provisioner_delete_device(struct bt_mesh_device_delete *del_dev)
945 {
946     uint8_t zero[16] = {0};
947     int i;
948 
949     if (del_dev == NULL) {
950         BT_ERR("%s, Invalid parameter", __func__);
951         return -EINVAL;
952     }
953 
954     if (!memcmp(del_dev->uuid, zero, 16)) {
955         BT_ERR("Invalid device uuid to delete");
956         return -EINVAL;
957     }
958 
959     /* Find if the device is in the device queue */
960     for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
961         if (!memcmp(unprov_dev[i].uuid, del_dev->uuid, 16)) {
962             memset(&unprov_dev[i], 0, sizeof(struct unprov_dev_queue));
963             break;
964         }
965     }
966 
967     /* Find if the device is being provisioned */
968     for (i = 0; i < ARRAY_SIZE(link); i++) {
969         if (!memcmp(link[i].uuid, del_dev->uuid, 16)) {
970             close_link(i, CLOSE_REASON_FAILED);
971             break;
972         }
973     }
974 
975     return 0;
976 }
977 
978 int bt_mesh_provisioner_set_dev_uuid_match(uint8_t offset, uint8_t length,
979                                            const uint8_t *match, bool prov_flag)
980 {
981     if (length && (!match || (offset + length > 16))) {
982         BT_ERR("%s, Invalid parameter", __func__);
983         return -EINVAL;
984     }
985 
986     (void)memset(prov_ctx.match_value, 0, 16);
987 
988     prov_ctx.match_offset = offset;
989     prov_ctx.match_length = length;
990     if (length) {
991         memcpy(prov_ctx.match_value, match, length);
992     }
993     prov_ctx.prov_after_match = prov_flag;
994 
995     return 0;
996 }
997 
998 int bt_mesh_provisioner_adv_pkt_cb_register(unprov_adv_pkt_cb_t cb)
999 {
1000     if (!cb) {
1001         BT_ERR("%s, Invalid parameter", __func__);
1002         return -EINVAL;
1003     }
1004 
1005     notify_unprov_adv_pkt_cb = cb;
1006     return 0;
1007 }
1008 
1009 int bt_mesh_provisioner_set_prov_data_info(struct bt_mesh_prov_data_info *info)
1010 {
1011     const uint8_t *key = NULL;
1012 
1013     if (!info || info->flag == 0) {
1014         return -EINVAL;
1015     }
1016 
1017     if (info->flag & NET_IDX_FLAG) {
1018         key = bt_mesh_provisioner_net_key_get(info->net_idx);
1019         if (!key) {
1020             BT_ERR("Failed to get NetKey");
1021             return -EINVAL;
1022         }
1023         prov_ctx.curr_net_idx = info->net_idx;
1024     } else if (info->flag & FLAGS_FLAG) {
1025         prov_ctx.curr_flags = info->flags;
1026     } else if (info->flag & IV_INDEX_FLAG) {
1027         prov_ctx.curr_iv_index = info->iv_index;
1028     }
1029 
1030     return 0;
1031 }
1032 
1033 int bt_mesh_provisioner_init_prov_info(void)
1034 {
1035     if (prov_ctx.primary_addr == BLE_MESH_ADDR_UNASSIGNED) {
1036         /* If unicast address of primary element of Provisioner has not been set
1037          * before, then the following initialization procedure will be used.
1038          */
1039         if (prov == NULL) {
1040             BT_ERR("No provisioning context provided");
1041             return -EINVAL;
1042         }
1043 
1044         if (!BLE_MESH_ADDR_IS_UNICAST(prov->prov_unicast_addr) ||
1045             !BLE_MESH_ADDR_IS_UNICAST(prov->prov_start_address)) {
1046             BT_ERR("Invalid address, own 0x%04x, start 0x%04x",
1047                     prov->prov_unicast_addr, prov->prov_start_address);
1048             return -EINVAL;
1049         }
1050 
1051         const struct bt_mesh_comp *comp = bt_mesh_comp_get();
1052         if (!comp) {
1053             BT_ERR("Invalid composition data");
1054             return -EINVAL;
1055         }
1056 
1057         if (prov->prov_unicast_addr + comp->elem_count > prov->prov_start_address) {
1058             BT_WARN("Too small start address 0x%04x, update to 0x%04x",
1059                 prov->prov_start_address, prov->prov_unicast_addr + comp->elem_count);
1060             prov_ctx.curr_alloc_addr = prov->prov_unicast_addr + comp->elem_count;
1061         } else {
1062             prov_ctx.curr_alloc_addr = prov->prov_start_address;
1063         }
1064 
1065         /* Update primary element address with the initialized value here. */
1066         prov_ctx.primary_addr = prov->prov_unicast_addr;
1067 
1068         if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1069             bt_mesh_store_prov_info(prov_ctx.primary_addr, prov_ctx.curr_alloc_addr);
1070         }
1071     }
1072 
1073     prov_ctx.curr_net_idx = BLE_MESH_KEY_PRIMARY;
1074     struct bt_mesh_subnet *sub = bt_mesh_provisioner_subnet_get(BLE_MESH_KEY_PRIMARY);
1075     prov_ctx.curr_flags = bt_mesh_net_flags(sub);
1076     prov_ctx.curr_iv_index = bt_mesh.iv_index;
1077 
1078     return 0;
1079 }
1080 
1081 void bt_mesh_provisioner_set_prov_bearer(bt_mesh_prov_bearer_t bearers, bool clear)
1082 {
1083     if (clear == false) {
1084         prov_ctx.bearers |= bearers;
1085     } else {
1086         prov_ctx.bearers &= ~bearers;
1087     }
1088 }
1089 
1090 bt_mesh_prov_bearer_t bt_mesh_provisioner_get_prov_bearer(void)
1091 {
1092     return prov_ctx.bearers;
1093 }
1094 
1095 int bt_mesh_provisioner_set_static_oob_value(const uint8_t *value, uint8_t length)
1096 {
1097     int i;
1098 
1099     if (value == NULL || length == 0U || length > 16U) {
1100         BT_ERR("%s, Invalid parameter", __func__);
1101         return -EINVAL;
1102     }
1103 
1104     /* Make sure Static OOB is not being used. */
1105     for (i = 0; i < BLE_MESH_PROV_SAME_TIME; i++) {
1106         if (link[i].auth_method == AUTH_METHOD_STATIC) {
1107             BT_ERR("Static OOB is being used");
1108             return -EINVAL;
1109         }
1110     }
1111 
1112     (void)memset(prov_ctx.static_oob_val, 0, 16);
1113 
1114     prov_ctx.static_oob_len = MIN(16, length);
1115     memcpy(prov_ctx.static_oob_val, value, prov_ctx.static_oob_len);
1116 
1117     return 0;
1118 }
1119 
1120 uint16_t bt_mesh_provisioner_get_primary_elem_addr(void)
1121 {
1122     return prov_ctx.primary_addr;
1123 }
1124 
1125 int bt_mesh_provisioner_set_primary_elem_addr(uint16_t addr)
1126 {
1127     const struct bt_mesh_comp *comp = NULL;
1128 
1129     if (!BLE_MESH_ADDR_IS_UNICAST(addr)) {
1130         BT_ERR("Invalid primary address 0x%04x", addr);
1131         return -EINVAL;
1132     }
1133 
1134     comp = bt_mesh_comp_get();
1135     if (!comp) {
1136         BT_ERR("Invalid composition data");
1137         return -EINVAL;
1138     }
1139 
1140     /* Make sure Provisioner address is not identical with the addresses of nodes */
1141     if (bt_mesh_provisioner_check_is_addr_dup(addr, comp->elem_count, false)) {
1142         BT_ERR("Address 0x%04x is duplicated with node address", addr);
1143         return -EINVAL;
1144     }
1145 
1146     /* If the current can-be allocated address is bigger than primary address +
1147      * element number, then the curr_alloc_addr will not be changed, and only
1148      * the Provisioner related addresses will be updated.
1149      */
1150     if (addr + comp->elem_count > prov_ctx.curr_alloc_addr) {
1151         prov_ctx.curr_alloc_addr = addr + comp->elem_count;
1152     }
1153 
1154     BT_INFO("Primary address updated, old 0x%04x, new 0x%04x", prov_ctx.primary_addr, addr);
1155     prov_ctx.primary_addr = addr;
1156 
1157     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1158         bt_mesh_store_prov_info(prov_ctx.primary_addr, prov_ctx.curr_alloc_addr);
1159     }
1160 
1161     bt_mesh_comp_provision(addr);
1162 
1163     return 0;
1164 }
1165 
1166 #if CONFIG_BLE_MESH_TEST_AUTO_ENTER_NETWORK
1167 int bt_mesh_test_provisioner_update_alloc_addr(uint16_t unicast_addr, uint16_t element_num)
1168 {
1169     uint16_t max_addr = FAST_PROV_ENABLE() ? prov_ctx.fast_prov.unicast_addr_max : PROV_MAX_ADDR_TO_ASSIGN;
1170 
1171     if (unicast_addr + element_num > max_addr) {
1172         BT_WARN("Not enough unicast address to allocate");
1173         prov_ctx.curr_alloc_addr = BLE_MESH_ADDR_UNASSIGNED;
1174     } else {
1175         prov_ctx.curr_alloc_addr = unicast_addr + element_num;
1176     }
1177 
1178     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1179         bt_mesh_store_prov_info(prov_ctx.primary_addr, prov_ctx.curr_alloc_addr);
1180     }
1181 
1182     return 0;
1183 }
1184 #endif /* CONFIG_BLE_MESH_TEST_AUTO_ENTER_NETWORK */
1185 
1186 /* The following APIs are for fast provisioning */
1187 
1188 void bt_mesh_provisioner_fast_prov_enable(bool enable)
1189 {
1190     prov_ctx.fast_prov.enable = enable;
1191 }
1192 
1193 void bt_mesh_provisioner_set_fast_prov_net_idx(uint16_t net_idx)
1194 {
1195     prov_ctx.fast_prov.net_idx = net_idx;
1196 }
1197 
1198 uint16_t bt_mesh_provisioner_get_fast_prov_net_idx(void)
1199 {
1200     return prov_ctx.fast_prov.net_idx;
1201 }
1202 
1203 uint8_t bt_mesh_set_fast_prov_unicast_addr_range(uint16_t min, uint16_t max)
1204 {
1205     if (!BLE_MESH_ADDR_IS_UNICAST(min) || !BLE_MESH_ADDR_IS_UNICAST(max)) {
1206         BT_ERR("Invalid unicast address, min 0x%04x, max 0x%04x", min, max);
1207         return 0x01; /* status: not a unicast address */
1208     }
1209 
1210     if (min > max) {
1211         BT_ERR("Unicast address min is bigger than max");
1212         return 0x02; /* status: min is bigger than max */
1213     }
1214 
1215     if (min <= prov_ctx.fast_prov.unicast_addr_max) {
1216         BT_ERR("Unicast address overlap");
1217         return 0x03; /* status: address overlaps with current value */
1218     }
1219 
1220     prov_ctx.fast_prov.unicast_addr_min = min;
1221     prov_ctx.fast_prov.unicast_addr_max = max;
1222 
1223     prov_ctx.curr_alloc_addr = prov_ctx.fast_prov.unicast_addr_min;
1224 
1225     return 0x0; /* status: success */
1226 }
1227 
1228 void bt_mesh_set_fast_prov_flags_iv_index(uint8_t flags, uint32_t iv_index)
1229 {
1230     /* BIT0: Key Refresh flag, BIT1: IV Update flag */
1231     prov_ctx.fast_prov.flags = flags & BIT_MASK(2);
1232     prov_ctx.fast_prov.iv_index = iv_index;
1233 }
1234 
1235 #if defined(CONFIG_BLE_MESH_PB_ADV)
1236 static struct net_buf_simple *bt_mesh_pba_get_buf(const uint8_t idx)
1237 {
1238     struct net_buf_simple *buf = &(adv_buf[idx].buf);
1239 
1240     net_buf_simple_reset(buf);
1241 
1242     return buf;
1243 }
1244 #endif /* CONFIG_BLE_MESH_PB_ADV */
1245 
1246 static void prov_memory_free(const uint8_t idx)
1247 {
1248     PROV_FREE_MEM(idx, dhkey);
1249     PROV_FREE_MEM(idx, auth);
1250     PROV_FREE_MEM(idx, rand);
1251     PROV_FREE_MEM(idx, conf);
1252     PROV_FREE_MEM(idx, local_conf);
1253     PROV_FREE_MEM(idx, conf_salt);
1254     PROV_FREE_MEM(idx, conf_key);
1255     PROV_FREE_MEM(idx, conf_inputs);
1256     PROV_FREE_MEM(idx, prov_salt);
1257 }
1258 
1259 #if defined(CONFIG_BLE_MESH_PB_ADV)
1260 static void buf_sent(int err, void *user_data)
1261 {
1262     uint8_t idx = (int)user_data;
1263 
1264     if (!link[idx].tx.buf[0]) {
1265         return;
1266     }
1267 
1268     k_delayed_work_submit(&link[idx].tx.retransmit, RETRANSMIT_TIMEOUT);
1269 }
1270 
1271 static struct bt_mesh_send_cb buf_sent_cb = {
1272     .end = buf_sent,
1273 };
1274 
1275 static void free_segments(const uint8_t idx)
1276 {
1277     int i;
1278 
1279     bt_mesh_pb_buf_lock();
1280 
1281     for (i = 0; i < ARRAY_SIZE(link[idx].tx.buf); i++) {
1282         struct net_buf *buf = link[idx].tx.buf[i];
1283 
1284         if (!buf) {
1285             break;
1286         }
1287 
1288         link[idx].tx.buf[i] = NULL;
1289         bt_mesh_adv_buf_ref_debug(__func__, buf, 3U, BLE_MESH_BUF_REF_SMALL);
1290         /* Mark as canceled */
1291         BLE_MESH_ADV(buf)->busy = 0U;
1292         net_buf_unref(buf);
1293     }
1294 
1295     bt_mesh_pb_buf_unlock();
1296 }
1297 
1298 static void prov_clear_tx(const uint8_t idx)
1299 {
1300     BT_DBG("%s", __func__);
1301 
1302     k_delayed_work_cancel(&link[idx].tx.retransmit);
1303 
1304     free_segments(idx);
1305 }
1306 
1307 static void reset_link(const uint8_t idx, uint8_t reason)
1308 {
1309     prov_clear_tx(idx);
1310 
1311     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
1312         k_delayed_work_cancel(&link[idx].timeout);
1313     }
1314 
1315     if (prov->prov_link_close) {
1316         prov->prov_link_close(BLE_MESH_PROV_ADV, reason);
1317     }
1318 
1319     prov_memory_free(idx);
1320 
1321 #if defined(CONFIG_BLE_MESH_USE_DUPLICATE_SCAN)
1322     /* Remove the link id from exceptional list */
1323     bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_SUB_CODE_REMOVE,
1324                                     BLE_MESH_EXCEP_LIST_TYPE_MESH_LINK_ID, &link[idx].link_id);
1325 #endif
1326 
1327     /* Clear everything except the retransmit delayed work config */
1328     memset(&link[idx], 0, offsetof(struct prov_link, tx.retransmit));
1329 
1330     link[idx].pending_ack = XACT_NVAL;
1331     link[idx].rx.prev_id  = XACT_NVAL;
1332 
1333     if (bt_mesh_pub_key_get()) {
1334         bt_mesh_atomic_set_bit(link[idx].flags, LOCAL_PUB_KEY);
1335     }
1336 
1337     link[idx].rx.buf = bt_mesh_pba_get_buf(idx);
1338 
1339     if (prov_ctx.pba_count) {
1340         prov_ctx.pba_count--;
1341     }
1342 }
1343 
1344 static struct net_buf *adv_buf_create(void)
1345 {
1346     struct net_buf *buf = NULL;
1347 
1348     buf = bt_mesh_adv_create(BLE_MESH_ADV_PROV, PROV_XMIT, BUF_TIMEOUT);
1349     if (!buf) {
1350         BT_ERR("Out of provisioning buffers");
1351         return NULL;
1352     }
1353 
1354     return buf;
1355 }
1356 
1357 static void ack_complete(uint16_t duration, int err, void *user_data)
1358 {
1359     uint8_t idx = (int)user_data;
1360 
1361     BT_DBG("xact %u complete", link[idx].pending_ack);
1362 
1363     link[idx].pending_ack = XACT_NVAL;
1364 }
1365 
1366 static void gen_prov_ack_send(const uint8_t idx, uint8_t xact_id)
1367 {
1368     static const struct bt_mesh_send_cb cb = {
1369         .start = ack_complete,
1370     };
1371     const struct bt_mesh_send_cb *complete = NULL;
1372     struct net_buf *buf = NULL;
1373 
1374     BT_DBG("xact_id %u", xact_id);
1375 
1376     if (link[idx].pending_ack == xact_id) {
1377         BT_DBG("Not sending duplicate ack");
1378         return;
1379     }
1380 
1381     buf = adv_buf_create();
1382     if (!buf) {
1383         return;
1384     }
1385 
1386     if (link[idx].pending_ack == XACT_NVAL) {
1387         link[idx].pending_ack = xact_id;
1388         complete = &cb;
1389     } else {
1390         complete = NULL;
1391     }
1392 
1393     net_buf_add_be32(buf, link[idx].link_id);
1394     net_buf_add_u8(buf, xact_id);
1395     net_buf_add_u8(buf, GPC_ACK);
1396 
1397     bt_mesh_adv_send(buf, complete, (void *)(int)idx);
1398     net_buf_unref(buf);
1399 }
1400 
1401 static void send_reliable(const uint8_t idx)
1402 {
1403     int i;
1404 
1405     link[idx].tx.start = k_uptime_get();
1406 
1407     for (i = 0; i < ARRAY_SIZE(link[idx].tx.buf); i++) {
1408         struct net_buf *buf = link[idx].tx.buf[i];
1409 
1410         if (!buf) {
1411             break;
1412         }
1413 
1414         if (i + 1 < ARRAY_SIZE(link[idx].tx.buf) && link[idx].tx.buf[i + 1]) {
1415             bt_mesh_adv_send(buf, NULL, NULL);
1416         } else {
1417             bt_mesh_adv_send(buf, &buf_sent_cb, (void *)(int)idx);
1418         }
1419     }
1420 }
1421 
1422 static int bearer_ctl_send(const uint8_t idx, uint8_t op, void *data, uint8_t data_len)
1423 {
1424     struct net_buf *buf = NULL;
1425 
1426     BT_DBG("op 0x%02x data_len %u", op, data_len);
1427 
1428     prov_clear_tx(idx);
1429 
1430     buf = adv_buf_create();
1431     if (!buf) {
1432         return -ENOBUFS;
1433     }
1434 
1435     net_buf_add_be32(buf, link[idx].link_id);
1436     /* Transaction ID, always 0 for Bearer messages */
1437     net_buf_add_u8(buf, 0x00);
1438     net_buf_add_u8(buf, GPC_CTL(op));
1439     net_buf_add_mem(buf, data, data_len);
1440 
1441     link[idx].tx.buf[0] = buf;
1442     send_reliable(idx);
1443 
1444     /** We can also use buf->ref and a flag to decide that
1445      *  link close has been sent 3 times.
1446      *  Here we use another way: use retransmit timer and need
1447      *  to make sure the timer is not cancelled during sending
1448      *  link close pdu, so we add link[i].tx.id = 0
1449      */
1450     if (op == LINK_CLOSE) {
1451         uint8_t reason = *(uint8_t *)data;
1452         link[idx].send_link_close = ((reason & BIT_MASK(2)) << 1) | BIT(0);
1453         link[idx].tx.trans_id = 0;
1454     }
1455 
1456     return 0;
1457 }
1458 
1459 static void send_link_open(const uint8_t idx)
1460 {
1461     int j;
1462     uint8_t count;
1463 
1464     link[idx].link_id = 0;
1465 
1466     while (1) {
1467         count = 0;
1468 
1469         /* Make sure the generated Link ID is not 0 */
1470         while(link[idx].link_id == 0) {
1471             bt_mesh_rand(&link[idx].link_id, sizeof(link[idx].link_id));
1472             if (count++ > 10) {
1473                 BT_ERR("Link ID error: all zero");
1474                 return;
1475             }
1476         }
1477 
1478         /* Check if the generated Link ID is the same with other links */
1479         for (j = 0; j < CONFIG_BLE_MESH_PBA_SAME_TIME; j++) {
1480             if (bt_mesh_atomic_test_bit(link[j].flags, LINK_ACTIVE) || link[j].linking) {
1481                 if (link[idx].link_id == link[j].link_id) {
1482                     bt_mesh_rand(&link[idx].link_id, sizeof(link[idx].link_id));
1483                     break;
1484                 }
1485             }
1486         }
1487         if (j == CONFIG_BLE_MESH_PBA_SAME_TIME) {
1488             break;
1489         }
1490     }
1491 
1492 #if defined(CONFIG_BLE_MESH_USE_DUPLICATE_SCAN)
1493     /* Add the link id into exceptional list */
1494     bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_SUB_CODE_ADD,
1495                                     BLE_MESH_EXCEP_LIST_TYPE_MESH_LINK_ID, &link[idx].link_id);
1496 #endif
1497 
1498     bearer_ctl_send(idx, LINK_OPEN, link[idx].uuid, 16);
1499 
1500     /* If Provisioner sets LINK_ACTIVE flag once Link Open is sent, we have
1501      * no need to use linking flag (like PB-GATT connecting) to prevent the
1502      * stored device info (UUID, oob_info) being replaced by other received
1503      * unprovisioned device beacons.
1504      * But if Provisioner sets LINK_ACTIVE flag after Link ACK is received,
1505      * we need to use linking flag to prevent device info being replaced.
1506      * Currently we set LINK_ACTIVE flag after sending Link Open.
1507      */
1508     link[idx].linking = true;
1509 
1510     /* Set LINK_ACTIVE just to be in compatibility with current Zephyr code */
1511     bt_mesh_atomic_set_bit(link[idx].flags, LINK_ACTIVE);
1512 
1513     if (prov->prov_link_open) {
1514         prov->prov_link_open(BLE_MESH_PROV_ADV);
1515     }
1516 }
1517 
1518 static uint8_t last_seg(uint8_t len)
1519 {
1520     if (len <= START_PAYLOAD_MAX) {
1521         return 0;
1522     }
1523 
1524     len -= START_PAYLOAD_MAX;
1525 
1526     return 1 + (len / CONT_PAYLOAD_MAX);
1527 }
1528 
1529 static inline uint8_t next_transaction_id(const uint8_t idx)
1530 {
1531     if (link[idx].tx.trans_id > 0x7F) {
1532         link[idx].tx.trans_id = 0x0;
1533     }
1534     return link[idx].tx.trans_id++;
1535 }
1536 
1537 static int prov_send_adv(const uint8_t idx, struct net_buf_simple *msg)
1538 {
1539     struct net_buf *start = NULL, *buf = NULL;
1540     uint8_t seg_len = 0U, seg_id = 0U;
1541     uint8_t xact_id = 0U;
1542     int32_t timeout = PROVISION_TIMEOUT;
1543 
1544     BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
1545 
1546     prov_clear_tx(idx);
1547 
1548     start = adv_buf_create();
1549     if (!start) {
1550         return -ENOBUFS;
1551     }
1552 
1553     xact_id = next_transaction_id(idx);
1554     net_buf_add_be32(start, link[idx].link_id);
1555     net_buf_add_u8(start, xact_id);
1556 
1557     net_buf_add_u8(start, GPC_START(last_seg(msg->len)));
1558     net_buf_add_be16(start, msg->len);
1559     net_buf_add_u8(start, bt_mesh_fcs_calc(msg->data, msg->len));
1560 
1561     link[idx].tx.buf[0] = start;
1562     /* Changed by Espressif, get message type */
1563     link[idx].tx_pdu_type = msg->data[0];
1564 
1565     seg_len = MIN(msg->len, START_PAYLOAD_MAX);
1566     BT_DBG("seg 0 len %u: %s", seg_len, bt_hex(msg->data, seg_len));
1567     net_buf_add_mem(start, msg->data, seg_len);
1568     net_buf_simple_pull(msg, seg_len);
1569 
1570     buf = start;
1571     for (seg_id = 1; msg->len > 0; seg_id++) {
1572         if (seg_id >= ARRAY_SIZE(link[idx].tx.buf)) {
1573             BT_ERR("Too big message (seg_id %d)", seg_id);
1574             free_segments(idx);
1575             return -E2BIG;
1576         }
1577 
1578         buf = adv_buf_create();
1579         if (!buf) {
1580             free_segments(idx);
1581             return -ENOBUFS;
1582         }
1583 
1584         link[idx].tx.buf[seg_id] = buf;
1585 
1586         seg_len = MIN(msg->len, CONT_PAYLOAD_MAX);
1587 
1588         BT_DBG("seg_id %u len %u: %s", seg_id, seg_len,
1589                bt_hex(msg->data, seg_len));
1590 
1591         net_buf_add_be32(buf, link[idx].link_id);
1592         net_buf_add_u8(buf, xact_id);
1593         net_buf_add_u8(buf, GPC_CONT(seg_id));
1594         net_buf_add_mem(buf, msg->data, seg_len);
1595         net_buf_simple_pull(msg, seg_len);
1596     }
1597 
1598     send_reliable(idx);
1599 
1600 #if defined(CONFIG_BLE_MESH_FAST_PROV)
1601     if (link[idx].tx_pdu_type >= PROV_DATA) {
1602         timeout = K_SECONDS(60);
1603     }
1604 #endif
1605     if (!bt_mesh_atomic_test_and_set_bit(link[idx].flags, TIMEOUT_START)) {
1606         k_delayed_work_submit(&link[idx].timeout, timeout);
1607     }
1608 
1609     return 0;
1610 }
1611 #endif /* CONFIG_BLE_MESH_PB_ADV */
1612 
1613 #if defined(CONFIG_BLE_MESH_PB_GATT)
1614 static int prov_send_gatt(const uint8_t idx, struct net_buf_simple *msg)
1615 {
1616     int err = 0;
1617 
1618     if (!link[idx].conn) {
1619         return -ENOTCONN;
1620     }
1621 
1622     err = bt_mesh_proxy_client_send(link[idx].conn, BLE_MESH_PROXY_PROV, msg);
1623     if (err) {
1624         BT_ERR("Failed to send PB-GATT pdu");
1625         return err;
1626     }
1627 
1628     if (!bt_mesh_atomic_test_and_set_bit(link[idx].flags, TIMEOUT_START)) {
1629         k_delayed_work_submit(&link[idx].timeout, PROVISION_TIMEOUT);
1630     }
1631 
1632     return 0;
1633 }
1634 #endif /* CONFIG_BLE_MESH_PB_GATT */
1635 
1636 static inline int prov_send(const uint8_t idx, struct net_buf_simple *buf)
1637 {
1638 #if defined(CONFIG_BLE_MESH_PB_ADV)
1639     if (idx < CONFIG_BLE_MESH_PBA_SAME_TIME) {
1640         return prov_send_adv(idx, buf);
1641     }
1642 #endif
1643 
1644 #if defined(CONFIG_BLE_MESH_PB_GATT)
1645     if (idx < BLE_MESH_PROV_SAME_TIME
1646 #if defined(CONFIG_BLE_MESH_PB_ADV)
1647             && idx >= CONFIG_BLE_MESH_PBA_SAME_TIME
1648 #endif
1649        ) {
1650         return prov_send_gatt(idx, buf);
1651     }
1652 #endif
1653 
1654     BT_ERR("Invalid link index %d", idx);
1655     return -EINVAL;
1656 }
1657 
1658 static void prov_buf_init(struct net_buf_simple *buf, uint8_t type)
1659 {
1660     net_buf_simple_reserve(buf, PROV_BUF_HEADROOM);
1661     net_buf_simple_add_u8(buf, type);
1662 }
1663 
1664 static void prov_invite(const uint8_t idx, const uint8_t *data)
1665 {
1666     BT_DBG("%s", __func__);
1667 }
1668 
1669 static void prov_start(const uint8_t idx, const uint8_t *data)
1670 {
1671     BT_DBG("%s", __func__);
1672 }
1673 
1674 static void prov_data(const uint8_t idx, const uint8_t *data)
1675 {
1676     BT_DBG("%s", __func__);
1677 }
1678 
1679 static void send_invite(const uint8_t idx)
1680 {
1681     PROV_BUF(buf, 2);
1682 
1683     prov_buf_init(&buf, PROV_INVITE);
1684 
1685     net_buf_simple_add_u8(&buf, prov->prov_attention);
1686 
1687     link[idx].conf_inputs[0] = prov->prov_attention;
1688 
1689     if (prov_send(idx, &buf)) {
1690         BT_ERR("Failed to send Provisioning Invite");
1691         close_link(idx, CLOSE_REASON_FAILED);
1692         return;
1693     }
1694 
1695     link[idx].expect = PROV_CAPABILITIES;
1696 }
1697 
1698 static void prov_capabilities(const uint8_t idx, const uint8_t *data)
1699 {
1700     PROV_BUF(buf, 6);
1701     uint16_t algorithms = 0U, output_action = 0U, input_action = 0U;
1702     uint8_t  element_num = 0U, pub_key_oob = 0U, static_oob = 0U,
1703              output_size = 0U, input_size = 0U;
1704     uint8_t  auth_method = 0U, auth_action = 0U, auth_size = 0U;
1705 
1706     element_num = data[0];
1707     BT_INFO("Elements:          0x%02x", element_num);
1708     if (!element_num) {
1709         BT_ERR("Invalid element number %d", element_num);
1710         goto fail;
1711     }
1712     link[idx].element_num = element_num;
1713 
1714     algorithms = sys_get_be16(&data[1]);
1715     BT_INFO("Algorithms:        0x%04x", algorithms);
1716     if (!(algorithms & BIT(PROV_ALG_P256))) {
1717         BT_ERR("Invalid algorithms 0x%04x", algorithms);
1718         goto fail;
1719     }
1720 
1721     pub_key_oob = data[3];
1722     BT_INFO("Public Key Type:   0x%02x", pub_key_oob);
1723     if (pub_key_oob > 0x01) {
1724         BT_ERR("Invalid public key type 0x%02x", pub_key_oob);
1725         goto fail;
1726     }
1727     pub_key_oob = ((prov->prov_pub_key_oob &&
1728                     prov->prov_pub_key_oob_cb) ? pub_key_oob : 0x00);
1729 
1730     static_oob = data[4];
1731     BT_INFO("Static OOB Type:   0x%02x", static_oob);
1732     if (static_oob > 0x01) {
1733         BT_ERR("Invalid Static OOB type 0x%02x", static_oob);
1734         goto fail;
1735     }
1736     static_oob = (prov_ctx.static_oob_len ? static_oob : 0x00);
1737 
1738     output_size = data[5];
1739     BT_INFO("Output OOB Size:   0x%02x", output_size);
1740     if (output_size > 0x08) {
1741         BT_ERR("Invalid Output OOB size %d", output_size);
1742         goto fail;
1743     }
1744 
1745     output_action = sys_get_be16(&data[6]);
1746     BT_INFO("Output OOB Action: 0x%04x", output_action);
1747     if (output_action > 0x1f) {
1748         BT_ERR("Invalid Output OOB action 0x%04x", output_action);
1749         goto fail;
1750     }
1751 
1752     /* Provisioner select output action */
1753     if (prov->prov_input_num && output_size) {
1754         output_action = __builtin_ctz(output_action);
1755     } else {
1756         output_size = 0x0;
1757         output_action = 0x0;
1758     }
1759 
1760     input_size = data[8];
1761     BT_INFO("Input OOB Size:    0x%02x", input_size);
1762     if (input_size > 0x08) {
1763         BT_ERR("Invalid Input OOB size %d", input_size);
1764         goto fail;
1765     }
1766 
1767     input_action = sys_get_be16(&data[9]);
1768     BT_INFO("Input OOB Action:  0x%04x", input_action);
1769     if (input_action > 0x0f) {
1770         BT_ERR("Invalid Input OOB action 0x%04x", input_action);
1771         goto fail;
1772     }
1773 
1774     /* Make sure received pdu is ok and cancel the timeout timer */
1775     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
1776         k_delayed_work_cancel(&link[idx].timeout);
1777     }
1778 
1779     /* Provisioner select input action */
1780     if (prov->prov_output_num && input_size) {
1781         input_action = __builtin_ctz(input_action);
1782     } else {
1783         input_size = 0x0;
1784         input_action = 0x0;
1785     }
1786 
1787     if (static_oob) {
1788         /* if static oob is valid, just use static oob */
1789         auth_method = AUTH_METHOD_STATIC;
1790         auth_action = 0x00;
1791         auth_size   = 0x00;
1792     } else {
1793         if (!output_size && !input_size) {
1794             auth_method = AUTH_METHOD_NO_OOB;
1795             auth_action = 0x00;
1796             auth_size   = 0x00;
1797         } else if (!output_size && input_size) {
1798             auth_method = AUTH_METHOD_INPUT;
1799             auth_action = (uint8_t)input_action;
1800             auth_size   = input_size;
1801         } else {
1802             auth_method = AUTH_METHOD_OUTPUT;
1803             auth_action = (uint8_t)output_action;
1804             auth_size   = output_size;
1805         }
1806     }
1807 
1808     /* Store provisioning capabilities value in conf_inputs */
1809     memcpy(&link[idx].conf_inputs[1], data, 11);
1810 
1811     prov_buf_init(&buf, PROV_START);
1812     net_buf_simple_add_u8(&buf, prov->prov_algorithm);
1813     net_buf_simple_add_u8(&buf, pub_key_oob);
1814     net_buf_simple_add_u8(&buf, auth_method);
1815     net_buf_simple_add_u8(&buf, auth_action);
1816     net_buf_simple_add_u8(&buf, auth_size);
1817 
1818     memcpy(&link[idx].conf_inputs[12], &buf.data[1], 5);
1819 
1820     if (prov_send(idx, &buf)) {
1821         BT_ERR("Failed to send Provisioning Start");
1822         goto fail;
1823     }
1824 
1825     link[idx].auth_method = auth_method;
1826     link[idx].auth_action = auth_action;
1827     link[idx].auth_size   = auth_size;
1828 
1829     /** After prov start sent, use OOB to get remote public key.
1830      *  And we just follow the procedure in Figure 5.15 of Section
1831      *  5.4.2.3 of Mesh Profile Spec.
1832      */
1833     if (pub_key_oob) {
1834         if (prov->prov_pub_key_oob_cb(idx)) {
1835             BT_ERR("Failed to notify input OOB Public Key");
1836             goto fail;
1837         }
1838     }
1839 
1840     /** If using PB-ADV, need to listen for transaction ack,
1841      *  after ack is received, provisioner can send public key.
1842      */
1843 #if defined(CONFIG_BLE_MESH_PB_ADV)
1844     if (idx < CONFIG_BLE_MESH_PBA_SAME_TIME) {
1845         link[idx].expect_ack_for = PROV_START;
1846         return;
1847     }
1848 #endif /* CONFIG_BLE_MESH_PB_ADV */
1849 
1850     send_pub_key(idx, pub_key_oob);
1851     return;
1852 
1853 fail:
1854     close_link(idx, CLOSE_REASON_FAILED);
1855     return;
1856 }
1857 
1858 static bt_mesh_output_action_t output_action(uint8_t action)
1859 {
1860     switch (action) {
1861     case OUTPUT_OOB_BLINK:
1862         return BLE_MESH_BLINK;
1863     case OUTPUT_OOB_BEEP:
1864         return BLE_MESH_BEEP;
1865     case OUTPUT_OOB_VIBRATE:
1866         return BLE_MESH_VIBRATE;
1867     case OUTPUT_OOB_NUMBER:
1868         return BLE_MESH_DISPLAY_NUMBER;
1869     case OUTPUT_OOB_STRING:
1870         return BLE_MESH_DISPLAY_STRING;
1871     default:
1872         return BLE_MESH_NO_OUTPUT;
1873     }
1874 }
1875 
1876 static bt_mesh_input_action_t input_action(uint8_t action)
1877 {
1878     switch (action) {
1879     case INPUT_OOB_PUSH:
1880         return BLE_MESH_PUSH;
1881     case INPUT_OOB_TWIST:
1882         return BLE_MESH_TWIST;
1883     case INPUT_OOB_NUMBER:
1884         return BLE_MESH_ENTER_NUMBER;
1885     case INPUT_OOB_STRING:
1886         return BLE_MESH_ENTER_STRING;
1887     default:
1888         return BLE_MESH_NO_INPUT;
1889     }
1890 }
1891 
1892 static int prov_auth(const uint8_t idx, uint8_t method, uint8_t action, uint8_t size)
1893 {
1894     bt_mesh_output_action_t output = 0U;
1895     bt_mesh_input_action_t input = 0U;
1896 
1897     link[idx].auth = (uint8_t *)bt_mesh_calloc(PROV_AUTH_VAL_SIZE);
1898     if (!link[idx].auth) {
1899         BT_ERR("%s, Out of memory", __func__);
1900         close_link(idx, CLOSE_REASON_FAILED);
1901         return -ENOMEM;
1902     }
1903 
1904     switch (method) {
1905     case AUTH_METHOD_NO_OOB:
1906         if (action || size) {
1907             return -EINVAL;
1908         }
1909         memset(link[idx].auth, 0, 16);
1910         return 0;
1911 
1912     case AUTH_METHOD_STATIC:
1913         if (action || size) {
1914             return -EINVAL;
1915         }
1916         memcpy(link[idx].auth + 16 - prov_ctx.static_oob_len,
1917                prov_ctx.static_oob_val, prov_ctx.static_oob_len);
1918         memset(link[idx].auth, 0, 16 - prov_ctx.static_oob_len);
1919         return 0;
1920 
1921     case AUTH_METHOD_OUTPUT:
1922         /* Use auth_action to get device output action */
1923         output = output_action(action);
1924         if (!output) {
1925             return -EINVAL;
1926         }
1927         return prov->prov_input_num(AUTH_METHOD_OUTPUT, output, size, idx);
1928 
1929     case AUTH_METHOD_INPUT:
1930         /* Use auth_action to get device input action */
1931         input = input_action(action);
1932         if (!input) {
1933             return -EINVAL;
1934         }
1935 
1936         /* Provisioner ouput number/string and wait for device's Provisioning Input Complete PDU */
1937         link[idx].expect = PROV_INPUT_COMPLETE;
1938 
1939         /* NOTE: The Bluetooth SIG recommends that mesh implementations enforce a randomly
1940          * selected AuthValue using all of the available bits, where permitted by the
1941          * implementation. A large entropy helps ensure that a brute-force of the AuthValue,
1942          * even a static AuthValue, cannot normally be completed in a reasonable time (CVE-2020-26557).
1943          *
1944          * AuthValues selected using a cryptographically secure random or pseudorandom number
1945          * generator and having the maximum permitted entropy (128-bits) will be most difficult
1946          * to brute-force. AuthValues with reduced entropy or generated in a predictable manner
1947          * will not grant the same level of protection against this vulnerability. Selecting a
1948          * new AuthValue with each provisioning attempt can also make it more difficult to launch
1949          * a brute-force attack by requiring the attacker to restart the search with each
1950          * provisioning attempt (CVE-2020-26556).
1951          */
1952         if (input == BLE_MESH_ENTER_STRING) {
1953             unsigned char str[9] = {'\0'};
1954             uint8_t j = 0U;
1955 
1956             bt_mesh_rand(str, size);
1957 
1958             /* Normalize to '0' .. '9' & 'A' .. 'Z' */
1959             for (j = 0U; j < size; j++) {
1960                 str[j] %= 36;
1961                 if (str[j] < 10) {
1962                     str[j] += '0';
1963                 } else {
1964                     str[j] += 'A' - 10;
1965                 }
1966             }
1967             str[size] = '\0';
1968 
1969             memcpy(link[idx].auth, str, size);
1970             memset(link[idx].auth + size, 0, PROV_AUTH_VAL_SIZE - size);
1971 
1972             return prov->prov_output_num(AUTH_METHOD_INPUT, input, str, size, idx);
1973         } else {
1974             uint32_t div[8] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
1975             uint32_t num = 0U;
1976 
1977             bt_mesh_rand(&num, sizeof(num));
1978 
1979             if (input == BLE_MESH_PUSH ||
1980                 input == BLE_MESH_TWIST) {
1981                 /** NOTE: According to the Bluetooth Mesh Profile Specification
1982                  *  Section 5.4.2.4, push and twist should be a random integer
1983                  *  between 0 and 10^size.
1984                  */
1985                 num = (num % (div[size - 1] - 1)) + 1;
1986             } else {
1987                 num %= div[size - 1];
1988             }
1989 
1990             sys_put_be32(num, &link[idx].auth[12]);
1991             memset(link[idx].auth, 0, 12);
1992 
1993             return prov->prov_output_num(AUTH_METHOD_INPUT, input, &num, size, idx);
1994         }
1995 
1996     default:
1997         return -EINVAL;
1998     }
1999 }
2000 
2001 static void send_confirm(const uint8_t idx)
2002 {
2003     PROV_BUF(buf, 17);
2004     uint8_t *conf = NULL;
2005 
2006     BT_DBG("ConfInputs[0]   %s", bt_hex(link[idx].conf_inputs, 64));
2007     BT_DBG("ConfInputs[64]  %s", bt_hex(link[idx].conf_inputs + 64, 64));
2008     BT_DBG("ConfInputs[128] %s", bt_hex(link[idx].conf_inputs + 128, 17));
2009 
2010     link[idx].conf_salt = (uint8_t *)bt_mesh_calloc(PROV_CONF_SALT_SIZE);
2011     if (!link[idx].conf_salt) {
2012         BT_ERR("%s, Out of memory", __func__);
2013         goto fail;
2014     }
2015 
2016     link[idx].conf_key = (uint8_t *)bt_mesh_calloc(PROV_CONF_KEY_SIZE);
2017     if (!link[idx].conf_key) {
2018         BT_ERR("%s, Out of memory", __func__);
2019         goto fail;
2020     }
2021 
2022     if (bt_mesh_prov_conf_salt(link[idx].conf_inputs, link[idx].conf_salt)) {
2023         BT_ERR("Failed to generate confirmation salt");
2024         goto fail;
2025     }
2026 
2027     BT_DBG("ConfirmationSalt: %s", bt_hex(link[idx].conf_salt, 16));
2028 
2029     if (bt_mesh_prov_conf_key(link[idx].dhkey, link[idx].conf_salt, link[idx].conf_key)) {
2030         BT_ERR("Failed to generate confirmation key");
2031         goto fail;
2032     }
2033 
2034     BT_DBG("ConfirmationKey: %s", bt_hex(link[idx].conf_key, 16));
2035 
2036     link[idx].rand = bt_mesh_calloc(PROV_RANDOM_SIZE);
2037     if (!link[idx].rand) {
2038         BT_ERR("%s, Out of memory", __func__);
2039         goto fail;
2040     }
2041 
2042     if (bt_mesh_rand(link[idx].rand, PROV_RANDOM_SIZE)) {
2043         BT_ERR("Failed to generate random number");
2044         goto fail;
2045     }
2046 
2047     BT_DBG("LocalRandom: %s", bt_hex(link[idx].rand, 16));
2048 
2049     prov_buf_init(&buf, PROV_CONFIRM);
2050 
2051     conf = net_buf_simple_add(&buf, 16);
2052 
2053     if (bt_mesh_prov_conf(link[idx].conf_key, link[idx].rand,
2054                           link[idx].auth, conf)) {
2055         BT_ERR("Failed to generate confirmation value");
2056         goto fail;
2057     }
2058 
2059     link[idx].local_conf = bt_mesh_calloc(PROV_CONFIRM_SIZE);
2060     if (!link[idx].local_conf) {
2061         BT_ERR("%s, Out of memory", __func__);
2062         goto fail;
2063     }
2064 
2065     memcpy(link[idx].local_conf, conf, PROV_CONFIRM_SIZE);
2066 
2067     if (prov_send(idx, &buf)) {
2068         BT_ERR("Failed to send Provisioning Confirm");
2069         goto fail;
2070     }
2071 
2072     link[idx].expect = PROV_CONFIRM;
2073     return;
2074 
2075 fail:
2076     close_link(idx, CLOSE_REASON_FAILED);
2077     return;
2078 }
2079 
2080 int bt_mesh_provisioner_set_oob_input_data(const uint8_t idx, const uint8_t *val, bool num_flag)
2081 {
2082     /** This function should be called in the prov_input_num
2083      *  callback, after the data output by device has been
2084      *  input by provisioner.
2085      *  Paramter size is used to indicate the length of data
2086      *  indicated by Pointer val, for example, if device output
2087      *  data is 12345678(decimal), the data in auth value will
2088      *  be 0xBC614E.
2089      *  Parameter num_flag is used to indicate whether the value
2090      *  input by provisioner is number or string.
2091      */
2092     if (!link[idx].auth) {
2093         BT_ERR("Invalid link auth");
2094         return -EINVAL;
2095     }
2096 
2097     BT_INFO("Link idx %d, type %s", idx, num_flag ? "number" : "string");
2098 
2099     memset(link[idx].auth, 0, 16);
2100     if (num_flag) {
2101         /* Provisioner inputs number */
2102         sys_memcpy_swap(link[idx].auth + 12, val, sizeof(uint32_t));
2103     } else {
2104         /* Provisioner inputs string */
2105         memcpy(link[idx].auth, val, link[idx].auth_size);
2106     }
2107 
2108     send_confirm(idx);
2109     return 0;
2110 }
2111 
2112 int bt_mesh_provisioner_set_oob_output_data(const uint8_t idx, const uint8_t *num,
2113                                             uint8_t size, bool num_flag)
2114 {
2115     /** This function should be called in the prov_output_num
2116      *  callback, after the data has been output by provisioner.
2117      *  Parameter size is used to indicate the length of data
2118      *  indicated by Pointer num, for example, if provisioner
2119      *  output data is 12345678(decimal), the data in auth value
2120      *  will be 0xBC614E.
2121      *  Parameter num_flag is used to indicate whether the value
2122      *  output by provisioner is number or string.
2123      */
2124     if (num == NULL || size > BLE_MESH_PROV_INPUT_OOB_MAX_LEN) {
2125         BT_ERR("%s, Invalid parameter", __func__);
2126         return -EINVAL;
2127     }
2128 
2129     if (!link[idx].auth) {
2130         BT_ERR("Invalid link auth");
2131         return -EINVAL;
2132     }
2133 
2134     BT_INFO("Link idx %d, type %s", idx, num_flag ? "number" : "string");
2135 
2136     if (num_flag) {
2137         /* Provisioner output number */
2138         memset(link[idx].auth, 0, 16);
2139         sys_memcpy_swap(link[idx].auth + 16 - size, num, size);
2140     } else {
2141         /* Provisioner output string */
2142         memset(link[idx].auth, 0, 16);
2143         memcpy(link[idx].auth, num, size);
2144     }
2145 
2146     link[idx].expect = PROV_INPUT_COMPLETE;
2147 
2148     return 0;
2149 }
2150 
2151 int bt_mesh_provisioner_read_oob_pub_key(const uint8_t idx, const uint8_t pub_key_x[32],
2152                                          const uint8_t pub_key_y[32])
2153 {
2154     if (!link[idx].conf_inputs) {
2155         BT_ERR("Invalid link conf_inputs");
2156         return -EINVAL;
2157     }
2158 
2159     /* Swap X and Y halves independently to big-endian */
2160     sys_memcpy_swap(&link[idx].conf_inputs[81], pub_key_x, 32);
2161     sys_memcpy_swap(&link[idx].conf_inputs[81] + 32, pub_key_y, 32);
2162 
2163     bt_mesh_atomic_set_bit(link[idx].flags, REMOTE_PUB_KEY);
2164 
2165     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, WAIT_GEN_DHKEY)) {
2166         prov_gen_dh_key(idx);
2167     }
2168 
2169     return 0;
2170 }
2171 
2172 static void prov_dh_key_cb(const uint8_t key[32], const uint8_t idx)
2173 {
2174     BT_DBG("%p", key);
2175 
2176     if (!key) {
2177         BT_ERR("Failed to generate DHKey");
2178         goto fail;
2179     }
2180 
2181     link[idx].dhkey = (uint8_t *)bt_mesh_calloc(PROV_DH_KEY_SIZE);
2182     if (!link[idx].dhkey) {
2183         BT_ERR("%s, Out of memory", __func__);
2184         goto fail;
2185     }
2186     sys_memcpy_swap(link[idx].dhkey, key, 32);
2187 
2188     BT_DBG("DHkey: %s", bt_hex(link[idx].dhkey, 32));
2189 
2190     bt_mesh_atomic_set_bit(link[idx].flags, HAVE_DHKEY);
2191 
2192     /** After dhkey is generated, if auth_method is No OOB or
2193      *  Static OOB, provisioner can start to send confirmation.
2194      *  If output OOB is used by the device, provisioner need
2195      *  to watch out the output number and input it as auth_val.
2196      *  If input OOB is used by the device, provisioner need
2197      *  to output a value, and wait for prov input complete pdu.
2198      */
2199     if (prov_auth(idx, link[idx].auth_method,
2200                   link[idx].auth_action, link[idx].auth_size) < 0) {
2201         BT_ERR("Failed to authenticate");
2202         goto fail;
2203     }
2204     if (link[idx].auth_method == AUTH_METHOD_OUTPUT ||
2205             link[idx].auth_method == AUTH_METHOD_INPUT) {
2206         return;
2207     }
2208 
2209     if (link[idx].expect != PROV_INPUT_COMPLETE) {
2210         send_confirm(idx);
2211     }
2212     return;
2213 
2214 fail:
2215     close_link(idx, CLOSE_REASON_FAILED);
2216     return;
2217 }
2218 
2219 static void prov_gen_dh_key(const uint8_t idx)
2220 {
2221     uint8_t pub_key[64] = {0};
2222 
2223     /* Copy device public key in little-endian for bt_mesh_dh_key_gen().
2224      * X and Y halves are swapped independently.
2225      */
2226     sys_memcpy_swap(&pub_key[0], &link[idx].conf_inputs[81], 32);
2227     sys_memcpy_swap(&pub_key[32], &link[idx].conf_inputs[113], 32);
2228 
2229     if (bt_mesh_dh_key_gen(pub_key, prov_dh_key_cb, idx)) {
2230         BT_ERR("Failed to generate DHKey");
2231         close_link(idx, CLOSE_REASON_FAILED);
2232         return;
2233     }
2234 }
2235 
2236 static void send_pub_key(const uint8_t idx, uint8_t oob)
2237 {
2238     PROV_BUF(buf, 65);
2239     const uint8_t *key = NULL;
2240 
2241     key = bt_mesh_pub_key_get();
2242     if (!key) {
2243         BT_ERR("No public key available");
2244         close_link(idx, CLOSE_REASON_FAILED);
2245         return;
2246     }
2247 
2248     BT_DBG("Local Public Key: %s", bt_hex(key, 64));
2249 
2250     bt_mesh_atomic_set_bit(link[idx].flags, LOCAL_PUB_KEY);
2251 
2252     prov_buf_init(&buf, PROV_PUB_KEY);
2253 
2254     /* Swap X and Y halves independently to big-endian */
2255     sys_memcpy_swap(net_buf_simple_add(&buf, 32), key, 32);
2256     sys_memcpy_swap(net_buf_simple_add(&buf, 32), &key[32], 32);
2257 
2258     /* Store provisioner public key value in conf_inputs */
2259     memcpy(&link[idx].conf_inputs[17], &buf.data[1], 64);
2260 
2261     if (prov_send(idx, &buf)) {
2262         BT_ERR("Failed to send Provisioning Public Key");
2263         close_link(idx, CLOSE_REASON_FAILED);
2264         return;
2265     }
2266 
2267     if (!oob) {
2268         link[idx].expect = PROV_PUB_KEY;
2269     } else {
2270         /** Have already got device public key. If next is to
2271          *  send confirm(not wait for input complete), need to
2272          *  wait for transactiona ack for public key then send
2273          *  provisioning confirm pdu.
2274          */
2275 #if defined(CONFIG_BLE_MESH_PB_ADV)
2276         if (idx < CONFIG_BLE_MESH_PBA_SAME_TIME) {
2277             link[idx].expect_ack_for = PROV_PUB_KEY;
2278             return;
2279         }
2280 #endif /* CONFIG_BLE_MESH_PB_ADV */
2281 
2282         /* If remote public key has been read, then start to generate DHkey,
2283          * otherwise wait for device oob public key.
2284          */
2285         if (bt_mesh_atomic_test_bit(link[idx].flags, REMOTE_PUB_KEY)) {
2286             prov_gen_dh_key(idx);
2287         } else {
2288             bt_mesh_atomic_set_bit(link[idx].flags, WAIT_GEN_DHKEY);
2289         }
2290     }
2291 }
2292 
2293 static void prov_pub_key(const uint8_t idx, const uint8_t *data)
2294 {
2295     BT_DBG("Remote Public Key: %s", bt_hex(data, 64));
2296 
2297     /* Make sure received pdu is ok and cancel the timeout timer */
2298     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
2299         k_delayed_work_cancel(&link[idx].timeout);
2300     }
2301 
2302     memcpy(&link[idx].conf_inputs[81], data, 64);
2303 
2304     if (!bt_mesh_atomic_test_bit(link[idx].flags, LOCAL_PUB_KEY)) {
2305         /* Clear retransmit timer */
2306 #if defined(CONFIG_BLE_MESH_PB_ADV)
2307         prov_clear_tx(idx);
2308 #endif
2309         bt_mesh_atomic_set_bit(link[idx].flags, REMOTE_PUB_KEY);
2310         BT_WARN("Waiting for local public key");
2311         return;
2312     }
2313 
2314     prov_gen_dh_key(idx);
2315 }
2316 
2317 static void prov_input_complete(const uint8_t idx, const uint8_t *data)
2318 {
2319     /* Make sure received pdu is ok and cancel the timeout timer */
2320     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
2321         k_delayed_work_cancel(&link[idx].timeout);
2322     }
2323 
2324     /* Provisioner receives input complete and send confirm */
2325     send_confirm(idx);
2326 }
2327 
2328 static void prov_confirm(const uint8_t idx, const uint8_t *data)
2329 {
2330     PROV_BUF(buf, 17);
2331 
2332     BT_DBG("Remote Confirm: %s", bt_hex(data, 16));
2333 
2334     /* NOTE: The Bluetooth SIG recommends that potentially vulnerable mesh provisioners
2335      * restrict the authentication procedure and not accept provisioning random and
2336      * provisioning confirmation numbers from a remote peer that are the same as those
2337      * selected by the local device (CVE-2020-26560).
2338      */
2339     if (!memcmp(data, link[idx].local_conf, 16)) {
2340         BT_ERR("Confirmation value is identical to ours, rejecting.");
2341         close_link(idx, CLOSE_REASON_FAILED);
2342         return;
2343     }
2344 
2345     /* Make sure received pdu is ok and cancel the timeout timer */
2346     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
2347         k_delayed_work_cancel(&link[idx].timeout);
2348     }
2349 
2350     link[idx].conf = (uint8_t *)bt_mesh_calloc(PROV_CONFIRM_SIZE);
2351     if (!link[idx].conf) {
2352         BT_ERR("%s, Out of memory", __func__);
2353         close_link(idx, CLOSE_REASON_FAILED);
2354         return;
2355     }
2356 
2357     memcpy(link[idx].conf, data, 16);
2358 
2359     if (!bt_mesh_atomic_test_bit(link[idx].flags, HAVE_DHKEY)) {
2360 #if defined(CONFIG_BLE_MESH_PB_ADV)
2361         prov_clear_tx(idx);
2362 #endif
2363         bt_mesh_atomic_set_bit(link[idx].flags, SEND_CONFIRM);
2364     }
2365 
2366     prov_buf_init(&buf, PROV_RANDOM);
2367 
2368     net_buf_simple_add_mem(&buf, link[idx].rand, 16);
2369 
2370     if (prov_send(idx, &buf)) {
2371         BT_ERR("Failed to send Provisioning Random");
2372         close_link(idx, CLOSE_REASON_FAILED);
2373         return;
2374     }
2375 
2376     link[idx].expect = PROV_RANDOM;
2377 }
2378 
2379 static void send_prov_data(const uint8_t idx)
2380 {
2381     PROV_BUF(buf, 34);
2382     uint16_t prev_addr = BLE_MESH_ADDR_UNASSIGNED;
2383     uint16_t max_addr = BLE_MESH_ADDR_UNASSIGNED;
2384     struct bt_mesh_node *node = NULL;
2385     const uint8_t *netkey = NULL;
2386     uint8_t session_key[16] = {0};
2387     uint8_t nonce[13] = {0};
2388     uint8_t pdu[25] = {0};
2389     int err = 0;
2390 
2391     err = bt_mesh_session_key(link[idx].dhkey, link[idx].prov_salt, session_key);
2392     if (err) {
2393         BT_ERR("Failed to generate session key");
2394         goto fail;
2395     }
2396     BT_DBG("SessionKey: %s", bt_hex(session_key, 16));
2397 
2398     err = bt_mesh_prov_nonce(link[idx].dhkey, link[idx].prov_salt, nonce);
2399     if (err) {
2400         BT_ERR("Failed to generate session nonce");
2401         goto fail;
2402     }
2403     BT_DBG("Nonce: %s", bt_hex(nonce, 13));
2404 
2405     /* Assign provisioning data for the device. Currently all provisioned devices
2406      * will be added to the primary subnet, and may add an API to choose to which
2407      * subnet will the device be provisioned later.
2408      */
2409     if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && FAST_PROV_ENABLE()) {
2410         netkey = bt_mesh_fast_prov_net_key_get(prov_ctx.fast_prov.net_idx);
2411         if (!netkey) {
2412             BT_ERR("No NetKey for fast provisioning");
2413             goto fail;
2414         }
2415         memcpy(pdu, netkey, 16);
2416         sys_put_be16(prov_ctx.fast_prov.net_idx, &pdu[16]);
2417         pdu[18] = prov_ctx.fast_prov.flags;
2418         sys_put_be32(prov_ctx.fast_prov.iv_index, &pdu[19]);
2419     } else {
2420         netkey = bt_mesh_provisioner_net_key_get(prov_ctx.curr_net_idx);
2421         if (!netkey) {
2422             BT_ERR("No NetKey for provisioning data");
2423             goto fail;
2424         }
2425         memcpy(pdu, netkey, 16);
2426         sys_put_be16(prov_ctx.curr_net_idx, &pdu[16]);
2427         pdu[18] = prov_ctx.curr_flags;
2428         sys_put_be32(prov_ctx.curr_iv_index, &pdu[19]);
2429     }
2430 
2431     /**
2432      * The Provisioner must not reuse unicast addresses that have been
2433      * allocated to a device and sent in a Provisioning Data PDU until
2434      * the Provisioner receives an Unprovisioned Device beacon or
2435      * Service Data for the Mesh Provisioning Service from that same
2436      * device, identified using the Device UUID of the device.
2437      */
2438 
2439     /* Check if this device is a re-provisioned device */
2440     node = bt_mesh_provisioner_get_node_with_uuid(link[idx].uuid);
2441     if (node) {
2442         if (link[idx].element_num <= node->element_num) {
2443             /**
2444              * If the device is provisioned before, but the element number of
2445              * the device is bigger now, then we treat it as a new device.
2446              */
2447             prev_addr = node->unicast_addr;
2448         }
2449         bt_mesh_provisioner_remove_node(link[idx].uuid);
2450     }
2451 
2452     max_addr = FAST_PROV_ENABLE() ? prov_ctx.fast_prov.unicast_addr_max : PROV_MAX_ADDR_TO_ASSIGN;
2453 
2454     if (BLE_MESH_ADDR_IS_UNICAST(prev_addr)) {
2455         sys_put_be16(prev_addr, &pdu[23]);
2456         link[idx].unicast_addr = prev_addr;
2457     } else {
2458         uint16_t alloc_addr = BLE_MESH_ADDR_UNASSIGNED;
2459 
2460         if (BLE_MESH_ADDR_IS_UNICAST(link[idx].assign_addr)) {
2461             alloc_addr = link[idx].assign_addr;
2462         } else {
2463             /* If this device to be provisioned is a new device */
2464             if (prov_ctx.curr_alloc_addr == BLE_MESH_ADDR_UNASSIGNED) {
2465                 BT_ERR("Not enough unicast address to be allocated");
2466                 goto fail;
2467             }
2468             alloc_addr = prov_ctx.curr_alloc_addr;
2469         }
2470 
2471         if (alloc_addr + link[idx].element_num - 1 > max_addr) {
2472             BT_ERR("Not enough unicast address for the device");
2473             goto fail;
2474         }
2475 
2476         /* Make sure the assigned unicast address is not identical with any unicast
2477          * address of other nodes. And make sure the address is not identical with
2478          * any unicast address of Provisioner.
2479          */
2480         if (bt_mesh_provisioner_check_is_addr_dup(alloc_addr, link[idx].element_num, true)) {
2481             BT_ERR("Duplicate assigned address 0x%04x", alloc_addr);
2482             goto fail;
2483         }
2484 
2485         sys_put_be16(alloc_addr, &pdu[23]);
2486         link[idx].unicast_addr = alloc_addr;
2487     }
2488 
2489     prov_buf_init(&buf, PROV_DATA);
2490 
2491     err = bt_mesh_prov_encrypt(session_key, nonce, pdu, net_buf_simple_add(&buf, 33));
2492     if (err) {
2493         BT_ERR("Failed to encrypt provisioning data");
2494         goto fail;
2495     }
2496 
2497     if (prov_send(idx, &buf)) {
2498         BT_ERR("Failed to send Provisioning Data");
2499         goto fail;
2500     }
2501 
2502     /**
2503      * We update the next unicast address to be allocated here because if
2504      * Provisioner is provisioning two devices at the same time, we need
2505      * to assign the unicast address for them correctly. Hence we should
2506      * not update the prov_ctx.curr_alloc_addr after the proper provisioning
2507      * complete pdu is received.
2508      */
2509     if (!BLE_MESH_ADDR_IS_UNICAST(prev_addr)) {
2510         if (BLE_MESH_ADDR_IS_UNICAST(link[idx].assign_addr)) {
2511             /* Even if the unicast address of the node is assigned by the
2512              * application, we will also update the prov_ctx.curr_alloc_addr
2513              * here, in case Users use the two methods together (i.e. allocate
2514              * the unicast address for the node internally and assign the
2515              * unicast address for the node from application).
2516              */
2517             if (prov_ctx.curr_alloc_addr < link[idx].assign_addr + link[idx].element_num) {
2518                 prov_ctx.curr_alloc_addr = link[idx].assign_addr + link[idx].element_num;
2519             }
2520         } else {
2521             prov_ctx.curr_alloc_addr += link[idx].element_num;
2522             if (prov_ctx.curr_alloc_addr > max_addr) {
2523                 /* No unicast address will be used for further provisioning */
2524                 prov_ctx.curr_alloc_addr = BLE_MESH_ADDR_UNASSIGNED;
2525             }
2526         }
2527         /* Store the available unicast address range to flash */
2528         if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
2529             bt_mesh_store_prov_info(prov_ctx.primary_addr, prov_ctx.curr_alloc_addr);
2530         }
2531     }
2532 
2533     if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && FAST_PROV_ENABLE()) {
2534         link[idx].ki_flags = prov_ctx.fast_prov.flags;
2535         link[idx].iv_index = prov_ctx.fast_prov.iv_index;
2536     } else {
2537         link[idx].ki_flags = prov_ctx.curr_flags;
2538         link[idx].iv_index = prov_ctx.curr_iv_index;
2539     }
2540 
2541     link[idx].expect = PROV_COMPLETE;
2542     return;
2543 
2544 fail:
2545     close_link(idx, CLOSE_REASON_FAILED);
2546     return;
2547 }
2548 
2549 static void prov_random(const uint8_t idx, const uint8_t *data)
2550 {
2551     uint8_t conf_verify[16] = {0};
2552 
2553     BT_DBG("Remote Random: %s", bt_hex(data, 16));
2554 
2555     /* NOTE: The Bluetooth SIG recommends that potentially vulnerable mesh provisioners
2556      * restrict the authentication procedure and not accept provisioning random and
2557      * provisioning confirmation numbers from a remote peer that are the same as those
2558      * selected by the local device (CVE-2020-26560).
2559      */
2560     if (!memcmp(data, link[idx].rand, 16)) {
2561         BT_ERR("Random value is identical to ours, rejecting.");
2562         goto fail;
2563     }
2564 
2565     if (bt_mesh_prov_conf(link[idx].conf_key, data, link[idx].auth, conf_verify)) {
2566         BT_ERR("Failed to calculate confirmation verification");
2567         goto fail;
2568     }
2569 
2570     if (memcmp(conf_verify, link[idx].conf, 16)) {
2571         BT_ERR("Invalid confirmation value");
2572         BT_DBG("Received:   %s", bt_hex(link[idx].conf, 16));
2573         BT_DBG("Calculated: %s",  bt_hex(conf_verify, 16));
2574         goto fail;
2575     }
2576 
2577     /*Verify received confirm is ok and cancel the timeout timer */
2578     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
2579         k_delayed_work_cancel(&link[idx].timeout);
2580     }
2581 
2582     /** After provisioner receives provisioning random from device,
2583      *  and successfully check the confirmation, the following
2584      *  should be done:
2585      *  1. bt_mesh_calloc memory for prov_salt
2586      *  2. calculate prov_salt
2587      *  3. prepare provisioning data and send
2588      */
2589     link[idx].prov_salt = (uint8_t *)bt_mesh_calloc(PROV_PROV_SALT_SIZE);
2590     if (!link[idx].prov_salt) {
2591         BT_ERR("%s, Out of memory", __func__);
2592         goto fail;
2593     }
2594 
2595     if (bt_mesh_prov_salt(link[idx].conf_salt, link[idx].rand, data,
2596                           link[idx].prov_salt)) {
2597         BT_ERR("Failed to generate ProvisioningSalt");
2598         goto fail;
2599     }
2600 
2601     BT_DBG("ProvisioningSalt: %s", bt_hex(link[idx].prov_salt, 16));
2602 
2603     send_prov_data(idx);
2604     return;
2605 
2606 fail:
2607     close_link(idx, CLOSE_REASON_FAILED);
2608     return;
2609 }
2610 
2611 static void prov_complete(const uint8_t idx, const uint8_t *data)
2612 {
2613     uint8_t device_key[16] = {0};
2614     uint16_t net_idx = 0U;
2615     uint16_t index = 0U;
2616     int err = 0;
2617     int i;
2618 
2619     /* Make sure received pdu is ok and cancel the timeout timer */
2620     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
2621         k_delayed_work_cancel(&link[idx].timeout);
2622     }
2623 
2624     err = bt_mesh_dev_key(link[idx].dhkey, link[idx].prov_salt, device_key);
2625     if (err) {
2626         BT_ERR("Failed to generate device key");
2627         close_link(idx, CLOSE_REASON_FAILED);
2628         return;
2629     }
2630 
2631     if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV) && FAST_PROV_ENABLE()) {
2632         net_idx = prov_ctx.fast_prov.net_idx;
2633     } else {
2634         net_idx = prov_ctx.curr_net_idx;
2635     }
2636     err = bt_mesh_provisioner_provision(&link[idx].addr, link[idx].uuid, link[idx].oob_info,
2637                                         link[idx].unicast_addr, link[idx].element_num, net_idx,
2638                                         link[idx].ki_flags, link[idx].iv_index, device_key, &index);
2639     if (err) {
2640         BT_ERR("Failed to store node info");
2641         close_link(idx, CLOSE_REASON_FAILED);
2642         return;
2643     }
2644 
2645     if (prov->prov_complete) {
2646         prov->prov_complete(index, link[idx].uuid, link[idx].unicast_addr,
2647                             link[idx].element_num, net_idx);
2648     }
2649 
2650     /* Find if the device is in the device queue */
2651     for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
2652         if (!memcmp(unprov_dev[i].uuid, link[idx].uuid, 16) &&
2653             (unprov_dev[i].flags & RM_AFTER_PROV)) {
2654             memset(&unprov_dev[i], 0, sizeof(struct unprov_dev_queue));
2655             break;
2656         }
2657     }
2658 
2659     close_link(idx, CLOSE_REASON_SUCCESS);
2660 }
2661 
2662 static void prov_failed(const uint8_t idx, const uint8_t *data)
2663 {
2664     BT_WARN("Error 0x%02x", data[0]);
2665 
2666     close_link(idx, CLOSE_REASON_FAILED);
2667 }
2668 
2669 static const struct {
2670     void (*func)(const uint8_t idx, const uint8_t *data);
2671     uint16_t len;
2672 } prov_handlers[] = {
2673     { prov_invite,         1  },
2674     { prov_capabilities,   11 },
2675     { prov_start,          5  },
2676     { prov_pub_key,        64 },
2677     { prov_input_complete, 0  },
2678     { prov_confirm,        16 },
2679     { prov_random,         16 },
2680     { prov_data,           33 },
2681     { prov_complete,       0  },
2682     { prov_failed,         1  },
2683 };
2684 
2685 static void close_link(const uint8_t idx, uint8_t reason)
2686 {
2687 #if defined(CONFIG_BLE_MESH_PB_ADV)
2688     if (idx < CONFIG_BLE_MESH_PBA_SAME_TIME) {
2689         bearer_ctl_send(idx, LINK_CLOSE, &reason, sizeof(reason));
2690         return;
2691     }
2692 #endif
2693 
2694 #if defined(CONFIG_BLE_MESH_PB_GATT)
2695     if (idx < BLE_MESH_PROV_SAME_TIME
2696 #if defined(CONFIG_BLE_MESH_PB_ADV)
2697             && idx >= CONFIG_BLE_MESH_PBA_SAME_TIME
2698 #endif
2699        ) {
2700         if (link[idx].conn) {
2701             bt_mesh_gattc_disconnect(link[idx].conn);
2702         }
2703         return;
2704     }
2705 #endif
2706 
2707     BT_ERR("Invalid link idx %d", idx);
2708     return;
2709 }
2710 
2711 static void prov_timeout(struct k_work *work)
2712 {
2713     uint8_t idx = (uint8_t)work->index;
2714 
2715     BT_WARN("%s", __func__);
2716 
2717     close_link(idx, CLOSE_REASON_TIMEOUT);
2718 }
2719 
2720 #if defined(CONFIG_BLE_MESH_PB_ADV)
2721 static void prov_retransmit(struct k_work *work)
2722 {
2723     int64_t timeout = TRANSACTION_TIMEOUT;
2724     uint8_t idx = (uint8_t)work->index;
2725     int i;
2726 
2727     BT_DBG("%s", __func__);
2728 
2729     if (!bt_mesh_atomic_test_bit(link[idx].flags, LINK_ACTIVE)) {
2730         BT_WARN("Link is not active");
2731         return;
2732     }
2733 
2734 #if defined(CONFIG_BLE_MESH_FAST_PROV)
2735     if (link[idx].tx_pdu_type >= PROV_DATA) {
2736         timeout = K_SECONDS(30);
2737     }
2738 #endif
2739     if (k_uptime_get() - link[idx].tx.start > timeout) {
2740         BT_WARN("Provisioner timeout, giving up transaction");
2741         /* Provisioner should send Link Close here */
2742         close_link(idx, CLOSE_REASON_TIMEOUT);
2743         return;
2744     }
2745 
2746     if (link[idx].send_link_close & BIT(0)) {
2747         uint8_t reason = (link[idx].send_link_close >> 1) & BIT_MASK(2);
2748         uint16_t count = (link[idx].send_link_close >> 3);
2749         if (count >= 2) {
2750             reset_link(idx, reason);
2751             return;
2752         }
2753         link[idx].send_link_close += BIT(3);
2754     }
2755 
2756     bt_mesh_pb_buf_lock();
2757 
2758     for (i = 0; i < ARRAY_SIZE(link[idx].tx.buf); i++) {
2759         struct net_buf *buf = link[idx].tx.buf[i];
2760 
2761         if (!buf) {
2762             break;
2763         }
2764 
2765         if (BLE_MESH_ADV(buf)->busy) {
2766             continue;
2767         }
2768 
2769         BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
2770 
2771         if (i + 1 < ARRAY_SIZE(link[idx].tx.buf) && link[idx].tx.buf[i + 1]) {
2772             bt_mesh_adv_send(buf, NULL, NULL);
2773         } else {
2774             bt_mesh_adv_send(buf, &buf_sent_cb, (void *)(int)idx);
2775         }
2776     }
2777 
2778     bt_mesh_pb_buf_unlock();
2779 }
2780 
2781 static void link_ack(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2782 {
2783     BT_DBG("len %u", buf->len);
2784 
2785     if (buf->len) {
2786         BT_ERR("Invalid Link ACK length %d", buf->len);
2787         close_link(idx, CLOSE_REASON_FAILED);
2788         return;
2789     }
2790 
2791     if (link[idx].expect == PROV_CAPABILITIES) {
2792         BT_INFO("Link ACK is already received");
2793         return;
2794     }
2795 
2796     link[idx].conf_inputs = (uint8_t *)bt_mesh_calloc(PROV_CONF_INPUTS_SIZE);
2797     if (!link[idx].conf_inputs) {
2798         BT_ERR("%s, Out of memory", __func__);
2799         close_link(idx, CLOSE_REASON_FAILED);
2800         return;
2801     }
2802 
2803     send_invite(idx);
2804 }
2805 
2806 static void link_close(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2807 {
2808     uint8_t reason = 0U;
2809 
2810     BT_DBG("len %u", buf->len);
2811 
2812     reason = net_buf_simple_pull_u8(buf);
2813 
2814     reset_link(idx, reason);
2815 }
2816 
2817 static void gen_prov_ctl(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2818 {
2819     BT_DBG("op 0x%02x len %u", BEARER_CTL(rx->gpc), buf->len);
2820 
2821     switch (BEARER_CTL(rx->gpc)) {
2822     case LINK_OPEN:
2823         break;
2824 
2825     case LINK_ACK:
2826         if (!bt_mesh_atomic_test_bit(link[idx].flags, LINK_ACTIVE)) {
2827             return;
2828         }
2829         link_ack(idx, rx, buf);
2830         break;
2831 
2832     case LINK_CLOSE:
2833         if (!bt_mesh_atomic_test_bit(link[idx].flags, LINK_ACTIVE)) {
2834             return;
2835         }
2836         link_close(idx, rx, buf);
2837         break;
2838 
2839     default:
2840         BT_ERR("Unknown bearer opcode 0x%02x", BEARER_CTL(rx->gpc));
2841         return;
2842     }
2843 }
2844 
2845 static void prov_msg_recv(const uint8_t idx)
2846 {
2847     uint8_t type = link[idx].rx.buf->data[0];
2848 
2849     BT_DBG("type 0x%02x len %u", type, link[idx].rx.buf->len);
2850 
2851     /**
2852      * Provisioner first checks information within the received
2853      * Provisioning PDU. If the check succeeds then check fcs.
2854      */
2855     if (type != PROV_FAILED && type != link[idx].expect) {
2856         BT_ERR("Unexpected msg 0x%02x != 0x%02x", type, link[idx].expect);
2857         goto fail;
2858     }
2859 
2860     if (type >= 0x0A) {
2861         BT_ERR("Unknown provisioning PDU type 0x%02x", type);
2862         goto fail;
2863     }
2864 
2865     if (1 + prov_handlers[type].len != link[idx].rx.buf->len) {
2866         BT_ERR("Invalid length %u for type 0x%02x", link[idx].rx.buf->len, type);
2867         goto fail;
2868     }
2869 
2870     if (!bt_mesh_fcs_check(link[idx].rx.buf, link[idx].rx.fcs)) {
2871         BT_ERR("Incorrect FCS");
2872         goto fail;
2873     }
2874 
2875     gen_prov_ack_send(idx, link[idx].rx.trans_id);
2876     link[idx].rx.prev_id = link[idx].rx.trans_id;
2877     link[idx].rx.trans_id = 0;
2878 
2879     prov_handlers[type].func(idx, &link[idx].rx.buf->data[1]);
2880     return;
2881 
2882 fail:
2883     /**
2884      * For the case MESH/PVNR/PROV/BV-10-C and MESH/PVNR/PROV/BI-14-C,
2885      * provisioner should send transaction ack before closing the link.
2886      */
2887     gen_prov_ack_send(idx, link[idx].rx.trans_id);
2888 
2889     close_link(idx, CLOSE_REASON_FAILED);
2890     return;
2891 }
2892 
2893 static void gen_prov_cont(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2894 {
2895     uint8_t seg = CONT_SEG_INDEX(rx->gpc);
2896 
2897     BT_DBG("len %u, seg_index %u", buf->len, seg);
2898 
2899     if (!link[idx].rx.seg && link[idx].rx.prev_id == rx->xact_id) {
2900         BT_INFO("Resending ack");
2901         gen_prov_ack_send(idx, rx->xact_id);
2902         return;
2903     }
2904 
2905     if (rx->xact_id != link[idx].rx.trans_id) {
2906         BT_WARN("Data for unknown transaction (%u != %u)",
2907             rx->xact_id, link[idx].rx.trans_id);
2908         return;
2909     }
2910 
2911     if (seg > link[idx].rx.last_seg) {
2912         BT_ERR("Invalid segment index %u", seg);
2913         goto fail;
2914     } else if (seg == link[idx].rx.last_seg) {
2915         uint8_t expect_len = 0U;
2916 
2917         expect_len = (link[idx].rx.buf->len - 20 -
2918                       (23 * (link[idx].rx.last_seg - 1)));
2919         if (expect_len != buf->len) {
2920             BT_ERR("Incorrect last seg len: %u != %u",
2921                     expect_len, buf->len);
2922             goto fail;
2923         }
2924     }
2925 
2926     if (!(link[idx].rx.seg & BIT(seg))) {
2927         BT_INFO("Ignore already received segment");
2928         return;
2929     }
2930 
2931     memcpy(XACT_SEG_DATA(idx, seg), buf->data, buf->len);
2932     XACT_SEG_RECV(idx, seg);
2933 
2934     if (!link[idx].rx.seg) {
2935         prov_msg_recv(idx);
2936     }
2937     return;
2938 
2939 fail:
2940     close_link(idx, CLOSE_REASON_FAILED);
2941     return;
2942 }
2943 
2944 static void gen_prov_ack(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2945 {
2946     uint8_t ack_type = 0U, pub_key_oob = 0U;
2947 
2948     BT_DBG("len %u", buf->len);
2949 
2950     if (!link[idx].tx.buf[0]) {
2951         return;
2952     }
2953 
2954     if (!link[idx].tx.trans_id) {
2955         return;
2956     }
2957 
2958     if (rx->xact_id == (link[idx].tx.trans_id - 1)) {
2959         prov_clear_tx(idx);
2960 
2961         ack_type = link[idx].expect_ack_for;
2962         switch (ack_type) {
2963         case PROV_START:
2964             pub_key_oob = link[idx].conf_inputs[13];
2965             send_pub_key(idx, pub_key_oob);
2966             /* For case MESH/PVNR/PROV/BV-04-C, if using OOB public key,
2967              * the value of expect_ack_for shall be PROV_PUB_KEY.
2968              */
2969             if (pub_key_oob) {
2970                 return;
2971             }
2972             break;
2973         case PROV_PUB_KEY:
2974             prov_gen_dh_key(idx);
2975             break;
2976         default:
2977             break;
2978         }
2979         link[idx].expect_ack_for = 0x00;
2980     }
2981 }
2982 
2983 static void gen_prov_start(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
2984 {
2985     if (link[idx].rx.seg) {
2986         BT_INFO("Get Start while there are unreceived segments");
2987         return;
2988     }
2989 
2990     if (link[idx].rx.prev_id == rx->xact_id) {
2991         BT_INFO("Resending ack");
2992         gen_prov_ack_send(idx, rx->xact_id);
2993         return;
2994     }
2995 
2996     link[idx].rx.buf->len = net_buf_simple_pull_be16(buf);
2997     link[idx].rx.trans_id = rx->xact_id;
2998     link[idx].rx.fcs = net_buf_simple_pull_u8(buf);
2999 
3000     BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len,
3001            START_LAST_SEG(rx->gpc), link[idx].rx.buf->len, link[idx].rx.fcs);
3002 
3003     /* Provisioner can not receive zero-length provisioning pdu */
3004     if (link[idx].rx.buf->len < 1) {
3005         BT_ERR("Ignoring zero-length provisioning PDU");
3006         close_link(idx, CLOSE_REASON_FAILED);
3007         return;
3008     }
3009 
3010     if (START_LAST_SEG(rx->gpc) > START_LAST_SEG_MAX) {
3011         BT_ERR("Invalid SegN 0x%02x", START_LAST_SEG(rx->gpc));
3012         close_link(idx, CLOSE_REASON_FAILED);
3013         return;
3014     }
3015 
3016     if (link[idx].rx.buf->len > link[idx].rx.buf->size) {
3017         BT_ERR("Too large provisioning PDU (%u bytes)",
3018                 link[idx].rx.buf->len);
3019         close_link(idx, CLOSE_REASON_FAILED);
3020         return;
3021     }
3022 
3023     if (START_LAST_SEG(rx->gpc) > 0 && link[idx].rx.buf->len <= 20) {
3024         BT_ERR("Too small total length for multi-segment PDU");
3025         close_link(idx, CLOSE_REASON_FAILED);
3026         return;
3027     }
3028 
3029     link[idx].rx.seg = (1 << (START_LAST_SEG(rx->gpc) + 1)) - 1;
3030     link[idx].rx.last_seg = START_LAST_SEG(rx->gpc);
3031     memcpy(link[idx].rx.buf->data, buf->data, buf->len);
3032     XACT_SEG_RECV(idx, 0);
3033 
3034     if (!link[idx].rx.seg) {
3035         prov_msg_recv(idx);
3036     }
3037 }
3038 
3039 static const struct {
3040     void (*const func)(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf);
3041     const uint8_t require_link;
3042     const uint8_t min_len;
3043 } gen_prov[] = {
3044     { gen_prov_start, true,  3 },
3045     { gen_prov_ack,   true,  0 },
3046     { gen_prov_cont,  true,  0 },
3047     { gen_prov_ctl,   true,  0 },
3048 };
3049 
3050 static void gen_prov_recv(const uint8_t idx, struct prov_rx *rx, struct net_buf_simple *buf)
3051 {
3052     if (buf->len < gen_prov[GPCF(rx->gpc)].min_len) {
3053         BT_ERR("Too short GPC message type %u", GPCF(rx->gpc));
3054         close_link(idx, CLOSE_REASON_FAILED);
3055         return;
3056     }
3057 
3058     /**
3059      * require_link can be used combining with link[].linking flag to
3060      * set LINK_ACTIVE status after Link ACK is received. In this case
3061      * there is no need to check LINK_ACTIVE status in find_link().
3062      */
3063     if (!bt_mesh_atomic_test_bit(link[idx].flags, LINK_ACTIVE) &&
3064             gen_prov[GPCF(rx->gpc)].require_link) {
3065         BT_DBG("Ignoring message that requires active link");
3066         return;
3067     }
3068 
3069     gen_prov[GPCF(rx->gpc)].func(idx, rx, buf);
3070 }
3071 
3072 static int find_link(uint32_t link_id, uint8_t *idx)
3073 {
3074     int i;
3075 
3076     /* link for PB-ADV is from 0 to CONFIG_BLE_MESH_PBA_SAME_TIME */
3077     for (i = 0; i < CONFIG_BLE_MESH_PBA_SAME_TIME; i++) {
3078         if (bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
3079             if (link[i].link_id == link_id) {
3080                 if (idx) {
3081                     *idx = i;
3082                 }
3083                 return 0;
3084             }
3085         }
3086     }
3087 
3088     return -1;
3089 }
3090 
3091 void bt_mesh_provisioner_pb_adv_recv(struct net_buf_simple *buf)
3092 {
3093     struct prov_rx rx = {0};
3094     uint8_t idx = 0U;
3095 
3096     rx.link_id = net_buf_simple_pull_be32(buf);
3097     if (find_link(rx.link_id, &idx) < 0) {
3098         BT_DBG("Data for unexpected link");
3099         return;
3100     }
3101 
3102     if (buf->len < 2) {
3103         BT_ERR("Too short provisioning packet (len %u)", buf->len);
3104         close_link(idx, CLOSE_REASON_FAILED);
3105         return;
3106     }
3107 
3108     rx.xact_id = net_buf_simple_pull_u8(buf);
3109     rx.gpc = net_buf_simple_pull_u8(buf);
3110 
3111     BT_DBG("link_id 0x%08x xact_id %u", rx.link_id, rx.xact_id);
3112 
3113     gen_prov_recv(idx, &rx, buf);
3114 }
3115 #endif /* CONFIG_BLE_MESH_PB_ADV */
3116 
3117 #if defined(CONFIG_BLE_MESH_PB_GATT)
3118 static struct bt_mesh_conn *find_conn(struct bt_mesh_conn *conn, uint8_t *idx)
3119 {
3120     int i;
3121 
3122     /* link for PB-GATT is from CONFIG_BLE_MESH_PBA_SAME_TIME to BLE_MESH_PROV_SAME_TIME */
3123     for (i = CONFIG_BLE_MESH_PBA_SAME_TIME; i < BLE_MESH_PROV_SAME_TIME; i++) {
3124         if (bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
3125             if (link[i].conn == conn) {
3126                 if (idx) {
3127                     *idx = i;
3128                 }
3129                 return conn;
3130             }
3131         }
3132     }
3133 
3134     return NULL;
3135 }
3136 
3137 int bt_mesh_provisioner_pb_gatt_recv(struct bt_mesh_conn *conn, struct net_buf_simple *buf)
3138 {
3139     uint8_t type = 0U;
3140     uint8_t idx = 0U;
3141 
3142     BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
3143 
3144     if (!find_conn(conn, &idx)) {
3145         BT_ERR("Data for unexpected connection");
3146         return -ENOTCONN;
3147     }
3148 
3149     if (buf->len < 1) {
3150         BT_ERR("Too short provisioning packet (len %u)", buf->len);
3151         goto fail;
3152     }
3153 
3154     type = net_buf_simple_pull_u8(buf);
3155     if (type != PROV_FAILED && type != link[idx].expect) {
3156         BT_ERR("Unexpected msg 0x%02x != 0x%02x", type, link[idx].expect);
3157         goto fail;
3158     }
3159 
3160     if (type >= 0x0A) {
3161         BT_ERR("Unknown provisioning PDU type 0x%02x", type);
3162         goto fail;
3163     }
3164 
3165     if (prov_handlers[type].len != buf->len) {
3166         BT_ERR("Invalid length %u for type 0x%02x", buf->len, type);
3167         goto fail;
3168     }
3169 
3170     prov_handlers[type].func(idx, buf->data);
3171 
3172     return 0;
3173 
3174 fail:
3175     /* Mesh Spec Section 5.4.4 Provisioning errors */
3176     close_link(idx, CLOSE_REASON_FAILED);
3177     return -EINVAL;
3178 }
3179 
3180 int bt_mesh_provisioner_set_prov_conn(const uint8_t addr[6], struct bt_mesh_conn *conn)
3181 {
3182     int i;
3183 
3184     if (!addr || !conn) {
3185         BT_ERR("%s, Invalid parameter", __func__);
3186         return -EINVAL;
3187     }
3188 
3189     for (i = CONFIG_BLE_MESH_PBA_SAME_TIME; i < BLE_MESH_PROV_SAME_TIME; i++) {
3190         if (!memcmp(link[i].addr.val, addr, BLE_MESH_ADDR_LEN)) {
3191             link[i].conn = bt_mesh_conn_ref(conn);
3192             return 0;
3193         }
3194     }
3195 
3196     BT_ERR("Addr %s not found", bt_hex(addr, BLE_MESH_ADDR_LEN));
3197     return -ENOMEM;
3198 }
3199 
3200 int bt_mesh_provisioner_pb_gatt_open(struct bt_mesh_conn *conn, uint8_t *addr)
3201 {
3202     uint8_t idx = 0U;
3203     int i;
3204 
3205     BT_DBG("conn %p", conn);
3206 
3207     /**
3208      * Double check if the device is currently being provisioned using PB-ADV.
3209      * Provisioner binds conn with proper device when proxy_prov_connected()
3210      * is invoked, and here after proper GATT procedures are completed, we just
3211      * check if this conn already exists in the proxy servers array.
3212      */
3213     for (i = CONFIG_BLE_MESH_PBA_SAME_TIME; i < BLE_MESH_PROV_SAME_TIME; i++) {
3214         if (link[i].conn == conn) {
3215             idx = i;
3216             break;
3217         }
3218     }
3219 
3220     if (i == BLE_MESH_PROV_SAME_TIME) {
3221         BT_ERR("Link not found");
3222         return -ENOTCONN;
3223     }
3224 
3225 #if defined(CONFIG_BLE_MESH_PB_ADV)
3226     for (i = 0; i < CONFIG_BLE_MESH_PBA_SAME_TIME; i++) {
3227         if (bt_mesh_atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
3228             if (!memcmp(link[i].uuid, link[idx].uuid, 16)) {
3229                 BT_WARN("Provision using PB-GATT & PB-ADV same time");
3230                 close_link(idx, CLOSE_REASON_FAILED);
3231                 return -EALREADY;
3232             }
3233         }
3234     }
3235 #endif
3236 
3237     bt_mesh_atomic_set_bit(link[idx].flags, LINK_ACTIVE);
3238     link[idx].conn = bt_mesh_conn_ref(conn);
3239 
3240     /* May use lcd to indicate starting provisioning each device */
3241     if (prov->prov_link_open) {
3242         prov->prov_link_open(BLE_MESH_PROV_GATT);
3243     }
3244 
3245     link[idx].conf_inputs = (uint8_t *)bt_mesh_calloc(PROV_CONF_INPUTS_SIZE);
3246     if (!link[idx].conf_inputs) {
3247         /* Disconnect this connection, clear corresponding informations */
3248         BT_ERR("%s, Out of memory", __func__);
3249         close_link(idx, CLOSE_REASON_FAILED);
3250         return -ENOMEM;
3251     }
3252 
3253     send_invite(idx);
3254     return 0;
3255 }
3256 
3257 int bt_mesh_provisioner_pb_gatt_close(struct bt_mesh_conn *conn, uint8_t reason)
3258 {
3259     uint8_t idx = 0U;
3260 
3261     BT_DBG("conn %p", conn);
3262 
3263     if (!find_conn(conn, &idx)) {
3264         BT_ERR("Conn %p not found", conn);
3265         return -ENOTCONN;
3266     }
3267 
3268     if (bt_mesh_atomic_test_and_clear_bit(link[idx].flags, TIMEOUT_START)) {
3269         k_delayed_work_cancel(&link[idx].timeout);
3270     }
3271 
3272     if (prov->prov_link_close) {
3273         prov->prov_link_close(BLE_MESH_PROV_GATT, reason);
3274     }
3275 
3276     prov_memory_free(idx);
3277 
3278     memset(&link[idx], 0, offsetof(struct prov_link, timeout));
3279 
3280     if (bt_mesh_pub_key_get()) {
3281         bt_mesh_atomic_set_bit(link[idx].flags, LOCAL_PUB_KEY);
3282     }
3283 
3284     return 0;
3285 }
3286 #endif /* CONFIG_BLE_MESH_PB_GATT */
3287 
3288 int bt_mesh_provisioner_prov_init(const struct bt_mesh_prov *prov_info)
3289 {
3290     const uint8_t *key = NULL;
3291     int i;
3292 
3293     if (!prov_info) {
3294         BT_ERR("No provisioning context provided");
3295         return -EINVAL;
3296     }
3297 
3298     key = bt_mesh_pub_key_get();
3299     if (!key) {
3300         BT_ERR("Failed to generate Public Key");
3301         return -EIO;
3302     }
3303 
3304     prov = prov_info;
3305 
3306     prov_ctx.primary_addr = BLE_MESH_ADDR_UNASSIGNED;
3307 
3308     if (prov->prov_static_oob_val && prov->prov_static_oob_len) {
3309         prov_ctx.static_oob_len = MIN(16, prov->prov_static_oob_len);
3310         memcpy(prov_ctx.static_oob_val, prov->prov_static_oob_val, prov_ctx.static_oob_len);
3311     }
3312 
3313 #if defined(CONFIG_BLE_MESH_PB_ADV)
3314     for (i = 0; i < CONFIG_BLE_MESH_PBA_SAME_TIME; i++) {
3315         struct prov_adv_buf *adv = &adv_buf[i];
3316         adv->buf.size = ADV_BUF_SIZE;
3317         adv->buf.__buf = adv_buf_data + (i * ADV_BUF_SIZE);
3318 
3319         link[i].pending_ack = XACT_NVAL;
3320         k_delayed_work_init(&link[i].tx.retransmit, prov_retransmit);
3321         link[i].tx.retransmit.work.index = (int)i;
3322         link[i].rx.prev_id = XACT_NVAL;
3323         link[i].rx.buf = bt_mesh_pba_get_buf(i);
3324     }
3325 #endif
3326 
3327     for (i = 0; i < BLE_MESH_PROV_SAME_TIME; i++) {
3328         k_delayed_work_init(&link[i].timeout, prov_timeout);
3329         link[i].timeout.work.index = (int)i;
3330     }
3331 
3332 #if defined(CONFIG_BLE_MESH_PB_ADV)
3333     bt_mesh_pb_adv_mutex_new();
3334     bt_mesh_pb_buf_mutex_new();
3335 #endif
3336 #if defined(CONFIG_BLE_MESH_PB_GATT)
3337     bt_mesh_pb_gatt_mutex_new();
3338 #endif
3339 
3340     return 0;
3341 }
3342 
3343 int bt_mesh_provisioner_prov_reset(bool erase)
3344 {
3345     int i;
3346 
3347     if (prov == NULL) {
3348         BT_ERR("No provisioning context provided");
3349         return -EINVAL;
3350     }
3351 
3352     for (i = 0; i < BLE_MESH_PROV_SAME_TIME; i++) {
3353         k_delayed_work_cancel(&link[i].timeout);
3354 
3355         prov_memory_free(i);
3356 
3357         if (i < CONFIG_BLE_MESH_PBA_SAME_TIME) {
3358 #if CONFIG_BLE_MESH_PB_ADV
3359             prov_clear_tx(i);
3360 #if CONFIG_BLE_MESH_USE_DUPLICATE_SCAN
3361             bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_SUB_CODE_REMOVE,
3362                 BLE_MESH_EXCEP_LIST_TYPE_MESH_LINK_ID, &link[i].link_id);
3363 #endif
3364             memset(&link[i], 0, offsetof(struct prov_link, tx.retransmit));
3365             link[i].pending_ack = XACT_NVAL;
3366             link[i].rx.prev_id = XACT_NVAL;
3367             link[i].rx.buf = bt_mesh_pba_get_buf(i);
3368 #endif /* CONFIG_BLE_MESH_PB_ADV */
3369         } else {
3370             memset(&link[i], 0, offsetof(struct prov_link, timeout));
3371         }
3372 
3373         if (bt_mesh_pub_key_get()) {
3374             bt_mesh_atomic_set_bit(link[i].flags, LOCAL_PUB_KEY);
3375         }
3376     }
3377 
3378     /* static_oob_len & static_oob_val are initialized during mesh init.
3379      * When reset the Provisioner, they should not be reset. Otherwise
3380      * users need to invoke the corresponding function to set the static
3381      * oob information before using them.
3382      */
3383     memset(&prov_ctx, 0, offsetof(struct bt_mesh_prov_ctx, static_oob_len));
3384     prov_ctx.match_offset = 0;
3385     prov_ctx.match_length = 0;
3386     prov_ctx.prov_after_match = false;
3387     memset(prov_ctx.match_value, 0, sizeof(prov_ctx.match_value));
3388     memset(&prov_ctx.fast_prov, 0, sizeof(prov_ctx.fast_prov));
3389 
3390     memset(unprov_dev, 0, sizeof(unprov_dev));
3391 
3392     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS) && erase) {
3393         bt_mesh_clear_prov_info();
3394     }
3395 
3396     return 0;
3397 }
3398 
3399 #if CONFIG_BLE_MESH_DEINIT
3400 int bt_mesh_provisioner_prov_deinit(bool erase)
3401 {
3402     int i;
3403 
3404     if (prov == NULL) {
3405         BT_ERR("%s, No provisioning context provided", __func__);
3406         return -EINVAL;
3407     }
3408 
3409     bt_mesh_provisioner_prov_reset(erase);
3410 
3411     for (i = 0; i < BLE_MESH_PROV_SAME_TIME; i++) {
3412 #if defined(CONFIG_BLE_MESH_PB_ADV)
3413         if (i < CONFIG_BLE_MESH_PBA_SAME_TIME) {
3414             k_delayed_work_free(&link[i].tx.retransmit);
3415         }
3416 #endif
3417         k_delayed_work_free(&link[i].timeout);
3418         memset(&link[i], 0, sizeof(link[i]));
3419     }
3420 
3421 #if defined(CONFIG_BLE_MESH_PB_ADV)
3422     bt_mesh_pb_adv_mutex_free();
3423     bt_mesh_pb_buf_mutex_free();
3424 #endif
3425 #if defined(CONFIG_BLE_MESH_PB_GATT)
3426     bt_mesh_pb_gatt_mutex_free();
3427 #endif
3428     prov_ctx.static_oob_len = 0U;
3429     memset(prov_ctx.static_oob_val, 0, sizeof(prov_ctx.static_oob_val));
3430 
3431 #if defined(CONFIG_BLE_MESH_PB_ADV)
3432     memset(adv_buf, 0, sizeof(adv_buf));
3433     memset(adv_buf_data, 0, sizeof(adv_buf_data));
3434 #endif
3435 
3436     prov = NULL;
3437 
3438     return 0;
3439 }
3440 #endif /* CONFIG_BLE_MESH_DEINIT */
3441 
3442 static bool bt_mesh_prov_svc_adv_filter(void)
3443 {
3444     static uint32_t timestamp = 0;
3445     static uint32_t pre_timestamp = 0;
3446 
3447     timestamp = k_uptime_get_32();
3448 
3449     if (PROV_SVC_ADV_RX_CHECK(pre_timestamp, timestamp)) {
3450         pre_timestamp = timestamp;
3451         return false;
3452     }
3453 
3454     return true;
3455 }
3456 
3457 static bool is_unprov_dev_info_callback_to_app(bt_mesh_prov_bearer_t bearer, const uint8_t uuid[16],
3458                                                const bt_mesh_addr_t *addr, uint16_t oob_info, int8_t rssi)
3459 {
3460     int i;
3461 
3462     if (prov_ctx.prov_after_match == false) {
3463         uint8_t adv_type = (bearer == BLE_MESH_PROV_ADV) ?
3464                             BLE_MESH_ADV_NONCONN_IND : BLE_MESH_ADV_IND;
3465 
3466         for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
3467             if (!memcmp(unprov_dev[i].uuid, uuid, 16)) {
3468                 break;
3469             }
3470         }
3471 
3472         if (i == ARRAY_SIZE(unprov_dev)) {
3473             BT_DBG("Device not in queue, notify to app layer");
3474 
3475             if (adv_type == BLE_MESH_ADV_IND && bt_mesh_prov_svc_adv_filter()) {
3476                 return true;
3477             }
3478 
3479             if (notify_unprov_adv_pkt_cb) {
3480                 notify_unprov_adv_pkt_cb(addr->val, addr->type, adv_type, uuid, oob_info, bearer, rssi);
3481             }
3482             return true;
3483         }
3484 
3485         if (!(unprov_dev[i].bearer & bearer)) {
3486             BT_WARN("Device in queue not support PB-%s",
3487                     (bearer == BLE_MESH_PROV_ADV) ? "ADV" : "GATT");
3488             if (notify_unprov_adv_pkt_cb) {
3489                 notify_unprov_adv_pkt_cb(addr->val, addr->type, adv_type, uuid, oob_info, bearer, rssi);
3490             }
3491             return true;
3492         }
3493     }
3494 
3495     return false;
3496 }
3497 
3498 void bt_mesh_provisioner_unprov_beacon_recv(struct net_buf_simple *buf, int8_t rssi)
3499 {
3500 #if defined(CONFIG_BLE_MESH_PB_ADV)
3501     const bt_mesh_addr_t *addr = NULL;
3502     const uint8_t *uuid = NULL;
3503     uint16_t oob_info = 0U;
3504 
3505     if (!(prov_ctx.bearers & BLE_MESH_PROV_ADV)) {
3506         BT_INFO("Not support PB-ADV bearer");
3507         return;
3508     }
3509 
3510     if (buf->len != 0x12 && buf->len != 0x16) {
3511         BT_ERR("Invalid Unprovisioned Device Beacon length %d", buf->len);
3512         return;
3513     }
3514 
3515     addr = bt_mesh_get_unprov_dev_addr();
3516     uuid = buf->data;
3517     net_buf_simple_pull(buf, 16);
3518     /* Mesh beacon uses big-endian to send beacon data */
3519     oob_info = net_buf_simple_pull_be16(buf);
3520 
3521     if (provisioner_check_unprov_dev_info(uuid, BLE_MESH_PROV_ADV)) {
3522         return;
3523     }
3524 
3525     if (is_unprov_dev_info_callback_to_app(
3526                 BLE_MESH_PROV_ADV, uuid, addr, oob_info, rssi)) {
3527         return;
3528     }
3529 
3530     provisioner_start_prov_pb_adv(uuid, addr, oob_info, BLE_MESH_ADDR_UNASSIGNED);
3531 #endif /* CONFIG_BLE_MESH_PB_ADV */
3532 }
3533 
3534 void bt_mesh_provisioner_prov_adv_recv(struct net_buf_simple *buf,
3535                                        const bt_mesh_addr_t *addr, int8_t rssi)
3536 {
3537 #if defined(CONFIG_BLE_MESH_PB_GATT)
3538     const uint8_t *uuid = NULL;
3539     uint16_t oob_info = 0U;
3540 
3541     if (!(prov_ctx.bearers & BLE_MESH_PROV_GATT)) {
3542         BT_INFO("Not support PB-GATT bearer");
3543         return;
3544     }
3545 
3546     if (bt_mesh_gattc_get_free_conn_count() == 0) {
3547         BT_INFO("BLE connections for mesh reach max limit");
3548         return;
3549     }
3550 
3551     uuid = buf->data;
3552     net_buf_simple_pull(buf, 16);
3553     /* Mesh beacon uses big-endian to send beacon data */
3554     oob_info = net_buf_simple_pull_be16(buf);
3555 
3556     if (provisioner_check_unprov_dev_info(uuid, BLE_MESH_PROV_GATT)) {
3557         return;
3558     }
3559 
3560     if (is_unprov_dev_info_callback_to_app(
3561                 BLE_MESH_PROV_GATT, uuid, addr, oob_info, rssi)) {
3562         return;
3563     }
3564 
3565     /* Provisioner will copy the device uuid, oob info, etc. into an unused link
3566      * struct, and at this moment the link has not been activated. Even if we
3567      * receive an Unprovisioned Device Beacon and a Connectable Provisioning adv
3568      * pkt from the same device, and store the device info received within each
3569      * adv pkt into two link structs which will has no impact on the provisioning
3570      * of this device, because no matter which link among PB-GATT and PB-ADV is
3571      * activated first, the other one will be dropped finally and the link struct
3572      * occupied by the dropped link will be used by other devices (because the link
3573      * is not activated).
3574      * Use connecting flag to prevent if two devices's adv pkts are both received,
3575      * the previous one info will be replaced by the second one.
3576      */
3577     provisioner_start_prov_pb_gatt(uuid, addr, oob_info, BLE_MESH_ADDR_UNASSIGNED);
3578 #endif /* CONFIG_BLE_MESH_PB_GATT */
3579 }
3580 
3581 #endif /* CONFIG_BLE_MESH_PROVISIONER */
3582