xref: /btstack/src/ble/att_server.c (revision 36de8547547b23bfc12dbd2fab0b6fd04f548911)
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 MATTHIAS
24  * RINGWALD 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 "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 #endif
69 
70 #ifndef NVN_NUM_GATT_SERVER_CCC
71 #define NVN_NUM_GATT_SERVER_CCC 20
72 #endif
73 
74 static void att_run_for_context(att_server_t * att_server);
75 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
76 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle);
77 static void att_server_handle_can_send_now(void);
78 static void att_server_persistent_ccc_restore(att_server_t * att_server);
79 static void att_server_persistent_ccc_clear(att_server_t * att_server);
80 static void att_server_handle_att_pdu(att_server_t * att_server, uint8_t * packet, uint16_t size);
81 
82 typedef enum {
83     ATT_SERVER_RUN_PHASE_1_REQUESTS,
84     ATT_SERVER_RUN_PHASE_2_INDICATIONS,
85     ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS,
86 } att_server_run_phase_t;
87 
88 //
89 typedef struct {
90     uint32_t seq_nr;
91     uint16_t att_handle;
92     uint8_t  value;
93     uint8_t  device_index;
94 } persistent_ccc_entry_t;
95 
96 // global
97 static btstack_packet_callback_registration_t hci_event_callback_registration;
98 static btstack_packet_callback_registration_t sm_event_callback_registration;
99 static btstack_packet_handler_t               att_client_packet_handler = NULL;
100 static btstack_linked_list_t                  service_handlers;
101 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration;
102 
103 static att_read_callback_t                    att_server_client_read_callback;
104 static att_write_callback_t                   att_server_client_write_callback;
105 
106 // round robin
107 static hci_con_handle_t att_server_last_can_send_now = HCI_CON_HANDLE_INVALID;
108 
109 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
110     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
111     if (!hci_connection) return NULL;
112     return &hci_connection->att_server;
113 }
114 
115 #ifdef ENABLE_GATT_OVER_CLASSIC
116 static att_server_t * att_server_for_l2cap_cid(uint16_t l2cap_cid){
117     btstack_linked_list_iterator_t it;
118     hci_connections_get_iterator(&it);
119     while(btstack_linked_list_iterator_has_next(&it)){
120         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
121         att_server_t * att_server = &connection->att_server;
122         if (att_server->l2cap_cid == l2cap_cid) return att_server;
123     }
124     return NULL;
125 }
126 #endif
127 
128 #ifdef ENABLE_LE_SIGNED_WRITE
129 static att_server_t * att_server_for_state(att_server_state_t state){
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 * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
134         att_server_t * att_server = &connection->att_server;
135         if (att_server->state == state) return att_server;
136     }
137     return NULL;
138 }
139 #endif
140 
141 static void att_server_request_can_send_now(att_server_t * att_server){
142 #ifdef ENABLE_GATT_OVER_CLASSIC
143     if (att_server->l2cap_cid != 0){
144         l2cap_request_can_send_now_event(att_server->l2cap_cid);
145         return;
146     }
147 #endif
148     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
149 }
150 
151 static int att_server_can_send_packet(att_server_t * att_server){
152 #ifdef ENABLE_GATT_OVER_CLASSIC
153     if (att_server->l2cap_cid != 0){
154         return l2cap_can_send_packet_now(att_server->l2cap_cid);
155     }
156 #endif
157     return att_dispatch_server_can_send_now(att_server->connection.con_handle);
158 }
159 
160 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
161     btstack_packet_handler_t packet_handler = att_server_packet_handler_for_handle(attribute_handle);
162     if (!packet_handler) return;
163 
164     uint8_t event[7];
165     int pos = 0;
166     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
167     event[pos++] = sizeof(event) - 2;
168     event[pos++] = status;
169     little_endian_store_16(event, pos, client_handle);
170     pos += 2;
171     little_endian_store_16(event, pos, attribute_handle);
172     (*packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
173 }
174 
175 static void att_emit_event_to_all(const uint8_t * event, uint16_t size){
176     // dispatch to app level handler
177     if (att_client_packet_handler){
178         (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
179     }
180 
181     // dispatch to service handlers
182     btstack_linked_list_iterator_t it;
183     btstack_linked_list_iterator_init(&it, &service_handlers);
184     while (btstack_linked_list_iterator_has_next(&it)){
185         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
186         if (!handler->packet_handler) continue;
187         (*handler->packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t*) event, size);
188     }
189 }
190 
191 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
192     uint8_t event[6];
193     int pos = 0;
194     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
195     event[pos++] = sizeof(event) - 2;
196     little_endian_store_16(event, pos, con_handle);
197     pos += 2;
198     little_endian_store_16(event, pos, mtu);
199 
200     // also dispatch to GATT Clients
201     att_dispatch_server_mtu_exchanged(con_handle, mtu);
202 
203     // dispatch to app level handler and service handlers
204     att_emit_event_to_all(&event[0], sizeof(event));
205 }
206 
207 static void att_emit_can_send_now_event(void * context){
208     UNUSED(context);
209     if (!att_client_packet_handler) return;
210 
211     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
212     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
213 }
214 
215 static void att_emit_connected_event(att_server_t * att_server){
216     uint8_t event[11];
217     int pos = 0;
218     event[pos++] = ATT_EVENT_CONNECTED;
219     event[pos++] = sizeof(event) - 2;
220     event[pos++] = att_server->peer_addr_type;
221     reverse_bd_addr(att_server->peer_address, &event[pos]);
222     pos += 6;
223     little_endian_store_16(event, pos, att_server->connection.con_handle);
224     pos += 2;
225 
226     // dispatch to app level handler and service handlers
227     att_emit_event_to_all(&event[0], sizeof(event));
228 }
229 
230 
231 static void att_emit_disconnected_event(uint16_t con_handle){
232     uint8_t event[4];
233     int pos = 0;
234     event[pos++] = ATT_EVENT_DISCONNECTED;
235     event[pos++] = sizeof(event) - 2;
236     little_endian_store_16(event, pos, con_handle);
237     pos += 2;
238 
239     // dispatch to app level handler and service handlers
240     att_emit_event_to_all(&event[0], sizeof(event));
241 }
242 
243 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
244     void * context = btstack_run_loop_get_timer_context(ts);
245     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
246     att_server_t * att_server = att_server_for_handle(con_handle);
247     if (!att_server) return;
248     // @note: after a transcation timeout, no more requests shall be sent over this ATT Bearer
249     // (that's why we don't reset the value_indication_handle)
250     uint16_t att_handle = att_server->value_indication_handle;
251     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
252 }
253 
254 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
255 
256     UNUSED(channel); // ok: there is no channel
257     UNUSED(size);    // ok: handling own l2cap events
258 
259     att_server_t * att_server;
260     hci_con_handle_t con_handle;
261 #ifdef ENABLE_GATT_OVER_CLASSIC
262     bd_addr_t address;
263 #endif
264 
265     switch (packet_type) {
266 
267         case HCI_EVENT_PACKET:
268             switch (hci_event_packet_get_type(packet)) {
269 
270 #ifdef ENABLE_GATT_OVER_CLASSIC
271                 case L2CAP_EVENT_INCOMING_CONNECTION:
272                     l2cap_event_incoming_connection_get_address(packet, address);
273                     l2cap_accept_connection(channel);
274                     log_info("Accept incoming connection from %s", bd_addr_to_str(address));
275                     break;
276                 case L2CAP_EVENT_CHANNEL_OPENED:
277                     con_handle = l2cap_event_channel_opened_get_handle(packet);
278                     att_server = att_server_for_handle(con_handle);
279                     if (!att_server) break;
280                     // store connection info
281                     att_server->peer_addr_type = BD_ADDR_TYPE_CLASSIC;
282                     l2cap_event_channel_opened_get_address(packet, att_server->peer_address);
283                     att_server->connection.con_handle = con_handle;
284                     att_server->l2cap_cid = l2cap_event_channel_opened_get_local_cid(packet);
285                     // reset connection properties
286                     att_server->state = ATT_SERVER_IDLE;
287                     att_server->connection.mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
288                     att_server->connection.max_mtu = l2cap_max_mtu();
289                     if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
290                         att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
291                     }
292                     // update security params
293                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
294                     att_server->connection.authenticated = gap_authenticated(con_handle);
295                     att_server->connection.secure_connection = gap_secure_connection(con_handle);
296                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
297                         att_server->connection.encryption_key_size, att_server->connection.authenticated, att_server->connection.secure_connection);
298                     // restore persisten ccc if encrypted
299                     if ( gap_security_level(con_handle) >= LEVEL_2){
300                         att_server_persistent_ccc_restore(att_server);
301                     }
302                     // TODO: what to do about le device db?
303                     att_server->pairing_active = 0;
304                     log_info("Connection opened %s, l2cap cid %04x", bd_addr_to_str(address), att_server->l2cap_cid);
305                     break;
306                 case L2CAP_EVENT_CAN_SEND_NOW:
307                     att_server_handle_can_send_now();
308                     break;
309 
310 #endif
311                 case HCI_EVENT_LE_META:
312                     switch (packet[2]) {
313                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
314                             con_handle = little_endian_read_16(packet, 4);
315                             att_server = att_server_for_handle(con_handle);
316                             if (!att_server) break;
317                         	// store connection info
318                         	att_server->peer_addr_type = packet[7];
319                             reverse_bd_addr(&packet[8], att_server->peer_address);
320                             att_server->connection.con_handle = con_handle;
321                             // reset connection properties
322                             att_server->state = ATT_SERVER_IDLE;
323                             att_server->connection.mtu = ATT_DEFAULT_MTU;
324                             att_server->connection.max_mtu = l2cap_max_le_mtu();
325                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
326                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
327                             }
328                             att_server->connection.encryption_key_size = 0;
329                             att_server->connection.authenticated = 0;
330 		                	att_server->connection.authorized = 0;
331                             // workaround: identity resolving can already be complete, at least store result
332                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
333                             att_server->ir_lookup_active = 0;
334                             att_server->pairing_active = 0;
335                             // notify all - old
336                             att_emit_event_to_all(packet, size);
337                             // notify all - new
338                             att_emit_connected_event(att_server);
339                             break;
340 
341                         default:
342                             break;
343                     }
344                     break;
345 
346                 case HCI_EVENT_ENCRYPTION_CHANGE:
347                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
348                 	// check handle
349                     con_handle = little_endian_read_16(packet, 3);
350                     att_server = att_server_for_handle(con_handle);
351                     if (!att_server) break;
352                     if (gap_get_connection_type(con_handle) != GAP_CONNECTION_LE) break;
353                     // update security params
354                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
355                     att_server->connection.authenticated = gap_authenticated(con_handle);
356                     att_server->connection.secure_connection = gap_secure_connection(con_handle);
357                     log_info("encrypted key size %u, authenticated %u, secure connection %u",
358                         att_server->connection.encryption_key_size, att_server->connection.authenticated, att_server->connection.secure_connection);
359                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
360                         // restore CCC values when encrypted for LE Connections
361                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
362                             att_server_persistent_ccc_restore(att_server);
363                         }
364                     }
365                     att_run_for_context(att_server);
366                     break;
367 
368                 case HCI_EVENT_DISCONNECTION_COMPLETE:
369                     // check handle
370                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
371                     att_server = att_server_for_handle(con_handle);
372                     if (!att_server) break;
373                     att_clear_transaction_queue(&att_server->connection);
374                     att_server->connection.con_handle = 0;
375                     att_server->pairing_active = 0;
376                     att_server->state = ATT_SERVER_IDLE;
377                     if (att_server->value_indication_handle){
378                         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
379                         uint16_t att_handle = att_server->value_indication_handle;
380                         att_server->value_indication_handle = 0; // reset error state
381                         att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_DISCONNECT, att_server->connection.con_handle, att_handle);
382                     }
383                     // notify all - new
384                     att_emit_disconnected_event(con_handle);
385                     // notify all - old
386                     att_emit_event_to_all(packet, size);
387                     break;
388 
389                 // Identity Resolving
390                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
391                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
392                     att_server = att_server_for_handle(con_handle);
393                     if (!att_server) break;
394                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
395                     att_server->ir_lookup_active = 1;
396                     break;
397                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
398                     con_handle = sm_event_identity_created_get_handle(packet);
399                     att_server = att_server_for_handle(con_handle);
400                     if (!att_server) return;
401                     att_server->ir_lookup_active = 0;
402                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
403                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
404                     att_run_for_context(att_server);
405                     break;
406                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
407                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
408                     att_server = att_server_for_handle(con_handle);
409                     if (!att_server) break;
410                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
411                     att_server->ir_lookup_active = 0;
412                     att_server->ir_le_device_db_index = -1;
413                     att_run_for_context(att_server);
414                     break;
415 
416                 // Pairing started - delete stored CCC values
417                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
418                 // - assumes that all events have the con handle as the first field
419                 case SM_EVENT_JUST_WORKS_REQUEST:
420                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
421                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
422                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
423                     con_handle = sm_event_just_works_request_get_handle(packet);
424                     att_server = att_server_for_handle(con_handle);
425                     if (!att_server) break;
426                     att_server->pairing_active = 1;
427                     log_info("SM Pairing started");
428                     if (att_server->ir_le_device_db_index < 0) break;
429                     att_server_persistent_ccc_clear(att_server);
430                     // index not valid anymore
431                     att_server->ir_le_device_db_index = -1;
432                     break;
433 
434                 // Bonding completed
435                 case SM_EVENT_IDENTITY_CREATED:
436                     con_handle = sm_event_identity_created_get_handle(packet);
437                     att_server = att_server_for_handle(con_handle);
438                     if (!att_server) return;
439                     att_server->pairing_active = 0;
440                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
441                     att_run_for_context(att_server);
442                     break;
443 
444                 // Pairing complete (with/without bonding=storing of pairing information)
445                 case SM_EVENT_PAIRING_COMPLETE:
446                     con_handle = sm_event_pairing_complete_get_handle(packet);
447                     att_server = att_server_for_handle(con_handle);
448                     if (!att_server) return;
449                     att_server->pairing_active = 0;
450                     att_run_for_context(att_server);
451                     break;
452 
453                 // Authorization
454                 case SM_EVENT_AUTHORIZATION_RESULT: {
455                     con_handle = sm_event_authorization_result_get_handle(packet);
456                     att_server = att_server_for_handle(con_handle);
457                     if (!att_server) break;
458                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
459                     att_server_request_can_send_now(att_server);
460                 	break;
461                 }
462                 default:
463                     break;
464             }
465             break;
466 #ifdef ENABLE_GATT_OVER_CLASSIC
467         case L2CAP_DATA_PACKET:
468             att_server = att_server_for_l2cap_cid(channel);
469             if (!att_server) break;
470 
471             att_server_handle_att_pdu(att_server, packet, size);
472             break;
473 #endif
474 
475         default:
476             break;
477     }
478 }
479 
480 #ifdef ENABLE_LE_SIGNED_WRITE
481 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
482 
483     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
484     if (!att_server) return;
485 
486     uint8_t hash_flipped[8];
487     reverse_64(hash, hash_flipped);
488     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
489         log_info("ATT Signed Write, invalid signature");
490         att_server->state = ATT_SERVER_IDLE;
491         return;
492     }
493     log_info("ATT Signed Write, valid signature");
494 
495     // update sequence number
496     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
497     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
498     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
499     att_server_request_can_send_now(att_server);
500 }
501 #endif
502 
503 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
504 // pre: can send now
505 // returns: 1 if packet was sent
506 static int att_server_process_validated_request(att_server_t * att_server){
507 
508     l2cap_reserve_packet_buffer();
509     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
510     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
511 
512 #ifdef ENABLE_ATT_DELAYED_RESPONSE
513     if (att_response_size == ATT_READ_RESPONSE_PENDING || att_response_size == ATT_INTERNAL_WRITE_RESPONSE_PENDING){
514         // update state
515         att_server->state = ATT_SERVER_RESPONSE_PENDING;
516 
517         // callback with handle ATT_READ_RESPONSE_PENDING for reads
518         if (att_response_size == ATT_READ_RESPONSE_PENDING){
519             att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
520         }
521 
522         // free reserved buffer
523         l2cap_release_packet_buffer();
524         return 0;
525     }
526 #endif
527 
528     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
529     if ((att_response_size     >= 4)
530     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
531     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
532     && (att_server->connection.authenticated)){
533 
534         switch (gap_authorization_state(att_server->connection.con_handle)){
535             case AUTHORIZATION_UNKNOWN:
536                 l2cap_release_packet_buffer();
537                 sm_request_pairing(att_server->connection.con_handle);
538                 return 0;
539             case AUTHORIZATION_PENDING:
540                 l2cap_release_packet_buffer();
541                 return 0;
542             default:
543                 break;
544         }
545     }
546 
547     att_server->state = ATT_SERVER_IDLE;
548     if (att_response_size == 0) {
549         l2cap_release_packet_buffer();
550         return 0;
551     }
552 
553 #ifdef ENABLE_GATT_OVER_CLASSIC
554     if (att_server->l2cap_cid != 0){
555         l2cap_send_prepared(att_server->l2cap_cid, att_response_size);
556     } else
557 #endif
558     {
559         l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
560     }
561 
562     // notify client about MTU exchange result
563     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
564         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
565     }
566     return 1;
567 }
568 
569 #ifdef ENABLE_ATT_DELAYED_RESPONSE
570 int att_server_response_ready(hci_con_handle_t con_handle){
571     att_server_t * att_server = att_server_for_handle(con_handle);
572     if (!att_server)                                        return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
573     if (att_server->state != ATT_SERVER_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
574 
575     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
576     att_server_request_can_send_now(att_server);
577     return ERROR_CODE_SUCCESS;
578 }
579 #endif
580 
581 static void att_run_for_context(att_server_t * att_server){
582     switch (att_server->state){
583         case ATT_SERVER_REQUEST_RECEIVED:
584 
585 #ifdef ENABLE_GATT_OVER_CLASSIC
586             if (att_server->l2cap_cid != 0){
587                 // ok
588             } else
589 #endif
590             {
591                 // wait until re-encryption as central is complete
592                 if (gap_reconnect_security_setup_active(att_server->connection.con_handle)) break;
593             }
594 
595             // wait until pairing is complete
596             if (att_server->pairing_active) break;
597 
598 #ifdef ENABLE_LE_SIGNED_WRITE
599             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
600                 log_info("ATT Signed Write!");
601                 if (!sm_cmac_ready()) {
602                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
603                     att_server->state = ATT_SERVER_IDLE;
604                     return;
605                 }
606                 if (att_server->request_size < (3 + 12)) {
607                     log_info("ATT Signed Write, request to short. Abort.");
608                     att_server->state = ATT_SERVER_IDLE;
609                     return;
610                 }
611                 if (att_server->ir_lookup_active){
612                     return;
613                 }
614                 if (att_server->ir_le_device_db_index < 0){
615                     log_info("ATT Signed Write, CSRK not available");
616                     att_server->state = ATT_SERVER_IDLE;
617                     return;
618                 }
619 
620                 // check counter
621                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
622                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
623                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
624                 if (counter_packet < counter_db){
625                     log_info("ATT Signed Write, db reports higher counter, abort");
626                     att_server->state = ATT_SERVER_IDLE;
627                     return;
628                 }
629 
630                 // signature is { sequence counter, secure hash }
631                 sm_key_t csrk;
632                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
633                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
634                 log_info("Orig Signature: ");
635                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
636                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
637                 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);
638                 return;
639             }
640 #endif
641             // move on
642             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
643             att_server_request_can_send_now(att_server);
644             break;
645 
646         default:
647             break;
648     }
649 }
650 
651 static int att_server_data_ready_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
652     switch (phase){
653         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
654             return att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
655         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
656              return (!btstack_linked_list_empty(&att_server->indication_requests) && att_server->value_indication_handle == 0);
657         case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
658             return (!btstack_linked_list_empty(&att_server->notification_requests));
659     }
660     // avoid warning
661     return 0;
662 }
663 
664 static void att_server_trigger_send_for_phase(att_server_t * att_server,  att_server_run_phase_t phase){
665     btstack_context_callback_registration_t * client;
666     switch (phase){
667         case ATT_SERVER_RUN_PHASE_1_REQUESTS:
668             att_server_process_validated_request(att_server);
669             break;
670         case ATT_SERVER_RUN_PHASE_2_INDICATIONS:
671             client = (btstack_context_callback_registration_t*) att_server->indication_requests;
672             btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client);
673             client->callback(client->context);
674             break;
675        case ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS:
676             client = (btstack_context_callback_registration_t*) att_server->notification_requests;
677             btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client);
678             client->callback(client->context);
679             break;
680     }
681 }
682 
683 static void att_server_handle_can_send_now(void){
684 
685     hci_con_handle_t last_send_con_handle = HCI_CON_HANDLE_INVALID;
686     att_server_t *   request_att_server   = NULL;
687     int can_send_now = 1;
688     int phase_index;
689 
690     for (phase_index = ATT_SERVER_RUN_PHASE_1_REQUESTS; phase_index <= ATT_SERVER_RUN_PHASE_3_NOTIFICATIONS; phase_index++){
691         att_server_run_phase_t phase = (att_server_run_phase_t) phase_index;
692         hci_con_handle_t skip_connections_until = att_server_last_can_send_now;
693         while (1){
694             btstack_linked_list_iterator_t it;
695             hci_connections_get_iterator(&it);
696             while(btstack_linked_list_iterator_has_next(&it)){
697                 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
698                 att_server_t * att_server = &connection->att_server;
699 
700                 int data_ready = att_server_data_ready_for_phase(att_server, phase);
701 
702                 // log_debug("phase %u, handle 0x%04x, skip until 0x%04x, data ready %u", phase, att_server->connection.con_handle, skip_connections_until, data_ready);
703 
704                 // skip until last sender found (which is also skipped)
705                 if (skip_connections_until != HCI_CON_HANDLE_INVALID){
706                     if (data_ready && request_att_server == NULL){
707                         request_att_server = att_server;
708                     }
709                     if (skip_connections_until == att_server->connection.con_handle){
710                         skip_connections_until = HCI_CON_HANDLE_INVALID;
711                     }
712                     continue;
713                 };
714 
715                 if (data_ready){
716                     if (can_send_now){
717                         att_server_trigger_send_for_phase(att_server, phase);
718                         last_send_con_handle = att_server->connection.con_handle;
719                         can_send_now = att_server_can_send_packet(att_server);
720                         data_ready = att_server_data_ready_for_phase(att_server, phase);
721                         if (data_ready && request_att_server == NULL){
722                             request_att_server = att_server;
723                         }
724                     } else {
725                         request_att_server = att_server;
726                         break;
727                     }
728                 }
729             }
730 
731             // stop skipping (handles disconnect by last send connection)
732             skip_connections_until = HCI_CON_HANDLE_INVALID;
733 
734             // Exit loop, if we cannot send
735             if (!can_send_now) break;
736 
737             // Exit loop, if we can send but there are also no further request
738             if (request_att_server == NULL) break;
739 
740             // Finally, if we still can send and there are requests, just try again
741             request_att_server = NULL;
742         }
743         // update last send con handle for round robin
744         if (last_send_con_handle != HCI_CON_HANDLE_INVALID){
745             att_server_last_can_send_now = last_send_con_handle;
746         }
747     }
748 
749     if (request_att_server == NULL) return;
750     att_server_request_can_send_now(request_att_server);
751 }
752 
753 static void att_server_handle_att_pdu(att_server_t * att_server, uint8_t * packet, uint16_t size){
754 
755     // handle value indication confirms
756     if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
757         btstack_run_loop_remove_timer(&att_server->value_indication_timer);
758         uint16_t att_handle = att_server->value_indication_handle;
759         att_server->value_indication_handle = 0;
760         att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
761         att_server_request_can_send_now(att_server);
762         return;
763     }
764 
765     // directly process command
766     // note: signed write cannot be handled directly as authentication needs to be verified
767     if (packet[0] == ATT_WRITE_COMMAND){
768         att_handle_request(&att_server->connection, packet, size, 0);
769         return;
770     }
771 
772     // check size
773     if (size > sizeof(att_server->request_buffer)) {
774         log_info("drop att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
775         return;
776     }
777 
778 #ifdef ENABLE_LE_SIGNED_WRITE
779     // abort signed write validation if a new request comes in (but finish previous signed write if possible)
780     if (att_server->state == ATT_SERVER_W4_SIGNED_WRITE_VALIDATION){
781         if (packet[0] == ATT_SIGNED_WRITE_COMMAND){
782             log_info("skip new signed write request as previous is in validation");
783             return;
784         } else {
785             log_info("abort signed write validation to process new request");
786             att_server->state = ATT_SERVER_IDLE;
787         }
788     }
789 #endif
790     // last request still in processing?
791     if (att_server->state != ATT_SERVER_IDLE){
792         log_info("skip att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
793         return;
794     }
795 
796     // store request
797     att_server->state = ATT_SERVER_REQUEST_RECEIVED;
798     att_server->request_size = size;
799     memcpy(att_server->request_buffer, packet, size);
800 
801     att_run_for_context(att_server);
802 }
803 
804 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
805     att_server_t * att_server;
806 
807     switch (packet_type){
808         case HCI_EVENT_PACKET:
809             switch (packet[0]){
810                 case L2CAP_EVENT_CAN_SEND_NOW:
811                     att_server_handle_can_send_now();
812                     break;
813                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
814                     // GATT client has negotiated the mtu for this connection
815                     att_server = att_server_for_handle(handle);
816                     if (!att_server) break;
817                     att_server->connection.mtu = little_endian_read_16(packet, 4);
818                     break;
819                 default:
820                     break;
821             }
822             break;
823 
824         case ATT_DATA_PACKET:
825             log_debug("ATT Packet, handle 0x%04x", handle);
826             att_server = att_server_for_handle(handle);
827             if (!att_server) break;
828 
829             att_server_handle_att_pdu(att_server, packet, size);
830             break;
831     }
832 }
833 
834 // ---------------------
835 // persistent CCC writes
836 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
837     return 'B' << 24 | 'T' << 16 | 'C' << 8 | index;
838 }
839 
840 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
841     // lookup att_server instance
842     att_server_t * att_server = att_server_for_handle(con_handle);
843     if (!att_server) return;
844     int le_device_index = att_server->ir_le_device_db_index;
845     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);
846 
847     // check if bonded
848     if (le_device_index < 0) return;
849 
850     // get btstack_tlv
851     const btstack_tlv_t * tlv_impl = NULL;
852     void * tlv_context;
853     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
854     if (!tlv_impl) return;
855 
856     // update ccc tag
857     int index;
858     uint32_t highest_seq_nr = 0;
859     uint32_t lowest_seq_nr = 0;
860     uint32_t tag_for_lowest_seq_nr = 0;
861     uint32_t tag_for_empty = 0;
862     persistent_ccc_entry_t entry;
863     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
864         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
865         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
866 
867         // empty/invalid tag
868         if (len != sizeof(persistent_ccc_entry_t)){
869             tag_for_empty = tag;
870             continue;
871         }
872         // update highest seq nr
873         if (entry.seq_nr > highest_seq_nr){
874             highest_seq_nr = entry.seq_nr;
875         }
876         // find entry with lowest seq nr
877         if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){
878             tag_for_lowest_seq_nr = tag;
879             lowest_seq_nr = entry.seq_nr;
880         }
881 
882         if (entry.device_index != le_device_index) continue;
883         if (entry.att_handle   != att_handle)      continue;
884 
885         // found matching entry
886         if (value){
887             // update
888             if (entry.value == value) {
889                 log_info("CCC Index %u: Up-to-date", index);
890                 return;
891             }
892             entry.value = value;
893             entry.seq_nr = highest_seq_nr + 1;
894             log_info("CCC Index %u: Store", index);
895             tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
896         } else {
897             // delete
898             log_info("CCC Index %u: Delete", index);
899             tlv_impl->delete_tag(tlv_context, tag);
900         }
901         return;
902     }
903 
904     log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
905 
906     if (value == 0){
907         // done
908         return;
909     }
910 
911     uint32_t tag_to_use = 0;
912     if (tag_for_empty){
913         tag_to_use = tag_for_empty;
914     } else if (tag_for_lowest_seq_nr){
915         tag_to_use = tag_for_lowest_seq_nr;
916     } else {
917         // should not happen
918         return;
919     }
920     // store ccc tag
921     entry.seq_nr       = highest_seq_nr + 1;
922     entry.device_index = le_device_index;
923     entry.att_handle   = att_handle;
924     entry.value        = value;
925     tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
926 }
927 
928 static void att_server_persistent_ccc_clear(att_server_t * att_server){
929     if (!att_server) return;
930     int le_device_index = att_server->ir_le_device_db_index;
931     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
932     // check if bonded
933     if (le_device_index < 0) return;
934     // get btstack_tlv
935     const btstack_tlv_t * tlv_impl = NULL;
936     void * tlv_context;
937     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
938     if (!tlv_impl) return;
939     // get all ccc tag
940     int index;
941     persistent_ccc_entry_t entry;
942     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
943         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
944         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
945         if (len != sizeof(persistent_ccc_entry_t)) continue;
946         if (entry.device_index != le_device_index) continue;
947         // delete entry
948         log_info("CCC Index %u: Delete", index);
949         tlv_impl->delete_tag(tlv_context, tag);
950     }
951 }
952 
953 static void att_server_persistent_ccc_restore(att_server_t * att_server){
954     if (!att_server) return;
955     int le_device_index = att_server->ir_le_device_db_index;
956     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
957     // check if bonded
958     if (le_device_index < 0) return;
959     // get btstack_tlv
960     const btstack_tlv_t * tlv_impl = NULL;
961     void * tlv_context;
962     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
963     if (!tlv_impl) return;
964     // get all ccc tag
965     int index;
966     persistent_ccc_entry_t entry;
967     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
968         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
969         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
970         if (len != sizeof(persistent_ccc_entry_t)) continue;
971         if (entry.device_index != le_device_index) continue;
972         // simulate write callback
973         uint16_t attribute_handle = entry.att_handle;
974         uint8_t  value[2];
975         little_endian_store_16(value, 0, entry.value);
976         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
977         if (!callback) continue;
978         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
979         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
980     }
981 }
982 
983 // persistent CCC writes
984 // ---------------------
985 
986 // gatt service management
987 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
988     btstack_linked_list_iterator_t it;
989     btstack_linked_list_iterator_init(&it, &service_handlers);
990     while (btstack_linked_list_iterator_has_next(&it)){
991         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
992         if (handler->start_handle > handle) continue;
993         if (handler->end_handle   < handle) continue;
994         return handler;
995     }
996     return NULL;
997 }
998 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
999     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1000     if (handler) return handler->read_callback;
1001     return att_server_client_read_callback;
1002 }
1003 
1004 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
1005     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1006     if (handler) return handler->write_callback;
1007     return att_server_client_write_callback;
1008 }
1009 
1010 static btstack_packet_handler_t att_server_packet_handler_for_handle(uint16_t handle){
1011     att_service_handler_t * handler = att_service_handler_for_handle(handle);
1012     if (handler) return handler->packet_handler;
1013     return att_client_packet_handler;
1014 }
1015 
1016 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
1017     // notify all callbacks
1018     btstack_linked_list_iterator_t it;
1019     btstack_linked_list_iterator_init(&it, &service_handlers);
1020     while (btstack_linked_list_iterator_has_next(&it)){
1021         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1022         if (!handler->write_callback) continue;
1023         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1024     }
1025     if (!att_server_client_write_callback) return;
1026     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
1027 }
1028 
1029 // returns first reported error or 0
1030 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
1031     btstack_linked_list_iterator_t it;
1032     btstack_linked_list_iterator_init(&it, &service_handlers);
1033     while (btstack_linked_list_iterator_has_next(&it)){
1034         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
1035         if (!handler->write_callback) continue;
1036         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1037         if (error_code) return error_code;
1038     }
1039     if (!att_server_client_write_callback) return 0;
1040     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1041 }
1042 
1043 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){
1044     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
1045     if (!callback) return 0;
1046     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
1047 }
1048 
1049 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){
1050     switch (transaction_mode){
1051         case ATT_TRANSACTION_MODE_VALIDATE:
1052             return att_validate_prepared_write(con_handle);
1053         case ATT_TRANSACTION_MODE_EXECUTE:
1054         case ATT_TRANSACTION_MODE_CANCEL:
1055             att_notify_write_callbacks(con_handle, transaction_mode);
1056             return 0;
1057         default:
1058             break;
1059     }
1060 
1061     // track CCC writes
1062     if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){
1063         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
1064     }
1065 
1066     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
1067     if (!callback) return 0;
1068     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
1069 }
1070 
1071 /**
1072  * @brief register read/write callbacks for specific handle range
1073  * @param att_service_handler_t
1074  */
1075 void att_server_register_service_handler(att_service_handler_t * handler){
1076     if (att_service_handler_for_handle(handler->start_handle) ||
1077         att_service_handler_for_handle(handler->end_handle)){
1078         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
1079         return;
1080     }
1081     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
1082 }
1083 
1084 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
1085 
1086     // store callbacks
1087     att_server_client_read_callback  = read_callback;
1088     att_server_client_write_callback = write_callback;
1089 
1090     // register for HCI Events
1091     hci_event_callback_registration.callback = &att_event_packet_handler;
1092     hci_add_event_handler(&hci_event_callback_registration);
1093 
1094     // register for SM events
1095     sm_event_callback_registration.callback = &att_event_packet_handler;
1096     sm_add_event_handler(&sm_event_callback_registration);
1097 
1098     // and L2CAP ATT Server PDUs
1099     att_dispatch_register_server(att_packet_handler);
1100 
1101 #ifdef ENABLE_GATT_OVER_CLASSIC
1102     // setup l2cap service
1103     l2cap_register_service(&att_event_packet_handler, PSM_ATT, 0xffff, LEVEL_2);
1104 #endif
1105 
1106     att_set_db(db);
1107     att_set_read_callback(att_server_read_callback);
1108     att_set_write_callback(att_server_write_callback);
1109 }
1110 
1111 void att_server_register_packet_handler(btstack_packet_handler_t handler){
1112     att_client_packet_handler = handler;
1113 }
1114 
1115 
1116 // to be deprecated
1117 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
1118     att_server_t * att_server = att_server_for_handle(con_handle);
1119     if (!att_server) return 0;
1120     return att_server_can_send_packet(att_server);
1121 }
1122 
1123 int att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1124     return att_server_request_to_send_notification(callback_registration, con_handle);
1125 }
1126 
1127 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
1128     att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event;
1129     att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle);
1130 }
1131 // end of deprecated
1132 
1133 int att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1134     att_server_t * att_server = att_server_for_handle(con_handle);
1135     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1136     btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration);
1137     att_server_request_can_send_now(att_server);
1138     return ERROR_CODE_SUCCESS;
1139 }
1140 
1141 int att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
1142     att_server_t * att_server = att_server_for_handle(con_handle);
1143     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1144     btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration);
1145     att_server_request_can_send_now(att_server);
1146     return ERROR_CODE_SUCCESS;
1147 }
1148 
1149 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1150     att_server_t * att_server = att_server_for_handle(con_handle);
1151     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1152     if (!att_server_can_send_packet(att_server)) return BTSTACK_ACL_BUFFERS_FULL;
1153 
1154     l2cap_reserve_packet_buffer();
1155     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
1156     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
1157 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
1158 }
1159 
1160 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, const uint8_t *value, uint16_t value_len){
1161     att_server_t * att_server = att_server_for_handle(con_handle);
1162     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1163 
1164     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
1165     if (!att_server_can_send_packet(att_server)) return BTSTACK_ACL_BUFFERS_FULL;
1166 
1167     // track indication
1168     att_server->value_indication_handle = attribute_handle;
1169     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
1170     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
1171     btstack_run_loop_add_timer(&att_server->value_indication_timer);
1172 
1173     l2cap_reserve_packet_buffer();
1174     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
1175     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
1176 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
1177     return 0;
1178 }
1179 
1180 uint16_t att_server_get_mtu(hci_con_handle_t con_handle){
1181     att_server_t * att_server = att_server_for_handle(con_handle);
1182     if (!att_server) return 0;
1183     return att_server->connection.mtu;
1184 }
1185