xref: /btstack/src/classic/sdp_client.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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__ "sdp_client.c"
39 
40 /*
41  *  sdp_client.c
42  */
43 #include "btstack_config.h"
44 
45 #include "bluetooth_psm.h"
46 #include "bluetooth_sdp.h"
47 #include "btstack_debug.h"
48 #include "btstack_event.h"
49 #include "classic/core.h"
50 #include "classic/sdp_client.h"
51 #include "classic/sdp_server.h"
52 #include "classic/sdp_util.h"
53 #include "hci_cmd.h"
54 #include "l2cap.h"
55 
56 // Types SDP Parser - Data Element stream helper
57 typedef enum {
58     GET_LIST_LENGTH = 1,
59     GET_RECORD_LENGTH,
60     GET_ATTRIBUTE_ID_HEADER_LENGTH,
61     GET_ATTRIBUTE_ID,
62     GET_ATTRIBUTE_VALUE_LENGTH,
63     GET_ATTRIBUTE_VALUE
64 } sdp_parser_state_t;
65 
66 // Types SDP Client
67 typedef enum {
68     INIT, W4_CONNECT, W2_SEND, W4_RESPONSE, QUERY_COMPLETE
69 } sdp_client_state_t;
70 
71 
72 // Prototypes SDP Parser
73 void sdp_parser_init(btstack_packet_handler_t callback);
74 void sdp_parser_handle_chunk(uint8_t * data, uint16_t size);
75 void sdp_parser_handle_done(uint8_t status);
76 void sdp_parser_init_service_attribute_search(void);
77 void sdp_parser_init_service_search(void);
78 void sdp_parser_handle_service_search(uint8_t * data, uint16_t total_count, uint16_t record_handle_count);
79 
80 // Prototypes SDP Client
81 void sdp_client_reset(void);
82 void sdp_client_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
83 static uint16_t sdp_client_setup_service_search_attribute_request(uint8_t * data);
84 #ifdef ENABLE_SDP_EXTRA_QUERIES
85 static uint16_t sdp_client_setup_service_search_request(uint8_t * data);
86 static uint16_t sdp_client_setup_service_attribute_request(uint8_t * data);
87 static void     sdp_client_parse_service_search_response(uint8_t* packet, uint16_t size);
88 static void     sdp_client_parse_service_attribute_response(uint8_t* packet, uint16_t size);
89 #endif
90 
91 static uint8_t des_attributeIDList[] = { 0x35, 0x05, 0x0A, 0x00, 0x00, 0xff, 0xff};  // Attribute: 0x0000 - 0xffff
92 
93 // State DES Parser
94 static de_state_t de_header_state;
95 
96 // State SDP Parser
97 static sdp_parser_state_t  state = GET_LIST_LENGTH;
98 static uint16_t attribute_id = 0;
99 static uint16_t attribute_bytes_received = 0;
100 static uint16_t attribute_bytes_delivered = 0;
101 static uint16_t list_offset = 0;
102 static uint16_t list_size;
103 static uint16_t record_offset = 0;
104 static uint16_t record_size;
105 static uint16_t attribute_value_size;
106 static int record_counter = 0;
107 static btstack_packet_handler_t sdp_parser_callback;
108 
109 // State SDP Client
110 static uint16_t  mtu;
111 static uint16_t  sdp_cid = 0x40;
112 static const uint8_t * service_search_pattern;
113 static const uint8_t * attribute_id_list;
114 static uint16_t  transactionID = 0;
115 static uint8_t   continuationState[16];
116 static uint8_t   continuationStateLen;
117 static sdp_client_state_t sdp_client_state = INIT;
118 static SDP_PDU_ID_t PDU_ID = SDP_Invalid;
119 
120 // Query registration
121 static btstack_linked_list_t sdp_client_query_requests;
122 
123 #ifdef ENABLE_SDP_EXTRA_QUERIES
124 static uint32_t serviceRecordHandle;
125 static uint32_t record_handle;
126 #endif
127 
128 // DES Parser
129 void de_state_init(de_state_t * de_state){
130     de_state->in_state_GET_DE_HEADER_LENGTH = 1;
131     de_state->addon_header_bytes = 0;
132     de_state->de_size = 0;
133     de_state->de_offset = 0;
134 }
135 
136 int de_state_size(uint8_t eventByte, de_state_t *de_state){
137     if (de_state->in_state_GET_DE_HEADER_LENGTH){
138         de_state->addon_header_bytes = de_get_header_size(&eventByte) - 1;
139         de_state->de_size = 0;
140         de_state->de_offset = 0;
141 
142         if (de_state->addon_header_bytes == 0){
143             de_state->de_size = de_get_data_size(&eventByte);
144             if (de_state->de_size == 0) {
145                 log_error("  ERROR: ID size is zero");
146             }
147             // log_info("Data element payload is %d bytes.", de_state->de_size);
148             return 1;
149         }
150         de_state->in_state_GET_DE_HEADER_LENGTH = 0;
151         return 0;
152     }
153 
154     if (de_state->addon_header_bytes > 0){
155         de_state->de_size = (de_state->de_size << 8) | eventByte;
156         de_state->addon_header_bytes--;
157     }
158     if (de_state->addon_header_bytes > 0) return 0;
159     // log_info("Data element payload is %d bytes.", de_state->de_size);
160     de_state->in_state_GET_DE_HEADER_LENGTH = 1;
161     return 1;
162 }
163 
164 // SDP Parser
165 static void sdp_parser_emit_value_byte(uint8_t event_byte){
166     uint8_t event[11];
167     event[0] = SDP_EVENT_QUERY_ATTRIBUTE_VALUE;
168     event[1] = 9;
169     little_endian_store_16(event, 2, record_counter);
170     little_endian_store_16(event, 4, attribute_id);
171     little_endian_store_16(event, 6, attribute_value_size);
172     little_endian_store_16(event, 8, attribute_bytes_delivered);
173     event[10] = event_byte;
174     (*sdp_parser_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
175 }
176 
177 static void sdp_parser_process_byte(uint8_t eventByte){
178     // count all bytes
179     list_offset++;
180     record_offset++;
181 
182     // log_info(" parse BYTE_RECEIVED %02x", eventByte);
183     switch(state){
184         case GET_LIST_LENGTH:
185             if (!de_state_size(eventByte, &de_header_state)) break;
186             list_offset = de_header_state.de_offset;
187             list_size = de_header_state.de_size;
188             // log_info("parser: List offset %u, list size %u", list_offset, list_size);
189 
190             record_counter = 0;
191             state = GET_RECORD_LENGTH;
192             break;
193 
194         case GET_RECORD_LENGTH:
195             // check size
196             if (!de_state_size(eventByte, &de_header_state)) break;
197             // log_info("parser: Record payload is %d bytes.", de_header_state.de_size);
198             record_offset = de_header_state.de_offset;
199             record_size = de_header_state.de_size;
200             state = GET_ATTRIBUTE_ID_HEADER_LENGTH;
201             break;
202 
203         case GET_ATTRIBUTE_ID_HEADER_LENGTH:
204             if (!de_state_size(eventByte, &de_header_state)) break;
205             attribute_id = 0;
206             log_debug("ID data is stored in %d bytes.", (int) de_header_state.de_size);
207             state = GET_ATTRIBUTE_ID;
208             break;
209 
210         case GET_ATTRIBUTE_ID:
211             attribute_id = (attribute_id << 8) | eventByte;
212             de_header_state.de_size--;
213             if (de_header_state.de_size > 0) break;
214             log_debug("parser: Attribute ID: %04x.", attribute_id);
215 
216             state = GET_ATTRIBUTE_VALUE_LENGTH;
217             attribute_bytes_received  = 0;
218             attribute_bytes_delivered = 0;
219             attribute_value_size      = 0;
220             de_state_init(&de_header_state);
221             break;
222 
223         case GET_ATTRIBUTE_VALUE_LENGTH:
224             attribute_bytes_received++;
225             sdp_parser_emit_value_byte(eventByte);
226             attribute_bytes_delivered++;
227             if (!de_state_size(eventByte, &de_header_state)) break;
228 
229             attribute_value_size = de_header_state.de_size + attribute_bytes_received;
230 
231             state = GET_ATTRIBUTE_VALUE;
232             break;
233 
234         case GET_ATTRIBUTE_VALUE:
235             attribute_bytes_received++;
236             sdp_parser_emit_value_byte(eventByte);
237             attribute_bytes_delivered++;
238             // log_debug("paser: attribute_bytes_received %u, attribute_value_size %u", attribute_bytes_received, attribute_value_size);
239 
240             if (attribute_bytes_received < attribute_value_size) break;
241             // log_debug("parser: Record offset %u, record size %u", record_offset, record_size);
242             if (record_offset != record_size){
243                 state = GET_ATTRIBUTE_ID_HEADER_LENGTH;
244                 // log_debug("Get next attribute");
245                 break;
246             }
247             record_offset = 0;
248             // log_debug("parser: List offset %u, list size %u", list_offset, list_size);
249 
250             if ((list_size > 0) && (list_offset != list_size)){
251                 record_counter++;
252                 state = GET_RECORD_LENGTH;
253                 log_debug("parser: END_OF_RECORD");
254                 break;
255             }
256             list_offset = 0;
257             de_state_init(&de_header_state);
258             state = GET_LIST_LENGTH;
259             record_counter = 0;
260             log_debug("parser: END_OF_RECORD & DONE");
261             break;
262         default:
263             break;
264     }
265 }
266 
267 void sdp_parser_init(btstack_packet_handler_t callback){
268     // init
269     sdp_parser_callback = callback;
270     de_state_init(&de_header_state);
271     state = GET_LIST_LENGTH;
272     list_offset = 0;
273     record_offset = 0;
274     record_counter = 0;
275 }
276 
277 void sdp_parser_handle_chunk(uint8_t * data, uint16_t size){
278     int i;
279     for (i=0;i<size;i++){
280         sdp_parser_process_byte(data[i]);
281     }
282 }
283 
284 #ifdef ENABLE_SDP_EXTRA_QUERIES
285 void sdp_parser_init_service_attribute_search(void){
286     // init
287     de_state_init(&de_header_state);
288     state = GET_RECORD_LENGTH;
289     list_offset = 0;
290     record_offset = 0;
291     record_counter = 0;
292 }
293 
294 void sdp_parser_init_service_search(void){
295     record_offset = 0;
296 }
297 
298 void sdp_parser_handle_service_search(uint8_t * data, uint16_t total_count, uint16_t record_handle_count){
299     int i;
300     for (i=0;i<record_handle_count;i++){
301         record_handle = big_endian_read_32(data, i*4);
302         record_counter++;
303         uint8_t event[10];
304         event[0] = SDP_EVENT_QUERY_SERVICE_RECORD_HANDLE;
305         event[1] = 8;
306         little_endian_store_16(event, 2, total_count);
307         little_endian_store_16(event, 4, record_counter);
308         little_endian_store_32(event, 6, record_handle);
309         (*sdp_parser_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
310     }
311 }
312 #endif
313 
314 static void sdp_client_notify_callbacks(void){
315     if (sdp_client_ready() == false) {
316         return;
317     }
318     btstack_context_callback_registration_t * callback = (btstack_context_callback_registration_t*) btstack_linked_list_pop(&sdp_client_query_requests);
319     if (callback == NULL) {
320         return;
321     }
322     (*callback->callback)(callback->context);
323 }
324 
325 void sdp_parser_handle_done(uint8_t status){
326     // reset state
327     sdp_client_state = INIT;
328 
329     // emit query complete event
330     uint8_t event[3];
331     event[0] = SDP_EVENT_QUERY_COMPLETE;
332     event[1] = 1;
333     event[2] = status;
334     (*sdp_parser_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
335 
336     // trigger next query if pending
337     sdp_client_notify_callbacks();
338 }
339 
340 // SDP Client
341 
342 // TODO: inline if not needed (des(des))
343 
344 static void sdp_client_parse_attribute_lists(uint8_t* packet, uint16_t length){
345     sdp_parser_handle_chunk(packet, length);
346 }
347 
348 
349 static void sdp_client_send_request(uint16_t channel){
350 
351     if (sdp_client_state != W2_SEND) return;
352 
353     l2cap_reserve_packet_buffer();
354     uint8_t * data = l2cap_get_outgoing_buffer();
355     uint16_t request_len = 0;
356 
357     switch (PDU_ID){
358 #ifdef ENABLE_SDP_EXTRA_QUERIES
359         case SDP_ServiceSearchResponse:
360             request_len = sdp_client_setup_service_search_request(data);
361             break;
362         case SDP_ServiceAttributeResponse:
363             request_len = sdp_client_setup_service_attribute_request(data);
364             break;
365 #endif
366         case SDP_ServiceSearchAttributeResponse:
367             request_len = sdp_client_setup_service_search_attribute_request(data);
368             break;
369         default:
370             log_error("SDP Client sdp_client_send_request :: PDU ID invalid. %u", PDU_ID);
371             return;
372     }
373 
374     // prevent re-entrance
375     sdp_client_state = W4_RESPONSE;
376     PDU_ID = SDP_Invalid;
377     l2cap_send_prepared(channel, request_len);
378 }
379 
380 
381 static void sdp_client_parse_service_search_attribute_response(uint8_t* packet, uint16_t size){
382 
383     uint16_t offset = 3;
384     if ((offset + 2 + 2) > size) return;  // parameterLength + attributeListByteCount
385     uint16_t parameterLength = big_endian_read_16(packet,offset);
386     offset+=2;
387     if ((offset + parameterLength) > size) return;
388 
389     // AttributeListByteCount <= mtu
390     uint16_t attributeListByteCount = big_endian_read_16(packet,offset);
391     offset+=2;
392     if (attributeListByteCount > mtu){
393         log_error("Error parsing ServiceSearchAttributeResponse: Number of bytes in found attribute list is larger then the MaximumAttributeByteCount.");
394         return;
395     }
396 
397     // AttributeLists
398     if ((offset + attributeListByteCount) > size) return;
399     sdp_client_parse_attribute_lists(packet+offset, attributeListByteCount);
400     offset+=attributeListByteCount;
401 
402     // continuation state len
403     if ((offset + 1) > size) return;
404     continuationStateLen = packet[offset];
405     offset++;
406     if (continuationStateLen > 16){
407         continuationStateLen = 0;
408         log_error("Error parsing ServiceSearchAttributeResponse: Number of bytes in continuation state exceedes 16.");
409         return;
410     }
411 
412     // continuation state
413     if ((offset + continuationStateLen) > size) return;
414     (void)memcpy(continuationState, packet + offset, continuationStateLen);
415     // offset+=continuationStateLen;
416 }
417 
418 void sdp_client_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
419 
420     // uint16_t handle;
421     if (packet_type == L2CAP_DATA_PACKET){
422         if (size < 3) return;
423         uint16_t responseTransactionID = big_endian_read_16(packet,1);
424         if (responseTransactionID != transactionID){
425             log_error("Mismatching transaction ID, expected %u, found %u.", transactionID, responseTransactionID);
426             return;
427         }
428 
429         PDU_ID = (SDP_PDU_ID_t)packet[0];
430         switch (PDU_ID){
431             case SDP_ErrorResponse:
432                 log_error("Received error response with code %u, disconnecting", packet[2]);
433                 l2cap_disconnect(sdp_cid, 0);
434                 return;
435 #ifdef ENABLE_SDP_EXTRA_QUERIES
436             case SDP_ServiceSearchResponse:
437                 sdp_client_parse_service_search_response(packet, size);
438                 break;
439             case SDP_ServiceAttributeResponse:
440                 sdp_client_parse_service_attribute_response(packet, size);
441                 break;
442 #endif
443             case SDP_ServiceSearchAttributeResponse:
444                 sdp_client_parse_service_search_attribute_response(packet, size);
445                 break;
446             default:
447                 log_error("PDU ID %u unexpected/invalid", PDU_ID);
448                 return;
449         }
450 
451         // continuation set or DONE?
452         if (continuationStateLen == 0){
453             log_debug("SDP Client Query DONE! ");
454             sdp_client_state = QUERY_COMPLETE;
455             l2cap_disconnect(sdp_cid, 0);
456             return;
457         }
458         // prepare next request and send
459         sdp_client_state = W2_SEND;
460         l2cap_request_can_send_now_event(sdp_cid);
461         return;
462     }
463 
464     if (packet_type != HCI_EVENT_PACKET) return;
465 
466     switch(hci_event_packet_get_type(packet)){
467         case L2CAP_EVENT_CHANNEL_OPENED:
468             if (sdp_client_state != W4_CONNECT) break;
469             // data: event (8), len(8), status (8), address(48), handle (16), psm (16), local_cid(16), remote_cid (16), local_mtu(16), remote_mtu(16)
470             if (packet[2]) {
471                 log_info("SDP Client Connection failed, status 0x%02x.", packet[2]);
472                 sdp_parser_handle_done(packet[2]);
473                 break;
474             }
475             sdp_cid = channel;
476             mtu = little_endian_read_16(packet, 17);
477             // handle = little_endian_read_16(packet, 9);
478             log_debug("SDP Client Connected, cid %x, mtu %u.", sdp_cid, mtu);
479 
480             sdp_client_state = W2_SEND;
481             l2cap_request_can_send_now_event(sdp_cid);
482             break;
483 
484         case L2CAP_EVENT_CAN_SEND_NOW:
485             if(l2cap_event_can_send_now_get_local_cid(packet) == sdp_cid){
486                 sdp_client_send_request(sdp_cid);
487             }
488             break;
489         case L2CAP_EVENT_CHANNEL_CLOSED: {
490             if (sdp_cid != little_endian_read_16(packet, 2)) {
491                 // log_info("Received L2CAP_EVENT_CHANNEL_CLOSED for cid %x, current cid %x\n",  little_endian_read_16(packet, 2),sdp_cid);
492                 break;
493             }
494             log_info("SDP Client disconnected.");
495             uint8_t status = (sdp_client_state == QUERY_COMPLETE) ? 0 : SDP_QUERY_INCOMPLETE;
496             sdp_parser_handle_done(status);
497             break;
498         }
499         default:
500             break;
501     }
502 }
503 
504 
505 static uint16_t sdp_client_setup_service_search_attribute_request(uint8_t * data){
506 
507     uint16_t offset = 0;
508     transactionID++;
509     // uint8_t SDP_PDU_ID_t.SDP_ServiceSearchRequest;
510     data[offset++] = SDP_ServiceSearchAttributeRequest;
511     // uint16_t transactionID
512     big_endian_store_16(data, offset, transactionID);
513     offset += 2;
514 
515     // param legnth
516     offset += 2;
517 
518     // parameters:
519     //     Service_search_pattern - DES (min 1 UUID, max 12)
520     uint16_t service_search_pattern_len = de_get_len(service_search_pattern);
521     (void)memcpy(data + offset, service_search_pattern,
522                  service_search_pattern_len);
523     offset += service_search_pattern_len;
524 
525     //     MaximumAttributeByteCount - uint16_t  0x0007 - 0xffff -> mtu
526     big_endian_store_16(data, offset, mtu);
527     offset += 2;
528 
529     //     AttibuteIDList
530     uint16_t attribute_id_list_len = de_get_len(attribute_id_list);
531     (void)memcpy(data + offset, attribute_id_list, attribute_id_list_len);
532     offset += attribute_id_list_len;
533 
534     //     ContinuationState - uint8_t number of cont. bytes N<=16
535     data[offset++] = continuationStateLen;
536     //                       - N-bytes previous response from server
537     (void)memcpy(data + offset, continuationState, continuationStateLen);
538     offset += continuationStateLen;
539 
540     // uint16_t paramLength
541     big_endian_store_16(data, 3, offset - 5);
542 
543     return offset;
544 }
545 
546 #ifdef ENABLE_SDP_EXTRA_QUERIES
547 void sdp_client_parse_service_record_handle_list(uint8_t* packet, uint16_t total_count, uint16_t current_count){
548     sdp_parser_handle_service_search(packet, total_count, current_count);
549 }
550 
551 static uint16_t sdp_client_setup_service_search_request(uint8_t * data){
552     uint16_t offset = 0;
553     transactionID++;
554     // uint8_t SDP_PDU_ID_t.SDP_ServiceSearchRequest;
555     data[offset++] = SDP_ServiceSearchRequest;
556     // uint16_t transactionID
557     big_endian_store_16(data, offset, transactionID);
558     offset += 2;
559 
560     // param legnth
561     offset += 2;
562 
563     // parameters:
564     //     Service_search_pattern - DES (min 1 UUID, max 12)
565     uint16_t service_search_pattern_len = de_get_len(service_search_pattern);
566     (void)memcpy(data + offset, service_search_pattern,
567                  service_search_pattern_len);
568     offset += service_search_pattern_len;
569 
570     //     MaximumAttributeByteCount - uint16_t  0x0007 - 0xffff -> mtu
571     big_endian_store_16(data, offset, mtu);
572     offset += 2;
573 
574     //     ContinuationState - uint8_t number of cont. bytes N<=16
575     data[offset++] = continuationStateLen;
576     //                       - N-bytes previous response from server
577     (void)memcpy(data + offset, continuationState, continuationStateLen);
578     offset += continuationStateLen;
579 
580     // uint16_t paramLength
581     big_endian_store_16(data, 3, offset - 5);
582 
583     return offset;
584 }
585 
586 
587 static uint16_t sdp_client_setup_service_attribute_request(uint8_t * data){
588 
589     uint16_t offset = 0;
590     transactionID++;
591     // uint8_t SDP_PDU_ID_t.SDP_ServiceSearchRequest;
592     data[offset++] = SDP_ServiceAttributeRequest;
593     // uint16_t transactionID
594     big_endian_store_16(data, offset, transactionID);
595     offset += 2;
596 
597     // param legnth
598     offset += 2;
599 
600     // parameters:
601     //     ServiceRecordHandle
602     big_endian_store_32(data, offset, serviceRecordHandle);
603     offset += 4;
604 
605     //     MaximumAttributeByteCount - uint16_t  0x0007 - 0xffff -> mtu
606     big_endian_store_16(data, offset, mtu);
607     offset += 2;
608 
609     //     AttibuteIDList
610     uint16_t attribute_id_list_len = de_get_len(attribute_id_list);
611     (void)memcpy(data + offset, attribute_id_list, attribute_id_list_len);
612     offset += attribute_id_list_len;
613 
614     //     ContinuationState - uint8_t number of cont. bytes N<=16
615     data[offset++] = continuationStateLen;
616     //                       - N-bytes previous response from server
617     (void)memcpy(data + offset, continuationState, continuationStateLen);
618     offset += continuationStateLen;
619 
620     // uint16_t paramLength
621     big_endian_store_16(data, 3, offset - 5);
622 
623     return offset;
624 }
625 
626 static void sdp_client_parse_service_search_response(uint8_t* packet, uint16_t size){
627 
628     uint16_t offset = 3;
629     if (offset + 2 + 2 + 2 > size) return;  // parameterLength, totalServiceRecordCount, currentServiceRecordCount
630 
631     uint16_t parameterLength = big_endian_read_16(packet,offset);
632     offset+=2;
633     if (offset + parameterLength > size) return;
634 
635     uint16_t totalServiceRecordCount = big_endian_read_16(packet,offset);
636     offset+=2;
637 
638     uint16_t currentServiceRecordCount = big_endian_read_16(packet,offset);
639     offset+=2;
640     if (currentServiceRecordCount > totalServiceRecordCount){
641         log_error("CurrentServiceRecordCount is larger then TotalServiceRecordCount.");
642         return;
643     }
644 
645     if (offset + currentServiceRecordCount * 4 > size) return;
646     sdp_client_parse_service_record_handle_list(packet+offset, totalServiceRecordCount, currentServiceRecordCount);
647     offset+= currentServiceRecordCount * 4;
648 
649     if (offset + 1 > size) return;
650     continuationStateLen = packet[offset];
651     offset++;
652     if (continuationStateLen > 16){
653         continuationStateLen = 0;
654         log_error("Error parsing ServiceSearchResponse: Number of bytes in continuation state exceedes 16.");
655         return;
656     }
657     if (offset + continuationStateLen > size) return;
658     (void)memcpy(continuationState, packet + offset, continuationStateLen);
659     // offset+=continuationStateLen;
660 }
661 
662 static void sdp_client_parse_service_attribute_response(uint8_t* packet, uint16_t size){
663 
664     uint16_t offset = 3;
665     if (offset + 2 + 2 > size) return;  // parameterLength, attributeListByteCount
666     uint16_t parameterLength = big_endian_read_16(packet,offset);
667     offset+=2;
668     if (offset+parameterLength > size) return;
669 
670     // AttributeListByteCount <= mtu
671     uint16_t attributeListByteCount = big_endian_read_16(packet,offset);
672     offset+=2;
673     if (attributeListByteCount > mtu){
674         log_error("Error parsing ServiceSearchAttributeResponse: Number of bytes in found attribute list is larger then the MaximumAttributeByteCount.");
675         return;
676     }
677 
678     // AttributeLists
679     if (offset+attributeListByteCount > size) return;
680     sdp_client_parse_attribute_lists(packet+offset, attributeListByteCount);
681     offset+=attributeListByteCount;
682 
683     // continuationStateLen
684     if (offset + 1 > size) return;
685     continuationStateLen = packet[offset];
686     offset++;
687     if (continuationStateLen > 16){
688         continuationStateLen = 0;
689         log_error("Error parsing ServiceAttributeResponse: Number of bytes in continuation state exceedes 16.");
690         return;
691     }
692     if (offset + continuationStateLen > size) return;
693     (void)memcpy(continuationState, packet + offset, continuationStateLen);
694     // offset+=continuationStateLen;
695 }
696 #endif
697 
698 // for testing only
699 void sdp_client_reset(void){
700     sdp_client_state = INIT;
701 }
702 
703 // Public API
704 
705 bool sdp_client_ready(void){
706     return sdp_client_state == INIT;
707 }
708 
709 uint8_t sdp_client_register_query_callback(btstack_context_callback_registration_t * callback_registration){
710     bool added = btstack_linked_list_add_tail(&sdp_client_query_requests, (btstack_linked_item_t*) callback_registration);
711     if (!added) return ERROR_CODE_COMMAND_DISALLOWED;
712     sdp_client_notify_callbacks();
713     return ERROR_CODE_SUCCESS;
714 }
715 
716 uint8_t sdp_client_query(btstack_packet_handler_t callback, bd_addr_t remote, const uint8_t * des_service_search_pattern, const uint8_t * des_attribute_id_list){
717     if (!sdp_client_ready()) return SDP_QUERY_BUSY;
718 
719     sdp_parser_init(callback);
720     service_search_pattern = des_service_search_pattern;
721     attribute_id_list = des_attribute_id_list;
722     continuationStateLen = 0;
723     PDU_ID = SDP_ServiceSearchAttributeResponse;
724 
725     sdp_client_state = W4_CONNECT;
726     return l2cap_create_channel(sdp_client_packet_handler, remote, BLUETOOTH_PSM_SDP, l2cap_max_mtu(), NULL);
727 }
728 
729 uint8_t sdp_client_query_uuid16(btstack_packet_handler_t callback, bd_addr_t remote, uint16_t uuid){
730     if (!sdp_client_ready()) return SDP_QUERY_BUSY;
731     return sdp_client_query(callback, remote, sdp_service_search_pattern_for_uuid16(uuid), des_attributeIDList);
732 }
733 
734 uint8_t sdp_client_query_uuid128(btstack_packet_handler_t callback, bd_addr_t remote, const uint8_t* uuid){
735     if (!sdp_client_ready()) return SDP_QUERY_BUSY;
736     return sdp_client_query(callback, remote, sdp_service_search_pattern_for_uuid128(uuid), des_attributeIDList);
737 }
738 
739 #ifdef ENABLE_SDP_EXTRA_QUERIES
740 uint8_t sdp_client_service_attribute_search(btstack_packet_handler_t callback, bd_addr_t remote, uint32_t search_service_record_handle, const uint8_t * des_attribute_id_list){
741     if (!sdp_client_ready()) return SDP_QUERY_BUSY;
742 
743     sdp_parser_init(callback);
744     serviceRecordHandle = search_service_record_handle;
745     attribute_id_list = des_attribute_id_list;
746     continuationStateLen = 0;
747     PDU_ID = SDP_ServiceAttributeResponse;
748 
749     sdp_client_state = W4_CONNECT;
750     l2cap_create_channel(sdp_client_packet_handler, remote, BLUETOOTH_PSM_SDP, l2cap_max_mtu(), NULL);
751     return 0;
752 }
753 
754 uint8_t sdp_client_service_search(btstack_packet_handler_t callback, bd_addr_t remote, const uint8_t * des_service_search_pattern){
755 
756     if (!sdp_client_ready()) return SDP_QUERY_BUSY;
757 
758     sdp_parser_init(callback);
759     service_search_pattern = des_service_search_pattern;
760     continuationStateLen = 0;
761     PDU_ID = SDP_ServiceSearchResponse;
762 
763     sdp_client_state = W4_CONNECT;
764     l2cap_create_channel(sdp_client_packet_handler, remote, BLUETOOTH_PSM_SDP, l2cap_max_mtu(), NULL);
765     return 0;
766 }
767 #endif
768 
769