xref: /btstack/src/ble/att_server.c (revision 06e1ef76482a4c9e6c01926f0f9636fff00eff9b)
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 <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "btstack_config.h"
52 
53 #include "att_dispatch.h"
54 #include "ble/att_db.h"
55 #include "ble/att_server.h"
56 #include "ble/core.h"
57 #include "ble/le_device_db.h"
58 #include "ble/sm.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "gap.h"
64 #include "hci.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 #include "btstack_tlv.h"
68 
69 #ifndef NVN_NUM_GATT_SERVER_CCC
70 #define NVN_NUM_GATT_SERVER_CCC 20
71 #endif
72 
73 static void att_run_for_context(att_server_t * att_server);
74 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
75 static void att_server_persistent_ccc_restore(att_server_t * att_server);
76 static void att_server_persistent_ccc_clear(att_server_t * att_server);
77 
78 //
79 typedef struct {
80     uint32_t seq_nr;
81     uint16_t att_handle;
82     uint8_t  value;
83     uint8_t  device_index;
84 } persistent_ccc_entry_t;
85 
86 // global
87 static btstack_packet_callback_registration_t hci_event_callback_registration;
88 static btstack_packet_callback_registration_t sm_event_callback_registration;
89 static btstack_packet_handler_t               att_client_packet_handler = NULL;
90 static btstack_linked_list_t                  can_send_now_clients;
91 static btstack_linked_list_t                  service_handlers;
92 static uint8_t                                att_client_waiting_for_can_send;
93 
94 static att_read_callback_t                    att_server_client_read_callback;
95 static att_write_callback_t                   att_server_client_write_callback;
96 
97 // track CCC 1-entry cache
98 // static att_server_t *    att_persistent_ccc_server;
99 // static hci_con_handle_t  att_persistent_ccc_con_handle;
100 
101 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
102     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
103     if (!hci_connection) return NULL;
104     return &hci_connection->att_server;
105 }
106 
107 #ifdef ENABLE_LE_SIGNED_WRITE
108 static att_server_t * att_server_for_state(att_server_state_t state){
109     btstack_linked_list_iterator_t it;
110     hci_connections_get_iterator(&it);
111     while(btstack_linked_list_iterator_has_next(&it)){
112         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
113         att_server_t * att_server = &connection->att_server;
114         if (att_server->state == state) return att_server;
115     }
116     return NULL;
117 }
118 #endif
119 
120 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
121     if (!att_client_packet_handler) return;
122 
123     uint8_t event[7];
124     int pos = 0;
125     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
126     event[pos++] = sizeof(event) - 2;
127     event[pos++] = status;
128     little_endian_store_16(event, pos, client_handle);
129     pos += 2;
130     little_endian_store_16(event, pos, attribute_handle);
131     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
132 }
133 
134 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
135     if (!att_client_packet_handler) return;
136 
137     uint8_t event[6];
138     int pos = 0;
139     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
140     event[pos++] = sizeof(event) - 2;
141     little_endian_store_16(event, pos, con_handle);
142     pos += 2;
143     little_endian_store_16(event, pos, mtu);
144     att_dispatch_server_mtu_exchanged(con_handle, mtu);
145     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
146 }
147 
148 static void att_emit_can_send_now_event(void){
149     if (!att_client_packet_handler) return;
150 
151     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
152     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
153 }
154 
155 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
156     void * context = btstack_run_loop_get_timer_context(ts);
157     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
158     att_server_t * att_server = att_server_for_handle(con_handle);
159     if (!att_server) return;
160     uint16_t att_handle = att_server->value_indication_handle;
161     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
162 }
163 
164 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
165 
166     UNUSED(channel); // ok: there is no channel
167     UNUSED(size);    // ok: handling own l2cap events
168 
169     att_server_t * att_server;
170     hci_con_handle_t con_handle;
171 
172     switch (packet_type) {
173 
174         case HCI_EVENT_PACKET:
175             switch (hci_event_packet_get_type(packet)) {
176 
177                 case HCI_EVENT_LE_META:
178                     switch (packet[2]) {
179                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
180                             con_handle = little_endian_read_16(packet, 4);
181                             att_server = att_server_for_handle(con_handle);
182                             if (!att_server) break;
183                         	// store connection info
184                         	att_server->peer_addr_type = packet[7];
185                             reverse_bd_addr(&packet[8], att_server->peer_address);
186                             att_server->connection.con_handle = con_handle;
187                             // reset connection properties
188                             att_server->state = ATT_SERVER_IDLE;
189                             att_server->connection.mtu = ATT_DEFAULT_MTU;
190                             att_server->connection.max_mtu = l2cap_max_le_mtu();
191                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
192                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
193                             }
194                             att_server->connection.encryption_key_size = 0;
195                             att_server->connection.authenticated = 0;
196 		                	att_server->connection.authorized = 0;
197                             // workaround: identity resolving can already be complete, at least store result
198                             att_server->ir_le_device_db_index = sm_le_device_index(con_handle);
199                             att_server->pairing_active = 0;
200                             break;
201 
202                         default:
203                             break;
204                     }
205                     break;
206 
207                 case HCI_EVENT_ENCRYPTION_CHANGE:
208                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
209                 	// check handle
210                     con_handle = little_endian_read_16(packet, 3);
211                     att_server = att_server_for_handle(con_handle);
212                     if (!att_server) break;
213                     att_server->connection.encryption_key_size = gap_encryption_key_size(con_handle);
214                     att_server->connection.authenticated = gap_authenticated(con_handle);
215                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
216                         // restore CCC values when encrypted
217                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
218                             att_server_persistent_ccc_restore(att_server);
219                         }
220                     }
221                 	break;
222 
223                 case HCI_EVENT_DISCONNECTION_COMPLETE:
224                     // check handle
225                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
226                     att_server = att_server_for_handle(con_handle);
227                     if (!att_server) break;
228                     att_clear_transaction_queue(&att_server->connection);
229                     att_server->connection.con_handle = 0;
230                     att_server->value_indication_handle = 0; // reset error state
231                     att_server->pairing_active = 0;
232                     att_server->state = ATT_SERVER_IDLE;
233                     break;
234 
235                 // Identity Resolving
236                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
237                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
238                     att_server = att_server_for_handle(con_handle);
239                     if (!att_server) break;
240                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
241                     att_server->ir_lookup_active = 1;
242                     break;
243                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
244                     con_handle = sm_event_identity_created_get_handle(packet);
245                     att_server = att_server_for_handle(con_handle);
246                     if (!att_server) return;
247                     att_server->ir_lookup_active = 0;
248                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index(packet);
249                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED");
250                     att_run_for_context(att_server);
251                     break;
252                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
253                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
254                     att_server = att_server_for_handle(con_handle);
255                     if (!att_server) break;
256                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
257                     att_server->ir_lookup_active = 0;
258                     att_server->ir_le_device_db_index = -1;
259                     att_run_for_context(att_server);
260                     break;
261 
262                 // Pairing started - delete stored CCC values
263                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
264                 // - assumes that all events have the con handle as the first field
265                 case SM_EVENT_JUST_WORKS_REQUEST:
266                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
267                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
268                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
269                     con_handle = sm_event_just_works_request_get_handle(packet);
270                     att_server = att_server_for_handle(con_handle);
271                     if (!att_server) break;
272                     att_server->pairing_active = 1;
273                     log_info("SM Pairing started");
274                     if (att_server->ir_le_device_db_index < 0) break;
275                     att_server_persistent_ccc_clear(att_server);
276                     // index not valid anymore
277                     att_server->ir_le_device_db_index = -1;
278                     break;
279 
280                 // Bonding completed
281                 case SM_EVENT_IDENTITY_CREATED:
282                     con_handle = sm_event_identity_created_get_handle(packet);
283                     att_server = att_server_for_handle(con_handle);
284                     if (!att_server) return;
285                     att_server->pairing_active = 0;
286                     att_server->ir_le_device_db_index = sm_event_identity_created_get_index(packet);
287                     att_run_for_context(att_server);
288                     break;
289 
290                 // Pairing complete (with/without bonding=storing of pairing information)
291                 case SM_EVENT_PAIRING_COMPLETE:
292                     con_handle = sm_event_pairing_complete_get_handle(packet);
293                     att_server = att_server_for_handle(con_handle);
294                     if (!att_server) return;
295                     att_server->pairing_active = 0;
296                     att_run_for_context(att_server);
297                     break;
298 
299                 // Authorization
300                 case SM_EVENT_AUTHORIZATION_RESULT: {
301                     con_handle = sm_event_authorization_result_get_handle(packet);
302                     att_server = att_server_for_handle(con_handle);
303                     if (!att_server) break;
304                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
305                     att_dispatch_server_request_can_send_now_event(con_handle);
306                 	break;
307                 }
308                 default:
309                     break;
310             }
311             break;
312         default:
313             break;
314     }
315 }
316 
317 #ifdef ENABLE_LE_SIGNED_WRITE
318 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
319 
320     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
321     if (!att_server) return;
322 
323     uint8_t hash_flipped[8];
324     reverse_64(hash, hash_flipped);
325     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
326         log_info("ATT Signed Write, invalid signature");
327         att_server->state = ATT_SERVER_IDLE;
328         return;
329     }
330     log_info("ATT Signed Write, valid signature");
331 
332     // update sequence number
333     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
334     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
335     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
336     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
337 }
338 #endif
339 
340 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
341 // pre: can send now
342 // returns: 1 if packet was sent
343 static int att_server_process_validated_request(att_server_t * att_server){
344 
345     l2cap_reserve_packet_buffer();
346     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
347     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
348 
349 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
350     if (att_response_size == ATT_READ_RESPONSE_PENDING){
351         // update state
352         att_server->state = ATT_SERVER_READ_RESPONSE_PENDING;
353 
354         // callback with handle ATT_READ_RESPONSE_PENDING
355         att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0);
356 
357         // free reserved buffer
358         l2cap_release_packet_buffer();
359         return 0;
360     }
361 #endif
362 
363     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
364     if ((att_response_size     >= 4)
365     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
366     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
367     && (att_server->connection.authenticated)){
368 
369         switch (gap_authorization_state(att_server->connection.con_handle)){
370             case AUTHORIZATION_UNKNOWN:
371                 l2cap_release_packet_buffer();
372                 sm_request_pairing(att_server->connection.con_handle);
373                 return 0;
374             case AUTHORIZATION_PENDING:
375                 l2cap_release_packet_buffer();
376                 return 0;
377             default:
378                 break;
379         }
380     }
381 
382     att_server->state = ATT_SERVER_IDLE;
383     if (att_response_size == 0) {
384         l2cap_release_packet_buffer();
385         return 0;
386     }
387 
388     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
389 
390     // notify client about MTU exchange result
391     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
392         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
393     }
394     return 1;
395 }
396 
397 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
398 int att_server_read_response_ready(hci_con_handle_t con_handle){
399     att_server_t * att_server = att_server_for_handle(con_handle);
400     if (!att_server)                                             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
401     if (att_server->state != ATT_SERVER_READ_RESPONSE_PENDING)   return ERROR_CODE_COMMAND_DISALLOWED;
402 
403     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
404     att_dispatch_server_request_can_send_now_event(con_handle);
405     return ERROR_CODE_SUCCESS;
406 }
407 #endif
408 
409 static void att_run_for_context(att_server_t * att_server){
410     switch (att_server->state){
411         case ATT_SERVER_REQUEST_RECEIVED:
412 
413             // wait until pairing is complete
414             if (att_server->pairing_active) break;
415 
416 #ifdef ENABLE_LE_SIGNED_WRITE
417             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
418                 log_info("ATT Signed Write!");
419                 if (!sm_cmac_ready()) {
420                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
421                     att_server->state = ATT_SERVER_IDLE;
422                     return;
423                 }
424                 if (att_server->request_size < (3 + 12)) {
425                     log_info("ATT Signed Write, request to short. Abort.");
426                     att_server->state = ATT_SERVER_IDLE;
427                     return;
428                 }
429                 if (att_server->ir_lookup_active){
430                     return;
431                 }
432                 if (att_server->ir_le_device_db_index < 0){
433                     log_info("ATT Signed Write, CSRK not available");
434                     att_server->state = ATT_SERVER_IDLE;
435                     return;
436                 }
437 
438                 // check counter
439                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
440                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
441                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
442                 if (counter_packet < counter_db){
443                     log_info("ATT Signed Write, db reports higher counter, abort");
444                     att_server->state = ATT_SERVER_IDLE;
445                     return;
446                 }
447 
448                 // signature is { sequence counter, secure hash }
449                 sm_key_t csrk;
450                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
451                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
452                 log_info("Orig Signature: ");
453                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
454                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
455                 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);
456                 return;
457             }
458 #endif
459             // move on
460             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
461             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
462             break;
463 
464         default:
465             break;
466     }
467 }
468 
469 static void att_server_handle_can_send_now(void){
470 
471     // NOTE: we get l2cap fixed channel instead of con_handle
472 
473     btstack_linked_list_iterator_t it;
474     hci_connections_get_iterator(&it);
475     while(btstack_linked_list_iterator_has_next(&it)){
476         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
477         att_server_t * att_server = &connection->att_server;
478         if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
479             int sent = att_server_process_validated_request(att_server);
480             if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){
481                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
482                 return;
483             }
484         }
485     }
486 
487     while (!btstack_linked_list_empty(&can_send_now_clients)){
488         // handle first client
489         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
490         hci_con_handle_t con_handle = (uintptr_t) client->context;
491         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
492         client->callback(client->context);
493 
494         // request again if needed
495         if (!att_dispatch_server_can_send_now(con_handle)){
496             if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){
497                 att_dispatch_server_request_can_send_now_event(con_handle);
498             }
499             return;
500         }
501     }
502 
503     if (att_client_waiting_for_can_send){
504         att_client_waiting_for_can_send = 0;
505         att_emit_can_send_now_event();
506     }
507 }
508 
509 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
510 
511     att_server_t * att_server;
512 
513     switch (packet_type){
514 
515         case HCI_EVENT_PACKET:
516             switch (packet[0]){
517                 case L2CAP_EVENT_CAN_SEND_NOW:
518                     att_server_handle_can_send_now();
519                     break;
520                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
521                     // GATT client has negotiated the mtu for this connection
522                     att_server = att_server_for_handle(handle);
523                     if (!att_server) break;
524                     att_server->connection.mtu = little_endian_read_16(packet, 4);
525                     break;
526                 default:
527                     break;
528             }
529             break;
530 
531         case ATT_DATA_PACKET:
532             log_debug("ATT Packet, handle 0x%04x", handle);
533             att_server = att_server_for_handle(handle);
534             if (!att_server) break;
535 
536             // handle value indication confirms
537             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
538                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
539                 uint16_t att_handle = att_server->value_indication_handle;
540                 att_server->value_indication_handle = 0;
541                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
542                 return;
543             }
544 
545             // directly process command
546             // note: signed write cannot be handled directly as authentication needs to be verified
547             if (packet[0] == ATT_WRITE_COMMAND){
548                 att_handle_request(&att_server->connection, packet, size, 0);
549                 return;
550             }
551 
552             // check size
553             if (size > sizeof(att_server->request_buffer)) {
554                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
555                 return;
556             }
557 
558             // last request still in processing?
559             if (att_server->state != ATT_SERVER_IDLE){
560                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
561                 return;
562             }
563 
564             // store request
565             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
566             att_server->request_size = size;
567             memcpy(att_server->request_buffer, packet, size);
568 
569             att_run_for_context(att_server);
570             break;
571     }
572 }
573 
574 // ---------------------
575 // persistent CCC writes
576 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
577     return 'B' << 24 | 'T' << 16 | 'C' << 8 | index;
578 }
579 
580 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
581     // lookup att_server instance
582     att_server_t * att_server = att_server_for_handle(con_handle);
583     if (!att_server) return;
584     int le_device_index = att_server->ir_le_device_db_index;
585     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);
586 
587     // check if bonded
588     if (le_device_index < 0) return;
589 
590     // get btstack_tlv
591     const btstack_tlv_t * tlv_impl = NULL;
592     void * tlv_context;
593     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
594     if (!tlv_impl) return;
595 
596     // update ccc tag
597     int index;
598     uint32_t highest_seq_nr = 0;
599     uint32_t lowest_seq_nr = 0;
600     uint32_t tag_for_lowest_seq_nr = 0;
601     uint32_t tag_for_empty = 0;
602     persistent_ccc_entry_t entry;
603     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
604         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
605         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
606 
607         // empty/invalid tag
608         if (len != sizeof(persistent_ccc_entry_t)){
609             tag_for_empty = tag;
610             continue;
611         }
612         // update highest seq nr
613         if (entry.seq_nr > highest_seq_nr){
614             highest_seq_nr = entry.seq_nr;
615         }
616         // find entry with lowest seq nr
617         if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){
618             tag_for_lowest_seq_nr = tag;
619             lowest_seq_nr = entry.seq_nr;
620         }
621 
622         if (entry.device_index != le_device_index) continue;
623         if (entry.att_handle   != att_handle)      continue;
624 
625         // found matching entry
626         if (value){
627             // update
628             if (entry.value == value) {
629                 log_info("CCC Index %u: Up-to-date", index);
630                 return;
631             }
632             entry.value = value;
633             entry.seq_nr = highest_seq_nr + 1;
634             log_info("CCC Index %u: Store", index);
635             tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
636         } else {
637             // delete
638             log_info("CCC Index %u: Delete", index);
639             tlv_impl->delete_tag(tlv_context, tag);
640         }
641         return;
642     }
643 
644     log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr);
645 
646     if (value == 0){
647         // done
648         return;
649     }
650 
651     uint32_t tag_to_use = 0;
652     if (tag_for_empty){
653         tag_to_use = tag_for_empty;
654     } else if (tag_for_lowest_seq_nr){
655         tag_to_use = tag_for_lowest_seq_nr;
656     } else {
657         // should not happen
658         return;
659     }
660     // store ccc tag
661     entry.seq_nr       = highest_seq_nr + 1;
662     entry.device_index = le_device_index;
663     entry.att_handle   = att_handle;
664     entry.value        = value;
665     tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
666 }
667 
668 static void att_server_persistent_ccc_clear(att_server_t * att_server){
669     if (!att_server) return;
670     int le_device_index = att_server->ir_le_device_db_index;
671     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
672     // check if bonded
673     if (le_device_index < 0) return;
674     // get btstack_tlv
675     const btstack_tlv_t * tlv_impl = NULL;
676     void * tlv_context;
677     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
678     if (!tlv_impl) return;
679     // get all ccc tag
680     int index;
681     persistent_ccc_entry_t entry;
682     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
683         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
684         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
685         if (len != sizeof(persistent_ccc_entry_t)) continue;
686         if (entry.device_index != le_device_index) continue;
687         // delete entry
688         log_info("CCC Index %u: Delete", index);
689         tlv_impl->delete_tag(tlv_context, tag);
690     }
691 }
692 
693 static void att_server_persistent_ccc_restore(att_server_t * att_server){
694     if (!att_server) return;
695     int le_device_index = att_server->ir_le_device_db_index;
696     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
697     // check if bonded
698     if (le_device_index < 0) return;
699     // get btstack_tlv
700     const btstack_tlv_t * tlv_impl = NULL;
701     void * tlv_context;
702     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
703     if (!tlv_impl) return;
704     // get all ccc tag
705     int index;
706     persistent_ccc_entry_t entry;
707     for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){
708         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
709         int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t));
710         if (len != sizeof(persistent_ccc_entry_t)) continue;
711         if (entry.device_index != le_device_index) continue;
712         // simulate write callback
713         uint16_t attribute_handle = entry.att_handle;
714         uint8_t  value[2];
715         little_endian_store_16(value, 0, entry.value);
716         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
717         if (!callback) continue;
718         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value );
719         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
720     }
721 }
722 
723 // persistent CCC writes
724 // ---------------------
725 
726 // gatt service management
727 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
728     btstack_linked_list_iterator_t it;
729     btstack_linked_list_iterator_init(&it, &service_handlers);
730     while (btstack_linked_list_iterator_has_next(&it)){
731         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
732         if (handler->start_handle > handle) continue;
733         if (handler->end_handle   < handle) continue;
734         return handler;
735     }
736     return NULL;
737 }
738 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
739     att_service_handler_t * handler = att_service_handler_for_handle(handle);
740     if (handler) return handler->read_callback;
741     return att_server_client_read_callback;
742 }
743 
744 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
745     att_service_handler_t * handler = att_service_handler_for_handle(handle);
746     if (handler) return handler->write_callback;
747     return att_server_client_write_callback;
748 }
749 
750 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
751     // notify all callbacks
752     btstack_linked_list_iterator_t it;
753     btstack_linked_list_iterator_init(&it, &service_handlers);
754     while (btstack_linked_list_iterator_has_next(&it)){
755         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
756         if (!handler->write_callback) continue;
757         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
758     }
759     if (!att_server_client_write_callback) return;
760     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
761 }
762 
763 // returns first reported error or 0
764 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
765     btstack_linked_list_iterator_t it;
766     btstack_linked_list_iterator_init(&it, &service_handlers);
767     while (btstack_linked_list_iterator_has_next(&it)){
768         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
769         if (!handler->write_callback) continue;
770         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
771         if (error_code) return error_code;
772     }
773     if (!att_server_client_write_callback) return 0;
774     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
775 }
776 
777 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){
778     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
779     if (!callback) return 0;
780     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
781 }
782 
783 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){
784     switch (transaction_mode){
785         case ATT_TRANSACTION_MODE_VALIDATE:
786             return att_validate_prepared_write(con_handle);
787         case ATT_TRANSACTION_MODE_EXECUTE:
788         case ATT_TRANSACTION_MODE_CANCEL:
789             att_notify_write_callbacks(con_handle, transaction_mode);
790             return 0;
791         default:
792             break;
793     }
794 
795     // track CCC writes
796     if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){
797         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
798     }
799 
800     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
801     if (!callback) return 0;
802     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
803 }
804 
805 /**
806  * @brief register read/write callbacks for specific handle range
807  * @param att_service_handler_t
808  */
809 void att_server_register_service_handler(att_service_handler_t * handler){
810     if (att_service_handler_for_handle(handler->start_handle) ||
811         att_service_handler_for_handle(handler->end_handle)){
812         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
813         return;
814     }
815     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
816 }
817 
818 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
819 
820     // store callbacks
821     att_server_client_read_callback  = read_callback;
822     att_server_client_write_callback = write_callback;
823 
824     // register for HCI Events
825     hci_event_callback_registration.callback = &att_event_packet_handler;
826     hci_add_event_handler(&hci_event_callback_registration);
827 
828     // register for SM events
829     sm_event_callback_registration.callback = &att_event_packet_handler;
830     sm_add_event_handler(&sm_event_callback_registration);
831 
832     // and L2CAP ATT Server PDUs
833     att_dispatch_register_server(att_packet_handler);
834 
835     att_set_db(db);
836     att_set_read_callback(att_server_read_callback);
837     att_set_write_callback(att_server_write_callback);
838 
839 }
840 
841 void att_server_register_packet_handler(btstack_packet_handler_t handler){
842     att_client_packet_handler = handler;
843 }
844 
845 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
846 	return att_dispatch_server_can_send_now(con_handle);
847 }
848 
849 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
850     log_debug("att_server_request_can_send_now_event 0x%04x", con_handle);
851     att_client_waiting_for_can_send = 1;
852     att_dispatch_server_request_can_send_now_event(con_handle);
853 }
854 
855 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
856     // check if can send already
857     if (att_dispatch_server_can_send_now(con_handle)){
858         callback_registration->callback(callback_registration->context);
859         return;
860     }
861     callback_registration->context = (void*)(uintptr_t) con_handle;
862     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
863     att_dispatch_server_request_can_send_now_event(con_handle);
864 }
865 
866 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
867     att_server_t * att_server = att_server_for_handle(con_handle);
868     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
869 
870     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
871 
872     l2cap_reserve_packet_buffer();
873     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
874     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
875 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
876 }
877 
878 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
879     att_server_t * att_server = att_server_for_handle(con_handle);
880     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
881 
882     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
883     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
884 
885     // track indication
886     att_server->value_indication_handle = attribute_handle;
887     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
888     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
889     btstack_run_loop_add_timer(&att_server->value_indication_timer);
890 
891     l2cap_reserve_packet_buffer();
892     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
893     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
894 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
895     return 0;
896 }
897