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