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