1 /* 2 * Copyright (C) 2019 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define __BTSTACK_FILE__ "mesh_access.c" 39 40 #include <string.h> 41 #include <stdio.h> 42 #include <stdarg.h> 43 44 #include "mesh/mesh_access.h" 45 46 #include "btstack_debug.h" 47 #include "btstack_memory.h" 48 #include "btstack_tlv.h" 49 50 #include "mesh/beacon.h" 51 #include "mesh/mesh_foundation.h" 52 #include "mesh/mesh_iv_index_seq_number.h" 53 #include "mesh/mesh_node.h" 54 #include "mesh/mesh_proxy.h" 55 #include "mesh/mesh_upper_transport.h" 56 #include "mesh/mesh.h" 57 58 #define MEST_TRANSACTION_TIMEOUT_MS 6000 59 60 static void mesh_access_message_process_handler(mesh_pdu_t * pdu); 61 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 62 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu); 63 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode); 64 static void mesh_persist_iv_index_and_sequence_number(void); 65 66 // acknowledged messages 67 static btstack_linked_list_t mesh_access_acknowledged_messages; 68 static btstack_timer_source_t mesh_access_acknowledged_timer; 69 70 static uint16_t mid_counter; 71 72 static const btstack_tlv_t * btstack_tlv_singleton_impl; 73 static void * btstack_tlv_singleton_context; 74 75 // Transitions 76 static btstack_linked_list_t transitions; 77 static btstack_timer_source_t transitions_timer; 78 static uint32_t transition_step_min_ms; 79 static uint8_t mesh_transaction_id_counter = 0; 80 81 static void mesh_access_setup_tlv(void){ 82 if (btstack_tlv_singleton_impl) return; 83 btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context); 84 } 85 86 void mesh_access_init(void){ 87 // register with upper transport 88 mesh_upper_transport_register_access_message_handler(&mesh_access_message_process_handler); 89 mesh_upper_transport_set_higher_layer_handler(&mesh_access_upper_transport_handler); 90 91 // register for secure network beacons 92 beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler); 93 94 // register for seq number updates 95 mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number); 96 } 97 98 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier, 99 model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){ 100 if (event_handler == NULL) return; 101 uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL}; 102 int pos = 3; 103 event[pos++] = element_index; 104 little_endian_store_32(event, pos, model_identifier); 105 pos += 4; 106 little_endian_store_32(event, pos, (uint32_t)state_identifier); 107 pos += 4; 108 event[pos++] = (uint8_t)reason; 109 event[pos++] = value; 110 (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 111 } 112 113 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier, 114 model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){ 115 if (event_handler == NULL) return; 116 uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL}; 117 int pos = 3; 118 event[pos++] = element_index; 119 little_endian_store_32(event, pos, model_identifier); 120 pos += 4; 121 little_endian_store_32(event, pos, (uint32_t)state_identifier); 122 pos += 4; 123 event[pos++] = (uint8_t)reason; 124 little_endian_store_16(event, pos, (uint16_t) value); 125 pos += 2; 126 (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 127 } 128 129 uint8_t mesh_access_acknowledged_message_retransmissions(void){ 130 return 3; 131 } 132 133 uint32_t mesh_access_acknowledged_message_timeout_ms(void){ 134 return 30000; 135 } 136 137 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu 138 139 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){ 140 pdu->ack_opcode = MESH_ACCESS_OPCODE_INVALID;; 141 mesh_upper_transport_send_access_pdu(pdu); 142 } 143 144 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){ 145 pdu->retransmit_count = retransmissions; 146 pdu->ack_opcode = ack_opcode; 147 148 mesh_upper_transport_send_access_pdu(pdu); 149 } 150 151 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED 0x30 152 153 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){ 154 UNUSED(ts); 155 156 uint32_t now = btstack_run_loop_get_time_ms(); 157 158 // handle timeouts 159 btstack_linked_list_iterator_t ack_it; 160 btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages); 161 while (btstack_linked_list_iterator_has_next(&ack_it)){ 162 mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it); 163 if (btstack_time_delta(now, pdu->retransmit_timeout_ms) >= 0) { 164 // remove from list 165 btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu); 166 // retransmit or report failure 167 if (pdu->retransmit_count){ 168 pdu->retransmit_count--; 169 mesh_upper_transport_send_access_pdu(pdu); 170 } else { 171 // find correct model and emit error 172 uint16_t src = mesh_pdu_src(pdu); 173 uint16_t dst = mesh_pdu_dst(pdu); 174 mesh_element_t * element = mesh_node_element_for_unicast_address(src); 175 if (element){ 176 // find 177 mesh_model_iterator_t model_it; 178 mesh_model_iterator_init(&model_it, element); 179 while (mesh_model_iterator_has_next(&model_it)){ 180 mesh_model_t * model = mesh_model_iterator_next(&model_it); 181 // find opcode in table 182 const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, pdu->ack_opcode); 183 if (operation == NULL) continue; 184 if (model->model_packet_handler == NULL) continue; 185 // emit event 186 uint8_t event[13]; 187 event[0] = HCI_EVENT_MESH_META; 188 event[1] = sizeof(event) - 2; 189 event[2] = element->element_index; 190 little_endian_store_32(event, 3, model->model_identifier); 191 little_endian_store_32(event, 7, pdu->ack_opcode); 192 little_endian_store_16(event, 11, dst); 193 (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 194 } 195 } 196 197 // free 198 mesh_upper_transport_pdu_free(pdu); 199 } 200 } 201 } 202 203 // find earliest timeout and set timer 204 btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages); 205 int32_t next_timeout_ms = 0; 206 while (btstack_linked_list_iterator_has_next(&ack_it)){ 207 mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it); 208 int32_t timeout_delta_ms = btstack_time_delta(pdu->retransmit_timeout_ms, now); 209 if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){ 210 next_timeout_ms = timeout_delta_ms; 211 } 212 } 213 214 // set timer 215 if (next_timeout_ms == 0) return; 216 217 btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms); 218 btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run); 219 btstack_run_loop_add_timer(&mesh_access_acknowledged_timer); 220 } 221 222 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){ 223 // check if received src matches our dest 224 // free acknowledged messages if we were waiting for this message 225 226 btstack_linked_list_iterator_t ack_it; 227 btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages); 228 while (btstack_linked_list_iterator_has_next(&ack_it)){ 229 mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it); 230 uint16_t tx_dest = mesh_pdu_dst(tx_pdu); 231 if (tx_dest != rx_src) continue; 232 if (tx_pdu->ack_opcode != opcode) continue; 233 // got expected response from dest, remove from outgoing messages 234 mesh_upper_transport_pdu_free(tx_pdu); 235 return; 236 } 237 } 238 239 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){ 240 switch (callback_type){ 241 case MESH_TRANSPORT_PDU_SENT: 242 // unacknowledged -> free 243 if (pdu->ack_opcode == MESH_ACCESS_OPCODE_INVALID){ 244 mesh_upper_transport_pdu_free(pdu); 245 break; 246 } 247 // setup timeout 248 pdu->retransmit_timeout_ms = btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms(); 249 // add to mesh_access_acknowledged_messages 250 btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu); 251 // update timer 252 mesh_access_acknowledged_run(NULL); 253 break; 254 default: 255 break; 256 } 257 } 258 259 // Mesh Model Transitions 260 261 void mesh_access_transitions_setup_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){ 262 transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms(); 263 transition->transaction_identifier = transaction_identifier; 264 transition->src_address = src_address; 265 transition->dst_address = dst_address; 266 } 267 268 void mesh_access_transitions_abort_transaction(mesh_transition_t * transition){ 269 mesh_access_transitions_remove(transition); 270 } 271 272 273 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){ 274 return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS; 275 } 276 277 mesh_transaction_status_t mesh_access_transitions_transaction_status(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){ 278 if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC; 279 280 if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){ 281 return MESH_TRANSACTION_STATUS_RETRANSMISSION; 282 } 283 return MESH_TRANSACTION_STATUS_NEW; 284 } 285 286 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){ 287 return time_gdtt >> 2; 288 } 289 290 static uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){ 291 mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt & 0x03u); 292 switch (step_resolution){ 293 case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms: 294 return 100; 295 case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s: 296 return 1000; 297 case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s: 298 return 10000; 299 case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min: 300 return 600000; 301 default: 302 return 0; 303 } 304 } 305 306 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){ 307 uint8_t num_steps = mesh_access_transitions_num_steps_from_gdtt(time_gdtt); 308 if (num_steps > 0x3E) return 0; 309 310 return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps; 311 } 312 313 static void mesh_access_transitions_timeout_handler(btstack_timer_source_t * timer){ 314 btstack_linked_list_iterator_t it; 315 btstack_linked_list_iterator_init(&it, &transitions); 316 while (btstack_linked_list_iterator_has_next(&it)){ 317 mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it); 318 (transition->transition_callback)(transition, TRANSITION_UPDATE, btstack_run_loop_get_time_ms()); 319 } 320 if (btstack_linked_list_empty(&transitions)) return; 321 322 btstack_run_loop_set_timer(timer, transition_step_min_ms); 323 btstack_run_loop_add_timer(timer); 324 } 325 326 static void mesh_access_transitions_timer_start(void){ 327 btstack_run_loop_remove_timer(&transitions_timer); 328 btstack_run_loop_set_timer_handler(&transitions_timer, mesh_access_transitions_timeout_handler); 329 btstack_run_loop_set_timer(&transitions_timer, transition_step_min_ms); 330 btstack_run_loop_add_timer(&transitions_timer); 331 } 332 333 static void mesh_access_transitions_timer_stop(void){ 334 btstack_run_loop_remove_timer(&transitions_timer); 335 } 336 337 static uint32_t mesh_access_transitions_get_step_min_ms(void){ 338 uint32_t min_timeout_ms = 0; 339 340 btstack_linked_list_iterator_t it; 341 btstack_linked_list_iterator_init(&it, &transitions); 342 while (btstack_linked_list_iterator_has_next(&it)){ 343 mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it); 344 if (min_timeout_ms == 0 || transition->step_duration_ms < min_timeout_ms){ 345 min_timeout_ms = transition->step_duration_ms; 346 } 347 } 348 return min_timeout_ms; 349 } 350 351 void mesh_access_transitions_setup(mesh_transition_t * transition, mesh_model_t * mesh_model, 352 uint8_t transition_time_gdtt, uint8_t delay_gdtt, 353 void (* transition_callback)(struct mesh_transition * transition, transition_event_t event, uint32_t current_timestamp)){ 354 355 // Only values of 0x00 through 0x3E shall be used to specify the value of the Transition Number of Steps field 356 uint8_t num_steps = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt); 357 if (num_steps > 0x3E) return; 358 359 transition->state = MESH_TRANSITION_STATE_IDLE; 360 transition->phase_start_ms = 0; 361 362 transition->mesh_model = mesh_model; 363 transition->transition_callback = transition_callback; 364 transition->step_duration_ms = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt); 365 transition->remaining_delay_time_ms = delay_gdtt * 5; 366 transition->remaining_transition_time_ms = num_steps * transition->step_duration_ms; 367 } 368 369 void mesh_access_transitions_add(mesh_transition_t * transition){ 370 if (transition->step_duration_ms == 0) return; 371 372 if (btstack_linked_list_empty(&transitions) || transition->step_duration_ms < transition_step_min_ms){ 373 transition_step_min_ms = transition->step_duration_ms; 374 } 375 mesh_access_transitions_timer_start(); 376 btstack_linked_list_add(&transitions, (btstack_linked_item_t *) transition); 377 (transition->transition_callback)(transition, TRANSITION_START, btstack_run_loop_get_time_ms()); 378 } 379 380 void mesh_access_transitions_remove(mesh_transition_t * transition){ 381 mesh_access_transitions_setup(transition, NULL, 0, 0, NULL); 382 btstack_linked_list_remove(&transitions, (btstack_linked_item_t *) transition); 383 384 if (btstack_linked_list_empty(&transitions)){ 385 mesh_access_transitions_timer_stop(); 386 } else { 387 transition_step_min_ms = mesh_access_transitions_get_step_min_ms(); 388 } 389 } 390 391 uint8_t mesh_access_transactions_get_next_transaction_id(void){ 392 mesh_transaction_id_counter++; 393 if (mesh_transaction_id_counter == 0){ 394 mesh_transaction_id_counter = 1; 395 } 396 return mesh_transaction_id_counter; 397 } 398 399 // Mesh Node Element functions 400 uint8_t mesh_access_get_element_index(mesh_model_t * mesh_model){ 401 return mesh_model->element->element_index; 402 } 403 404 uint16_t mesh_access_get_element_address(mesh_model_t * mesh_model){ 405 return mesh_node_get_primary_element_address() + mesh_model->element->element_index; 406 } 407 408 // Model Identifier utilities 409 410 uint32_t mesh_model_get_model_identifier(uint16_t vendor_id, uint16_t model_id){ 411 return (vendor_id << 16) | model_id; 412 } 413 414 uint32_t mesh_model_get_model_identifier_bluetooth_sig(uint16_t model_id){ 415 return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | model_id; 416 } 417 418 uint16_t mesh_model_get_model_id(uint32_t model_identifier){ 419 return model_identifier & 0xFFFFu; 420 } 421 422 uint16_t mesh_model_get_vendor_id(uint32_t model_identifier){ 423 return model_identifier >> 16; 424 } 425 426 int mesh_model_is_bluetooth_sig(uint32_t model_identifier){ 427 return mesh_model_get_vendor_id(model_identifier) == BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC; 428 } 429 430 mesh_model_t * mesh_model_get_configuration_server(void){ 431 return mesh_model_get_by_identifier(mesh_node_get_primary_element(), mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER)); 432 } 433 434 void mesh_element_add_model(mesh_element_t * element, mesh_model_t * mesh_model){ 435 // reset app keys 436 mesh_model_reset_appkeys(mesh_model); 437 438 if (mesh_model_is_bluetooth_sig(mesh_model->model_identifier)){ 439 element->models_count_sig++; 440 } else { 441 element->models_count_vendor++; 442 } 443 mesh_model->mid = mid_counter++; 444 mesh_model->element = element; 445 btstack_linked_list_add_tail(&element->models, (btstack_linked_item_t *) mesh_model); 446 } 447 448 void mesh_model_iterator_init(mesh_model_iterator_t * iterator, mesh_element_t * element){ 449 btstack_linked_list_iterator_init(&iterator->it, &element->models); 450 } 451 452 int mesh_model_iterator_has_next(mesh_model_iterator_t * iterator){ 453 return btstack_linked_list_iterator_has_next(&iterator->it); 454 } 455 456 mesh_model_t * mesh_model_iterator_next(mesh_model_iterator_t * iterator){ 457 return (mesh_model_t *) btstack_linked_list_iterator_next(&iterator->it); 458 } 459 460 mesh_model_t * mesh_model_get_by_identifier(mesh_element_t * element, uint32_t model_identifier){ 461 mesh_model_iterator_t it; 462 mesh_model_iterator_init(&it, element); 463 while (mesh_model_iterator_has_next(&it)){ 464 mesh_model_t * model = mesh_model_iterator_next(&it); 465 if (model->model_identifier != model_identifier) continue; 466 return model; 467 } 468 return NULL; 469 } 470 471 mesh_model_t * mesh_access_model_for_address_and_model_identifier(uint16_t element_address, uint32_t model_identifier, uint8_t * status){ 472 mesh_element_t * element = mesh_node_element_for_unicast_address(element_address); 473 if (element == NULL){ 474 *status = MESH_FOUNDATION_STATUS_INVALID_ADDRESS; 475 return NULL; 476 } 477 mesh_model_t * model = mesh_model_get_by_identifier(element, model_identifier); 478 if (model == NULL) { 479 *status = MESH_FOUNDATION_STATUS_INVALID_MODEL; 480 } else { 481 *status = MESH_FOUNDATION_STATUS_SUCCESS; 482 } 483 return model; 484 } 485 486 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){ 487 switch (pdu->pdu_type){ 488 case MESH_PDU_TYPE_TRANSPORT: 489 return mesh_transport_src((mesh_transport_pdu_t*) pdu); 490 case MESH_PDU_TYPE_NETWORK: 491 return mesh_network_src((mesh_network_pdu_t *) pdu); 492 default: 493 return MESH_ADDRESS_UNSASSIGNED; 494 } 495 } 496 497 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){ 498 switch (pdu->pdu_type){ 499 case MESH_PDU_TYPE_TRANSPORT: 500 return mesh_transport_dst((mesh_transport_pdu_t*) pdu); 501 case MESH_PDU_TYPE_NETWORK: 502 return mesh_network_dst((mesh_network_pdu_t *) pdu); 503 default: 504 return MESH_ADDRESS_UNSASSIGNED; 505 } 506 } 507 508 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){ 509 switch (pdu->pdu_type){ 510 case MESH_PDU_TYPE_TRANSPORT: 511 return ((mesh_transport_pdu_t*) pdu)->netkey_index; 512 case MESH_PDU_TYPE_NETWORK: 513 return ((mesh_network_pdu_t *) pdu)->netkey_index; 514 default: 515 return 0; 516 } 517 } 518 519 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){ 520 switch (pdu->pdu_type){ 521 case MESH_PDU_TYPE_TRANSPORT: 522 return ((mesh_transport_pdu_t*) pdu)->appkey_index; 523 case MESH_PDU_TYPE_NETWORK: 524 return ((mesh_network_pdu_t *) pdu)->appkey_index; 525 default: 526 return 0; 527 } 528 } 529 530 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){ 531 switch (pdu->pdu_type){ 532 case MESH_PDU_TYPE_TRANSPORT: 533 return ((mesh_transport_pdu_t*) pdu)->len; 534 case MESH_PDU_TYPE_NETWORK: 535 return ((mesh_network_pdu_t *) pdu)->len - 10; 536 default: 537 return 0; 538 } 539 } 540 541 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){ 542 switch (pdu->pdu_type){ 543 case MESH_PDU_TYPE_TRANSPORT: 544 return ((mesh_transport_pdu_t*) pdu)->data; 545 case MESH_PDU_TYPE_NETWORK: 546 return &((mesh_network_pdu_t *) pdu)->data[10]; 547 default: 548 return NULL; 549 } 550 } 551 552 // message parser 553 554 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){ 555 switch (buffer[0] >> 6){ 556 case 0: 557 case 1: 558 if (buffer[0] == 0x7f) return 0; 559 *opcode = buffer[0]; 560 *opcode_size = 1; 561 return 1; 562 case 2: 563 if (buffer_size < 2) return 0; 564 *opcode = big_endian_read_16(buffer, 0); 565 *opcode_size = 2; 566 return 1; 567 case 3: 568 if (buffer_size < 3) return 0; 569 *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1); 570 *opcode_size = 3; 571 return 1; 572 default: 573 return 0; 574 } 575 } 576 577 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){ 578 return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size); 579 } 580 581 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){ 582 // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm 583 return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size); 584 } 585 586 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){ 587 switch (pdu->pdu_type){ 588 case MESH_PDU_TYPE_TRANSPORT: 589 return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size); 590 case MESH_PDU_TYPE_NETWORK: 591 return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size); 592 default: 593 return 0; 594 } 595 } 596 597 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){ 598 state->data += bytes_to_skip; 599 state->len -= bytes_to_skip; 600 } 601 602 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){ 603 state->data = mesh_pdu_data(pdu); 604 state->len = mesh_pdu_len(pdu); 605 606 uint16_t opcode_size = 0; 607 int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size); 608 if (ok){ 609 mesh_access_parser_skip(state, opcode_size); 610 } 611 return ok; 612 } 613 614 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){ 615 return state->len; 616 } 617 618 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){ 619 uint8_t value = *state->data; 620 mesh_access_parser_skip(state, 1); 621 return value; 622 } 623 624 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){ 625 uint16_t value = little_endian_read_16(state->data, 0); 626 mesh_access_parser_skip(state, 2); 627 return value; 628 } 629 630 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){ 631 uint32_t value = little_endian_read_24(state->data, 0); 632 mesh_access_parser_skip(state, 3); 633 return value; 634 } 635 636 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){ 637 uint32_t value = little_endian_read_24(state->data, 0); 638 mesh_access_parser_skip(state, 4); 639 return value; 640 } 641 642 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){ 643 reverse_128( state->data, dest); 644 mesh_access_parser_skip(state, 16); 645 } 646 647 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){ 648 memcpy( dest, state->data, 16); 649 mesh_access_parser_skip(state, 16); 650 } 651 652 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){ 653 memcpy( dest, state->data, 16); 654 mesh_access_parser_skip(state, 16); 655 } 656 657 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){ 658 if (mesh_access_parser_available(parser) == 4){ 659 return mesh_access_parser_get_u32(parser); 660 } else { 661 return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser); 662 } 663 } 664 665 // Mesh Access Message Builder 666 667 // message builder 668 669 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){ 670 if (opcode < 0x100){ 671 buffer[0] = opcode; 672 return 1; 673 } 674 if (opcode < 0x10000){ 675 big_endian_store_16(buffer, 0, opcode); 676 return 2; 677 } 678 buffer[0] = opcode >> 16; 679 little_endian_store_16(buffer, 1, opcode & 0xffff); 680 return 3; 681 } 682 683 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){ 684 mesh_transport_pdu_t * pdu = mesh_transport_pdu_get(); 685 if (!pdu) return NULL; 686 687 pdu->len = mesh_access_setup_opcode(pdu->data, opcode); 688 return pdu; 689 } 690 691 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){ 692 pdu->data[pdu->len++] = value; 693 } 694 695 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){ 696 little_endian_store_16(pdu->data, pdu->len, value); 697 pdu->len += 2; 698 } 699 700 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){ 701 little_endian_store_24(pdu->data, pdu->len, value); 702 pdu->len += 3; 703 } 704 705 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){ 706 little_endian_store_32(pdu->data, pdu->len, value); 707 pdu->len += 4; 708 } 709 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){ 710 if (mesh_model_is_bluetooth_sig(model_identifier)){ 711 mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) ); 712 } else { 713 mesh_access_transport_add_uint32( pdu, model_identifier ); 714 } 715 } 716 717 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){ 718 mesh_network_pdu_t * pdu = mesh_network_pdu_get(); 719 if (!pdu) return NULL; 720 721 pdu->len = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10; 722 return pdu; 723 } 724 725 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){ 726 pdu->data[pdu->len++] = value; 727 } 728 729 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){ 730 little_endian_store_16(pdu->data, pdu->len, value); 731 pdu->len += 2; 732 } 733 734 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){ 735 little_endian_store_24(pdu->data, pdu->len, value); 736 pdu->len += 3; 737 } 738 739 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){ 740 little_endian_store_32(pdu->data, pdu->len, value); 741 pdu->len += 4; 742 } 743 744 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){ 745 if (mesh_model_is_bluetooth_sig(model_identifier)){ 746 mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) ); 747 } else { 748 mesh_access_network_add_uint32( pdu, model_identifier ); 749 } 750 } 751 752 // access message template 753 754 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *template, ...){ 755 mesh_network_pdu_t * network_pdu = mesh_access_network_init(template->opcode); 756 if (!network_pdu) return NULL; 757 758 va_list argptr; 759 va_start(argptr, template); 760 761 // add params 762 const char * format = template->format; 763 uint16_t word; 764 uint32_t longword; 765 while (*format){ 766 switch (*format){ 767 case '1': 768 word = va_arg(argptr, int); // minimal va_arg is int: 2 bytes on 8+16 bit CPUs 769 mesh_access_network_add_uint8( network_pdu, word); 770 break; 771 case '2': 772 word = va_arg(argptr, int); // minimal va_arg is int: 2 bytes on 8+16 bit CPUs 773 mesh_access_network_add_uint16( network_pdu, word); 774 break; 775 case '3': 776 longword = va_arg(argptr, uint32_t); 777 mesh_access_network_add_uint24( network_pdu, longword); 778 break; 779 case '4': 780 longword = va_arg(argptr, uint32_t); 781 mesh_access_network_add_uint32( network_pdu, longword); 782 break; 783 case 'm': 784 longword = va_arg(argptr, uint32_t); 785 mesh_access_network_add_model_identifier( network_pdu, longword); 786 break; 787 default: 788 log_error("Unsupported mesh message format specifier '%c", *format); 789 break; 790 } 791 format++; 792 } 793 794 va_end(argptr); 795 796 return network_pdu; 797 } 798 799 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *template, ...){ 800 mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(template->opcode); 801 if (!transport_pdu) return NULL; 802 803 va_list argptr; 804 va_start(argptr, template); 805 806 // add params 807 const char * format = template->format; 808 uint16_t word; 809 uint32_t longword; 810 while (*format){ 811 switch (*format++){ 812 case '1': 813 word = va_arg(argptr, int); // minimal va_arg is int: 2 bytes on 8+16 bit CPUs 814 mesh_access_transport_add_uint8( transport_pdu, word); 815 break; 816 case '2': 817 word = va_arg(argptr, int); // minimal va_arg is int: 2 bytes on 8+16 bit CPUs 818 mesh_access_transport_add_uint16( transport_pdu, word); 819 break; 820 case '3': 821 longword = va_arg(argptr, uint32_t); 822 mesh_access_transport_add_uint24( transport_pdu, longword); 823 break; 824 case '4': 825 longword = va_arg(argptr, uint32_t); 826 mesh_access_transport_add_uint32( transport_pdu, longword); 827 break; 828 case 'm': 829 longword = va_arg(argptr, uint32_t); 830 mesh_access_transport_add_model_identifier( transport_pdu, longword); 831 break; 832 default: 833 break; 834 } 835 } 836 837 va_end(argptr); 838 839 return transport_pdu; 840 } 841 842 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){ 843 // find opcode in table 844 const mesh_operation_t * operation = model->operations; 845 if (operation == NULL) return NULL; 846 for ( ; operation->handler != NULL ; operation++){ 847 if (operation->opcode != opcode) continue; 848 return operation; 849 } 850 return NULL; 851 } 852 853 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){ 854 855 uint32_t opcode = 0; 856 uint16_t opcode_size = 0; 857 int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size); 858 if (!ok) return NULL; 859 860 uint16_t len = mesh_pdu_len(pdu); 861 862 // find opcode in table 863 const mesh_operation_t * operation = model->operations; 864 if (operation == NULL) return NULL; 865 for ( ; operation->handler != NULL ; operation++){ 866 if (operation->opcode != opcode) continue; 867 if ((opcode_size + operation->minimum_length) > len) continue; 868 return operation; 869 } 870 return NULL; 871 } 872 873 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){ 874 // DeviceKey is valid for all models 875 if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1; 876 // check if AppKey that is bound to this particular model 877 return mesh_model_contains_appkey(model, appkey_index); 878 } 879 880 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){ 881 // get opcode and size 882 uint32_t opcode = 0; 883 uint16_t opcode_size = 0; 884 885 886 int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size); 887 if (!ok) { 888 mesh_access_message_processed(pdu); 889 return; 890 } 891 892 uint16_t len = mesh_pdu_len(pdu); 893 printf("MESH Access Message, Opcode = %x: ", opcode); 894 printf_hexdump(mesh_pdu_data(pdu), len); 895 896 uint16_t src = mesh_pdu_src(pdu); 897 uint16_t dst = mesh_pdu_dst(pdu); 898 uint16_t appkey_index = mesh_pdu_appkey_index(pdu); 899 if (mesh_network_address_unicast(dst)){ 900 // loookup element by unicast address 901 mesh_element_t * element = mesh_node_element_for_unicast_address(dst); 902 if (element != NULL){ 903 // iterate over models, look for operation 904 mesh_model_iterator_t model_it; 905 mesh_model_iterator_init(&model_it, element); 906 while (mesh_model_iterator_has_next(&model_it)){ 907 mesh_model_t * model = mesh_model_iterator_next(&model_it); 908 // find opcode in table 909 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu); 910 if (operation == NULL) continue; 911 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue; 912 mesh_access_acknowledged_received(src, opcode); 913 operation->handler(model, pdu); 914 return; 915 } 916 } 917 } 918 else if (mesh_network_address_group(dst)){ 919 920 // handle fixed group address 921 if (dst >= 0xff00){ 922 int deliver_to_primary_element = 1; 923 switch (dst){ 924 case MESH_ADDRESS_ALL_PROXIES: 925 if (mesh_foundation_gatt_proxy_get() == 1){ 926 deliver_to_primary_element = 1; 927 } 928 break; 929 case MESH_ADDRESS_ALL_FRIENDS: 930 // TODO: not implemented 931 break; 932 case MESH_ADDRESS_ALL_RELAYS: 933 if (mesh_foundation_relay_get() == 1){ 934 deliver_to_primary_element =1; 935 } 936 break; 937 case MESH_ADDRESS_ALL_NODES: 938 deliver_to_primary_element = 1; 939 break; 940 default: 941 break; 942 } 943 if (deliver_to_primary_element){ 944 mesh_model_iterator_t model_it; 945 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element()); 946 while (mesh_model_iterator_has_next(&model_it)){ 947 mesh_model_t * model = mesh_model_iterator_next(&model_it); 948 // find opcode in table 949 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu); 950 if (operation == NULL) continue; 951 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue; 952 mesh_access_acknowledged_received(src, opcode); 953 operation->handler(model, pdu); 954 return; 955 } 956 } 957 } 958 else { 959 // iterate over all elements / models, check subscription list 960 mesh_element_iterator_t it; 961 mesh_element_iterator_init(&it); 962 while (mesh_element_iterator_has_next(&it)){ 963 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it); 964 mesh_model_iterator_t model_it; 965 mesh_model_iterator_init(&model_it, element); 966 while (mesh_model_iterator_has_next(&model_it)){ 967 mesh_model_t * model = mesh_model_iterator_next(&model_it); 968 if (mesh_model_contains_subscription(model, dst)){ 969 // find opcode in table 970 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu); 971 if (operation == NULL) continue; 972 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue; 973 mesh_access_acknowledged_received(src, opcode); 974 operation->handler(model, pdu); 975 return; 976 } 977 } 978 } 979 } 980 } 981 982 // operation not found -> done 983 printf("Message not handled\n"); 984 mesh_access_message_processed(pdu); 985 } 986 987 void mesh_access_message_processed(mesh_pdu_t * pdu){ 988 mesh_upper_transport_message_processed_by_higher_layer(pdu); 989 } 990 991 int mesh_model_contains_subscription(mesh_model_t * mesh_model, uint16_t address){ 992 uint16_t i; 993 for (i=0;i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL;i++){ 994 if (mesh_model->subscriptions[i] == address) return 1; 995 } 996 return 0; 997 } 998 999 // Foundation state 1000 1001 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8); 1002 1003 typedef struct { 1004 uint8_t gatt_proxy; 1005 uint8_t beacon; 1006 uint8_t default_ttl; 1007 uint8_t network_transmit; 1008 uint8_t relay; 1009 uint8_t relay_retransmit; 1010 uint8_t friend; 1011 } mesh_persistent_foundation_t; 1012 1013 void mesh_foundation_state_load(void){ 1014 mesh_access_setup_tlv(); 1015 mesh_persistent_foundation_t data; 1016 1017 int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data)); 1018 if (app_key_len == 0) return; 1019 1020 mesh_foundation_gatt_proxy_set(data.gatt_proxy); 1021 mesh_foundation_beacon_set(data.gatt_proxy); 1022 mesh_foundation_default_ttl_set(data.default_ttl); 1023 mesh_foundation_friend_set(data.friend); 1024 mesh_foundation_network_transmit_set(data.network_transmit); 1025 mesh_foundation_relay_set(data.relay); 1026 mesh_foundation_relay_retransmit_set(data.relay_retransmit); 1027 } 1028 1029 void mesh_foundation_state_store(void){ 1030 mesh_access_setup_tlv(); 1031 mesh_persistent_foundation_t data; 1032 data.gatt_proxy = mesh_foundation_gatt_proxy_get(); 1033 data.gatt_proxy = mesh_foundation_beacon_get(); 1034 data.default_ttl = mesh_foundation_default_ttl_get(); 1035 data.friend = mesh_foundation_friend_get(); 1036 data.network_transmit = mesh_foundation_network_transmit_get(); 1037 data.relay = mesh_foundation_relay_get(); 1038 data.relay_retransmit = mesh_foundation_relay_retransmit_get(); 1039 btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data)); 1040 } 1041 1042 1043 // Mesh IV Index 1044 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){ 1045 return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S'); 1046 } 1047 1048 typedef struct { 1049 uint32_t iv_index; 1050 uint32_t seq_number; 1051 } iv_index_and_sequence_number_t; 1052 1053 static uint32_t sequence_number_last_stored; 1054 static uint32_t sequence_number_storage_trigger; 1055 1056 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){ 1057 iv_index_and_sequence_number_t data; 1058 mesh_access_setup_tlv(); 1059 uint32_t tag = mesh_tag_for_iv_index_and_seq_number(); 1060 data.iv_index = iv_index; 1061 data.seq_number = 0; 1062 btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data)); 1063 1064 sequence_number_last_stored = data.seq_number; 1065 sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL; 1066 } 1067 1068 void mesh_store_iv_index_and_sequence_number(void){ 1069 iv_index_and_sequence_number_t data; 1070 mesh_access_setup_tlv(); 1071 uint32_t tag = mesh_tag_for_iv_index_and_seq_number(); 1072 data.iv_index = mesh_get_iv_index(); 1073 data.seq_number = mesh_sequence_number_peek(); 1074 btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data)); 1075 1076 sequence_number_last_stored = data.seq_number; 1077 sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL; 1078 } 1079 1080 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){ 1081 iv_index_and_sequence_number_t data; 1082 mesh_access_setup_tlv(); 1083 uint32_t tag = mesh_tag_for_iv_index_and_seq_number(); 1084 uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data)); 1085 if (len == sizeof(iv_index_and_sequence_number_t)){ 1086 *iv_index = data.iv_index; 1087 *sequence_number = data.seq_number; 1088 return 1; 1089 } 1090 return 0; 1091 } 1092 1093 // higher layer 1094 static void mesh_persist_iv_index_and_sequence_number(void){ 1095 if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){ 1096 mesh_store_iv_index_and_sequence_number(); 1097 } 1098 } 1099 1100 1101 // Mesh Model Publication 1102 static btstack_timer_source_t mesh_access_publication_timer; 1103 1104 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){ 1105 return retransmit & 0x07u; 1106 } 1107 1108 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){ 1109 return ((uint32_t)((retransmit >> 3) + 1)) * 50; 1110 } 1111 1112 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){ 1113 1114 // set retransmit counter 1115 publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit); 1116 1117 // schedule next publication or retransmission 1118 uint32_t publication_period_ms = mesh_access_transitions_step_ms_from_gdtt(publication_model->period); 1119 1120 // set next publication 1121 if (publication_period_ms != 0){ 1122 publication_model->next_publication_ms = now + publication_period_ms; 1123 publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS; 1124 } 1125 } 1126 1127 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){ 1128 uint8_t num_retransmits = mesh_model_publication_retransmit_count(publication_model->retransmit); 1129 if (num_retransmits == 0) return; 1130 1131 // calc next retransmit time 1132 uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit); 1133 1134 // ignore if retransmission would be after next publication timeout 1135 if (publication_model->state == MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS){ 1136 if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return; 1137 } 1138 1139 // schedule next retransmission 1140 publication_model->next_retransmit_ms = retransmission_ms; 1141 publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS; 1142 } 1143 1144 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){ 1145 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1146 if (publication_model == NULL) return; 1147 if (publication_model->publish_state_fn == NULL) return; 1148 uint16_t dest = publication_model->address; 1149 if (dest == MESH_ADDRESS_UNSASSIGNED) return; 1150 uint16_t appkey_index = publication_model->appkey_index; 1151 mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index); 1152 if (app_key == NULL) return; 1153 1154 // compose message 1155 mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model); 1156 if (pdu == NULL) return; 1157 1158 mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, publication_model->ttl, mesh_access_get_element_address(mesh_model), dest, 0); 1159 mesh_upper_transport_send_access_pdu(pdu); 1160 } 1161 1162 static void mesh_model_publication_run(btstack_timer_source_t * ts){ 1163 UNUSED(ts); 1164 1165 uint32_t now = btstack_run_loop_get_time_ms(); 1166 1167 // iterate over elements and models and handle time-based transitions 1168 mesh_element_iterator_t element_it; 1169 mesh_element_iterator_init(&element_it); 1170 while (mesh_element_iterator_has_next(&element_it)){ 1171 mesh_element_t * element = mesh_element_iterator_next(&element_it); 1172 mesh_model_iterator_t model_it; 1173 mesh_model_iterator_init(&model_it, element); 1174 while (mesh_model_iterator_has_next(&model_it)){ 1175 mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it); 1176 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1177 if (publication_model == NULL) continue; 1178 1179 // schedule next 1180 switch (publication_model->state){ 1181 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS: 1182 if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break; 1183 // timeout 1184 publication_model->publish_now = 1; 1185 // schedule next publication and retransmission 1186 mesh_model_publication_setup_publication(publication_model, now); 1187 mesh_model_publication_setup_retransmission(publication_model, now); 1188 break; 1189 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS: 1190 if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break; 1191 // timeout 1192 publication_model->publish_now = 1; 1193 publication_model->retransmit_count--; 1194 // schedule next retransmission 1195 mesh_model_publication_setup_retransmission(publication_model, now); 1196 break; 1197 default: 1198 break; 1199 } 1200 1201 if (publication_model->publish_now == 0) continue; 1202 1203 publication_model->publish_now = 0; 1204 mesh_model_publication_publish_now_model(mesh_model); 1205 } 1206 } 1207 1208 int32_t next_timeout_ms = 0; 1209 mesh_element_iterator_init(&element_it); 1210 while (mesh_element_iterator_has_next(&element_it)){ 1211 mesh_element_t * element = mesh_element_iterator_next(&element_it); 1212 mesh_model_iterator_t model_it; 1213 mesh_model_iterator_init(&model_it, element); 1214 while (mesh_model_iterator_has_next(&model_it)){ 1215 mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it); 1216 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1217 if (publication_model == NULL) continue; 1218 1219 // schedule next 1220 int32_t timeout_delta_ms; 1221 switch (publication_model->state){ 1222 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS: 1223 timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now); 1224 if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){ 1225 next_timeout_ms = timeout_delta_ms; 1226 } 1227 break; 1228 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS: 1229 timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now); 1230 if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){ 1231 next_timeout_ms = timeout_delta_ms; 1232 } 1233 break; 1234 default: 1235 break; 1236 } 1237 } 1238 } 1239 1240 // set timer 1241 if (next_timeout_ms == 0) return; 1242 1243 btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms); 1244 btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run); 1245 btstack_run_loop_add_timer(&mesh_access_publication_timer); 1246 } 1247 1248 void mesh_model_publication_start(mesh_model_t * mesh_model){ 1249 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1250 if (publication_model == NULL) return; 1251 1252 // reset state 1253 publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE; 1254 1255 // publish right away 1256 publication_model->publish_now = 1; 1257 1258 // setup next publication and retransmission 1259 uint32_t now = btstack_run_loop_get_time_ms(); 1260 mesh_model_publication_setup_publication(publication_model, now); 1261 mesh_model_publication_setup_retransmission(publication_model, now); 1262 1263 mesh_model_publication_run(NULL); 1264 } 1265 1266 void mesh_model_publication_stop(mesh_model_t * mesh_model){ 1267 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1268 if (publication_model == NULL) return; 1269 1270 // reset state 1271 publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE; 1272 } 1273 1274 void mesh_access_state_changed(mesh_model_t * mesh_model){ 1275 mesh_publication_model_t * publication_model = mesh_model->publication_model; 1276 if (publication_model == NULL) return; 1277 publication_model->publish_now = 1; 1278 mesh_model_publication_run(NULL); 1279 } 1280 1281 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){ 1282 mesh_network_key_remove(network_key); 1283 mesh_delete_network_key(network_key->internal_index); 1284 btstack_memory_mesh_network_key_free(network_key); 1285 } 1286 1287 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){ 1288 mesh_transport_key_remove(transport_key); 1289 mesh_delete_app_key(transport_key->appkey_index); 1290 btstack_memory_mesh_transport_key_free(transport_key); 1291 } 1292 1293 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){ 1294 // delete old netkey index 1295 mesh_access_netkey_finalize(subnet->old_key); 1296 subnet->old_key = subnet->new_key; 1297 subnet->new_key = NULL; 1298 1299 // delete old appkeys, if any 1300 mesh_transport_key_iterator_t it; 1301 mesh_transport_key_iterator_init(&it, subnet->netkey_index); 1302 while (mesh_transport_key_iterator_has_more(&it)){ 1303 mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it); 1304 if (transport_key->old_key == 0) continue; 1305 mesh_access_appkey_finalize(transport_key); 1306 } 1307 } 1308 1309 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1310 UNUSED(channel); 1311 UNUSED(size); 1312 1313 if (packet_type != MESH_BEACON_PACKET) return; 1314 1315 // lookup subnet and netkey by network id 1316 uint8_t * beacon_network_id = &packet[2]; 1317 mesh_subnet_iterator_t it; 1318 mesh_subnet_iterator_init(&it); 1319 mesh_subnet_t * subnet = NULL; 1320 uint8_t new_key = 0; 1321 while (mesh_subnet_iterator_has_more(&it)){ 1322 mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it); 1323 if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) { 1324 subnet = item; 1325 } 1326 if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) { 1327 subnet = item; 1328 new_key = 1; 1329 } 1330 break; 1331 } 1332 if (subnet == NULL) return; 1333 1334 uint8_t flags = packet[1]; 1335 1336 // Key refresh via secure network beacons that are authenticated with new netkey 1337 if (new_key){ 1338 // either first or second phase (in phase 0, new key is not set) 1339 int key_refresh_flag = flags & 1; 1340 if (key_refresh_flag){ 1341 // transition to phase 3 from either phase 1 or 2 1342 switch (subnet->key_refresh){ 1343 case MESH_KEY_REFRESH_FIRST_PHASE: 1344 case MESH_KEY_REFRESH_SECOND_PHASE: 1345 mesh_access_key_refresh_revoke_keys(subnet); 1346 subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE; 1347 break; 1348 default: 1349 break; 1350 } 1351 } else { 1352 // transition to phase 2 from either phase 1 1353 switch (subnet->key_refresh){ 1354 case MESH_KEY_REFRESH_FIRST_PHASE: 1355 // -- update state 1356 subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE; 1357 break; 1358 default: 1359 break; 1360 } 1361 } 1362 } 1363 1364 // IV Update 1365 1366 int beacon_iv_update_active = flags & 2; 1367 int local_iv_update_active = mesh_iv_update_active(); 1368 uint32_t beacon_iv_index = big_endian_read_32(packet, 10); 1369 uint32_t local_iv_index = mesh_get_iv_index(); 1370 1371 int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index); 1372 1373 // "If a node in Normal Operation receives a Secure Network beacon with an IV index less than the last known IV Index or greater than 1374 // the last known IV Index + 42, the Secure Network beacon shall be ignored." 1375 if (iv_index_delta < 0 || iv_index_delta > 42){ 1376 return; 1377 } 1378 1379 // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and 1380 // the IV Update Flag set to 0, the node may update its IV without going to the IV Update in Progress state, or it may initiate 1381 // an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending 1382 // on the time since last IV update and the likelihood that the node has missed the Secure Network beacons with the IV update Flag set to 1."" 1383 if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){ 1384 // instant iv update 1385 mesh_set_iv_index( beacon_iv_index ); 1386 // store updated iv index 1387 mesh_store_iv_index_and_sequence_number(); 1388 return; 1389 } 1390 1391 // "If this node is a member of a primary subnet and receives a Secure Network beacon on a secondary subnet with an IV Index greater than 1392 // the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored." 1393 int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL; 1394 int beacon_on_secondary_subnet = subnet->netkey_index != 0; 1395 if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){ 1396 return; 1397 } 1398 1399 // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..." 1400 // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6." 1401 if (local_iv_update_active == 0 && iv_index_delta > 1){ 1402 // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... " 1403 int beacon_on_primary_subnet = subnet->netkey_index == 0; 1404 if (!beacon_on_primary_subnet) return; 1405 // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall " 1406 // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon." 1407 mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index); 1408 // store updated iv index if in normal mode 1409 if (beacon_iv_update_active == 0){ 1410 mesh_store_iv_index_and_sequence_number(); 1411 } 1412 return; 1413 } 1414 1415 if (local_iv_update_active == 0){ 1416 if (beacon_iv_update_active){ 1417 mesh_trigger_iv_update(); 1418 } 1419 } else { 1420 if (beacon_iv_update_active == 0){ 1421 // " At the point of transition, the node shall reset the sequence number to 0x000000." 1422 mesh_sequence_number_set(0); 1423 mesh_iv_update_completed(); 1424 // store updated iv index 1425 mesh_store_iv_index_and_sequence_number(); 1426 } 1427 } 1428 } 1429