xref: /btstack/src/l2cap.c (revision 5611a760af48d1ce1beea59c7908be73bd2393f1)
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  *  l2cap.c
40  *
41  *  Logical Link Control and Adaption Protocl (L2CAP)
42  *
43  *  Created by Matthias Ringwald on 5/16/09.
44  */
45 
46 #include "l2cap.h"
47 #include "hci.h"
48 #include "hci_dump.h"
49 #include "btstack_debug.h"
50 #include "btstack_memory.h"
51 
52 #include <stdarg.h>
53 #include <string.h>
54 
55 #include <stdio.h>
56 
57 // nr of buffered acl packets in outgoing queue to get max performance
58 #define NR_BUFFERED_ACL_PACKETS 3
59 
60 // used to cache l2cap rejects, echo, and informational requests
61 #define NR_PENDING_SIGNALING_RESPONSES 3
62 
63 // offsets for L2CAP SIGNALING COMMANDS
64 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
65 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
66 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
67 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
68 
69 static void null_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
70 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
71 
72 // used to cache l2cap rejects, echo, and informational requests
73 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
74 static int signaling_responses_pending;
75 
76 static btstack_linked_list_t l2cap_channels;
77 static btstack_linked_list_t l2cap_services;
78 static btstack_linked_list_t l2cap_le_channels;
79 static btstack_linked_list_t l2cap_le_services;
80 static void (*packet_handler) (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
81 
82 static btstack_packet_handler_t attribute_protocol_packet_handler;
83 static btstack_packet_handler_t security_protocol_packet_handler;
84 static btstack_packet_handler_t connectionless_channel_packet_handler;
85 static uint8_t require_security_level2_for_outgoing_sdp;
86 
87 // prototypes
88 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
89 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
90 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
91 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
92 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
93 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
94 
95 
96 void l2cap_init(void){
97     signaling_responses_pending = 0;
98 
99     l2cap_channels = NULL;
100     l2cap_services = NULL;
101     l2cap_le_services = NULL;
102     l2cap_le_channels = NULL;
103 
104     packet_handler = null_packet_handler;
105     attribute_protocol_packet_handler = NULL;
106     security_protocol_packet_handler = NULL;
107     connectionless_channel_packet_handler = NULL;
108 
109     require_security_level2_for_outgoing_sdp = 0;
110 
111     //
112     // register callback with HCI
113     //
114     hci_register_packet_handler(&l2cap_packet_handler);
115     hci_connectable_control(0); // no services yet
116 }
117 
118 
119 /** Register L2CAP packet handlers */
120 static void null_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
121 }
122 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
123     packet_handler = handler;
124 }
125 
126 //  notify client/protocol handler
127 static void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
128     if (channel->packet_handler) {
129         (* (channel->packet_handler))(type, channel->local_cid, data, size);
130     } else {
131         (*packet_handler)(type, channel->local_cid, data, size);
132     }
133 }
134 
135 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
136     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
137              status, bd_addr_to_str(channel->address), channel->handle, channel->psm,
138              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
139     uint8_t event[23];
140     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
141     event[1] = sizeof(event) - 2;
142     event[2] = status;
143     bt_flip_addr(&event[3], channel->address);
144     bt_store_16(event,  9, channel->handle);
145     bt_store_16(event, 11, channel->psm);
146     bt_store_16(event, 13, channel->local_cid);
147     bt_store_16(event, 15, channel->remote_cid);
148     bt_store_16(event, 17, channel->local_mtu);
149     bt_store_16(event, 19, channel->remote_mtu);
150     bt_store_16(event, 21, channel->flush_timeout);
151     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
152     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
153 }
154 
155 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
156     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
157     uint8_t event[4];
158     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
159     event[1] = sizeof(event) - 2;
160     bt_store_16(event, 2, channel->local_cid);
161     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
162     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
163 }
164 
165 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
166     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
167              bd_addr_to_str(channel->address), channel->handle,  channel->psm, channel->local_cid, channel->remote_cid);
168     uint8_t event[16];
169     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
170     event[1] = sizeof(event) - 2;
171     bt_flip_addr(&event[2], channel->address);
172     bt_store_16(event,  8, channel->handle);
173     bt_store_16(event, 10, channel->psm);
174     bt_store_16(event, 12, channel->local_cid);
175     bt_store_16(event, 14, channel->remote_cid);
176     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
177     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
178 }
179 
180 static void l2cap_emit_connection_parameter_update_response(uint16_t handle, uint16_t result){
181     uint8_t event[6];
182     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
183     event[1] = 4;
184     bt_store_16(event, 2, handle);
185     bt_store_16(event, 4, result);
186     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
187     (*packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
188 }
189 
190 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
191     btstack_linked_list_iterator_t it;
192     btstack_linked_list_iterator_init(&it, &l2cap_channels);
193     while (btstack_linked_list_iterator_has_next(&it)){
194         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
195         if ( channel->local_cid == local_cid) {
196             return channel;
197         }
198     }
199     return NULL;
200 }
201 
202 int  l2cap_can_send_packet_now(uint16_t local_cid){
203     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
204     if (!channel) return 0;
205     return hci_can_send_acl_packet_now(channel->handle);
206 }
207 
208 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
209     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
210     if (!channel) return 0;
211     return hci_can_send_prepared_acl_packet_now(channel->handle);
212 }
213 
214 int  l2cap_can_send_fixed_channel_packet_now(uint16_t handle){
215     return hci_can_send_acl_packet_now(handle);
216 }
217 
218 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
219     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
220     if (channel) {
221         return channel->remote_mtu;
222     }
223     return 0;
224 }
225 
226 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
227     btstack_linked_list_iterator_t it;
228     btstack_linked_list_iterator_init(&it, &l2cap_channels);
229     while (btstack_linked_list_iterator_has_next(&it)){
230         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
231         if ( &channel->rtx == ts) {
232             return channel;
233         }
234     }
235     return NULL;
236 }
237 
238 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
239     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
240     if (!ts) return;
241 
242     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
243 
244     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
245     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
246     // notify client
247     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
248 
249     // discard channel
250     // no need to stop timer here, it is removed from list during timer callback
251     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
252     btstack_memory_l2cap_channel_free(channel);
253 }
254 
255 static void l2cap_stop_rtx(l2cap_channel_t * channel){
256     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
257     btstack_run_loop_remove_timer(&channel->rtx);
258 }
259 
260 static void l2cap_start_rtx(l2cap_channel_t * channel){
261     l2cap_stop_rtx(channel);
262     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
263     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
264     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
265     btstack_run_loop_add_timer(&channel->rtx);
266 }
267 
268 static void l2cap_start_ertx(l2cap_channel_t * channel){
269     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
270     l2cap_stop_rtx(channel);
271     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
272     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
273     btstack_run_loop_add_timer(&channel->rtx);
274 }
275 
276 void l2cap_require_security_level_2_for_outgoing_sdp(void){
277     require_security_level2_for_outgoing_sdp = 1;
278 }
279 
280 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
281     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
282 }
283 
284 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
285 
286     if (!hci_can_send_acl_packet_now(handle)){
287         log_info("l2cap_send_signaling_packet, cannot send");
288         return BTSTACK_ACL_BUFFERS_FULL;
289     }
290 
291     // log_info("l2cap_send_signaling_packet type %u", cmd);
292     hci_reserve_packet_buffer();
293     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
294     va_list argptr;
295     va_start(argptr, identifier);
296     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
297     va_end(argptr);
298     // log_info("l2cap_send_signaling_packet con %u!", handle);
299     return hci_send_acl_packet_buffer(len);
300 }
301 
302 #ifdef ENABLE_BLE
303 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
304 
305     if (!hci_can_send_acl_packet_now(handle)){
306         log_info("l2cap_send_signaling_packet, cannot send");
307         return BTSTACK_ACL_BUFFERS_FULL;
308     }
309 
310     // log_info("l2cap_send_signaling_packet type %u", cmd);
311     hci_reserve_packet_buffer();
312     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
313     va_list argptr;
314     va_start(argptr, identifier);
315     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
316     va_end(argptr);
317     // log_info("l2cap_send_signaling_packet con %u!", handle);
318     return hci_send_acl_packet_buffer(len);
319 }
320 #endif
321 
322 uint8_t *l2cap_get_outgoing_buffer(void){
323     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
324 }
325 
326 int l2cap_reserve_packet_buffer(void){
327     return hci_reserve_packet_buffer();
328 }
329 
330 void l2cap_release_packet_buffer(void){
331     hci_release_packet_buffer();
332 }
333 
334 
335 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
336 
337     if (!hci_is_packet_buffer_reserved()){
338         log_error("l2cap_send_prepared called without reserving packet first");
339         return BTSTACK_ACL_BUFFERS_FULL;
340     }
341 
342     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
343     if (!channel) {
344         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
345         return -1;   // TODO: define error
346     }
347 
348     if (!hci_can_send_prepared_acl_packet_now(channel->handle)){
349         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
350         return BTSTACK_ACL_BUFFERS_FULL;
351     }
352 
353     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->handle);
354 
355     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
356 
357     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
358 
359     // 0 - Connection handle : PB=pb : BC=00
360     bt_store_16(acl_buffer, 0, channel->handle | (pb << 12) | (0 << 14));
361     // 2 - ACL length
362     bt_store_16(acl_buffer, 2,  len + 4);
363     // 4 - L2CAP packet length
364     bt_store_16(acl_buffer, 4,  len + 0);
365     // 6 - L2CAP channel DEST
366     bt_store_16(acl_buffer, 6, channel->remote_cid);
367     // send
368     int err = hci_send_acl_packet_buffer(len+8);
369 
370     return err;
371 }
372 
373 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){
374 
375     if (!hci_is_packet_buffer_reserved()){
376         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
377         return BTSTACK_ACL_BUFFERS_FULL;
378     }
379 
380     if (!hci_can_send_prepared_acl_packet_now(handle)){
381         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", handle, cid);
382         return BTSTACK_ACL_BUFFERS_FULL;
383     }
384 
385     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", handle, cid);
386 
387     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
388 
389     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
390 
391     // 0 - Connection handle : PB=pb : BC=00
392     bt_store_16(acl_buffer, 0, handle | (pb << 12) | (0 << 14));
393     // 2 - ACL length
394     bt_store_16(acl_buffer, 2,  len + 4);
395     // 4 - L2CAP packet length
396     bt_store_16(acl_buffer, 4,  len + 0);
397     // 6 - L2CAP channel DEST
398     bt_store_16(acl_buffer, 6, cid);
399     // send
400     int err = hci_send_acl_packet_buffer(len+8);
401 
402     return err;
403 }
404 
405 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
406 
407     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
408     if (!channel) {
409         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
410         return -1;   // TODO: define error
411     }
412 
413     if (len > channel->remote_mtu){
414         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
415         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
416     }
417 
418     if (!hci_can_send_acl_packet_now(channel->handle)){
419         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
420         return BTSTACK_ACL_BUFFERS_FULL;
421     }
422 
423     hci_reserve_packet_buffer();
424     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
425 
426     memcpy(&acl_buffer[8], data, len);
427 
428     return l2cap_send_prepared(local_cid, len);
429 }
430 
431 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){
432 
433     if (!hci_can_send_acl_packet_now(handle)){
434         log_info("l2cap_send cid 0x%02x, cannot send", cid);
435         return BTSTACK_ACL_BUFFERS_FULL;
436     }
437 
438     hci_reserve_packet_buffer();
439     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
440 
441     memcpy(&acl_buffer[8], data, len);
442 
443     return l2cap_send_prepared_connectionless(handle, cid, len);
444 }
445 
446 int l2cap_send_echo_request(uint16_t handle, uint8_t *data, uint16_t len){
447     return l2cap_send_signaling_packet(handle, ECHO_REQUEST, 0x77, len, data);
448 }
449 
450 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
451     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
452 }
453 
454 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
455     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
456 }
457 
458 
459 
460 // MARK: L2CAP_RUN
461 // process outstanding signaling tasks
462 static void l2cap_run(void){
463 
464     // log_info("l2cap_run: entered");
465 
466     // check pending signaling responses
467     while (signaling_responses_pending){
468 
469         hci_con_handle_t handle = signaling_responses[0].handle;
470 
471         if (!hci_can_send_acl_packet_now(handle)) break;
472 
473         uint8_t  sig_id = signaling_responses[0].sig_id;
474         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
475         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
476         uint8_t  response_code = signaling_responses[0].code;
477 
478         // remove first item before sending (to avoid sending response mutliple times)
479         signaling_responses_pending--;
480         int i;
481         for (i=0; i < signaling_responses_pending; i++){
482             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
483         }
484 
485         switch (response_code){
486             case CONNECTION_REQUEST:
487                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
488                 // also disconnect if result is 0x0003 - security blocked
489                 if (result == 0x0003){
490                     hci_disconnect_security_block(handle);
491                 }
492                 break;
493             case ECHO_REQUEST:
494                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
495                 break;
496             case INFORMATION_REQUEST:
497                 switch (infoType){
498                     case 1: { // Connectionless MTU
499                         uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
500                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
501                         break;
502                     }
503                     case 2: { // Extended Features Supported
504                         // extended features request supported, features: fixed channels, unicast connectionless data reception
505                         uint32_t features = 0x280;
506                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
507                         break;
508                     }
509                     case 3: { // Fixed Channels Supported
510                         uint8_t map[8];
511                         memset(map, 0, 8);
512                         map[0] = 0x01;  // L2CAP Signaling Channel (0x01) + Connectionless reception (0x02)
513                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
514                         break;
515                     }
516                     default:
517                         // all other types are not supported
518                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
519                         break;
520                 }
521                 break;
522             case COMMAND_REJECT:
523                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
524 #ifdef ENABLE_BLE
525             case COMMAND_REJECT_LE:
526                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
527                 break;
528 #endif
529             default:
530                 // should not happen
531                 break;
532         }
533     }
534 
535     uint8_t  config_options[4];
536     btstack_linked_list_iterator_t it;
537     btstack_linked_list_iterator_init(&it, &l2cap_channels);
538     while (btstack_linked_list_iterator_has_next(&it)){
539 
540         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
541         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
542         switch (channel->state){
543 
544             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
545             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
546                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
547                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
548                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
549                     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
550                 }
551                 break;
552 
553             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
554                 if (!hci_can_send_command_packet_now()) break;
555                 // send connection request - set state first
556                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
557                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
558                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
559                 break;
560 
561             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
562                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
563                 channel->state = L2CAP_STATE_INVALID;
564                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
565                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
566                 l2cap_stop_rtx(channel);
567                 btstack_linked_list_iterator_remove(&it);
568                 btstack_memory_l2cap_channel_free(channel);
569                 break;
570 
571             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
572                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
573                 channel->state = L2CAP_STATE_CONFIG;
574                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
575                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
576                 break;
577 
578             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
579                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
580                 // success, start l2cap handshake
581                 channel->local_sig_id = l2cap_next_sig_id();
582                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
583                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
584                 l2cap_start_rtx(channel);
585                 break;
586 
587             case L2CAP_STATE_CONFIG:
588                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
589                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
590                     uint16_t flags = 0;
591                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
592                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
593                         flags = 1;
594                     } else {
595                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
596                     }
597                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
598                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
599                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
600                         config_options[0] = 1; // MTU
601                         config_options[1] = 2; // len param
602                         bt_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
603                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
604                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
605                     } else {
606                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
607                     }
608                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
609                 }
610                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
611                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
612                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
613                     channel->local_sig_id = l2cap_next_sig_id();
614                     config_options[0] = 1; // MTU
615                     config_options[1] = 2; // len param
616                     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
617                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
618                     l2cap_start_rtx(channel);
619                 }
620                 if (l2cap_channel_ready_for_open(channel)){
621                     channel->state = L2CAP_STATE_OPEN;
622                     l2cap_emit_channel_opened(channel, 0);  // success
623                 }
624                 break;
625 
626             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
627                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
628                 channel->state = L2CAP_STATE_INVALID;
629                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
630                 // we don't start an RTX timer for a disconnect - there's no point in closing the channel if the other side doesn't respond :)
631                 l2cap_finialize_channel_close(channel);  // -- remove from list
632                 break;
633 
634             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
635                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
636                 channel->local_sig_id = l2cap_next_sig_id();
637                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
638                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
639                 break;
640             default:
641                 break;
642         }
643     }
644 
645 #ifdef ENABLE_BLE
646     // send l2cap con paramter update if necessary
647     hci_connections_get_iterator(&it);
648     while(btstack_linked_list_iterator_has_next(&it)){
649         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
650         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
651         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
652         switch (connection->le_con_parameter_update_state){
653             case CON_PARAMETER_UPDATE_SEND_REQUEST:
654                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
655                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
656                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
657                 break;
658             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
659                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
660                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
661                 break;
662             case CON_PARAMETER_UPDATE_DENY:
663                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
664                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
665                 break;
666             default:
667                 break;
668         }
669     }
670 #endif
671 
672     // log_info("l2cap_run: exit");
673 }
674 
675 uint16_t l2cap_max_mtu(void){
676     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
677 }
678 
679 uint16_t l2cap_max_le_mtu(void){
680     return l2cap_max_mtu();
681 }
682 
683 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){
684     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
685         log_info("l2cap_handle_connection_complete expected state");
686         // success, start l2cap handshake
687         channel->handle = handle;
688         // check remote SSP feature first
689         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
690     }
691 }
692 
693 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
694     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
695 
696     // we have been waiting for remote supported features, if both support SSP,
697     log_info("l2cap received remote supported features, sec_level_0_allowed for psm %u = %u", channel->psm, l2cap_security_level_0_allowed_for_PSM(channel->psm));
698     if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
699         // request security level 2
700         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
701         gap_request_security_level(channel->handle, LEVEL_2);
702         return;
703     }
704     // fine, go ahead
705     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
706 }
707 
708 /**
709  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
710  * @param packet_handler
711  * @param address
712  * @param psm
713  * @param mtu
714  * @param local_cid
715  */
716 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid){
717     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu);
718 
719     // alloc structure
720     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
721     if (!chan) {
722         return BTSTACK_MEMORY_ALLOC_FAILED;
723     }
724 
725      // Init memory (make valgrind happy)
726     memset(chan, 0, sizeof(l2cap_channel_t));
727     // limit local mtu to max acl packet length - l2cap header
728     if (mtu > l2cap_max_mtu()) {
729         mtu = l2cap_max_mtu();
730     }
731 
732     // fill in
733     BD_ADDR_COPY(chan->address, address);
734     chan->psm = psm;
735     chan->handle = 0;
736     chan->packet_handler = channel_packet_handler;
737     chan->remote_mtu = L2CAP_MINIMAL_MTU;
738     chan->local_mtu = mtu;
739     chan->local_cid = l2cap_next_local_cid();
740 
741     // set initial state
742     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
743     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
744     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
745     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
746     chan->required_security_level = LEVEL_0;
747 
748     // add to connections list
749     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) chan);
750 
751     // store local_cid
752     if (out_local_cid){
753        *out_local_cid = chan->local_cid;
754     }
755 
756     // check if hci connection is already usable
757     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
758     if (conn){
759         log_info("l2cap_create_channel, hci connection already exists");
760         l2cap_handle_connection_complete(conn->con_handle, chan);
761         // check if remote supported fearures are already received
762         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
763             l2cap_handle_remote_supported_features_received(chan);
764         }
765     }
766 
767     l2cap_run();
768 
769     return 0;
770 }
771 
772 void
773 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
774     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
775     // find channel for local_cid
776     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
777     if (channel) {
778         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
779     }
780     // process
781     l2cap_run();
782 }
783 
784 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
785     btstack_linked_list_iterator_t it;
786     btstack_linked_list_iterator_init(&it, &l2cap_channels);
787     while (btstack_linked_list_iterator_has_next(&it)){
788         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
789         if ( BD_ADDR_CMP( channel->address, address) != 0) continue;
790         // channel for this address found
791         switch (channel->state){
792             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
793             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
794                 // failure, forward error code
795                 l2cap_emit_channel_opened(channel, status);
796                 // discard channel
797                 l2cap_stop_rtx(channel);
798                 btstack_linked_list_iterator_remove(&it);
799                 btstack_memory_l2cap_channel_free(channel);
800                 break;
801             default:
802                 break;
803         }
804     }
805 }
806 
807 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
808     btstack_linked_list_iterator_t it;
809     btstack_linked_list_iterator_init(&it, &l2cap_channels);
810     while (btstack_linked_list_iterator_has_next(&it)){
811         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
812         if ( ! BD_ADDR_CMP( channel->address, address) ){
813             l2cap_handle_connection_complete(handle, channel);
814         }
815     }
816     // process
817     l2cap_run();
818 }
819 
820 static void l2cap_event_handler(uint8_t *packet, uint16_t size){
821 
822     bd_addr_t address;
823     hci_con_handle_t handle;
824     btstack_linked_list_iterator_t it;
825     int hci_con_used;
826 
827     switch(packet[0]){
828 
829         // handle connection complete events
830         case HCI_EVENT_CONNECTION_COMPLETE:
831             bt_flip_addr(address, &packet[5]);
832             if (packet[2] == 0){
833                 handle = READ_BT_16(packet, 3);
834                 l2cap_handle_connection_success_for_addr(address, handle);
835             } else {
836                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
837             }
838             break;
839 
840         // handle successful create connection cancel command
841         case HCI_EVENT_COMMAND_COMPLETE:
842             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
843                 if (packet[5] == 0){
844                     bt_flip_addr(address, &packet[6]);
845                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
846                     l2cap_handle_connection_failed_for_addr(address, 0x16);
847                 }
848             }
849             l2cap_run();    // try sending signaling packets first
850             break;
851 
852         case HCI_EVENT_COMMAND_STATUS:
853             l2cap_run();    // try sending signaling packets first
854             break;
855 
856         // handle disconnection complete events
857         case HCI_EVENT_DISCONNECTION_COMPLETE:
858             // send l2cap disconnect events for all channels on this handle and free them
859             handle = READ_BT_16(packet, 3);
860             btstack_linked_list_iterator_init(&it, &l2cap_channels);
861             while (btstack_linked_list_iterator_has_next(&it)){
862                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
863                 if (channel->handle != handle) continue;
864                 l2cap_emit_channel_closed(channel);
865                 l2cap_stop_rtx(channel);
866                 btstack_linked_list_iterator_remove(&it);
867                 btstack_memory_l2cap_channel_free(channel);
868             }
869             break;
870 
871         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
872             l2cap_run();    // try sending signaling packets first
873             break;
874 
875         // HCI Connection Timeouts
876         case L2CAP_EVENT_TIMEOUT_CHECK:
877             handle = READ_BT_16(packet, 2);
878             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
879             if (hci_authentication_active_for_handle(handle)) break;
880             hci_con_used = 0;
881             btstack_linked_list_iterator_init(&it, &l2cap_channels);
882             while (btstack_linked_list_iterator_has_next(&it)){
883                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
884                 if (channel->handle != handle) continue;
885                 hci_con_used = 1;
886                 break;
887             }
888             if (hci_con_used) break;
889             if (!hci_can_send_command_packet_now()) break;
890             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
891             break;
892 
893         case DAEMON_EVENT_HCI_PACKET_SENT:
894             l2cap_run();    // try sending signaling packets first
895 
896             btstack_linked_list_iterator_init(&it, &l2cap_channels);
897             while (btstack_linked_list_iterator_has_next(&it)){
898                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
899                 if (!channel->packet_handler) continue;
900                 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
901             }
902             if (attribute_protocol_packet_handler) {
903                 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
904             }
905             if (security_protocol_packet_handler) {
906                 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
907             }
908             if (connectionless_channel_packet_handler) {
909                 (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
910             }
911             break;
912 
913         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
914             handle = READ_BT_16(packet, 3);
915             btstack_linked_list_iterator_init(&it, &l2cap_channels);
916             while (btstack_linked_list_iterator_has_next(&it)){
917                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
918                 if (channel->handle != handle) continue;
919                 l2cap_handle_remote_supported_features_received(channel);
920                 break;
921             }
922             break;
923 
924         case GAP_EVENT_SECURITY_LEVEL:
925             handle = READ_BT_16(packet, 2);
926             log_info("l2cap - security level update");
927             btstack_linked_list_iterator_init(&it, &l2cap_channels);
928             while (btstack_linked_list_iterator_has_next(&it)){
929                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
930                 if (channel->handle != handle) continue;
931 
932                 log_info("l2cap - state %u", channel->state);
933 
934                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
935                 gap_security_level_t required_level = channel->required_security_level;
936 
937                 switch (channel->state){
938                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
939                         if (actual_level >= required_level){
940                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
941                             l2cap_emit_connection_request(channel);
942                         } else {
943                             channel->reason = 0x0003; // security block
944                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
945                         }
946                         break;
947 
948                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
949                         if (actual_level >= required_level){
950                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
951                         } else {
952                             // disconnnect, authentication not good enough
953                             hci_disconnect_security_block(handle);
954                         }
955                         break;
956 
957                     default:
958                         break;
959                 }
960             }
961             break;
962 
963         default:
964             break;
965     }
966 
967     // pass on: main packet handler, att and sm packet handlers
968     (*packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
969     if (attribute_protocol_packet_handler){
970         (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
971     }
972     if (security_protocol_packet_handler) {
973         (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
974     }
975     if (connectionless_channel_packet_handler) {
976         (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
977     }
978 
979     l2cap_run();
980 }
981 
982 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
983     channel->remote_sig_id = identifier;
984     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
985     l2cap_run();
986 }
987 
988 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
989     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
990     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
991         signaling_responses[signaling_responses_pending].handle = handle;
992         signaling_responses[signaling_responses_pending].code = code;
993         signaling_responses[signaling_responses_pending].sig_id = sig_id;
994         signaling_responses[signaling_responses_pending].data = data;
995         signaling_responses_pending++;
996         l2cap_run();
997     }
998 }
999 
1000 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1001 
1002     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1003     l2cap_service_t *service = l2cap_get_service(psm);
1004     if (!service) {
1005         // 0x0002 PSM not supported
1006         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1007         return;
1008     }
1009 
1010     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1011     if (!hci_connection) {
1012         //
1013         log_error("no hci_connection for handle %u", handle);
1014         return;
1015     }
1016 
1017     // alloc structure
1018     // log_info("l2cap_handle_connection_request register channel");
1019     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1020     if (!channel){
1021         // 0x0004 No resources available
1022         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1023         return;
1024     }
1025     // Init memory (make valgrind happy)
1026     memset(channel, 0, sizeof(l2cap_channel_t));
1027     // fill in
1028     BD_ADDR_COPY(channel->address, hci_connection->address);
1029     channel->psm = psm;
1030     channel->handle = handle;
1031     channel->packet_handler = service->packet_handler;
1032     channel->local_cid  = l2cap_next_local_cid();
1033     channel->remote_cid = source_cid;
1034     channel->local_mtu  = service->mtu;
1035     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1036     channel->remote_sig_id = sig_id;
1037     channel->required_security_level = service->required_security_level;
1038 
1039     // limit local mtu to max acl packet length - l2cap header
1040     if (channel->local_mtu > l2cap_max_mtu()) {
1041         channel->local_mtu = l2cap_max_mtu();
1042     }
1043 
1044     // set initial state
1045     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1046     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1047 
1048     // add to connections list
1049     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1050 
1051     // assert security requirements
1052     gap_request_security_level(handle, channel->required_security_level);
1053 }
1054 
1055 void l2cap_accept_connection(uint16_t local_cid){
1056     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1057     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1058     if (!channel) {
1059         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1060         return;
1061     }
1062 
1063     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1064 
1065     // process
1066     l2cap_run();
1067 }
1068 
1069 void l2cap_decline_connection(uint16_t local_cid, uint8_t reason){
1070     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x, reason %x", local_cid, reason);
1071     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1072     if (!channel) {
1073         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1074         return;
1075     }
1076     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1077     channel->reason = reason;
1078     l2cap_run();
1079 }
1080 
1081 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1082 
1083     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1084 
1085     uint16_t flags = READ_BT_16(command, 6);
1086     if (flags & 1) {
1087         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1088     }
1089 
1090     // accept the other's configuration options
1091     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1092     uint16_t pos     = 8;
1093     while (pos < end_pos){
1094         uint8_t option_hint = command[pos] >> 7;
1095         uint8_t option_type = command[pos] & 0x7f;
1096         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1097         pos++;
1098         uint8_t length = command[pos++];
1099         // MTU { type(8): 1, len(8):2, MTU(16) }
1100         if (option_type == 1 && length == 2){
1101             channel->remote_mtu = READ_BT_16(command, pos);
1102             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1103             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1104         }
1105         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1106         if (option_type == 2 && length == 2){
1107             channel->flush_timeout = READ_BT_16(command, pos);
1108         }
1109         // check for unknown options
1110         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1111             log_info("l2cap cid %u, unknown options", channel->local_cid);
1112             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1113         }
1114         pos += length;
1115     }
1116 }
1117 
1118 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1119     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1120     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1121     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1122     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1123     if (channel->state == L2CAP_STATE_OPEN) return 0;
1124     return 1;
1125 }
1126 
1127 
1128 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1129 
1130     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1131     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1132     uint16_t result = 0;
1133 
1134     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1135 
1136     // handle DISCONNECT REQUESTS seperately
1137     if (code == DISCONNECTION_REQUEST){
1138         switch (channel->state){
1139             case L2CAP_STATE_CONFIG:
1140             case L2CAP_STATE_OPEN:
1141             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1142             case L2CAP_STATE_WAIT_DISCONNECT:
1143                 l2cap_handle_disconnect_request(channel, identifier);
1144                 break;
1145 
1146             default:
1147                 // ignore in other states
1148                 break;
1149         }
1150         return;
1151     }
1152 
1153     // @STATEMACHINE(l2cap)
1154     switch (channel->state) {
1155 
1156         case L2CAP_STATE_WAIT_CONNECT_RSP:
1157             switch (code){
1158                 case CONNECTION_RESPONSE:
1159                     l2cap_stop_rtx(channel);
1160                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1161                     switch (result) {
1162                         case 0:
1163                             // successful connection
1164                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1165                             channel->state = L2CAP_STATE_CONFIG;
1166                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1167                             break;
1168                         case 1:
1169                             // connection pending. get some coffee, but start the ERTX
1170                             l2cap_start_ertx(channel);
1171                             break;
1172                         default:
1173                             // channel closed
1174                             channel->state = L2CAP_STATE_CLOSED;
1175                             // map l2cap connection response result to BTstack status enumeration
1176                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1177 
1178                             // drop link key if security block
1179                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1180                                 hci_drop_link_key_for_bd_addr(channel->address);
1181                             }
1182 
1183                             // discard channel
1184                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1185                             btstack_memory_l2cap_channel_free(channel);
1186                             break;
1187                     }
1188                     break;
1189 
1190                 default:
1191                     //@TODO: implement other signaling packets
1192                     break;
1193             }
1194             break;
1195 
1196         case L2CAP_STATE_CONFIG:
1197             result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1198             switch (code) {
1199                 case CONFIGURE_REQUEST:
1200                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1201                     l2cap_signaling_handle_configure_request(channel, command);
1202                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1203                         // only done if continuation not set
1204                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1205                     }
1206                     break;
1207                 case CONFIGURE_RESPONSE:
1208                     l2cap_stop_rtx(channel);
1209                     switch (result){
1210                         case 0: // success
1211                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1212                             break;
1213                         case 4: // pending
1214                             l2cap_start_ertx(channel);
1215                             break;
1216                         default:
1217                             // retry on negative result
1218                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1219                             break;
1220                     }
1221                     break;
1222                 default:
1223                     break;
1224             }
1225             if (l2cap_channel_ready_for_open(channel)){
1226                 // for open:
1227                 channel->state = L2CAP_STATE_OPEN;
1228                 l2cap_emit_channel_opened(channel, 0);
1229             }
1230             break;
1231 
1232         case L2CAP_STATE_WAIT_DISCONNECT:
1233             switch (code) {
1234                 case DISCONNECTION_RESPONSE:
1235                     l2cap_finialize_channel_close(channel);
1236                     break;
1237                 default:
1238                     //@TODO: implement other signaling packets
1239                     break;
1240             }
1241             break;
1242 
1243         case L2CAP_STATE_CLOSED:
1244             // @TODO handle incoming requests
1245             break;
1246 
1247         case L2CAP_STATE_OPEN:
1248             //@TODO: implement other signaling packets, e.g. re-configure
1249             break;
1250         default:
1251             break;
1252     }
1253     // log_info("new state %u", channel->state);
1254 }
1255 
1256 
1257 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1258 
1259     // get code, signalind identifier and command len
1260     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1261     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1262 
1263     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1264     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1265         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1266         return;
1267     }
1268 
1269     // general commands without an assigned channel
1270     switch(code) {
1271 
1272         case CONNECTION_REQUEST: {
1273             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1274             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1275             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1276             return;
1277         }
1278 
1279         case ECHO_REQUEST:
1280             l2cap_register_signaling_response(handle, code, sig_id, 0);
1281             return;
1282 
1283         case INFORMATION_REQUEST: {
1284             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1285             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1286             return;
1287         }
1288 
1289         default:
1290             break;
1291     }
1292 
1293 
1294     // Get potential destination CID
1295     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1296 
1297     // Find channel for this sig_id and connection handle
1298     btstack_linked_list_iterator_t it;
1299     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1300     while (btstack_linked_list_iterator_has_next(&it)){
1301         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1302         if (channel->handle != handle) continue;
1303         if (code & 1) {
1304             // match odd commands (responses) by previous signaling identifier
1305             if (channel->local_sig_id == sig_id) {
1306                 l2cap_signaling_handler_channel(channel, command);
1307                 break;
1308             }
1309         } else {
1310             // match even commands (requests) by local channel id
1311             if (channel->local_cid == dest_cid) {
1312                 l2cap_signaling_handler_channel(channel, command);
1313                 break;
1314             }
1315         }
1316     }
1317 }
1318 
1319 static void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
1320 
1321     // Get Channel ID
1322     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1323     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1324 
1325     switch (channel_id) {
1326 
1327         case L2CAP_CID_SIGNALING: {
1328 
1329             uint16_t command_offset = 8;
1330             while (command_offset < size) {
1331 
1332                 // handle signaling commands
1333                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1334 
1335                 // increment command_offset
1336                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1337             }
1338             break;
1339         }
1340 
1341         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1342             if (attribute_protocol_packet_handler) {
1343                 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1344             }
1345             break;
1346 
1347         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1348             if (security_protocol_packet_handler) {
1349                 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1350             }
1351             break;
1352 
1353         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1354             if (connectionless_channel_packet_handler) {
1355                 (*connectionless_channel_packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1356             }
1357             break;
1358 
1359         case L2CAP_CID_SIGNALING_LE: {
1360             switch (packet[8]){
1361                 case CONNECTION_PARAMETER_UPDATE_RESPONSE: {
1362                     uint16_t result = READ_BT_16(packet, 12);
1363                     l2cap_emit_connection_parameter_update_response(handle, result);
1364                     break;
1365                 }
1366                 case CONNECTION_PARAMETER_UPDATE_REQUEST: {
1367                     uint8_t event[10];
1368                     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1369                     event[1] = 8;
1370                     memcpy(&event[2], &packet[12], 8);
1371 
1372                     hci_connection_t * connection = hci_connection_for_handle(handle);
1373                     if (connection){
1374                         if (connection->role != HCI_ROLE_MASTER){
1375                             // reject command without notifying upper layer when not in master role
1376                             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1377                             l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1378                             break;
1379                         }
1380                         int update_parameter = 1;
1381                         le_connection_parameter_range_t existing_range;
1382                         gap_le_get_connection_parameter_range(existing_range);
1383                         uint16_t le_conn_interval_min = READ_BT_16(packet,12);
1384                         uint16_t le_conn_interval_max = READ_BT_16(packet,14);
1385                         uint16_t le_conn_latency = READ_BT_16(packet,16);
1386                         uint16_t le_supervision_timeout = READ_BT_16(packet,18);
1387 
1388                         if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1389                         if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1390 
1391                         if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1392                         if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1393 
1394                         if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1395                         if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1396 
1397                         if (update_parameter){
1398                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1399                             connection->le_conn_interval_min = le_conn_interval_min;
1400                             connection->le_conn_interval_max = le_conn_interval_max;
1401                             connection->le_conn_latency = le_conn_latency;
1402                             connection->le_supervision_timeout = le_supervision_timeout;
1403                         } else {
1404                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1405                         }
1406                         connection->le_con_param_update_identifier = packet[COMPLETE_L2CAP_HEADER + 1];
1407                     }
1408 
1409                     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1410                     (*packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1411 
1412                     break;
1413                 }
1414                 default: {
1415                     uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1416                     l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1417                     break;
1418                 }
1419             }
1420             break;
1421         }
1422 
1423         default: {
1424             // Find channel for this channel_id and connection handle
1425             l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
1426             if (channel) {
1427                 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1428             }
1429             break;
1430         }
1431     }
1432 }
1433 
1434 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1435     switch (packet_type) {
1436         case HCI_EVENT_PACKET:
1437             l2cap_event_handler(packet, size);
1438             break;
1439         case HCI_ACL_DATA_PACKET:
1440             l2cap_acl_handler(packet, size);
1441             break;
1442         default:
1443             break;
1444     }
1445     l2cap_run();
1446 }
1447 
1448 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1449 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
1450     channel->state = L2CAP_STATE_CLOSED;
1451     l2cap_emit_channel_closed(channel);
1452     // discard channel
1453     l2cap_stop_rtx(channel);
1454     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1455     btstack_memory_l2cap_channel_free(channel);
1456 }
1457 
1458 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1459     btstack_linked_list_iterator_t it;
1460     btstack_linked_list_iterator_init(&it, services);
1461     while (btstack_linked_list_iterator_has_next(&it)){
1462         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
1463         if ( service->psm == psm){
1464             return service;
1465         };
1466     }
1467     return NULL;
1468 }
1469 
1470 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1471     return l2cap_get_service_internal(&l2cap_services, psm);
1472 }
1473 
1474 
1475 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1476 
1477     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
1478 
1479     // check for alread registered psm
1480     // TODO: emit error event
1481     l2cap_service_t *service = l2cap_get_service(psm);
1482     if (service) {
1483         log_error("l2cap_register_service: PSM %u already registered", psm);
1484         return L2CAP_SERVICE_ALREADY_REGISTERED;
1485     }
1486 
1487     // alloc structure
1488     // TODO: emit error event
1489     service = btstack_memory_l2cap_service_get();
1490     if (!service) {
1491         log_error("l2cap_register_service: no memory for l2cap_service_t");
1492         return BTSTACK_MEMORY_ALLOC_FAILED;
1493     }
1494 
1495     // fill in
1496     service->psm = psm;
1497     service->mtu = mtu;
1498     service->packet_handler = service_packet_handler;
1499     service->required_security_level = security_level;
1500 
1501     // add to services list
1502     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
1503 
1504     // enable page scan
1505     hci_connectable_control(1);
1506 
1507     return 0;
1508 }
1509 
1510 void l2cap_unregister_service(uint16_t psm){
1511 
1512     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
1513 
1514     l2cap_service_t *service = l2cap_get_service(psm);
1515     if (!service) return;
1516     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
1517     btstack_memory_l2cap_service_free(service);
1518 
1519     // disable page scan when no services registered
1520     if (!btstack_linked_list_empty(&l2cap_services)) return;
1521     hci_connectable_control(0);
1522 }
1523 
1524 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1525 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1526     switch(channel_id){
1527         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1528             attribute_protocol_packet_handler = the_packet_handler;
1529             break;
1530         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1531             security_protocol_packet_handler = the_packet_handler;
1532             break;
1533         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1534             connectionless_channel_packet_handler = the_packet_handler;
1535             break;
1536     }
1537 }
1538 
1539 #ifdef ENABLE_BLE
1540 
1541 
1542 #if 0
1543 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm){
1544     return l2cap_get_service_internal(&l2cap_le_services, psm);
1545 }
1546 /**
1547  * @brief Regster L2CAP LE Credit Based Flow Control Mode service
1548  * @param
1549  */
1550 void l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm,
1551     uint16_t mtu, uint16_t mps, uint16_t initial_credits, gap_security_level_t security_level){
1552 
1553     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x mtu %u connection %p", psm, mtu, connection);
1554 
1555     // check for alread registered psm
1556     // TODO: emit error event
1557     l2cap_service_t *service = l2cap_le_get_service(psm);
1558     if (service) {
1559         log_error("l2cap_le_register_service_internal: PSM %u already registered", psm);
1560         l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm);
1561         return;
1562     }
1563 
1564     // alloc structure
1565     // TODO: emit error event
1566     service = btstack_memory_l2cap_service_get();
1567     if (!service) {
1568         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
1569         l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm);
1570         return;
1571     }
1572 
1573     // fill in
1574     service->psm = psm;
1575     service->mtu = mtu;
1576     service->mps = mps;
1577     service->packet_handler = packet_handler;
1578     service->required_security_level = security_level;
1579 
1580     // add to services list
1581     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
1582 
1583     // done
1584     l2cap_emit_service_registered(connection, 0, psm);
1585 }
1586 
1587 void l2cap_le_unregister_service(uint16_t psm) {
1588 
1589     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
1590 
1591     l2cap_service_t *service = l2cap_le_get_service(psm);
1592     if (!service) return;
1593     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
1594     btstack_memory_l2cap_service_free(service);
1595 }
1596 #endif
1597 #endif
1598