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