xref: /btstack/src/ble/att_server.c (revision 42a2bbebe0f5cb756f37d635be1a160ee231a9a2)
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 BLUEKITCHEN
24  * GMBH 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 "ble/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 #include "bluetooth_psm.h"
69 
70 #endif
71 
72 #ifdef ENABLE_TESTING_SUPPORT
73 #include <stdio.h>
74 #endif
75 
76 #ifndef NVN_NUM_GATT_SERVER_CCC
77 #define NVN_NUM_GATT_SERVER_CCC 20
78 #endif
79 
80 #define ATT_SERVICE_FLAGS_DELAYED_RESPONSE (1<<0u)
81 
82 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection);
83 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
84 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
85 static void att_server_handle_can_send_now(void);
86 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection);
87 static void att_server_persistent_ccc_clear(att_server_t * att_server);
88 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size);
89 
90 typedef enum {
91     ATT_SERVER_RUN_PHASE_1_REQUESTS = 0,
92     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
93     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
94 } att_server_run_phase_t;
95 
96 //
97 typedef struct {
98     uint32_t seq_nr;
99     uint16_t att_handle;
100     uint8_t  value;
101     uint8_t  device_index;
102 } persistent_ccc_entry_t;
103 
104 // global
105 static btstack_packet_callback_registration_t hci_event_callback_registration;
106 static btstack_packet_callback_registration_t sm_event_callback_registration;
107 static btstack_packet_handler_t               att_client_packet_handler;
108 static btstack_linked_list_t                  service_handlers;
109 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
110 
111 static att_read_callback_t                    att_server_client_read_callback;
112 static att_write_callback_t                   att_server_client_write_callback;
113 
114 // round robin
115 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
116 
117 static uint8_t att_server_flags;
118 
119 #ifdef ENABLE_GATT_OVER_EATT
120 typedef struct {
121     btstack_linked_item_t item;
122     att_server_t     att_server;
123     att_connection_t att_connection;
124     uint8_t * receive_buffer;
125     uint8_t * send_buffer;
126 } att_server_eatt_bearer_t;
127 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle);
128 static btstack_linked_list_t att_server_eatt_bearer_pool;
129 static btstack_linked_list_t att_server_eatt_bearer_active;
130 #endif
131 
132 #ifdef ENABLE_LE_SIGNED_WRITE
133 static bool att_server_connections_for_state(att_server_state_t state, att_server_t ** att_server_out, att_connection_t ** att_connection_out){
134     btstack_linked_list_iterator_t it;
135     hci_connections_get_iterator(&it);
136     while(btstack_linked_list_iterator_has_next(&it)){
137         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
138         if (hci_connection->att_server.state == state) {
139             *att_server_out     = &hci_connection->att_server;
140             *att_connection_out = &hci_connection->att_connection;
141             return true;
142         }
143     }
144 
145 #ifdef ENABLE_GATT_OVER_EATT
146     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
147     while(btstack_linked_list_iterator_has_next(&it)){
148         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
149         if (eatt_bearer->att_server.state == state) {
150             *att_server_out     = &eatt_bearer->att_server;
151             *att_connection_out = &eatt_bearer->att_connection;
152             return true;
153         }
154     }
155 #endif
156 
157     return false;
158 }
159 #endif
160 
161 static void att_server_request_can_send_now(att_server_t * att_server, att_connection_t * att_connection ){
162     switch (att_server->bearer_type){
163         case ATT_BEARER_UNENHANCED_LE:
164 #ifdef ENABLE_GATT_OVER_CLASSIC
165         case ATT_BEARER_UNENHANCED_CLASSIC:
166             /* fall through */
167 #endif
168             att_dispatch_server_request_can_send_now_event(att_connection->con_handle);
169             break;
170 #ifdef ENABLE_GATT_OVER_EATT
171         case ATT_BEARER_ENHANCED_LE:
172             l2cap_request_can_send_now_event(att_server->l2cap_cid);
173             break;
174 #endif
175         default:
176             btstack_unreachable();
177             break;
178     }
179 }
180 
181 static bool att_server_can_send_packet(att_server_t * att_server, att_connection_t * att_connection){
182     switch (att_server->bearer_type) {
183         case ATT_BEARER_UNENHANCED_LE:
184 #ifdef ENABLE_GATT_OVER_CLASSIC
185         case ATT_BEARER_UNENHANCED_CLASSIC:
186             /* fall through */
187 #endif
188             return att_dispatch_server_can_send_now(att_connection->con_handle);
189 #ifdef ENABLE_GATT_OVER_EATT
190         case ATT_BEARER_ENHANCED_LE:
191             return l2cap_can_send_packet_now(att_server->l2cap_cid);
192 #endif
193         default:
194             btstack_unreachable();
195             break;
196     }
197     return false;
198 }
199 
200 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
201     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
202     if (!packet_handler) return;
203 
204     uint8_t event[7];
205     int pos = 0;
206     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
207     event[pos++] = sizeof(event) - 2u;
208     event[pos++] = status;
209     little_endian_store_16(event, pos, client_handle);
210     pos += 2;
211     little_endian_store_16(event, pos, attribute_handle);
212     (*packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
213 }
214 
215 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
216     // dispatch to app level handler
217     if (att_client_packet_handler != NULL){
218         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
219     }
220 
221     // dispatch to service handlers
222     btstack_linked_list_iterator_t it;
223     btstack_linked_list_iterator_init(&it, &service_handlers);
224     while (btstack_linked_list_iterator_has_next(&it)){
225         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
226         if (!handler->packet_handler) continue;
227         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
228     }
229 }
230 
231 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
232     uint8_t event[6];
233     int pos = 0;
234     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
235     event[pos++] = sizeof(event) - 2u;
236     little_endian_store_16(event, pos, con_handle);
237     pos += 2;
238     little_endian_store_16(event, pos, mtu);
239 
240     // also dispatch to GATT Clients
241     att_dispatch_server_mtu_exchanged(con_handle, mtu);
242 
243     // dispatch to app level handler and service handlers
244     att_emit_event_to_all(&event[0], sizeof(event));
245 }
246 
247 static void att_emit_can_send_now_event(void * context){
248     UNUSED(context);
249     if (!att_client_packet_handler) return;
250 
251     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
252     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
253 }
254 
255 static void att_emit_connected_event(att_server_t * att_server,  att_connection_t * att_connection){
256     uint8_t event[11];
257     int pos = 0;
258     event[pos++] = ATT_EVENT_CONNECTED;
259     event[pos++] = sizeof(event) - 2u;
260     event[pos++] = att_server->peer_addr_type;
261     reverse_bd_addr(att_server->peer_address, &event[pos]);
262     pos += 6;
263     little_endian_store_16(event, pos, att_connection->con_handle);
264     pos += 2;
265 
266     // dispatch to app level handler and service handlers
267     att_emit_event_to_all(&event[0], sizeof(event));
268 }
269 
270 
271 static void att_emit_disconnected_event(uint16_t con_handle){
272     uint8_t event[4];
273     int pos = 0;
274     event[pos++] = ATT_EVENT_DISCONNECTED;
275     event[pos++] = sizeof(event) - 2u;
276     little_endian_store_16(event, pos, con_handle);
277     pos += 2;
278 
279     // dispatch to app level handler and service handlers
280     att_emit_event_to_all(&event[0], sizeof(event));
281 }
282 
283 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
284     void * context = btstack_run_loop_get_timer_context(ts);
285     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
286     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
287     if (!hci_connection) return;
288     // @note: after a transaction timeout, no more requests shall be sent over this ATT Bearer
289     // (that's why we don't reset the value_indication_handle)
290     att_server_t * att_server = &hci_connection->att_server;
291     uint16_t att_handle = att_server->value_indication_handle;
292     att_connection_t * att_connection = &hci_connection->att_connection;
293     att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_connection->con_handle, att_handle);
294 }
295 
296 static void att_server_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
297 
298     UNUSED(channel); // ok: there is no channel
299     UNUSED(size);    // ok: handling own l2cap events
300 
301     att_server_t * att_server;
302     att_connection_t * att_connection;
303     hci_con_handle_t con_handle;
304     hci_connection_t * hci_connection;
305 
306     switch (packet_type) {
307 
308         case HCI_EVENT_PACKET:
309             switch (hci_event_packet_get_type(packet)) {
310                 case HCI_EVENT_META_GAP:
311                     switch (hci_event_gap_meta_get_subevent_code(packet)) {
312                         case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
313                             con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
314                             hci_connection = hci_connection_for_handle(con_handle);
315                             if (!hci_connection) break;
316                             att_server = &hci_connection->att_server;
317                         	// store connection info
318                         	att_server->peer_addr_type = gap_subevent_le_connection_complete_get_peer_address_type(packet);
319                             gap_subevent_le_connection_complete_get_peer_address(packet, att_server->peer_address);
320                             att_connection = &hci_connection->att_connection;
321                             att_connection->con_handle = con_handle;
322                             // reset connection properties
323                             att_server->state = ATT_SERVER_IDLE;
324                             att_server->bearer_type = ATT_BEARER_UNENHANCED_LE;
325                             att_connection->mtu = ATT_DEFAULT_MTU;
326                             att_connection->max_mtu = l2cap_max_le_mtu();
327                             if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
328                                 att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
329                             }
330                             att_connection->encryption_key_size = 0u;
331                             att_connection->authenticated = 0u;
332 		                	att_connection->authorized = 0u;
333                             // workaround: identity resolving can already be complete, at least store result
334                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
335                             att_server->ir_lookup_active = false;
336                             att_server->pairing_active = false;
337                             // notify all - new
338                             att_emit_connected_event(att_server, att_connection);
339                             break;
340                         default:
341                             break;
342                     }
343                     break;
344 
345                 case HCI_EVENT_LE_META:
346                     switch (hci_event_le_meta_get_subevent_code(packet)) {
347                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
348                             // forward LE Connection Complete event to keep backward compatibility
349                             // deprecated: please register hci handler with hci_add_event_handler or handle ATT_EVENT_CONNECTED
350                             att_emit_event_to_all(packet, size);
351                             break;
352                         default:
353                             break;
354                     }
355                     break;
356 
357                 case HCI_EVENT_ENCRYPTION_CHANGE:
358                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
359                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
360                 	// check handle
361                     con_handle = little_endian_read_16(packet, 3);
362                     hci_connection = hci_connection_for_handle(con_handle);
363                     if (!hci_connection) break;
364                     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) break;
365                     // update security params
366                     att_server = &hci_connection->att_server;
367                     att_connection = &hci_connection->att_connection;
368                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
369                     att_connection->authenticated = gap_authenticated(con_handle) ? 1 : 0;
370                     att_connection->secure_connection = gap_secure_connection(con_handle) ? 1 : 0;
371                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
372                         att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
373                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
374                         // restore CCC values when encrypted for LE Connections
375                         if (hci_event_encryption_change_get_encryption_enabled(packet) != 0){
376                             att_server_persistent_ccc_restore(att_server, att_connection);
377                         }
378                     }
379                     att_run_for_context(att_server, att_connection);
380                     break;
381 
382                 case HCI_EVENT_DISCONNECTION_COMPLETE:
383                     // check handle
384                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
385                     hci_connection = hci_connection_for_handle(con_handle);
386                     if (!hci_connection) break;
387                     att_server = &hci_connection->att_server;
388                     att_connection = &hci_connection->att_connection;
389                     att_clear_transaction_queue(att_connection);
390                     att_connection->con_handle = 0;
391                     att_server->pairing_active = false;
392                     att_server->state = ATT_SERVER_IDLE;
393                     if (att_server->value_indication_handle != 0u){
394                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
395                         uint16_t att_handle = att_server->value_indication_handle;
396                         att_server->value_indication_handle = 0u; // reset error state
397                         att_handle_value_indication_notify_client((uint8_t)ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_connection->con_handle, att_handle);
398                     }
399                     // notify all - new
400                     att_emit_disconnected_event(con_handle);
401                     // notify all - old
402                     att_emit_event_to_all(packet, size);
403                     break;
404 
405                 // Identity Resolving
406                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
407                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
408                     hci_connection = hci_connection_for_handle(con_handle);
409                     if (!hci_connection) break;
410                     att_server = &hci_connection->att_server;
411                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
412                     att_server->ir_lookup_active = true;
413                     break;
414                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
415                     con_handle = sm_event_identity_created_get_handle(packet);
416                     hci_connection = hci_connection_for_handle(con_handle);
417                     if (!hci_connection) return;
418                     att_connection = &hci_connection->att_connection;
419                     att_server = &hci_connection->att_server;
420                     att_server->ir_lookup_active = false;
421                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
422                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
423                     att_run_for_context(att_server, att_connection);
424                     break;
425                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
426                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
427                     hci_connection = hci_connection_for_handle(con_handle);
428                     if (!hci_connection) break;
429                     att_connection = &hci_connection->att_connection;
430                     att_server = &hci_connection->att_server;
431                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
432                     att_server->ir_lookup_active = false;
433                     att_server->ir_le_device_db_index = -1;
434                     att_run_for_context(att_server, att_connection);
435                     break;
436 
437                 // Pairing started - delete stored CCC values
438                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
439                 // - assumes that all events have the con handle as the first field
440                 case SM_EVENT_JUST_WORKS_REQUEST:
441                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
442                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
443                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
444                     con_handle = sm_event_just_works_request_get_handle(packet);
445                     hci_connection = hci_connection_for_handle(con_handle);
446                     if (!hci_connection) break;
447                     att_server = &hci_connection->att_server;
448                     log_info("SM Pairing started");
449                     att_server->pairing_active = true;
450                     if (att_server->ir_le_device_db_index < 0) break;
451                     att_server_persistent_ccc_clear(att_server);
452                     // index not valid anymore
453                     att_server->ir_le_device_db_index = -1;
454                     break;
455 
456                 // Bonding completed
457                 case SM_EVENT_IDENTITY_CREATED:
458                     con_handle = sm_event_identity_created_get_handle(packet);
459                     hci_connection = hci_connection_for_handle(con_handle);
460                     if (!hci_connection) return;
461                     att_connection = &hci_connection->att_connection;
462                     att_server = &hci_connection->att_server;
463                     att_server->pairing_active = false;
464                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
465                     att_run_for_context(att_server, att_connection);
466                     break;
467 
468                 // Pairing complete (with/without bonding=storing of pairing information)
469                 case SM_EVENT_PAIRING_COMPLETE:
470                     con_handle = sm_event_pairing_complete_get_handle(packet);
471                     hci_connection = hci_connection_for_handle(con_handle);
472                     if (!hci_connection) return;
473                     att_connection = &hci_connection->att_connection;
474                     att_server = &hci_connection->att_server;
475                     att_server->pairing_active = false;
476                     att_run_for_context(att_server, att_connection);
477                     break;
478 
479                 // Authorization
480                 case SM_EVENT_AUTHORIZATION_RESULT: {
481                     con_handle = sm_event_authorization_result_get_handle(packet);
482                     hci_connection = hci_connection_for_handle(con_handle);
483                     if (!hci_connection) break;
484                     att_connection = &hci_connection->att_connection;
485                     att_server = &hci_connection->att_server;
486                     att_connection->authorized = sm_event_authorization_result_get_authorization_result(packet);
487                     att_server_request_can_send_now(att_server, att_connection);
488                 	break;
489                 }
490                 default:
491                     break;
492             }
493             break;
494         default:
495             break;
496     }
497 }
498 
499 static uint8_t
500 att_server_send_prepared(const att_server_t *att_server, const att_connection_t *att_connection, uint8_t *buffer,
501                          uint16_t size) {
502     UNUSED(buffer);
503     uint8_t status = ERROR_CODE_SUCCESS;
504     switch (att_server->bearer_type) {
505         case ATT_BEARER_UNENHANCED_LE:
506             status = l2cap_send_prepared_connectionless(att_connection->con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
507             break;
508 #ifdef ENABLE_GATT_OVER_CLASSIC
509         case ATT_BEARER_UNENHANCED_CLASSIC:
510             status = l2cap_send_prepared(att_server->l2cap_cid, size);
511             break;
512 #endif
513 #ifdef ENABLE_GATT_OVER_EATT
514         case ATT_BEARER_ENHANCED_LE:
515             btstack_assert(buffer != NULL);
516             status = l2cap_send(att_server->l2cap_cid, buffer, size);
517             break;
518 #endif
519         default:
520             btstack_unreachable();
521             break;
522     }
523     return status;
524 }
525 
526 #ifdef ENABLE_LE_SIGNED_WRITE
527 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
528     att_server_t * att_server = NULL;
529     att_connection_t * att_connection = NULL;
530     bool found = att_server_connections_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION, &att_server, &att_connection);
531 
532     if (found == false){
533         return;
534     }
535 
536     uint8_t hash_flipped[8];
537     reverse_64(hash, hash_flipped);
538     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8) != 0){
539         log_info("ATT Signed Write, invalid signature");
540 #ifdef ENABLE_TESTING_SUPPORT
541         printf("ATT Signed Write, invalid signature\n");
542 #endif
543         att_server->state = ATT_SERVER_IDLE;
544         return;
545     }
546     log_info("ATT Signed Write, valid signature");
547 #ifdef ENABLE_TESTING_SUPPORT
548     printf("ATT Signed Write, valid signature\n");
549 #endif
550 
551     // update sequence number
552     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
553     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
554     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
555     att_server_request_can_send_now(att_server, att_connection);
556 }
557 #endif
558 
559 #ifdef ENABLE_ATT_DELAYED_RESPONSE
560 static void att_server_handle_response_pending(att_server_t *att_server, const att_connection_t *att_connection,
561                                                const uint8_t *eatt_buffer,
562                                                uint16_t att_response_size) {
563     // update state
564     att_server->state = ATT_SERVER_RESPONSE_PENDING;
565 
566     // callback with handle ATT_READ_RESPONSE_PENDING for reads
567     if (att_response_size == ATT_READ_RESPONSE_PENDING){
568         // notify services that returned response pending
569         btstack_linked_list_iterator_t it;
570         btstack_linked_list_iterator_init(&it, &service_handlers);
571         while (btstack_linked_list_iterator_has_next(&it)) {
572             att_service_handler_t *handler = (att_service_handler_t *) btstack_linked_list_iterator_next(&it);
573             if ((handler->flags & ATT_SERVICE_FLAGS_DELAYED_RESPONSE) != 0){
574                 handler->flags &= ~ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
575                 handler->read_callback(att_connection->con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
576             }
577         }
578         // notify main read callback if it returned response pending
579         if ((att_server_flags & ATT_SERVICE_FLAGS_DELAYED_RESPONSE) != 0){
580             // flag was set by read callback
581             btstack_assert(att_server_client_read_callback != NULL);
582             (*att_server_client_read_callback)(att_connection->con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
583         }
584     }
585 
586     // free reserved buffer - might trigger next read/write
587     if (eatt_buffer == NULL){
588         l2cap_release_packet_buffer();
589     }
590 }
591 #endif
592 
593 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
594 // pre: can send now
595 // uses l2cap outgoing buffer if no eatt_buffer provided
596 // returns: 1 if packet was sent
597 static int
598 att_server_process_validated_request(att_server_t *att_server, att_connection_t *att_connection, uint8_t *eatt_buffer) {
599 
600     uint8_t * att_response_buffer;
601     if (eatt_buffer != NULL){
602         att_response_buffer = eatt_buffer;
603     } else {
604         l2cap_reserve_packet_buffer();
605         att_response_buffer = l2cap_get_outgoing_buffer();
606     }
607 
608     uint16_t  att_response_size = 0;
609     // Send Error Response for MTU Request over connection-oriented channel
610     if ((att_server->bearer_type != ATT_BEARER_UNENHANCED_LE) && (att_server->request_buffer[0] == ATT_EXCHANGE_MTU_REQUEST)){
611         att_response_size = 5;
612         att_response_buffer[0] = ATT_ERROR_RESPONSE;
613         att_response_buffer[1] = ATT_EXCHANGE_MTU_REQUEST;
614         att_response_buffer[2] = 0;
615         att_response_buffer[3] = 0;
616         att_response_buffer[4] = ATT_ERROR_REQUEST_NOT_SUPPORTED;
617     } else {
618         att_response_size = att_handle_request(att_connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
619     }
620 
621 #ifdef ENABLE_ATT_DELAYED_RESPONSE
622     if ((att_response_size == ATT_READ_RESPONSE_PENDING) || (att_response_size == ATT_INTERNAL_WRITE_RESPONSE_PENDING)){
623         att_server_handle_response_pending(att_server, att_connection, eatt_buffer, att_response_size);
624         return 0;
625     }
626 #endif
627 
628     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
629     if ((att_response_size     >= 4u)
630     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
631     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
632     && (att_connection->authenticated != 0u)){
633 
634         switch (gap_authorization_state(att_connection->con_handle)){
635             case AUTHORIZATION_UNKNOWN:
636                 if (eatt_buffer == NULL){
637                     l2cap_release_packet_buffer();
638                 }
639                 sm_request_pairing(att_connection->con_handle);
640                 return 0;
641             case AUTHORIZATION_PENDING:
642                 if (eatt_buffer == NULL){
643                     l2cap_release_packet_buffer();
644                 }
645                 return 0;
646             default:
647                 break;
648         }
649     }
650 
651     att_server->state = ATT_SERVER_IDLE;
652     if (att_response_size == 0u) {
653         if (eatt_buffer == NULL){
654             l2cap_release_packet_buffer();
655         }
656         return 0;
657     }
658 
659     (void) att_server_send_prepared(att_server, att_connection, eatt_buffer, att_response_size);
660 
661     // notify client about MTU exchange result
662     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
663         att_emit_mtu_event(att_connection->con_handle, att_connection->mtu);
664     }
665     return 1;
666 }
667 
668 #ifdef ENABLE_ATT_DELAYED_RESPONSE
669 uint8_t att_server_response_ready(hci_con_handle_t con_handle){
670     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
671     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672     att_server_t * att_server = &hci_connection->att_server;
673     att_connection_t * att_connection = &hci_connection->att_connection;
674     if (att_server->state != ATT_SERVER_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
675 
676     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
677     att_server_request_can_send_now(att_server, att_connection);
678     return ERROR_CODE_SUCCESS;
679 }
680 #endif
681 
682 static void att_run_for_context(att_server_t * att_server, att_connection_t * att_connection){
683     switch (att_server->state){
684         case ATT_SERVER_REQUEST_RECEIVED:
685             switch (att_server->bearer_type){
686                 case ATT_BEARER_UNENHANCED_LE:
687                     // wait until re-encryption as central is complete
688                     if (gap_reconnect_security_setup_active(att_connection->con_handle)) {
689                         return;
690                     };
691                     break;
692 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined (ENABLE_GATT_OVER_EATT)
693 #ifdef ENABLE_GATT_OVER_CLASSIC
694                 case ATT_BEARER_UNENHANCED_CLASSIC:
695                     /* fall through */
696 #endif
697 #ifdef ENABLE_GATT_OVER_EATT
698                 case ATT_BEARER_ENHANCED_LE:
699 #endif
700                     // ok
701                     break;
702 #endif
703                 default:
704                     btstack_unreachable();
705                     break;
706             }
707 
708             // wait until pairing is complete
709             if (att_server->pairing_active) break;
710 
711 #ifdef ENABLE_LE_SIGNED_WRITE
712             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
713                 log_info("ATT Signed Write!");
714                 if (!sm_cmac_ready()) {
715                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
716                     att_server->state = ATT_SERVER_IDLE;
717                     return;
718                 }
719                 if (att_server->request_size < (3 + 12)) {
720                     log_info("ATT Signed Write, request to short. Abort.");
721                     att_server->state = ATT_SERVER_IDLE;
722                     return;
723                 }
724                 if (att_server->ir_lookup_active){
725                     return;
726                 }
727                 if (att_server->ir_le_device_db_index < 0){
728                     log_info("ATT Signed Write, CSRK not available");
729                     att_server->state = ATT_SERVER_IDLE;
730                     return;
731                 }
732 
733                 // check counter
734                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
735                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
736                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
737                 if (counter_packet < counter_db){
738                     log_info("ATT Signed Write, db reports higher counter, abort");
739                     att_server->state = ATT_SERVER_IDLE;
740                     return;
741                 }
742 
743                 // signature is { sequence counter, secure hash }
744                 sm_key_t csrk;
745                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
746                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
747                 log_info("Orig Signature: ");
748                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
749                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
750                 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);
751                 return;
752             }
753 #endif
754             // move on
755             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
756             att_server_request_can_send_now(att_server, att_connection);
757             break;
758 
759         default:
760             break;
761     }
762 }
763 
764 static bool att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
765     switch (phase){
766         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
767             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
768         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
769              return (!btstack_linked_list_empty(&att_server->indication_requests) && (att_server->value_indication_handle == 0u));
770         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
771             return (!btstack_linked_list_empty(&att_server->notification_requests));
772         default:
773             btstack_assert(false);
774             return false;
775     }
776 }
777 
778 static void att_server_trigger_send_for_phase(att_server_t * att_server, att_connection_t * att_connection, att_server_run_phase_t phase){
779     btstack_context_callback_registration_t * client;
780     switch (phase){
781         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
782             att_server_process_validated_request(att_server, att_connection, NULL);
783             break;
784         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
785             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
786             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
787             client->callback(client->context);
788             break;
789        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
790             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
791             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
792             client->callback(client->context);
793             break;
794         default:
795             btstack_assert(false);
796             break;
797     }
798 }
799 
800 static void att_server_handle_can_send_now(void){
801 
802     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
803     hci_connection_t * request_hci_connection   = NULL;
804     bool can_send_now = true;
805     uint8_t phase_index;
806 
807     for (phase_index = ATT_SERVER_RUN_PHASE_1_REQUESTS; phase_index <= ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase_index++){
808         att_server_run_phase_t phase = (att_server_run_phase_t) phase_index;
809         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
810         while (true){
811             btstack_linked_list_iterator_t it;
812             hci_connections_get_iterator(&it);
813             while(btstack_linked_list_iterator_has_next(&it)){
814                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
815                 att_server_t * att_server = &connection->att_server;
816                 att_connection_t * att_connection = &connection->att_connection;
817 
818                 bool data_ready = att_server_data_ready_for_phase(att_server, phase);
819 
820                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_connection->con_handle, skip_connections_until, data_ready);
821 
822                 // skip until last sender found (which is also skipped)
823                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
824                     if (data_ready && (request_hci_connection == NULL)){
825                         request_hci_connection = connection;
826                     }
827                     if (skip_connections_until == att_connection->con_handle){
828                         skip_connections_until = HCI_CON_HANDLE_INVALID;
829                     }
830                     continue;
831                 };
832 
833                 if (data_ready){
834                     if (can_send_now){
835                         att_server_trigger_send_for_phase(att_server, att_connection, phase);
836                         last_send_con_handle = att_connection->con_handle;
837                         can_send_now = att_server_can_send_packet(att_server, att_connection);
838                         data_ready = att_server_data_ready_for_phase(att_server, phase);
839                         if (data_ready && (request_hci_connection == NULL)){
840                             request_hci_connection = connection;
841                         }
842                     } else {
843                         request_hci_connection = connection;
844                         break;
845                     }
846                 }
847             }
848 
849             // stop skipping (handles disconnect by last send connection)
850             skip_connections_until = HCI_CON_HANDLE_INVALID;
851 
852             // Exit loop, if we cannot send
853             if (!can_send_now) break;
854 
855             // Exit loop, if we can send but there are also no further request
856             if (request_hci_connection == NULL) break;
857 
858             // Finally, if we still can send and there are requests, just try again
859             request_hci_connection = NULL;
860         }
861         // update last send con handle for round robin
862         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
863             att_server_last_can_send_now = last_send_con_handle;
864         }
865     }
866 
867     if (request_hci_connection == NULL) return;
868 
869     att_server_t * att_server = &request_hci_connection->att_server;
870     att_connection_t * att_connection = &request_hci_connection->att_connection;
871     att_server_request_can_send_now(att_server, att_connection);
872 }
873 
874 static void att_server_handle_att_pdu(att_server_t * att_server, att_connection_t * att_connection, uint8_t * packet, uint16_t size){
875 
876     uint8_t opcode  = packet[0u];
877     uint8_t method  = opcode & 0x03fu;
878     bool invalid = method > ATT_MULTIPLE_HANDLE_VALUE_NTF;
879     bool command = (opcode & 0x40u) != 0u;
880 
881     // ignore invalid commands
882     if (invalid && command){
883         return;
884     }
885 
886     // handle value indication confirms
887     if ((opcode == ATT_HANDLE_VALUE_CONFIRMATION) && (att_server->value_indication_handle != 0u)){
888         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
889         uint16_t att_handle = att_server->value_indication_handle;
890         att_server->value_indication_handle = 0u;
891         att_handle_value_indication_notify_client(0u, att_connection->con_handle, att_handle);
892         att_server_request_can_send_now(att_server, att_connection);
893         return;
894     }
895 
896     // directly process command
897     // note: signed write cannot be handled directly as authentication needs to be verified
898     if (opcode == ATT_WRITE_COMMAND){
899         att_handle_request(att_connection, packet, size, NULL);
900         return;
901     }
902 
903     // check size
904     if (size > sizeof(att_server->request_buffer)) {
905         log_info("drop att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
906         return;
907     }
908 
909 #ifdef ENABLE_LE_SIGNED_WRITE
910     // abort signed write validation if a new request comes in (but finish previous signed write if possible)
911     if (att_server->state == ATT_SERVER_W4_SIGNED_WRITE_VALIDATION){
912         if (packet[0] == ATT_SIGNED_WRITE_COMMAND){
913             log_info("skip new signed write request as previous is in validation");
914             return;
915         } else {
916             log_info("abort signed write validation to process new request");
917             att_server->state = ATT_SERVER_IDLE;
918         }
919     }
920 #endif
921     // last request still in processing?
922     if (att_server->state != ATT_SERVER_IDLE){
923         log_info("skip att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
924         return;
925     }
926 
927     // store request
928     att_server->state = ATT_SERVER_REQUEST_RECEIVED;
929     att_server->request_size = size;
930     (void)memcpy(att_server->request_buffer, packet, size);
931 
932     att_run_for_context(att_server, att_connection);
933 }
934 
935 static void att_server_dispatch_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
936     hci_connection_t * hci_connection;
937     att_connection_t * att_connection;
938     att_server_t     * att_server;
939 #ifdef ENABLE_GATT_OVER_CLASSIC
940     hci_con_handle_t con_handle;
941     bd_addr_t        address;
942     btstack_linked_list_iterator_t it;
943 #endif
944 
945     switch (packet_type){
946         case HCI_EVENT_PACKET:
947             switch (packet[0]){
948 #ifdef ENABLE_GATT_OVER_CLASSIC
949                 case L2CAP_EVENT_CHANNEL_OPENED:
950                     con_handle = l2cap_event_channel_opened_get_handle(packet);
951                     hci_connection = hci_connection_for_handle(con_handle);
952                     if (!hci_connection) break;
953                     att_server = &hci_connection->att_server;
954                     // store connection info
955                     att_server->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
956                     att_server->peer_addr_type = BD_ADDR_TYPE_ACL;
957                     l2cap_event_channel_opened_get_address(packet, att_server->peer_address);
958                     att_connection = &hci_connection->att_connection;
959                     att_connection->con_handle = con_handle;
960                     // reset connection properties
961                     att_server->state = ATT_SERVER_IDLE;
962                     att_connection->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
963                     att_connection->max_mtu = l2cap_max_mtu();
964                     if (att_connection->max_mtu > ATT_REQUEST_BUFFER_SIZE){
965                         att_connection->max_mtu = ATT_REQUEST_BUFFER_SIZE;
966                     }
967 
968                     log_info("Connection opened %s, l2cap cid %04x, mtu %u", bd_addr_to_str(address), att_server->l2cap_cid, att_connection->mtu);
969 
970                     // update security params
971                     att_connection->encryption_key_size = gap_encryption_key_size(con_handle);
972                     att_connection->authenticated = gap_authenticated(con_handle);
973                     att_connection->secure_connection = gap_secure_connection(con_handle);
974                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
975                              att_connection->encryption_key_size, att_connection->authenticated, att_connection->secure_connection);
976 
977                     // notify connection opened
978                     att_emit_connected_event(att_server, att_connection);
979 
980                     // restore persisten ccc if encrypted
981                     if ( gap_security_level(con_handle) >= LEVEL_2){
982                         att_server_persistent_ccc_restore(att_server, att_connection);
983                     }
984                     // TODO: what to do about le device db?
985                     att_server->pairing_active = 0;
986                     break;
987 #endif
988                 case L2CAP_EVENT_CAN_SEND_NOW:
989                     att_server_handle_can_send_now();
990                     break;
991                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
992                     // GATT client has negotiated the mtu for this connection
993                     hci_connection = hci_connection_for_handle(channel);
994                     if (!hci_connection) break;
995                     att_connection = &hci_connection->att_connection;
996                     att_connection->mtu = little_endian_read_16(packet, 4);
997                     break;
998                 default:
999                     break;
1000             }
1001             break;
1002 
1003         case ATT_DATA_PACKET:
1004             log_debug("ATT Packet, handle 0x%04x", channel);
1005             hci_connection = hci_connection_for_handle(channel);
1006             if (!hci_connection) break;
1007 
1008             att_server = &hci_connection->att_server;
1009             att_connection = &hci_connection->att_connection;
1010             att_server_handle_att_pdu(att_server, att_connection, packet, size);
1011             break;
1012 
1013 #ifdef ENABLE_GATT_OVER_CLASSIC
1014         case L2CAP_DATA_PACKET:
1015             hci_connections_get_iterator(&it);
1016             while(btstack_linked_list_iterator_has_next(&it)){
1017                 hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1018                 att_server = &hci_connection->att_server;
1019                 att_connection = &hci_connection->att_connection;
1020                 if (att_server->l2cap_cid == channel) {
1021                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
1022                     break;
1023                 }
1024             }
1025             break;
1026 #endif
1027 
1028         default:
1029             break;
1030     }
1031 }
1032 
1033 // ---------------------
1034 // persistent CCC writes
1035 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
1036     return ('B' << 24u) | ('T' << 16u) | ('C' << 8u) | index;
1037 }
1038 
1039 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
1040     // lookup att_server instance
1041     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1042     if (!hci_connection) return;
1043     att_server_t * att_server = &hci_connection->att_server;
1044     int le_device_index = att_server->ir_le_device_db_index;
1045     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);
1046 
1047     // check if bonded
1048     if (le_device_index < 0) return;
1049 
1050     // get btstack_tlv
1051     const btstack_tlv_t * tlv_impl = NULL;
1052     void * tlv_context;
1053     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1054     if (!tlv_impl) return;
1055 
1056     // update ccc tag
1057     int index;
1058     uint32_t highest_seq_nr = 0;
1059     uint32_t lowest_seq_nr = 0;
1060     uint32_t tag_for_lowest_seq_nr = 0;
1061     uint32_t tag_for_empty = 0;
1062     persistent_ccc_entry_t entry;
1063     for (index=0; index<NVN_NUM_GATT_SERVER_CCC; index++){
1064         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1065         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1066 
1067         // empty/invalid tag
1068         if (len != sizeof(persistent_ccc_entry_t)){
1069             tag_for_empty = tag;
1070             continue;
1071         }
1072         // update highest seq nr
1073         if (entry.seq_nr > highest_seq_nr){
1074             highest_seq_nr = entry.seq_nr;
1075         }
1076         // find entry with lowest seq nr
1077         if ((tag_for_lowest_seq_nr == 0u) || (entry.seq_nr < lowest_seq_nr)){
1078             tag_for_lowest_seq_nr = tag;
1079             lowest_seq_nr = entry.seq_nr;
1080         }
1081 
1082         if (entry.device_index != le_device_index) continue;
1083         if (entry.att_handle   != att_handle)      continue;
1084 
1085         // found matching entry
1086         if (value != 0){
1087             // update
1088             if (entry.value == value) {
1089                 log_info("CCC Index %u: Up-to-date", index);
1090                 return;
1091             }
1092             entry.value = (uint8_t) value;
1093             entry.seq_nr = highest_seq_nr + 1u;
1094             log_info("CCC Index %u: Store", index);
1095             int result = tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1096             if (result != 0){
1097                 log_error("Store tag index %u failed", index);
1098             }
1099         } else {
1100             // delete
1101             log_info("CCC Index %u: Delete", index);
1102             tlv_impl->delete_tag(tlv_context, tag);
1103         }
1104         return;
1105     }
1106 
1107     log_info("tag_for_empty %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
1108 
1109     if (value == 0u){
1110         // done
1111         return;
1112     }
1113 
1114     uint32_t tag_to_use = 0u;
1115     if (tag_for_empty != 0u){
1116         tag_to_use = tag_for_empty;
1117     } else if (tag_for_lowest_seq_nr != 0){
1118         tag_to_use = tag_for_lowest_seq_nr;
1119     } else {
1120         // should not happen
1121         return;
1122     }
1123     // store ccc tag
1124     entry.seq_nr       = highest_seq_nr + 1u;
1125     entry.device_index = le_device_index;
1126     entry.att_handle   = att_handle;
1127     entry.value        = (uint8_t) value;
1128     int result = tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1129     if (result != 0){
1130         log_error("Store tag index %u failed", index);
1131     }
1132 }
1133 
1134 static void att_server_persistent_ccc_clear(att_server_t * att_server){
1135     int le_device_index = att_server->ir_le_device_db_index;
1136     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1137     // check if bonded
1138     if (le_device_index < 0) return;
1139     // get btstack_tlv
1140     const btstack_tlv_t * tlv_impl = NULL;
1141     void * tlv_context;
1142     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1143     if (!tlv_impl) return;
1144     // get all ccc tag
1145     int index;
1146     persistent_ccc_entry_t entry;
1147     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1148         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1149         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1150         if (len != sizeof(persistent_ccc_entry_t)) continue;
1151         if (entry.device_index != le_device_index) continue;
1152         // delete entry
1153         log_info("CCC Index %u: Delete", index);
1154         tlv_impl->delete_tag(tlv_context, tag);
1155     }
1156 }
1157 
1158 static void att_server_persistent_ccc_restore(att_server_t * att_server, att_connection_t * att_connection){
1159     int le_device_index = att_server->ir_le_device_db_index;
1160     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
1161     // check if bonded
1162     if (le_device_index < 0) return;
1163     // get btstack_tlv
1164     const btstack_tlv_t * tlv_impl = NULL;
1165     void * tlv_context;
1166     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
1167     if (!tlv_impl) return;
1168     // get all ccc tag
1169     int index;
1170     persistent_ccc_entry_t entry;
1171     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
1172         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
1173         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
1174         if (len != sizeof(persistent_ccc_entry_t)) continue;
1175         if (entry.device_index != le_device_index) continue;
1176         // simulate write callback
1177         uint16_t attribute_handle = entry.att_handle;
1178         uint8_t  value[2];
1179         little_endian_store_16(value, 0, entry.value);
1180         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1181         if (!callback) continue;
1182         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
1183         (*callback)(att_connection->con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
1184     }
1185 }
1186 
1187 // persistent CCC writes
1188 // ---------------------
1189 
1190 // gatt service management
1191 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
1192     btstack_linked_list_iterator_t it;
1193     btstack_linked_list_iterator_init(&it, &service_handlers);
1194     while (btstack_linked_list_iterator_has_next(&it)){
1195         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1196         if (handler->start_handle > handle) continue;
1197         if (handler->end_handle   < handle) continue;
1198         return handler;
1199     }
1200     return NULL;
1201 }
1202 
1203 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
1204     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1205     if (handler != NULL) return handler->write_callback;
1206     return att_server_client_write_callback;
1207 }
1208 
1209 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
1210     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1211     if (handler != NULL) return handler->packet_handler;
1212     return att_client_packet_handler;
1213 }
1214 
1215 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
1216     // notify all callbacks
1217     btstack_linked_list_iterator_t it;
1218     btstack_linked_list_iterator_init(&it, &service_handlers);
1219     while (btstack_linked_list_iterator_has_next(&it)){
1220         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1221         if (!handler->write_callback) continue;
1222         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1223     }
1224     if (!att_server_client_write_callback) return;
1225     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1226 }
1227 
1228 // returns first reported error or 0
1229 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
1230     btstack_linked_list_iterator_t it;
1231     btstack_linked_list_iterator_init(&it, &service_handlers);
1232     while (btstack_linked_list_iterator_has_next(&it)){
1233         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1234         if (!handler->write_callback) continue;
1235         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1236         if (error_code != 0u) return error_code;
1237     }
1238     if (!att_server_client_write_callback) return 0;
1239     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1240 }
1241 
1242 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){
1243     att_service_handler_t * service = att_service_handler_for_handle(attribute_handle);
1244     att_read_callback_t read_callback = (service != NULL) ? service->read_callback : att_server_client_read_callback;
1245     uint16_t result = 0;
1246     if (read_callback != NULL){
1247         result = (*read_callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
1248 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1249         if (result == ATT_READ_RESPONSE_PENDING){
1250             if (service == NULL){
1251                 att_server_flags |= ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
1252             } else {
1253                 service->flags   |= ATT_SERVICE_FLAGS_DELAYED_RESPONSE;
1254             }
1255         }
1256 #endif
1257     }
1258     return result;
1259 }
1260 
1261 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){
1262     switch (transaction_mode){
1263         case ATT_TRANSACTION_MODE_VALIDATE:
1264             return att_validate_prepared_write(con_handle);
1265         case ATT_TRANSACTION_MODE_EXECUTE:
1266         case ATT_TRANSACTION_MODE_CANCEL:
1267             att_notify_write_callbacks(con_handle, transaction_mode);
1268             return 0;
1269         default:
1270             break;
1271     }
1272 
1273     // track CCC writes
1274     if (att_is_persistent_ccc(attribute_handle) && (offset == 0u) && (buffer_size == 2u)){
1275         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
1276     }
1277 
1278     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1279     if (!callback) return 0;
1280     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
1281 }
1282 
1283 /**
1284  * @brief register read/write callbacks for specific handle range
1285  * @param att_service_handler_t
1286  */
1287 void att_server_register_service_handler(att_service_handler_t * handler){
1288     bool att_server_registered = false;
1289     if (att_service_handler_for_handle(handler->start_handle) != NULL){
1290         att_server_registered = true;
1291     }
1292 
1293     if (att_service_handler_for_handle(handler->end_handle) != NULL){
1294         att_server_registered = true;
1295     }
1296 
1297     if (att_server_registered){
1298         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
1299         return;
1300     }
1301 
1302     handler->flags = 0;
1303     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
1304 }
1305 
1306 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
1307 
1308     // store callbacks
1309     att_server_client_read_callback  = read_callback;
1310     att_server_client_write_callback = write_callback;
1311 
1312     // register for HCI Events
1313     hci_event_callback_registration.callback = &att_server_event_packet_handler;
1314     hci_add_event_handler(&hci_event_callback_registration);
1315 
1316     // register for SM events
1317     sm_event_callback_registration.callback = &att_server_event_packet_handler;
1318     sm_add_event_handler(&sm_event_callback_registration);
1319 
1320     // and L2CAP ATT Server PDUs
1321     att_dispatch_register_server(att_server_dispatch_packet_handler);
1322 
1323 #ifdef ENABLE_GATT_OVER_CLASSIC
1324     // setup l2cap service
1325     att_dispatch_classic_register_service();
1326 #endif
1327 
1328     att_set_db(db);
1329     att_set_read_callback(att_server_read_callback);
1330     att_set_write_callback(att_server_write_callback);
1331 }
1332 
1333 void att_server_register_packet_handler(btstack_packet_handler_t handler){
1334     att_client_packet_handler = handler;
1335 }
1336 
1337 
1338 // to be deprecated
1339 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
1340     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1341     if (!hci_connection) return 0;
1342     att_server_t * att_server = &hci_connection->att_server;
1343     att_connection_t * att_connection = &hci_connection->att_connection;
1344     return att_server_can_send_packet(att_server, att_connection);
1345 }
1346 
1347 uint8_t att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1348     return att_server_request_to_send_notification(callback_registration, con_handle);
1349 }
1350 
1351 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
1352     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
1353     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
1354 }
1355 // end of deprecated
1356 
1357 uint8_t att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1358     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1359     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1360     att_server_t * att_server = &hci_connection->att_server;
1361     att_connection_t * att_connection = &hci_connection->att_connection;
1362     bool added = btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
1363     att_server_request_can_send_now(att_server, att_connection);
1364     if (added){
1365         return ERROR_CODE_SUCCESS;
1366     } else {
1367         return ERROR_CODE_COMMAND_DISALLOWED;
1368     }
1369 }
1370 
1371 uint8_t att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1372     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1373     if (!hci_connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1374     att_server_t * att_server = &hci_connection->att_server;
1375     att_connection_t * att_connection = &hci_connection->att_connection;
1376     bool added = btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
1377     att_server_request_can_send_now(att_server, att_connection);
1378     if (added){
1379         return ERROR_CODE_SUCCESS;
1380     } else {
1381         return ERROR_CODE_COMMAND_DISALLOWED;
1382     }
1383 }
1384 
1385 static uint8_t att_server_prepare_server_message(hci_con_handle_t con_handle, att_server_t ** out_att_server, att_connection_t ** out_att_connection, uint8_t ** out_packet_buffer){
1386 
1387     att_server_t *     att_server = NULL;
1388     att_connection_t * att_connection = NULL;
1389     uint8_t *          packet_buffer = NULL;
1390 
1391     // prefer enhanced bearer
1392 #ifdef ENABLE_GATT_OVER_EATT
1393     att_server_eatt_bearer_t * eatt_bearer = att_server_eatt_bearer_for_con_handle(con_handle);
1394     if (eatt_bearer != NULL){
1395         att_server     = &eatt_bearer->att_server;
1396         att_connection = &eatt_bearer->att_connection;
1397         packet_buffer  = eatt_bearer->send_buffer;
1398     } else
1399 #endif
1400     {
1401         hci_connection_t *hci_connection = hci_connection_for_handle(con_handle);
1402         if (hci_connection != NULL) {
1403             att_server     = &hci_connection->att_server;
1404             att_connection = &hci_connection->att_connection;
1405         }
1406     }
1407 
1408     if (att_server == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1409     if (!att_server_can_send_packet(att_server, att_connection)) return BTSTACK_ACL_BUFFERS_FULL;
1410 
1411     if (packet_buffer == NULL){
1412         l2cap_reserve_packet_buffer();
1413         packet_buffer = l2cap_get_outgoing_buffer();
1414     }
1415 
1416     *out_att_connection = att_connection;
1417     *out_att_server = att_server;
1418     *out_packet_buffer = packet_buffer;
1419     return ERROR_CODE_SUCCESS;
1420 }
1421 
1422 uint8_t att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1423     att_server_t * att_server = NULL;
1424     att_connection_t * att_connection = NULL;
1425     uint8_t * packet_buffer = NULL;
1426 
1427     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1428     if (status != ERROR_CODE_SUCCESS){
1429         return status;
1430     }
1431 
1432     uint16_t size = att_prepare_handle_value_notification(att_connection, attribute_handle, value, value_len, packet_buffer);
1433 
1434     return att_server_send_prepared(att_server, att_connection, NULL, size);
1435 }
1436 
1437 /**
1438  * @brief notify client about multiple attribute value changes
1439  * @param con_handle
1440  * @param num_attributes
1441  * @param attribute_handles[]
1442  * @param values_data[]
1443  * @param values_len[]
1444  * @return 0 if ok, error otherwise
1445  */
1446 uint8_t att_server_multiple_notify(hci_con_handle_t con_handle, uint8_t num_attributes,
1447                                    const uint16_t * attribute_handles, const uint8_t ** values_data, const uint16_t * values_len){
1448 
1449     att_server_t * att_server = NULL;
1450     att_connection_t * att_connection = NULL;
1451     uint8_t * packet_buffer = NULL;
1452 
1453     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1454     if (status != ERROR_CODE_SUCCESS){
1455         return status;
1456     }
1457 
1458     uint16_t size = att_prepare_handle_value_multiple_notification(att_connection, num_attributes, attribute_handles, values_data, values_len, packet_buffer);
1459 
1460     return att_server_send_prepared(att_server, att_connection, packet_buffer, size);
1461 }
1462 
1463 uint8_t att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1464 
1465     att_server_t * att_server = NULL;
1466     att_connection_t * att_connection = NULL;
1467     uint8_t * packet_buffer = NULL;
1468 
1469     uint8_t status = att_server_prepare_server_message(con_handle, &att_server, &att_connection, &packet_buffer);
1470     if (status != ERROR_CODE_SUCCESS){
1471         return status;
1472     }
1473 
1474     if (att_server->value_indication_handle != 0u) {
1475         // free reserved packet buffer
1476         if (att_server->bearer_type == ATT_BEARER_ENHANCED_LE){
1477             l2cap_release_packet_buffer();
1478         }
1479         return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1480     }
1481 
1482     // track indication
1483     att_server->value_indication_handle = attribute_handle;
1484     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1485     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1486     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1487 
1488     uint16_t size = att_prepare_handle_value_indication(att_connection, attribute_handle, value, value_len, packet_buffer);
1489 
1490     return att_server_send_prepared(att_server, att_connection, NULL, size);
1491 }
1492 
1493 uint16_t att_server_get_mtu(hci_con_handle_t con_handle){
1494     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
1495     if (!hci_connection) return 0;
1496     att_connection_t * att_connection = &hci_connection->att_connection;
1497     return att_connection->mtu;
1498 }
1499 
1500 void att_server_deinit(void){
1501     att_server_client_read_callback  = NULL;
1502     att_server_client_write_callback = NULL;
1503     att_client_packet_handler = NULL;
1504     service_handlers = NULL;
1505     att_server_flags = 0;
1506 }
1507 
1508 #ifdef ENABLE_GATT_OVER_EATT
1509 
1510 #define MAX_NR_EATT_CHANNELS 5
1511 
1512 static uint16_t att_server_eatt_receive_buffer_size;
1513 static uint16_t att_server_eatt_send_buffer_size;
1514 
1515 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_cid(uint16_t cid){
1516     btstack_linked_list_iterator_t it;
1517     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1518     while(btstack_linked_list_iterator_has_next(&it)){
1519         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1520         if (eatt_bearer->att_server.l2cap_cid == cid) {
1521             return eatt_bearer;
1522         }
1523     }
1524     return NULL;
1525 }
1526 
1527 static att_server_eatt_bearer_t * att_server_eatt_bearer_for_con_handle(hci_con_handle_t con_handle){
1528     btstack_linked_list_iterator_t it;
1529     btstack_linked_list_iterator_init(&it, &att_server_eatt_bearer_active);
1530     while(btstack_linked_list_iterator_has_next(&it)){
1531         att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) btstack_linked_list_iterator_next(&it);
1532         if (eatt_bearer->att_connection.con_handle == con_handle) {
1533             return eatt_bearer;
1534         }
1535     }
1536     return NULL;
1537 }
1538 
1539 static void att_server_eatt_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1540     uint16_t cid;
1541     uint8_t status;
1542     uint16_t remote_mtu;
1543 
1544     uint8_t i;
1545     uint8_t num_requested_bearers;
1546     uint8_t num_accepted_bearers;
1547     uint16_t initial_credits = L2CAP_LE_AUTOMATIC_CREDITS;
1548     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
1549     uint16_t cids[MAX_NR_EATT_CHANNELS];
1550     att_server_eatt_bearer_t * eatt_bearers[MAX_NR_EATT_CHANNELS];
1551     att_server_eatt_bearer_t * eatt_bearer;
1552     att_server_t * att_server;
1553     att_connection_t * att_connection;
1554     hci_con_handle_t con_handle;
1555     hci_connection_t * hci_connection;
1556 
1557     switch (packet_type) {
1558 
1559         case L2CAP_DATA_PACKET:
1560             eatt_bearer = att_server_eatt_bearer_for_cid(channel);
1561             btstack_assert(eatt_bearer != NULL);
1562             att_server = &eatt_bearer->att_server;
1563             att_connection = &eatt_bearer->att_connection;
1564             att_server_handle_att_pdu(att_server, att_connection, packet, size);
1565             break;
1566 
1567         case HCI_EVENT_PACKET:
1568             switch (packet[0]) {
1569 
1570                 case L2CAP_EVENT_CAN_SEND_NOW:
1571                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1572                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1573                     btstack_assert(eatt_bearer != NULL);
1574                     att_server = &eatt_bearer->att_server;
1575                     att_connection = &eatt_bearer->att_connection;
1576                     // only used for EATT request responses
1577                     btstack_assert(att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED);
1578                     att_server_process_validated_request(att_server, att_connection, eatt_bearer->send_buffer);
1579                     break;
1580 
1581                 case L2CAP_EVENT_PACKET_SENT:
1582                     cid = l2cap_event_packet_sent_get_local_cid(packet);
1583                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1584                     btstack_assert(eatt_bearer != NULL);
1585                     att_server = &eatt_bearer->att_server;
1586                     att_connection = &eatt_bearer->att_connection;
1587                     att_server_handle_att_pdu(att_server, att_connection, packet, size);
1588                     break;
1589 
1590                 case L2CAP_EVENT_ECBM_INCOMING_CONNECTION:
1591                     cid = l2cap_event_ecbm_incoming_connection_get_local_cid(packet);
1592 
1593                     // reject if outgoing l2cap connection active, L2CAP/TIM/BV-01-C
1594                     con_handle = l2cap_event_ecbm_incoming_connection_get_handle(packet);
1595                     hci_connection = hci_connection_for_handle(con_handle);
1596                     btstack_assert(hci_connection != NULL);
1597                     if (hci_connection->att_server.eatt_outgoing_active) {
1598                         hci_connection->att_server.incoming_connection_request = true;
1599                         l2cap_ecbm_decline_channels(cid, L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE );
1600                         log_info("Decline incoming connection from %s", bd_addr_to_str(hci_connection->address));
1601                     } else {
1602                         num_requested_bearers = l2cap_event_ecbm_incoming_connection_get_num_channels(packet);
1603                         for (i = 0; i < num_requested_bearers; i++){
1604                             eatt_bearers[i] = (att_server_eatt_bearer_t *) btstack_linked_list_pop(&att_server_eatt_bearer_pool);
1605                             if (eatt_bearers[i] == NULL) {
1606                                 break;
1607                             }
1608                             eatt_bearers[i]->att_connection.con_handle = l2cap_event_ecbm_incoming_connection_get_handle(packet);
1609                             eatt_bearers[i]->att_server.bearer_type = ATT_BEARER_ENHANCED_LE;
1610                             receive_buffers[i] = eatt_bearers[i]->receive_buffer;
1611                             btstack_linked_list_add(&att_server_eatt_bearer_active, (btstack_linked_item_t *) eatt_bearers[i]);
1612                         }
1613                         num_accepted_bearers = i;
1614                         status = l2cap_ecbm_accept_channels(cid, num_accepted_bearers, initial_credits, att_server_eatt_receive_buffer_size, receive_buffers, cids);
1615                         btstack_assert(status == ERROR_CODE_SUCCESS);
1616                         log_info("requested %u, accepted %u", num_requested_bearers, num_accepted_bearers);
1617                         for (i=0;i<num_accepted_bearers;i++){
1618                             log_info("eatt l2cap cid: 0x%04x", cids[i]);
1619                             eatt_bearers[i]->att_server.l2cap_cid = cids[i];
1620                         }
1621                     }
1622                     break;
1623 
1624                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
1625                     cid         = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
1626                     status      = l2cap_event_ecbm_channel_opened_get_status(packet);
1627                     remote_mtu  = l2cap_event_ecbm_channel_opened_get_remote_mtu(packet);
1628                     eatt_bearer = att_server_eatt_bearer_for_cid(cid);
1629                     btstack_assert(eatt_bearer != NULL);
1630                     eatt_bearer->att_connection.mtu_exchanged = true;
1631                     eatt_bearer->att_connection.mtu = remote_mtu;
1632                     eatt_bearer->att_connection.max_mtu = remote_mtu;
1633                     log_info("L2CAP_EVENT_ECBM_CHANNEL_OPENED - cid 0x%04x mtu %u, status 0x%02x", cid, remote_mtu, status);
1634                     break;
1635 
1636                 case L2CAP_EVENT_ECBM_RECONFIGURED:
1637                     break;
1638 
1639                 case L2CAP_EVENT_CHANNEL_CLOSED:
1640                     eatt_bearer = att_server_eatt_bearer_for_cid(l2cap_event_channel_closed_get_local_cid(packet));
1641                     btstack_assert(eatt_bearers != NULL);
1642 
1643                     // TODO: finalize - abort queued writes
1644 
1645                     btstack_linked_list_remove(&att_server_eatt_bearer_active, (btstack_linked_item_t  *) eatt_bearer);
1646                     btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t  *) eatt_bearer);
1647                     break;
1648                 default:
1649                     break;
1650             }
1651             break;
1652         default:
1653             btstack_unreachable();
1654             break;
1655     }
1656 }
1657 
1658 // create eatt bearers
1659 uint8_t att_server_eatt_init(uint8_t num_eatt_bearers, uint8_t * storage_buffer, uint16_t storage_size){
1660     uint16_t size_for_structs = num_eatt_bearers * sizeof(att_server_eatt_bearer_t);
1661     if (storage_size < size_for_structs) {
1662         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1663     }
1664 
1665     // TODO: The minimum ATT_MTU for an Enhanced ATT bearer is 64 octets.
1666 
1667     memset(storage_buffer, 0, storage_size);
1668     uint16_t buffer_size_per_bearer = ((storage_size - size_for_structs) / num_eatt_bearers);
1669     att_server_eatt_receive_buffer_size = buffer_size_per_bearer / 2;
1670     att_server_eatt_send_buffer_size    = buffer_size_per_bearer / 2;
1671     uint8_t * bearer_buffer = &storage_buffer[size_for_structs];
1672     uint8_t i;
1673     att_server_eatt_bearer_t * eatt_bearer = (att_server_eatt_bearer_t *) storage_buffer;
1674     log_info("%u EATT bearers with receive buffer size %u",
1675              num_eatt_bearers, att_server_eatt_receive_buffer_size);
1676     for (i=0;i<num_eatt_bearers;i++){
1677         eatt_bearer->att_connection.con_handle = HCI_CON_HANDLE_INVALID;
1678         eatt_bearer->receive_buffer = bearer_buffer;
1679         bearer_buffer += att_server_eatt_receive_buffer_size;
1680         eatt_bearer->send_buffer = bearer_buffer;
1681         bearer_buffer += att_server_eatt_send_buffer_size;
1682         btstack_linked_list_add(&att_server_eatt_bearer_pool, (btstack_linked_item_t *) eatt_bearer);
1683         eatt_bearer++;
1684     }
1685     // TODO: define minimum EATT MTU
1686     l2cap_ecbm_register_service(att_server_eatt_handler, BLUETOOTH_PSM_EATT, 64, 0, false);
1687 
1688     return 0;
1689 }
1690 #endif
1691