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