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