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