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