xref: /btstack/src/l2cap.c (revision e03e489a86d86ebcffcfedb64bcd238db916f68d)
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_packet_callback_registration_t hci_event_callback_registration;
77 
78 static btstack_linked_list_t l2cap_channels;
79 static btstack_linked_list_t l2cap_services;
80 static btstack_linked_list_t l2cap_le_channels;
81 static btstack_linked_list_t l2cap_le_services;
82 static void (*packet_handler) (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
83 
84 static btstack_packet_handler_t attribute_protocol_packet_handler;
85 static btstack_packet_handler_t security_protocol_packet_handler;
86 static btstack_packet_handler_t connectionless_channel_packet_handler;
87 static uint8_t require_security_level2_for_outgoing_sdp;
88 
89 // prototypes
90 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
91 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
92 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
93 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
94 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
95 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
96 
97 
98 void l2cap_init(void){
99     signaling_responses_pending = 0;
100 
101     l2cap_channels = NULL;
102     l2cap_services = NULL;
103     l2cap_le_services = NULL;
104     l2cap_le_channels = NULL;
105 
106     packet_handler = null_packet_handler;
107     attribute_protocol_packet_handler = NULL;
108     security_protocol_packet_handler = NULL;
109     connectionless_channel_packet_handler = NULL;
110 
111     require_security_level2_for_outgoing_sdp = 0;
112 
113     //
114     // register callback with HCI
115     //
116     hci_event_callback_registration.callback = &l2cap_packet_handler;
117     hci_add_event_handler(&hci_event_callback_registration);
118 
119     hci_register_acl_packet_handler(&l2cap_packet_handler);
120 
121     hci_connectable_control(0); // no services yet
122 }
123 
124 
125 /** Register L2CAP packet handlers */
126 static void null_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
127 }
128 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
129     packet_handler = handler;
130 }
131 
132 //  notify client/protocol handler
133 static void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
134     if (channel->packet_handler) {
135         (* (channel->packet_handler))(type, channel->local_cid, data, size);
136     } else {
137         (*packet_handler)(type, channel->local_cid, data, size);
138     }
139 }
140 
141 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
142     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",
143              status, bd_addr_to_str(channel->address), channel->handle, channel->psm,
144              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
145     uint8_t event[23];
146     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
147     event[1] = sizeof(event) - 2;
148     event[2] = status;
149     bt_flip_addr(&event[3], channel->address);
150     little_endian_store_16(event,  9, channel->handle);
151     little_endian_store_16(event, 11, channel->psm);
152     little_endian_store_16(event, 13, channel->local_cid);
153     little_endian_store_16(event, 15, channel->remote_cid);
154     little_endian_store_16(event, 17, channel->local_mtu);
155     little_endian_store_16(event, 19, channel->remote_mtu);
156     little_endian_store_16(event, 21, channel->flush_timeout);
157     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
158     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
159 }
160 
161 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
162     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
163     uint8_t event[4];
164     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
165     event[1] = sizeof(event) - 2;
166     little_endian_store_16(event, 2, channel->local_cid);
167     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
168     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
169 }
170 
171 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
172     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
173              bd_addr_to_str(channel->address), channel->handle,  channel->psm, channel->local_cid, channel->remote_cid);
174     uint8_t event[16];
175     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
176     event[1] = sizeof(event) - 2;
177     bt_flip_addr(&event[2], channel->address);
178     little_endian_store_16(event,  8, channel->handle);
179     little_endian_store_16(event, 10, channel->psm);
180     little_endian_store_16(event, 12, channel->local_cid);
181     little_endian_store_16(event, 14, channel->remote_cid);
182     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
183     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
184 }
185 
186 static void l2cap_emit_connection_parameter_update_response(uint16_t handle, uint16_t result){
187     uint8_t event[6];
188     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
189     event[1] = 4;
190     little_endian_store_16(event, 2, handle);
191     little_endian_store_16(event, 4, result);
192     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
193     (*packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
194 }
195 
196 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
197     btstack_linked_list_iterator_t it;
198     btstack_linked_list_iterator_init(&it, &l2cap_channels);
199     while (btstack_linked_list_iterator_has_next(&it)){
200         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
201         if ( channel->local_cid == local_cid) {
202             return channel;
203         }
204     }
205     return NULL;
206 }
207 
208 int  l2cap_can_send_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_acl_packet_now(channel->handle);
212 }
213 
214 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
215     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
216     if (!channel) return 0;
217     return hci_can_send_prepared_acl_packet_now(channel->handle);
218 }
219 
220 int  l2cap_can_send_fixed_channel_packet_now(uint16_t handle){
221     return hci_can_send_acl_packet_now(handle);
222 }
223 
224 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
225     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
226     if (channel) {
227         return channel->remote_mtu;
228     }
229     return 0;
230 }
231 
232 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
233     btstack_linked_list_iterator_t it;
234     btstack_linked_list_iterator_init(&it, &l2cap_channels);
235     while (btstack_linked_list_iterator_has_next(&it)){
236         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
237         if ( &channel->rtx == ts) {
238             return channel;
239         }
240     }
241     return NULL;
242 }
243 
244 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
245     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
246     if (!ts) return;
247 
248     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
249 
250     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
251     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
252     // notify client
253     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
254 
255     // discard channel
256     // no need to stop timer here, it is removed from list during timer callback
257     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
258     btstack_memory_l2cap_channel_free(channel);
259 }
260 
261 static void l2cap_stop_rtx(l2cap_channel_t * channel){
262     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
263     btstack_run_loop_remove_timer(&channel->rtx);
264 }
265 
266 static void l2cap_start_rtx(l2cap_channel_t * channel){
267     l2cap_stop_rtx(channel);
268     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
269     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
270     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
271     btstack_run_loop_add_timer(&channel->rtx);
272 }
273 
274 static void l2cap_start_ertx(l2cap_channel_t * channel){
275     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
276     l2cap_stop_rtx(channel);
277     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
278     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
279     btstack_run_loop_add_timer(&channel->rtx);
280 }
281 
282 void l2cap_require_security_level_2_for_outgoing_sdp(void){
283     require_security_level2_for_outgoing_sdp = 1;
284 }
285 
286 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
287     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
288 }
289 
290 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
291 
292     if (!hci_can_send_acl_packet_now(handle)){
293         log_info("l2cap_send_signaling_packet, cannot send");
294         return BTSTACK_ACL_BUFFERS_FULL;
295     }
296 
297     // log_info("l2cap_send_signaling_packet type %u", cmd);
298     hci_reserve_packet_buffer();
299     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
300     va_list argptr;
301     va_start(argptr, identifier);
302     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
303     va_end(argptr);
304     // log_info("l2cap_send_signaling_packet con %u!", handle);
305     return hci_send_acl_packet_buffer(len);
306 }
307 
308 #ifdef ENABLE_BLE
309 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
310 
311     if (!hci_can_send_acl_packet_now(handle)){
312         log_info("l2cap_send_signaling_packet, cannot send");
313         return BTSTACK_ACL_BUFFERS_FULL;
314     }
315 
316     // log_info("l2cap_send_signaling_packet type %u", cmd);
317     hci_reserve_packet_buffer();
318     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
319     va_list argptr;
320     va_start(argptr, identifier);
321     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
322     va_end(argptr);
323     // log_info("l2cap_send_signaling_packet con %u!", handle);
324     return hci_send_acl_packet_buffer(len);
325 }
326 #endif
327 
328 uint8_t *l2cap_get_outgoing_buffer(void){
329     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
330 }
331 
332 int l2cap_reserve_packet_buffer(void){
333     return hci_reserve_packet_buffer();
334 }
335 
336 void l2cap_release_packet_buffer(void){
337     hci_release_packet_buffer();
338 }
339 
340 
341 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
342 
343     if (!hci_is_packet_buffer_reserved()){
344         log_error("l2cap_send_prepared called without reserving packet first");
345         return BTSTACK_ACL_BUFFERS_FULL;
346     }
347 
348     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
349     if (!channel) {
350         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
351         return -1;   // TODO: define error
352     }
353 
354     if (!hci_can_send_prepared_acl_packet_now(channel->handle)){
355         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
356         return BTSTACK_ACL_BUFFERS_FULL;
357     }
358 
359     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->handle);
360 
361     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
362 
363     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
364 
365     // 0 - Connection handle : PB=pb : BC=00
366     little_endian_store_16(acl_buffer, 0, channel->handle | (pb << 12) | (0 << 14));
367     // 2 - ACL length
368     little_endian_store_16(acl_buffer, 2,  len + 4);
369     // 4 - L2CAP packet length
370     little_endian_store_16(acl_buffer, 4,  len + 0);
371     // 6 - L2CAP channel DEST
372     little_endian_store_16(acl_buffer, 6, channel->remote_cid);
373     // send
374     int err = hci_send_acl_packet_buffer(len+8);
375 
376     return err;
377 }
378 
379 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){
380 
381     if (!hci_is_packet_buffer_reserved()){
382         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
383         return BTSTACK_ACL_BUFFERS_FULL;
384     }
385 
386     if (!hci_can_send_prepared_acl_packet_now(handle)){
387         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", handle, cid);
388         return BTSTACK_ACL_BUFFERS_FULL;
389     }
390 
391     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", handle, cid);
392 
393     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
394 
395     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
396 
397     // 0 - Connection handle : PB=pb : BC=00
398     little_endian_store_16(acl_buffer, 0, handle | (pb << 12) | (0 << 14));
399     // 2 - ACL length
400     little_endian_store_16(acl_buffer, 2,  len + 4);
401     // 4 - L2CAP packet length
402     little_endian_store_16(acl_buffer, 4,  len + 0);
403     // 6 - L2CAP channel DEST
404     little_endian_store_16(acl_buffer, 6, cid);
405     // send
406     int err = hci_send_acl_packet_buffer(len+8);
407 
408     return err;
409 }
410 
411 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
412 
413     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
414     if (!channel) {
415         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
416         return -1;   // TODO: define error
417     }
418 
419     if (len > channel->remote_mtu){
420         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
421         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
422     }
423 
424     if (!hci_can_send_acl_packet_now(channel->handle)){
425         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
426         return BTSTACK_ACL_BUFFERS_FULL;
427     }
428 
429     hci_reserve_packet_buffer();
430     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
431 
432     memcpy(&acl_buffer[8], data, len);
433 
434     return l2cap_send_prepared(local_cid, len);
435 }
436 
437 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){
438 
439     if (!hci_can_send_acl_packet_now(handle)){
440         log_info("l2cap_send cid 0x%02x, cannot send", cid);
441         return BTSTACK_ACL_BUFFERS_FULL;
442     }
443 
444     hci_reserve_packet_buffer();
445     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
446 
447     memcpy(&acl_buffer[8], data, len);
448 
449     return l2cap_send_prepared_connectionless(handle, cid, len);
450 }
451 
452 int l2cap_send_echo_request(uint16_t handle, uint8_t *data, uint16_t len){
453     return l2cap_send_signaling_packet(handle, ECHO_REQUEST, 0x77, len, data);
454 }
455 
456 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
457     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
458 }
459 
460 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
461     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
462 }
463 
464 
465 
466 // MARK: L2CAP_RUN
467 // process outstanding signaling tasks
468 static void l2cap_run(void){
469 
470     // log_info("l2cap_run: entered");
471 
472     // check pending signaling responses
473     while (signaling_responses_pending){
474 
475         hci_con_handle_t handle = signaling_responses[0].handle;
476 
477         if (!hci_can_send_acl_packet_now(handle)) break;
478 
479         uint8_t  sig_id = signaling_responses[0].sig_id;
480         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
481         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
482         uint8_t  response_code = signaling_responses[0].code;
483 
484         // remove first item before sending (to avoid sending response mutliple times)
485         signaling_responses_pending--;
486         int i;
487         for (i=0; i < signaling_responses_pending; i++){
488             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
489         }
490 
491         switch (response_code){
492             case CONNECTION_REQUEST:
493                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
494                 // also disconnect if result is 0x0003 - security blocked
495                 if (result == 0x0003){
496                     hci_disconnect_security_block(handle);
497                 }
498                 break;
499             case ECHO_REQUEST:
500                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
501                 break;
502             case INFORMATION_REQUEST:
503                 switch (infoType){
504                     case 1: { // Connectionless MTU
505                         uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
506                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
507                         break;
508                     }
509                     case 2: { // Extended Features Supported
510                         // extended features request supported, features: fixed channels, unicast connectionless data reception
511                         uint32_t features = 0x280;
512                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
513                         break;
514                     }
515                     case 3: { // Fixed Channels Supported
516                         uint8_t map[8];
517                         memset(map, 0, 8);
518                         map[0] = 0x01;  // L2CAP Signaling Channel (0x01) + Connectionless reception (0x02)
519                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
520                         break;
521                     }
522                     default:
523                         // all other types are not supported
524                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
525                         break;
526                 }
527                 break;
528             case COMMAND_REJECT:
529                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
530 #ifdef ENABLE_BLE
531             case COMMAND_REJECT_LE:
532                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
533                 break;
534 #endif
535             default:
536                 // should not happen
537                 break;
538         }
539     }
540 
541     uint8_t  config_options[4];
542     btstack_linked_list_iterator_t it;
543     btstack_linked_list_iterator_init(&it, &l2cap_channels);
544     while (btstack_linked_list_iterator_has_next(&it)){
545 
546         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
547         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
548         switch (channel->state){
549 
550             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
551             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
552                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
553                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
554                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
555                     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
556                 }
557                 break;
558 
559             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
560                 if (!hci_can_send_command_packet_now()) break;
561                 // send connection request - set state first
562                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
563                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
564                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
565                 break;
566 
567             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
568                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
569                 channel->state = L2CAP_STATE_INVALID;
570                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
571                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
572                 l2cap_stop_rtx(channel);
573                 btstack_linked_list_iterator_remove(&it);
574                 btstack_memory_l2cap_channel_free(channel);
575                 break;
576 
577             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
578                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
579                 channel->state = L2CAP_STATE_CONFIG;
580                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
581                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
582                 break;
583 
584             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
585                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
586                 // success, start l2cap handshake
587                 channel->local_sig_id = l2cap_next_sig_id();
588                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
589                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
590                 l2cap_start_rtx(channel);
591                 break;
592 
593             case L2CAP_STATE_CONFIG:
594                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
595                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
596                     uint16_t flags = 0;
597                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
598                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
599                         flags = 1;
600                     } else {
601                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
602                     }
603                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
604                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
605                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
606                         config_options[0] = 1; // MTU
607                         config_options[1] = 2; // len param
608                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
609                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
610                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
611                     } else {
612                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
613                     }
614                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
615                 }
616                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
617                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
618                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
619                     channel->local_sig_id = l2cap_next_sig_id();
620                     config_options[0] = 1; // MTU
621                     config_options[1] = 2; // len param
622                     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
623                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
624                     l2cap_start_rtx(channel);
625                 }
626                 if (l2cap_channel_ready_for_open(channel)){
627                     channel->state = L2CAP_STATE_OPEN;
628                     l2cap_emit_channel_opened(channel, 0);  // success
629                 }
630                 break;
631 
632             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
633                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
634                 channel->state = L2CAP_STATE_INVALID;
635                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
636                 // 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 :)
637                 l2cap_finialize_channel_close(channel);  // -- remove from list
638                 break;
639 
640             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
641                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
642                 channel->local_sig_id = l2cap_next_sig_id();
643                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
644                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
645                 break;
646             default:
647                 break;
648         }
649     }
650 
651 #ifdef ENABLE_BLE
652     // send l2cap con paramter update if necessary
653     hci_connections_get_iterator(&it);
654     while(btstack_linked_list_iterator_has_next(&it)){
655         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
656         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
657         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
658         switch (connection->le_con_parameter_update_state){
659             case CON_PARAMETER_UPDATE_SEND_REQUEST:
660                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
661                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
662                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
663                 break;
664             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
665                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
666                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
667                 break;
668             case CON_PARAMETER_UPDATE_DENY:
669                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
670                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
671                 break;
672             default:
673                 break;
674         }
675     }
676 #endif
677 
678     // log_info("l2cap_run: exit");
679 }
680 
681 uint16_t l2cap_max_mtu(void){
682     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
683 }
684 
685 uint16_t l2cap_max_le_mtu(void){
686     return l2cap_max_mtu();
687 }
688 
689 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){
690     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
691         log_info("l2cap_handle_connection_complete expected state");
692         // success, start l2cap handshake
693         channel->handle = handle;
694         // check remote SSP feature first
695         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
696     }
697 }
698 
699 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
700     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
701 
702     // we have been waiting for remote supported features, if both support SSP,
703     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));
704     if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
705         // request security level 2
706         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
707         gap_request_security_level(channel->handle, LEVEL_2);
708         return;
709     }
710     // fine, go ahead
711     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
712 }
713 
714 /**
715  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
716  * @param packet_handler
717  * @param address
718  * @param psm
719  * @param mtu
720  * @param local_cid
721  */
722 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){
723     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu);
724 
725     // alloc structure
726     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
727     if (!chan) {
728         return BTSTACK_MEMORY_ALLOC_FAILED;
729     }
730 
731      // Init memory (make valgrind happy)
732     memset(chan, 0, sizeof(l2cap_channel_t));
733     // limit local mtu to max acl packet length - l2cap header
734     if (mtu > l2cap_max_mtu()) {
735         mtu = l2cap_max_mtu();
736     }
737 
738     // fill in
739     BD_ADDR_COPY(chan->address, address);
740     chan->psm = psm;
741     chan->handle = 0;
742     chan->packet_handler = channel_packet_handler;
743     chan->remote_mtu = L2CAP_MINIMAL_MTU;
744     chan->local_mtu = mtu;
745     chan->local_cid = l2cap_next_local_cid();
746 
747     // set initial state
748     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
749     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
750     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
751     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
752     chan->required_security_level = LEVEL_0;
753 
754     // add to connections list
755     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) chan);
756 
757     // store local_cid
758     if (out_local_cid){
759        *out_local_cid = chan->local_cid;
760     }
761 
762     // check if hci connection is already usable
763     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
764     if (conn){
765         log_info("l2cap_create_channel, hci connection already exists");
766         l2cap_handle_connection_complete(conn->con_handle, chan);
767         // check if remote supported fearures are already received
768         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
769             l2cap_handle_remote_supported_features_received(chan);
770         }
771     }
772 
773     l2cap_run();
774 
775     return 0;
776 }
777 
778 void
779 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
780     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
781     // find channel for local_cid
782     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
783     if (channel) {
784         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
785     }
786     // process
787     l2cap_run();
788 }
789 
790 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
791     btstack_linked_list_iterator_t it;
792     btstack_linked_list_iterator_init(&it, &l2cap_channels);
793     while (btstack_linked_list_iterator_has_next(&it)){
794         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
795         if ( BD_ADDR_CMP( channel->address, address) != 0) continue;
796         // channel for this address found
797         switch (channel->state){
798             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
799             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
800                 // failure, forward error code
801                 l2cap_emit_channel_opened(channel, status);
802                 // discard channel
803                 l2cap_stop_rtx(channel);
804                 btstack_linked_list_iterator_remove(&it);
805                 btstack_memory_l2cap_channel_free(channel);
806                 break;
807             default:
808                 break;
809         }
810     }
811 }
812 
813 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
814     btstack_linked_list_iterator_t it;
815     btstack_linked_list_iterator_init(&it, &l2cap_channels);
816     while (btstack_linked_list_iterator_has_next(&it)){
817         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
818         if ( ! BD_ADDR_CMP( channel->address, address) ){
819             l2cap_handle_connection_complete(handle, channel);
820         }
821     }
822     // process
823     l2cap_run();
824 }
825 
826 static void l2cap_event_handler(uint8_t *packet, uint16_t size){
827 
828     bd_addr_t address;
829     hci_con_handle_t handle;
830     btstack_linked_list_iterator_t it;
831     int hci_con_used;
832 
833     switch(packet[0]){
834 
835         // handle connection complete events
836         case HCI_EVENT_CONNECTION_COMPLETE:
837             bt_flip_addr(address, &packet[5]);
838             if (packet[2] == 0){
839                 handle = little_endian_read_16(packet, 3);
840                 l2cap_handle_connection_success_for_addr(address, handle);
841             } else {
842                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
843             }
844             break;
845 
846         // handle successful create connection cancel command
847         case HCI_EVENT_COMMAND_COMPLETE:
848             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
849                 if (packet[5] == 0){
850                     bt_flip_addr(address, &packet[6]);
851                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
852                     l2cap_handle_connection_failed_for_addr(address, 0x16);
853                 }
854             }
855             l2cap_run();    // try sending signaling packets first
856             break;
857 
858         case HCI_EVENT_COMMAND_STATUS:
859             l2cap_run();    // try sending signaling packets first
860             break;
861 
862         // handle disconnection complete events
863         case HCI_EVENT_DISCONNECTION_COMPLETE:
864             // send l2cap disconnect events for all channels on this handle and free them
865             handle = little_endian_read_16(packet, 3);
866             btstack_linked_list_iterator_init(&it, &l2cap_channels);
867             while (btstack_linked_list_iterator_has_next(&it)){
868                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
869                 if (channel->handle != handle) continue;
870                 l2cap_emit_channel_closed(channel);
871                 l2cap_stop_rtx(channel);
872                 btstack_linked_list_iterator_remove(&it);
873                 btstack_memory_l2cap_channel_free(channel);
874             }
875             break;
876 
877         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
878             l2cap_run();    // try sending signaling packets first
879             break;
880 
881         // HCI Connection Timeouts
882         case L2CAP_EVENT_TIMEOUT_CHECK:
883             handle = little_endian_read_16(packet, 2);
884             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
885             if (hci_authentication_active_for_handle(handle)) break;
886             hci_con_used = 0;
887             btstack_linked_list_iterator_init(&it, &l2cap_channels);
888             while (btstack_linked_list_iterator_has_next(&it)){
889                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
890                 if (channel->handle != handle) continue;
891                 hci_con_used = 1;
892                 break;
893             }
894             if (hci_con_used) break;
895             if (!hci_can_send_command_packet_now()) break;
896             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
897             break;
898 
899         case DAEMON_EVENT_HCI_PACKET_SENT:
900             l2cap_run();    // try sending signaling packets first
901 
902             btstack_linked_list_iterator_init(&it, &l2cap_channels);
903             while (btstack_linked_list_iterator_has_next(&it)){
904                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
905                 if (!channel->packet_handler) continue;
906                 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
907             }
908             if (attribute_protocol_packet_handler) {
909                 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
910             }
911             if (connectionless_channel_packet_handler) {
912                 (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
913             }
914             break;
915 
916         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
917             handle = little_endian_read_16(packet, 3);
918             btstack_linked_list_iterator_init(&it, &l2cap_channels);
919             while (btstack_linked_list_iterator_has_next(&it)){
920                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
921                 if (channel->handle != handle) continue;
922                 l2cap_handle_remote_supported_features_received(channel);
923                 break;
924             }
925             break;
926 
927         case GAP_EVENT_SECURITY_LEVEL:
928             handle = little_endian_read_16(packet, 2);
929             log_info("l2cap - security level update");
930             btstack_linked_list_iterator_init(&it, &l2cap_channels);
931             while (btstack_linked_list_iterator_has_next(&it)){
932                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
933                 if (channel->handle != handle) continue;
934 
935                 log_info("l2cap - state %u", channel->state);
936 
937                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
938                 gap_security_level_t required_level = channel->required_security_level;
939 
940                 switch (channel->state){
941                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
942                         if (actual_level >= required_level){
943                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
944                             l2cap_emit_connection_request(channel);
945                         } else {
946                             channel->reason = 0x0003; // security block
947                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
948                         }
949                         break;
950 
951                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
952                         if (actual_level >= required_level){
953                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
954                         } else {
955                             // disconnnect, authentication not good enough
956                             hci_disconnect_security_block(handle);
957                         }
958                         break;
959 
960                     default:
961                         break;
962                 }
963             }
964             break;
965 
966         default:
967             break;
968     }
969 
970     // pass on: main packet handler, att and sm packet handlers
971     (*packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
972     if (attribute_protocol_packet_handler){
973         (*attribute_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 = little_endian_read_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 + little_endian_read_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 = little_endian_read_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 = little_endian_read_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 = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1161                     switch (result) {
1162                         case 0:
1163                             // successful connection
1164                             channel->remote_cid = little_endian_read_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 = little_endian_read_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 =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1274             uint16_t source_cid = little_endian_read_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 = little_endian_read_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 = little_endian_read_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 + little_endian_read_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 = little_endian_read_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 = little_endian_read_16(packet,12);
1384                         uint16_t le_conn_interval_max = little_endian_read_16(packet,14);
1385                         uint16_t le_conn_latency = little_endian_read_16(packet,16);
1386                         uint16_t le_supervision_timeout = little_endian_read_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