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