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