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