xref: /btstack/src/ble/att_server.c (revision f9f2075ceac5e9dc08e9abea437e43d733a3a0ea)
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 
39 //
40 // ATT Server Globals
41 //
42 
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.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 
66 static void att_run_for_context(att_server_t * att_server);
67 
68 // global
69 static btstack_packet_callback_registration_t hci_event_callback_registration;
70 static btstack_packet_callback_registration_t sm_event_callback_registration;
71 static btstack_packet_handler_t               att_client_packet_handler = NULL;
72 static btstack_linked_list_t                  can_send_now_clients;
73 static uint8_t                                att_client_waiting_for_can_send;
74 
75 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
76     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
77     if (!hci_connection) return NULL;
78     return &hci_connection->att_server;
79 }
80 
81 #ifdef ENABLE_LE_SIGNED_WRITE
82 static att_server_t * att_server_for_state(att_server_state_t state){
83     btstack_linked_list_iterator_t it;
84     hci_connections_get_iterator(&it);
85     while(btstack_linked_list_iterator_has_next(&it)){
86         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
87         att_server_t * att_server = &connection->att_server;
88         if (att_server->state == state) return att_server;
89     }
90     return NULL;
91 }
92 #endif
93 
94 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
95     if (!att_client_packet_handler) return;
96 
97     uint8_t event[7];
98     int pos = 0;
99     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
100     event[pos++] = sizeof(event) - 2;
101     event[pos++] = status;
102     little_endian_store_16(event, pos, client_handle);
103     pos += 2;
104     little_endian_store_16(event, pos, attribute_handle);
105     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
106 }
107 
108 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
109     if (!att_client_packet_handler) return;
110 
111     uint8_t event[6];
112     int pos = 0;
113     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
114     event[pos++] = sizeof(event) - 2;
115     little_endian_store_16(event, pos, con_handle);
116     pos += 2;
117     little_endian_store_16(event, pos, mtu);
118     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
119 }
120 
121 static void att_emit_can_send_now_event(void){
122     if (!att_client_packet_handler) return;
123 
124     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
125     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
126 }
127 
128 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
129     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
130     att_server_t * att_server = att_server_for_handle(con_handle);
131     if (!att_server) return;
132     uint16_t att_handle = att_server->value_indication_handle;
133     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
134 }
135 
136 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
137 
138     UNUSED(channel);
139     UNUSED(size);
140 
141     att_server_t * att_server;
142     hci_con_handle_t con_handle;
143 
144     switch (packet_type) {
145 
146         case HCI_EVENT_PACKET:
147             switch (hci_event_packet_get_type(packet)) {
148 
149                 case HCI_EVENT_LE_META:
150                     switch (packet[2]) {
151                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
152                             con_handle = little_endian_read_16(packet, 4);
153                             att_server = att_server_for_handle(con_handle);
154                             if (!att_server) break;
155                         	// store connection info
156                         	att_server->peer_addr_type = packet[7];
157                             reverse_bd_addr(&packet[8], att_server->peer_address);
158                             att_server->connection.con_handle = con_handle;
159                             // reset connection properties
160                             att_server->state = ATT_SERVER_IDLE;
161                             att_server->connection.mtu = ATT_DEFAULT_MTU;
162                             att_server->connection.max_mtu = l2cap_max_le_mtu();
163                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
164                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
165                             }
166                             att_server->connection.encryption_key_size = 0;
167                             att_server->connection.authenticated = 0;
168 		                	att_server->connection.authorized = 0;
169                             att_server->ir_le_device_db_index = -1;
170                             break;
171 
172                         default:
173                             break;
174                     }
175                     break;
176 
177                 case HCI_EVENT_ENCRYPTION_CHANGE:
178                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
179                 	// check handle
180                     con_handle = little_endian_read_16(packet, 3);
181                     att_server = att_server_for_handle(con_handle);
182                     if (!att_server) break;
183                 	att_server->connection.encryption_key_size = sm_encryption_key_size(con_handle);
184                 	att_server->connection.authenticated = sm_authenticated(con_handle);
185                 	break;
186 
187                 case HCI_EVENT_DISCONNECTION_COMPLETE:
188                     // check handle
189                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
190                     att_server = att_server_for_handle(con_handle);
191                     if (!att_server) break;
192                     att_clear_transaction_queue(&att_server->connection);
193                     att_server->connection.con_handle = 0;
194                     att_server->value_indication_handle = 0; // reset error state
195                     att_server->state = ATT_SERVER_IDLE;
196                     break;
197 
198                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
199                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
200                     att_server = att_server_for_handle(con_handle);
201                     if (!att_server) break;
202                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
203                     att_server->ir_lookup_active = 1;
204                     break;
205                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
206                     con_handle = sm_event_identity_resolving_succeeded_get_handle(packet);
207                     att_server = att_server_for_handle(con_handle);
208                     if (!att_server) break;
209                     att_server->ir_lookup_active = 0;
210                     att_server->ir_le_device_db_index = sm_event_identity_resolving_succeeded_get_index_internal(packet);
211                     log_info("SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED id %u", att_server->ir_le_device_db_index);
212                     att_run_for_context(att_server);
213                     break;
214                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
215                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
216                     att_server = att_server_for_handle(con_handle);
217                     if (!att_server) break;
218                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
219                     att_server->ir_lookup_active = 0;
220                     att_server->ir_le_device_db_index = -1;
221                     att_run_for_context(att_server);
222                     break;
223                 case SM_EVENT_AUTHORIZATION_RESULT: {
224                     con_handle = sm_event_authorization_result_get_handle(packet);
225                     att_server = att_server_for_handle(con_handle);
226                     if (!att_server) break;
227                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
228                     att_dispatch_server_request_can_send_now_event(con_handle);
229                 	break;
230                 }
231                 default:
232                     break;
233             }
234             break;
235         default:
236             break;
237     }
238 }
239 
240 #ifdef ENABLE_LE_SIGNED_WRITE
241 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
242 
243     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
244     if (!att_server) return;
245 
246     uint8_t hash_flipped[8];
247     reverse_64(hash, hash_flipped);
248     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
249         log_info("ATT Signed Write, invalid signature");
250         att_server->state = ATT_SERVER_IDLE;
251         return;
252     }
253     log_info("ATT Signed Write, valid signature");
254 
255     // update sequence number
256     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
257     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
258     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
259     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
260 }
261 #endif
262 
263 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
264 // pre: can send now
265 // returns: 1 if packet was sent
266 static int att_server_process_validated_request(att_server_t * att_server){
267 
268     l2cap_reserve_packet_buffer();
269     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
270     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
271 
272     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
273     if ((att_response_size     >= 4)
274     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
275     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
276     && (att_server->connection.authenticated)){
277 
278         switch (sm_authorization_state(att_server->connection.con_handle)){
279             case AUTHORIZATION_UNKNOWN:
280                 l2cap_release_packet_buffer();
281                 sm_request_pairing(att_server->connection.con_handle);
282                 return 0;
283             case AUTHORIZATION_PENDING:
284                 l2cap_release_packet_buffer();
285                 return 0;
286             default:
287                 break;
288         }
289     }
290 
291     att_server->state = ATT_SERVER_IDLE;
292     if (att_response_size == 0) {
293         l2cap_release_packet_buffer();
294         return 0;
295     }
296 
297     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
298 
299     // notify client about MTU exchange result
300     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
301         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
302     }
303     return 1;
304 }
305 
306 static void att_run_for_context(att_server_t * att_server){
307     switch (att_server->state){
308         case ATT_SERVER_REQUEST_RECEIVED:
309 #ifdef ENABLE_LE_SIGNED_WRITE
310             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
311                 log_info("ATT Signed Write!");
312                 if (!sm_cmac_ready()) {
313                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
314                     att_server->state = ATT_SERVER_IDLE;
315                     return;
316                 }
317                 if (att_server->request_size < (3 + 12)) {
318                     log_info("ATT Signed Write, request to short. Abort.");
319                     att_server->state = ATT_SERVER_IDLE;
320                     return;
321                 }
322                 if (att_server->ir_lookup_active){
323                     return;
324                 }
325                 if (att_server->ir_le_device_db_index < 0){
326                     log_info("ATT Signed Write, CSRK not available");
327                     att_server->state = ATT_SERVER_IDLE;
328                     return;
329                 }
330 
331                 // check counter
332                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
333                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
334                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
335                 if (counter_packet < counter_db){
336                     log_info("ATT Signed Write, db reports higher counter, abort");
337                     att_server->state = ATT_SERVER_IDLE;
338                     return;
339                 }
340 
341                 // signature is { sequence counter, secure hash }
342                 sm_key_t csrk;
343                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
344                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
345                 log_info("Orig Signature: ");
346                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
347                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
348                 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);
349                 return;
350             }
351 #endif
352             // move on
353             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
354             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
355             break;
356 
357         default:
358             break;
359     }
360 }
361 
362 static void att_server_handle_can_send_now(void){
363 
364     // NOTE: we get l2cap fixed channel instead of con_handle
365 
366     btstack_linked_list_iterator_t it;
367     hci_connections_get_iterator(&it);
368     while(btstack_linked_list_iterator_has_next(&it)){
369         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
370         att_server_t * att_server = &connection->att_server;
371         if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
372             int sent = att_server_process_validated_request(att_server);
373             if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){
374                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
375                 return;
376             }
377         }
378     }
379 
380     while (!btstack_linked_list_empty(&can_send_now_clients)){
381         // handle first client
382         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
383         hci_con_handle_t con_handle = (uintptr_t) client->context;
384         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
385         client->callback(client->context);
386 
387         // request again if needed
388         if (!att_dispatch_server_can_send_now(con_handle)){
389             if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){
390                 att_dispatch_server_request_can_send_now_event(con_handle);
391             }
392             return;
393         }
394     }
395 
396     if (att_client_waiting_for_can_send){
397         att_client_waiting_for_can_send = 0;
398         att_emit_can_send_now_event();
399     }
400 }
401 
402 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
403 
404     att_server_t * att_server;
405 
406     switch (packet_type){
407 
408         case HCI_EVENT_PACKET:
409             if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break;
410             att_server_handle_can_send_now();
411             break;
412 
413         case ATT_DATA_PACKET:
414             log_info("ATT Packet, handle 0x%04x", handle);
415             att_server = att_server_for_handle(handle);
416             if (!att_server) break;
417 
418             // handle value indication confirms
419             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
420                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
421                 uint16_t att_handle = att_server->value_indication_handle;
422                 att_server->value_indication_handle = 0;
423                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
424                 return;
425             }
426 
427             // directly process command
428             // note: signed write cannot be handled directly as authentication needs to be verified
429             if (packet[0] == ATT_WRITE_COMMAND){
430                 att_handle_request(&att_server->connection, packet, size, 0);
431                 return;
432             }
433 
434             // check size
435             if (size > sizeof(att_server->request_buffer)) {
436                 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));
437                 return;
438             }
439 
440             // last request still in processing?
441             if (att_server->state != ATT_SERVER_IDLE){
442                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
443                 return;
444             }
445 
446             // store request
447             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
448             att_server->request_size = size;
449             memcpy(att_server->request_buffer, packet, size);
450 
451             att_run_for_context(att_server);
452             break;
453     }
454 }
455 
456 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
457 
458     // register for HCI Events
459     hci_event_callback_registration.callback = &att_event_packet_handler;
460     hci_add_event_handler(&hci_event_callback_registration);
461 
462     // register for SM events
463     sm_event_callback_registration.callback = &att_event_packet_handler;
464     sm_add_event_handler(&sm_event_callback_registration);
465 
466     // and L2CAP ATT Server PDUs
467     att_dispatch_register_server(att_packet_handler);
468 
469     att_set_db(db);
470     att_set_read_callback(read_callback);
471     att_set_write_callback(write_callback);
472 
473 }
474 
475 void att_server_register_packet_handler(btstack_packet_handler_t handler){
476     att_client_packet_handler = handler;
477 }
478 
479 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
480 	return att_dispatch_server_can_send_now(con_handle);
481 }
482 
483 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
484     log_debug("att_server_request_can_send_now_event 0x%04x", con_handle);
485     att_client_waiting_for_can_send = 1;
486     att_dispatch_server_request_can_send_now_event(con_handle);
487 }
488 
489 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
490     // check if can send already
491     if (att_dispatch_server_can_send_now(con_handle)){
492         callback_registration->callback(callback_registration->context);
493         return;
494     }
495     callback_registration->context = (void*)(uintptr_t) con_handle;
496     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
497     att_dispatch_server_request_can_send_now_event(con_handle);
498 }
499 
500 
501 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
502     att_server_t * att_server = att_server_for_handle(con_handle);
503     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
504 
505     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
506 
507     l2cap_reserve_packet_buffer();
508     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
509     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
510 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
511 }
512 
513 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
514     att_server_t * att_server = att_server_for_handle(con_handle);
515     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
516 
517     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PORGRESS;
518     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
519 
520     // track indication
521     att_server->value_indication_handle = attribute_handle;
522     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
523     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
524     btstack_run_loop_add_timer(&att_server->value_indication_timer);
525 
526     l2cap_reserve_packet_buffer();
527     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
528     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
529 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
530     return 0;
531 }
532