xref: /btstack/src/ble/att_server.c (revision 9e6f2329910d5193795b796692002063e5d8752d)
1 /*
2  * Copyright (C) 2014 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__ "att_server.c"
39 
40 
41 //
42 // ATT Server Globals
43 //
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "btstack_config.h"
52 
53 #include "att_dispatch.h"
54 #include "ble/att_db.h"
55 #include "ble/att_server.h"
56 #include "ble/core.h"
57 #include "ble/le_device_db.h"
58 #include "ble/sm.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "gap.h"
64 #include "hci.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 #include "btstack_tlv.h"
68 #ifdef ENABLE_LE_SIGNED_WRITE
69 #include "ble/sm.h"
70 #endif
71 
72 #ifndef NVN_NUM_GATT_SERVER_CCC
73 #define NVN_NUM_GATT_SERVER_CCC 20
74 #endif
75 
76 static void att_run_for_context(att_server_t * att_server);
77 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
78 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
79 static void att_server_persistent_ccc_restore(att_server_t * att_server);
80 static void att_server_persistent_ccc_clear(att_server_t * att_server);
81 
82 typedef enum {
83     ATT_SERVER_RUN_PHASE_1_REQUESTS,
84     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
85     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
86 } att_server_run_phase_t;
87 
88 //
89 typedef struct {
90     uint32_t seq_nr;
91     uint16_t att_handle;
92     uint8_t  value;
93     uint8_t  device_index;
94 } persistent_ccc_entry_t;
95 
96 // global
97 static btstack_packet_callback_registration_t hci_event_callback_registration;
98 static btstack_packet_callback_registration_t sm_event_callback_registration;
99 static btstack_packet_handler_t               att_client_packet_handler = NULL;
100 static btstack_linked_list_t                  service_handlers;
101 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
102 
103 static att_read_callback_t                    att_server_client_read_callback;
104 static att_write_callback_t                   att_server_client_write_callback;
105 
106 // round robin
107 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
108 
109 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
110     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
111     if (!hci_connection) return NULL;
112     return &hci_connection->att_server;
113 }
114 
115 #ifdef ENABLE_LE_SIGNED_WRITE
116 static att_server_t * att_server_for_state(att_server_state_t state){
117     btstack_linked_list_iterator_t it;
118     hci_connections_get_iterator(&it);
119     while(btstack_linked_list_iterator_has_next(&it)){
120         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
121         att_server_t * att_server = &connection->att_server;
122         if (att_server->state == state) return att_server;
123     }
124     return NULL;
125 }
126 #endif
127 
128 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
129     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
130     if (!packet_handler) return;
131 
132     uint8_t event[7];
133     int pos = 0;
134     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
135     event[pos++] = sizeof(event) - 2;
136     event[pos++] = status;
137     little_endian_store_16(event, pos, client_handle);
138     pos += 2;
139     little_endian_store_16(event, pos, attribute_handle);
140     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
141 }
142 
143 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
144     // dispatch to app level handler
145     if (att_client_packet_handler){
146         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
147     }
148 
149     // dispatch to service handlers
150     btstack_linked_list_iterator_t it;
151     btstack_linked_list_iterator_init(&it, &service_handlers);
152     while (btstack_linked_list_iterator_has_next(&it)){
153         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
154         if (!handler->packet_handler) continue;
155         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
156     }
157 }
158 
159 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
160     uint8_t event[6];
161     int pos = 0;
162     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
163     event[pos++] = sizeof(event) - 2;
164     little_endian_store_16(event, pos, con_handle);
165     pos += 2;
166     little_endian_store_16(event, pos, mtu);
167 
168     // also dispatch to GATT Clients
169     att_dispatch_server_mtu_exchanged(con_handle, mtu);
170 
171     // dispatch to app level handler and service handlers
172     att_emit_event_to_all(&event[0], sizeof(event));
173 }
174 
175 static void att_emit_can_send_now_event(void * context){
176     UNUSED(context);
177     if (!att_client_packet_handler) return;
178 
179     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
180     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
181 }
182 
183 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
184     void * context = btstack_run_loop_get_timer_context(ts);
185     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
186     att_server_t * att_server = att_server_for_handle(con_handle);
187     if (!att_server) return;
188     // @note: after a transcation timeout, no more requests shall be sent over this ATT Bearer
189     // (that's why we don't reset the value_indication_handle)
190     uint16_t att_handle = att_server->value_indication_handle;
191     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
192 }
193 
194 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
195 
196     UNUSED(channel); // ok: there is no channel
197     UNUSED(size);    // ok: handling own l2cap events
198 
199     att_server_t * att_server;
200     hci_con_handle_t con_handle;
201 
202     switch (packet_type) {
203 
204         case HCI_EVENT_PACKET:
205             switch (hci_event_packet_get_type(packet)) {
206 
207                 case HCI_EVENT_LE_META:
208                     switch (packet[2]) {
209                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
210                             con_handle = little_endian_read_16(packet, 4);
211                             att_server = att_server_for_handle(con_handle);
212                             if (!att_server) break;
213                         	// store connection info
214                         	att_server->peer_addr_type = packet[7];
215                             reverse_bd_addr(&packet[8], att_server->peer_address);
216                             att_server->connection.con_handle = con_handle;
217                             // reset connection properties
218                             att_server->state = ATT_SERVER_IDLE;
219                             att_server->connection.mtu = ATT_DEFAULT_MTU;
220                             att_server->connection.max_mtu = l2cap_max_le_mtu();
221                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
222                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
223                             }
224                             att_server->connection.encryption_key_size = 0;
225                             att_server->connection.authenticated = 0;
226 		                	att_server->connection.authorized = 0;
227                             // workaround: identity resolving can already be complete, at least store result
228                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
229                             att_server->pairing_active = 0;
230                             // notify all
231                             att_emit_event_to_all(packet, size);
232                             break;
233 
234                         default:
235                             break;
236                     }
237                     break;
238 
239                 case HCI_EVENT_ENCRYPTION_CHANGE:
240                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
241                 	// check handle
242                     con_handle = little_endian_read_16(packet, 3);
243                     att_server = att_server_for_handle(con_handle);
244                     if (!att_server) break;
245                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
246                     att_server->connection.authenticated = gap_authenticated(con_handle);
247                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
248                         // restore CCC values when encrypted
249                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
250                             att_server_persistent_ccc_restore(att_server);
251                         }
252                     }
253                     att_run_for_context(att_server);
254                     break;
255 
256                 case HCI_EVENT_DISCONNECTION_COMPLETE:
257                     // check handle
258                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
259                     att_server = att_server_for_handle(con_handle);
260                     if (!att_server) break;
261                     att_clear_transaction_queue(&att_server->connection);
262                     att_server->connection.con_handle = 0;
263                     att_server->pairing_active = 0;
264                     att_server->state = ATT_SERVER_IDLE;
265                     if (att_server->value_indication_handle){
266                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
267                         uint16_t att_handle = att_server->value_indication_handle;
268                         att_server->value_indication_handle = 0; // reset error state
269                         att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_server->connection.con_handle, att_handle);
270                     }
271                     // notify all
272                     att_emit_event_to_all(packet, size);
273                     break;
274 
275                 // Identity Resolving
276                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
277                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
278                     att_server = att_server_for_handle(con_handle);
279                     if (!att_server) break;
280                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
281                     att_server->ir_lookup_active = 1;
282                     break;
283                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
284                     con_handle = sm_event_identity_created_get_handle(packet);
285                     att_server = att_server_for_handle(con_handle);
286                     if (!att_server) return;
287                     att_server->ir_lookup_active = 0;
288                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
289                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
290                     att_run_for_context(att_server);
291                     break;
292                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
293                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
294                     att_server = att_server_for_handle(con_handle);
295                     if (!att_server) break;
296                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
297                     att_server->ir_lookup_active = 0;
298                     att_server->ir_le_device_db_index = -1;
299                     att_run_for_context(att_server);
300                     break;
301 
302                 // Pairing started - delete stored CCC values
303                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
304                 // - assumes that all events have the con handle as the first field
305                 case SM_EVENT_JUST_WORKS_REQUEST:
306                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
307                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
308                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
309                     con_handle = sm_event_just_works_request_get_handle(packet);
310                     att_server = att_server_for_handle(con_handle);
311                     if (!att_server) break;
312                     att_server->pairing_active = 1;
313                     log_info("SM Pairing started");
314                     if (att_server->ir_le_device_db_index < 0) break;
315                     att_server_persistent_ccc_clear(att_server);
316                     // index not valid anymore
317                     att_server->ir_le_device_db_index = -1;
318                     break;
319 
320                 // Bonding completed
321                 case SM_EVENT_IDENTITY_CREATED:
322                     con_handle = sm_event_identity_created_get_handle(packet);
323                     att_server = att_server_for_handle(con_handle);
324                     if (!att_server) return;
325                     att_server->pairing_active = 0;
326                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
327                     att_run_for_context(att_server);
328                     break;
329 
330                 // Pairing complete (with/without bonding=storing of pairing information)
331                 case SM_EVENT_PAIRING_COMPLETE:
332                     con_handle = sm_event_pairing_complete_get_handle(packet);
333                     att_server = att_server_for_handle(con_handle);
334                     if (!att_server) return;
335                     att_server->pairing_active = 0;
336                     att_run_for_context(att_server);
337                     break;
338 
339                 // Authorization
340                 case SM_EVENT_AUTHORIZATION_RESULT: {
341                     con_handle = sm_event_authorization_result_get_handle(packet);
342                     att_server = att_server_for_handle(con_handle);
343                     if (!att_server) break;
344                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
345                     att_dispatch_server_request_can_send_now_event(con_handle);
346                 	break;
347                 }
348                 default:
349                     break;
350             }
351             break;
352         default:
353             break;
354     }
355 }
356 
357 #ifdef ENABLE_LE_SIGNED_WRITE
358 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
359 
360     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
361     if (!att_server) return;
362 
363     uint8_t hash_flipped[8];
364     reverse_64(hash, hash_flipped);
365     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
366         log_info("ATT Signed Write, invalid signature");
367         att_server->state = ATT_SERVER_IDLE;
368         return;
369     }
370     log_info("ATT Signed Write, valid signature");
371 
372     // update sequence number
373     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
374     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
375     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
376     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
377 }
378 #endif
379 
380 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
381 // pre: can send now
382 // returns: 1 if packet was sent
383 static int att_server_process_validated_request(att_server_t * att_server){
384 
385     l2cap_reserve_packet_buffer();
386     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
387     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
388 
389 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
390     if (att_response_size == ATT_READ_RESPONSE_PENDING){
391         // update state
392         att_server->state = ATT_SERVER_READ_RESPONSE_PENDING;
393 
394         // callback with handle ATT_READ_RESPONSE_PENDING
395         att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
396 
397         // free reserved buffer
398         l2cap_release_packet_buffer();
399         return 0;
400     }
401 #endif
402 
403     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
404     if ((att_response_size     >= 4)
405     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
406     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
407     && (att_server->connection.authenticated)){
408 
409         switch (gap_authorization_state(att_server->connection.con_handle)){
410             case AUTHORIZATION_UNKNOWN:
411                 l2cap_release_packet_buffer();
412                 sm_request_pairing(att_server->connection.con_handle);
413                 return 0;
414             case AUTHORIZATION_PENDING:
415                 l2cap_release_packet_buffer();
416                 return 0;
417             default:
418                 break;
419         }
420     }
421 
422     att_server->state = ATT_SERVER_IDLE;
423     if (att_response_size == 0) {
424         l2cap_release_packet_buffer();
425         return 0;
426     }
427 
428     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
429 
430     // notify client about MTU exchange result
431     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
432         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
433     }
434     return 1;
435 }
436 
437 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
438 int att_server_read_response_ready(hci_con_handle_t con_handle){
439     att_server_t * att_server = att_server_for_handle(con_handle);
440     if (!att_server)                                             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
441     if (att_server->state != ATT_SERVER_READ_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
442 
443     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
444     att_dispatch_server_request_can_send_now_event(con_handle);
445     return ERROR_CODE_SUCCESS;
446 }
447 #endif
448 
449 static void att_run_for_context(att_server_t * att_server){
450     switch (att_server->state){
451         case ATT_SERVER_REQUEST_RECEIVED:
452 
453             // wait until re-encryption as central is complete
454             if (gap_reconnect_security_setup_active(att_server->connection.con_handle)) break;
455 
456             // wait until pairing is complete
457             if (att_server->pairing_active) break;
458 
459 #ifdef ENABLE_LE_SIGNED_WRITE
460             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
461                 log_info("ATT Signed Write!");
462                 if (!sm_cmac_ready()) {
463                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
464                     att_server->state = ATT_SERVER_IDLE;
465                     return;
466                 }
467                 if (att_server->request_size < (3 + 12)) {
468                     log_info("ATT Signed Write, request to short. Abort.");
469                     att_server->state = ATT_SERVER_IDLE;
470                     return;
471                 }
472                 if (att_server->ir_lookup_active){
473                     return;
474                 }
475                 if (att_server->ir_le_device_db_index < 0){
476                     log_info("ATT Signed Write, CSRK not available");
477                     att_server->state = ATT_SERVER_IDLE;
478                     return;
479                 }
480 
481                 // check counter
482                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
483                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
484                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
485                 if (counter_packet < counter_db){
486                     log_info("ATT Signed Write, db reports higher counter, abort");
487                     att_server->state = ATT_SERVER_IDLE;
488                     return;
489                 }
490 
491                 // signature is { sequence counter, secure hash }
492                 sm_key_t csrk;
493                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
494                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
495                 log_info("Orig Signature: ");
496                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
497                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
498                 sm_cmac_signed_write_start(csrk, att_server->request_buffer[0], attribute_handle, att_server->request_size - 15, &att_server->request_buffer[3], counter_packet, att_signed_write_handle_cmac_result);
499                 return;
500             }
501 #endif
502             // move on
503             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
504             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
505             break;
506 
507         default:
508             break;
509     }
510 }
511 
512 static int att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
513     switch (phase){
514         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
515             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
516         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
517              return (!btstack_linked_list_empty(&att_server->indication_requests) && att_server->value_indication_handle == 0);
518         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
519             return (!btstack_linked_list_empty(&att_server->notification_requests));
520     }
521     // avoid warning
522     return 0;
523 }
524 
525 static void att_server_trigger_send_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
526     btstack_context_callback_registration_t * client;
527     switch (phase){
528         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
529             att_server_process_validated_request(att_server);
530             break;
531         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
532             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
533             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
534             client->callback(client->context);
535             break;
536        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
537             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
538             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
539             client->callback(client->context);
540             break;
541     }
542 }
543 
544 static void att_server_handle_can_send_now(void){
545 
546     hci_con_handle_t request_con_handle   = HCI_CON_HANDLE_INVALID;
547     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
548     int can_send_now = 1;
549     int phase;
550 
551     for (phase = ATT_SERVER_RUN_PHASE_1_REQUESTS; phase <= ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase++){
552         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
553         while (1){
554             btstack_linked_list_iterator_t it;
555             hci_connections_get_iterator(&it);
556             while(btstack_linked_list_iterator_has_next(&it)){
557                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
558                 att_server_t * att_server = &connection->att_server;
559 
560                 int data_ready = att_server_data_ready_for_phase(att_server, phase);
561 
562                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_server->connection.con_handle, skip_connections_until, data_ready);
563 
564                 // skip until last sender found (which is also skipped)
565                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
566                     if (data_ready && request_con_handle == HCI_CON_HANDLE_INVALID){
567                         request_con_handle = att_server->connection.con_handle;
568                     }
569                     if (skip_connections_until == att_server->connection.con_handle){
570                         skip_connections_until = HCI_CON_HANDLE_INVALID;
571                     }
572                     continue;
573                 };
574 
575                 if (data_ready){
576                     if (can_send_now){
577                         att_server_trigger_send_for_phase(att_server, phase);
578                         last_send_con_handle = att_server->connection.con_handle;
579                         can_send_now = att_dispatch_server_can_send_now(att_server->connection.con_handle);
580                         data_ready = att_server_data_ready_for_phase(att_server, phase);
581                         if (data_ready && request_con_handle == HCI_CON_HANDLE_INVALID){
582                             request_con_handle = att_server->connection.con_handle;
583                         }
584                     } else {
585                         request_con_handle = att_server->connection.con_handle;
586                         break;
587                     }
588                 }
589             }
590 
591             // stop skipping (handles disconnect by last send connection)
592             skip_connections_until = HCI_CON_HANDLE_INVALID;
593 
594             // Exit loop, if we cannot send
595             if (!can_send_now) break;
596 
597             // Exit loop, if we can send but there are also no further request
598             if (request_con_handle == HCI_CON_HANDLE_INVALID) break;
599 
600             // Finally, if we still can send and there are requests, just try again
601             request_con_handle = HCI_CON_HANDLE_INVALID;
602         }
603         // update last send con handle for round robin
604         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
605             att_server_last_can_send_now = last_send_con_handle;
606         }
607     }
608 
609     if (request_con_handle == HCI_CON_HANDLE_INVALID) return;
610     att_dispatch_server_request_can_send_now_event(request_con_handle);
611 }
612 
613 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
614 
615     att_server_t * att_server;
616 
617     switch (packet_type){
618 
619         case HCI_EVENT_PACKET:
620             switch (packet[0]){
621                 case L2CAP_EVENT_CAN_SEND_NOW:
622                     att_server_handle_can_send_now();
623                     break;
624                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
625                     // GATT client has negotiated the mtu for this connection
626                     att_server = att_server_for_handle(handle);
627                     if (!att_server) break;
628                     att_server->connection.mtu = little_endian_read_16(packet, 4);
629                     break;
630                 default:
631                     break;
632             }
633             break;
634 
635         case ATT_DATA_PACKET:
636             log_debug("ATT Packet, handle 0x%04x", handle);
637             att_server = att_server_for_handle(handle);
638             if (!att_server) break;
639 
640             // handle value indication confirms
641             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
642                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
643                 uint16_t att_handle = att_server->value_indication_handle;
644                 att_server->value_indication_handle = 0;
645                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
646                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
647                 return;
648             }
649 
650             // directly process command
651             // note: signed write cannot be handled directly as authentication needs to be verified
652             if (packet[0] == ATT_WRITE_COMMAND){
653                 att_handle_request(&att_server->connection, packet, size, 0);
654                 return;
655             }
656 
657             // check size
658             if (size > sizeof(att_server->request_buffer)) {
659                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
660                 return;
661             }
662 
663             // last request still in processing?
664             if (att_server->state != ATT_SERVER_IDLE){
665                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
666                 return;
667             }
668 
669             // store request
670             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
671             att_server->request_size = size;
672             memcpy(att_server->request_buffer, packet, size);
673 
674             att_run_for_context(att_server);
675             break;
676     }
677 }
678 
679 // ---------------------
680 // persistent CCC writes
681 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
682     return 'B' << 24 | 'T' << 16 | 'C' << 8 | index;
683 }
684 
685 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
686     // lookup att_server instance
687     att_server_t * att_server = att_server_for_handle(con_handle);
688     if (!att_server) return;
689     int le_device_index = att_server->ir_le_device_db_index;
690     log_info("Store CCC value 0x%04x for handle 0x%04x of remote %s, le device id %d", value, att_handle, bd_addr_to_str(att_server->peer_address), le_device_index);
691 
692     // check if bonded
693     if (le_device_index < 0) return;
694 
695     // get btstack_tlv
696     const btstack_tlv_t * tlv_impl = NULL;
697     void * tlv_context;
698     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
699     if (!tlv_impl) return;
700 
701     // update ccc tag
702     int index;
703     uint32_t highest_seq_nr = 0;
704     uint32_t lowest_seq_nr = 0;
705     uint32_t tag_for_lowest_seq_nr = 0;
706     uint32_t tag_for_empty = 0;
707     persistent_ccc_entry_t entry;
708     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
709         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
710         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
711 
712         // empty/invalid tag
713         if (len != sizeof(persistent_ccc_entry_t)){
714             tag_for_empty = tag;
715             continue;
716         }
717         // update highest seq nr
718         if (entry.seq_nr > highest_seq_nr){
719             highest_seq_nr = entry.seq_nr;
720         }
721         // find entry with lowest seq nr
722         if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){
723             tag_for_lowest_seq_nr = tag;
724             lowest_seq_nr = entry.seq_nr;
725         }
726 
727         if (entry.device_index != le_device_index) continue;
728         if (entry.att_handle   != att_handle)      continue;
729 
730         // found matching entry
731         if (value){
732             // update
733             if (entry.value == value) {
734                 log_info("CCC Index %u: Up-to-date", index);
735                 return;
736             }
737             entry.value = value;
738             entry.seq_nr = highest_seq_nr + 1;
739             log_info("CCC Index %u: Store", index);
740             tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
741         } else {
742             // delete
743             log_info("CCC Index %u: Delete", index);
744             tlv_impl->delete_tag(tlv_context, tag);
745         }
746         return;
747     }
748 
749     log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
750 
751     if (value == 0){
752         // done
753         return;
754     }
755 
756     uint32_t tag_to_use = 0;
757     if (tag_for_empty){
758         tag_to_use = tag_for_empty;
759     } else if (tag_for_lowest_seq_nr){
760         tag_to_use = tag_for_lowest_seq_nr;
761     } else {
762         // should not happen
763         return;
764     }
765     // store ccc tag
766     entry.seq_nr       = highest_seq_nr + 1;
767     entry.device_index = le_device_index;
768     entry.att_handle   = att_handle;
769     entry.value        = value;
770     tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
771 }
772 
773 static void att_server_persistent_ccc_clear(att_server_t * att_server){
774     if (!att_server) return;
775     int le_device_index = att_server->ir_le_device_db_index;
776     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
777     // check if bonded
778     if (le_device_index < 0) return;
779     // get btstack_tlv
780     const btstack_tlv_t * tlv_impl = NULL;
781     void * tlv_context;
782     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
783     if (!tlv_impl) return;
784     // get all ccc tag
785     int index;
786     persistent_ccc_entry_t entry;
787     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
788         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
789         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
790         if (len != sizeof(persistent_ccc_entry_t)) continue;
791         if (entry.device_index != le_device_index) continue;
792         // delete entry
793         log_info("CCC Index %u: Delete", index);
794         tlv_impl->delete_tag(tlv_context, tag);
795     }
796 }
797 
798 static void att_server_persistent_ccc_restore(att_server_t * att_server){
799     if (!att_server) return;
800     int le_device_index = att_server->ir_le_device_db_index;
801     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
802     // check if bonded
803     if (le_device_index < 0) return;
804     // get btstack_tlv
805     const btstack_tlv_t * tlv_impl = NULL;
806     void * tlv_context;
807     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
808     if (!tlv_impl) return;
809     // get all ccc tag
810     int index;
811     persistent_ccc_entry_t entry;
812     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
813         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
814         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
815         if (len != sizeof(persistent_ccc_entry_t)) continue;
816         if (entry.device_index != le_device_index) continue;
817         // simulate write callback
818         uint16_t attribute_handle = entry.att_handle;
819         uint8_t  value[2];
820         little_endian_store_16(value, 0, entry.value);
821         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
822         if (!callback) continue;
823         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
824         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
825     }
826 }
827 
828 // persistent CCC writes
829 // ---------------------
830 
831 // gatt service management
832 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
833     btstack_linked_list_iterator_t it;
834     btstack_linked_list_iterator_init(&it, &service_handlers);
835     while (btstack_linked_list_iterator_has_next(&it)){
836         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
837         if (handler->start_handle > handle) continue;
838         if (handler->end_handle   < handle) continue;
839         return handler;
840     }
841     return NULL;
842 }
843 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
844     att_service_handler_t * handler = att_service_handler_for_handle(handle);
845     if (handler) return handler->read_callback;
846     return att_server_client_read_callback;
847 }
848 
849 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
850     att_service_handler_t * handler = att_service_handler_for_handle(handle);
851     if (handler) return handler->write_callback;
852     return att_server_client_write_callback;
853 }
854 
855 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
856     att_service_handler_t * handler = att_service_handler_for_handle(handle);
857     if (handler) return handler->packet_handler;
858     return att_client_packet_handler;
859 }
860 
861 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
862     // notify all callbacks
863     btstack_linked_list_iterator_t it;
864     btstack_linked_list_iterator_init(&it, &service_handlers);
865     while (btstack_linked_list_iterator_has_next(&it)){
866         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
867         if (!handler->write_callback) continue;
868         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
869     }
870     if (!att_server_client_write_callback) return;
871     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
872 }
873 
874 // returns first reported error or 0
875 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
876     btstack_linked_list_iterator_t it;
877     btstack_linked_list_iterator_init(&it, &service_handlers);
878     while (btstack_linked_list_iterator_has_next(&it)){
879         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
880         if (!handler->write_callback) continue;
881         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
882         if (error_code) return error_code;
883     }
884     if (!att_server_client_write_callback) return 0;
885     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
886 }
887 
888 static uint16_t att_server_read_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
889     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
890     if (!callback) return 0;
891     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
892 }
893 
894 static int att_server_write_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
895     switch (transaction_mode){
896         case ATT_TRANSACTION_MODE_VALIDATE:
897             return att_validate_prepared_write(con_handle);
898         case ATT_TRANSACTION_MODE_EXECUTE:
899         case ATT_TRANSACTION_MODE_CANCEL:
900             att_notify_write_callbacks(con_handle, transaction_mode);
901             return 0;
902         default:
903             break;
904     }
905 
906     // track CCC writes
907     if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){
908         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
909     }
910 
911     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
912     if (!callback) return 0;
913     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
914 }
915 
916 /**
917  * @brief register read/write callbacks for specific handle range
918  * @param att_service_handler_t
919  */
920 void att_server_register_service_handler(att_service_handler_t * handler){
921     if (att_service_handler_for_handle(handler->start_handle) ||
922         att_service_handler_for_handle(handler->end_handle)){
923         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
924         return;
925     }
926     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
927 }
928 
929 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
930 
931     // store callbacks
932     att_server_client_read_callback  = read_callback;
933     att_server_client_write_callback = write_callback;
934 
935     // register for HCI Events
936     hci_event_callback_registration.callback = &att_event_packet_handler;
937     hci_add_event_handler(&hci_event_callback_registration);
938 
939     // register for SM events
940     sm_event_callback_registration.callback = &att_event_packet_handler;
941     sm_add_event_handler(&sm_event_callback_registration);
942 
943     // and L2CAP ATT Server PDUs
944     att_dispatch_register_server(att_packet_handler);
945 
946     att_set_db(db);
947     att_set_read_callback(att_server_read_callback);
948     att_set_write_callback(att_server_write_callback);
949 
950 }
951 
952 void att_server_register_packet_handler(btstack_packet_handler_t handler){
953     att_client_packet_handler = handler;
954 }
955 
956 
957 // to be deprecated
958 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
959     return att_dispatch_server_can_send_now(con_handle);
960 }
961 
962 int att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
963     return att_server_request_to_send_notification(callback_registration, con_handle);
964 }
965 
966 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
967     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
968     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
969 }
970 // end of deprecated
971 
972 int att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
973     att_server_t * att_server = att_server_for_handle(con_handle);
974     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
975     btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
976     att_dispatch_server_request_can_send_now_event(con_handle);
977     return ERROR_CODE_SUCCESS;
978 }
979 
980 int att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
981     att_server_t * att_server = att_server_for_handle(con_handle);
982     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
983     btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
984     att_dispatch_server_request_can_send_now_event(con_handle);
985     return ERROR_CODE_SUCCESS;
986 }
987 
988 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
989     att_server_t * att_server = att_server_for_handle(con_handle);
990     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
991 
992     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
993 
994     l2cap_reserve_packet_buffer();
995     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
996     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
997 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
998 }
999 
1000 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
1001     att_server_t * att_server = att_server_for_handle(con_handle);
1002     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1003 
1004     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1005     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
1006 
1007     // track indication
1008     att_server->value_indication_handle = attribute_handle;
1009     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1010     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1011     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1012 
1013     l2cap_reserve_packet_buffer();
1014     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
1015     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
1016 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
1017     return 0;
1018 }
1019