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