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