xref: /btstack/src/l2cap.c (revision be005ed60da04c6fdce48cdb21ea9323da922cd9)
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_event.h"
51 #include "btstack_memory.h"
52 
53 #ifdef ENABLE_LE_DATA_CHANNELS
54 #include "ble/sm.h"
55 #endif
56 
57 #include <stdarg.h>
58 #include <string.h>
59 
60 #include <stdio.h>
61 
62 // nr of buffered acl packets in outgoing queue to get max performance
63 #define NR_BUFFERED_ACL_PACKETS 3
64 
65 // used to cache l2cap rejects, echo, and informational requests
66 #define NR_PENDING_SIGNALING_RESPONSES 3
67 
68 // nr of credits provided to remote if credits fall below watermark
69 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
70 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
71 
72 // offsets for L2CAP SIGNALING COMMANDS
73 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
74 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
75 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
76 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
77 
78 // internal table
79 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
80 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
81 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
82 #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
83 
84 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
85 #define L2CAP_USES_CHANNELS
86 #endif
87 
88 // prototypes
89 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
90 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
91 static void l2cap_notify_channel_can_send(void);
92 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
93 #ifdef ENABLE_CLASSIC
94 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
95 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
96 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
97 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
98 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
99 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
100 #endif
101 #ifdef ENABLE_LE_DATA_CHANNELS
102 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
103 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
104 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
105 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
106 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
107 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
108 #endif
109 
110 typedef struct l2cap_fixed_channel {
111     btstack_packet_handler_t callback;
112     uint8_t waiting_for_can_send_now;
113 } l2cap_fixed_channel_t;
114 
115 #ifdef ENABLE_CLASSIC
116 static btstack_linked_list_t l2cap_channels;
117 static btstack_linked_list_t l2cap_services;
118 static uint8_t require_security_level2_for_outgoing_sdp;
119 #endif
120 
121 #ifdef ENABLE_LE_DATA_CHANNELS
122 static btstack_linked_list_t l2cap_le_channels;
123 static btstack_linked_list_t l2cap_le_services;
124 #endif
125 
126 // used to cache l2cap rejects, echo, and informational requests
127 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
128 static int signaling_responses_pending;
129 
130 static btstack_packet_callback_registration_t hci_event_callback_registration;
131 
132 static btstack_packet_handler_t l2cap_event_packet_handler;
133 static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
134 
135 static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
136     switch (index){
137         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
138             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
139         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
140             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
141         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
142             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
143         default:
144             return 0;
145     }
146 }
147 static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
148     switch (channel_id){
149         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
150             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
151         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
152             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
153         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
154             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
155         default:
156             return -1;
157         }
158 }
159 
160 static int l2cap_fixed_channel_table_index_is_le(int index){
161     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
162     return 1;
163 }
164 
165 void l2cap_init(void){
166     signaling_responses_pending = 0;
167 
168 #ifdef ENABLE_CLASSIC
169     l2cap_channels = NULL;
170     l2cap_services = NULL;
171     require_security_level2_for_outgoing_sdp = 0;
172 #endif
173 
174 #ifdef ENABLE_LE_DATA_CHANNELS
175     l2cap_le_services = NULL;
176     l2cap_le_channels = NULL;
177 #endif
178 
179     l2cap_event_packet_handler = NULL;
180     memset(fixed_channels, 0, sizeof(fixed_channels));
181 
182     //
183     // register callback with HCI
184     //
185     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
186     hci_add_event_handler(&hci_event_callback_registration);
187 
188     hci_register_acl_packet_handler(&l2cap_acl_handler);
189 
190 #ifdef ENABLE_CLASSIC
191     gap_connectable_control(0); // no services yet
192 #endif
193 }
194 
195 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
196     l2cap_event_packet_handler = handler;
197 }
198 
199 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
200     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
201     if (index < 0) return;
202     fixed_channels[index].waiting_for_can_send_now = 1;
203     l2cap_notify_channel_can_send();
204 }
205 
206 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
207     return hci_can_send_acl_packet_now(con_handle);
208 }
209 
210 uint8_t *l2cap_get_outgoing_buffer(void){
211     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
212 }
213 
214 int l2cap_reserve_packet_buffer(void){
215     return hci_reserve_packet_buffer();
216 }
217 
218 void l2cap_release_packet_buffer(void){
219     hci_release_packet_buffer();
220 }
221 
222 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint16_t remote_cid, uint16_t len){
223     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
224 
225     // 0 - Connection handle : PB=pb : BC=00
226     little_endian_store_16(acl_buffer, 0, con_handle | (pb << 12) | (0 << 14));
227     // 2 - ACL length
228     little_endian_store_16(acl_buffer, 2,  len + 4);
229     // 4 - L2CAP packet length
230     little_endian_store_16(acl_buffer, 4,  len + 0);
231     // 6 - L2CAP channel DEST
232     little_endian_store_16(acl_buffer, 6,  remote_cid);
233 }
234 
235 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
236 
237     if (!hci_is_packet_buffer_reserved()){
238         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
239         return BTSTACK_ACL_BUFFERS_FULL;
240     }
241 
242     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
243         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
244         return BTSTACK_ACL_BUFFERS_FULL;
245     }
246 
247     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
248 
249     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
250     l2cap_setup_header(acl_buffer, con_handle, cid, len);
251     // send
252     return hci_send_acl_packet_buffer(len+8);
253 }
254 
255 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
256 
257     if (!hci_can_send_acl_packet_now(con_handle)){
258         log_info("l2cap_send cid 0x%02x, cannot send", cid);
259         return BTSTACK_ACL_BUFFERS_FULL;
260     }
261 
262     hci_reserve_packet_buffer();
263     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
264 
265     memcpy(&acl_buffer[8], data, len);
266 
267     return l2cap_send_prepared_connectionless(con_handle, cid, len);
268 }
269 
270 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
271     log_info("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
272     uint8_t event[4];
273     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
274     event[1] = sizeof(event) - 2;
275     little_endian_store_16(event, 2, channel);
276     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
277     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
278 }
279 
280 #ifdef L2CAP_USES_CHANNELS
281 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
282     (* (channel->packet_handler))(type, channel->local_cid, data, size);
283 }
284 
285 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
286     uint8_t event[4];
287     event[0] = event_code;
288     event[1] = sizeof(event) - 2;
289     little_endian_store_16(event, 2, channel->local_cid);
290     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
291     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
292 }
293 #endif
294 
295 #ifdef ENABLE_CLASSIC
296 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
297     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",
298              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
299              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
300     uint8_t event[23];
301     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
302     event[1] = sizeof(event) - 2;
303     event[2] = status;
304     reverse_bd_addr(channel->address, &event[3]);
305     little_endian_store_16(event,  9, channel->con_handle);
306     little_endian_store_16(event, 11, channel->psm);
307     little_endian_store_16(event, 13, channel->local_cid);
308     little_endian_store_16(event, 15, channel->remote_cid);
309     little_endian_store_16(event, 17, channel->local_mtu);
310     little_endian_store_16(event, 19, channel->remote_mtu);
311     little_endian_store_16(event, 21, channel->flush_timeout);
312     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
313     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
314 }
315 
316 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
317     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
318     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
319 }
320 
321 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
322     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
323              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
324     uint8_t event[16];
325     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
326     event[1] = sizeof(event) - 2;
327     reverse_bd_addr(channel->address, &event[2]);
328     little_endian_store_16(event,  8, channel->con_handle);
329     little_endian_store_16(event, 10, channel->psm);
330     little_endian_store_16(event, 12, channel->local_cid);
331     little_endian_store_16(event, 14, channel->remote_cid);
332     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
333     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
334 }
335 
336 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
337     btstack_linked_list_iterator_t it;
338     btstack_linked_list_iterator_init(&it, &l2cap_channels);
339     while (btstack_linked_list_iterator_has_next(&it)){
340         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
341         if ( channel->local_cid == local_cid) {
342             return channel;
343         }
344     }
345     return NULL;
346 }
347 
348 ///
349 
350 void l2cap_request_can_send_now_event(uint16_t local_cid){
351     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
352     if (!channel) return;
353     channel->waiting_for_can_send_now = 1;
354     l2cap_notify_channel_can_send();
355 }
356 
357 int  l2cap_can_send_packet_now(uint16_t local_cid){
358     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
359     if (!channel) return 0;
360     return hci_can_send_acl_packet_now(channel->con_handle);
361 }
362 
363 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
364     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
365     if (!channel) return 0;
366     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
367 }
368 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
369     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
370     if (channel) {
371         return channel->remote_mtu;
372     }
373     return 0;
374 }
375 
376 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
377     btstack_linked_list_iterator_t it;
378     btstack_linked_list_iterator_init(&it, &l2cap_channels);
379     while (btstack_linked_list_iterator_has_next(&it)){
380         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
381         if ( &channel->rtx == ts) {
382             return channel;
383         }
384     }
385     return NULL;
386 }
387 
388 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
389     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
390     if (!channel) return;
391 
392     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
393 
394     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
395     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
396     // notify client
397     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
398 
399     // discard channel
400     // no need to stop timer here, it is removed from list during timer callback
401     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
402     btstack_memory_l2cap_channel_free(channel);
403 }
404 
405 static void l2cap_stop_rtx(l2cap_channel_t * channel){
406     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
407     btstack_run_loop_remove_timer(&channel->rtx);
408 }
409 
410 static void l2cap_start_rtx(l2cap_channel_t * channel){
411     l2cap_stop_rtx(channel);
412     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
413     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
414     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
415     btstack_run_loop_add_timer(&channel->rtx);
416 }
417 
418 static void l2cap_start_ertx(l2cap_channel_t * channel){
419     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
420     l2cap_stop_rtx(channel);
421     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
422     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
423     btstack_run_loop_add_timer(&channel->rtx);
424 }
425 
426 void l2cap_require_security_level_2_for_outgoing_sdp(void){
427     require_security_level2_for_outgoing_sdp = 1;
428 }
429 
430 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
431     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
432 }
433 
434 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
435     if (!hci_can_send_acl_packet_now(handle)){
436         log_info("l2cap_send_signaling_packet, cannot send");
437         return BTSTACK_ACL_BUFFERS_FULL;
438     }
439 
440     // log_info("l2cap_send_signaling_packet type %u", cmd);
441     hci_reserve_packet_buffer();
442     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
443     va_list argptr;
444     va_start(argptr, identifier);
445     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
446     va_end(argptr);
447     // log_info("l2cap_send_signaling_packet con %u!", handle);
448     return hci_send_acl_packet_buffer(len);
449 }
450 
451 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
452 
453     if (!hci_is_packet_buffer_reserved()){
454         log_error("l2cap_send_prepared called without reserving packet first");
455         return BTSTACK_ACL_BUFFERS_FULL;
456     }
457 
458     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
459     if (!channel) {
460         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
461         return -1;   // TODO: define error
462     }
463 
464     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
465         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
466         return BTSTACK_ACL_BUFFERS_FULL;
467     }
468 
469     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
470 
471     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
472     l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, len);
473     // send
474     return hci_send_acl_packet_buffer(len+8);
475 }
476 
477 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
478 
479     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
480     if (!channel) {
481         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
482         return -1;   // TODO: define error
483     }
484 
485     if (len > channel->remote_mtu){
486         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
487         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
488     }
489 
490     if (!hci_can_send_acl_packet_now(channel->con_handle)){
491         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
492         return BTSTACK_ACL_BUFFERS_FULL;
493     }
494 
495     hci_reserve_packet_buffer();
496     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
497 
498     memcpy(&acl_buffer[8], data, len);
499 
500     return l2cap_send_prepared(local_cid, len);
501 }
502 
503 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
504     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
505 }
506 
507 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
508     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
509 }
510 
511 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
512     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
513 }
514 #endif
515 
516 
517 #ifdef ENABLE_BLE
518 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
519 
520     if (!hci_can_send_acl_packet_now(handle)){
521         log_info("l2cap_send_le_signaling_packet, cannot send");
522         return BTSTACK_ACL_BUFFERS_FULL;
523     }
524 
525     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
526     hci_reserve_packet_buffer();
527     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
528     va_list argptr;
529     va_start(argptr, identifier);
530     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
531     va_end(argptr);
532     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
533     return hci_send_acl_packet_buffer(len);
534 }
535 #endif
536 
537 uint16_t l2cap_max_mtu(void){
538     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
539 }
540 
541 uint16_t l2cap_max_le_mtu(void){
542     return l2cap_max_mtu();
543 }
544 
545 // MARK: L2CAP_RUN
546 // process outstanding signaling tasks
547 static void l2cap_run(void){
548 
549     // log_info("l2cap_run: entered");
550 
551     // check pending signaling responses
552     while (signaling_responses_pending){
553 
554         hci_con_handle_t handle = signaling_responses[0].handle;
555 
556         if (!hci_can_send_acl_packet_now(handle)) break;
557 
558         uint8_t  sig_id = signaling_responses[0].sig_id;
559         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
560         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
561         uint8_t  response_code = signaling_responses[0].code;
562 
563         // avoid warnings
564         (void) infoType;
565 
566         // remove first item before sending (to avoid sending response mutliple times)
567         signaling_responses_pending--;
568         int i;
569         for (i=0; i < signaling_responses_pending; i++){
570             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
571         }
572 
573         switch (response_code){
574 #ifdef ENABLE_CLASSIC
575             case CONNECTION_REQUEST:
576                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
577                 // also disconnect if result is 0x0003 - security blocked
578                 if (result == 0x0003){
579                     hci_disconnect_security_block(handle);
580                 }
581                 break;
582             case ECHO_REQUEST:
583                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
584                 break;
585             case INFORMATION_REQUEST:
586                 switch (infoType){
587                     case 1: { // Connectionless MTU
588                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
589                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
590                         }
591                         break;
592                     case 2: { // Extended Features Supported
593                             // extended features request supported, features: fixed channels, unicast connectionless data reception
594                             uint32_t features = 0x280;
595                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
596                         }
597                         break;
598                     case 3: { // Fixed Channels Supported
599                             uint8_t map[8];
600                             memset(map, 0, 8);
601                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
602                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
603                         }
604                         break;
605                     default:
606                         // all other types are not supported
607                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
608                         break;
609                 }
610                 break;
611             case COMMAND_REJECT:
612                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
613                 break;
614 #endif
615 #ifdef ENABLE_BLE
616             case LE_CREDIT_BASED_CONNECTION_REQUEST:
617                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
618                 break;
619             case COMMAND_REJECT_LE:
620                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
621                 break;
622 #endif
623             default:
624                 // should not happen
625                 break;
626         }
627     }
628 
629     btstack_linked_list_iterator_t it;
630     (void) it;
631 
632 #ifdef ENABLE_CLASSIC
633     uint8_t  config_options[4];
634     btstack_linked_list_iterator_init(&it, &l2cap_channels);
635     while (btstack_linked_list_iterator_has_next(&it)){
636 
637         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
638         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
639         switch (channel->state){
640 
641             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
642             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
643                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
644                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
645                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
646                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
647                 }
648                 break;
649 
650             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
651                 if (!hci_can_send_command_packet_now()) break;
652                 // send connection request - set state first
653                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
654                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
655                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
656                 break;
657 
658             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
659                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
660                 channel->state = L2CAP_STATE_INVALID;
661                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
662                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
663                 l2cap_stop_rtx(channel);
664                 btstack_linked_list_iterator_remove(&it);
665                 btstack_memory_l2cap_channel_free(channel);
666                 break;
667 
668             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
669                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
670                 channel->state = L2CAP_STATE_CONFIG;
671                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
672                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
673                 break;
674 
675             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
676                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
677                 // success, start l2cap handshake
678                 channel->local_sig_id = l2cap_next_sig_id();
679                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
680                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
681                 l2cap_start_rtx(channel);
682                 break;
683 
684             case L2CAP_STATE_CONFIG:
685                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
686                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
687                     uint16_t flags = 0;
688                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
689                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
690                         flags = 1;
691                     } else {
692                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
693                     }
694                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
695                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
696                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
697                         config_options[0] = 1; // MTU
698                         config_options[1] = 2; // len param
699                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
700                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
701                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
702                     } else {
703                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
704                     }
705                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
706                 }
707                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
708                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
709                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
710                     channel->local_sig_id = l2cap_next_sig_id();
711                     config_options[0] = 1; // MTU
712                     config_options[1] = 2; // len param
713                     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
714                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
715                     l2cap_start_rtx(channel);
716                 }
717                 if (l2cap_channel_ready_for_open(channel)){
718                     channel->state = L2CAP_STATE_OPEN;
719                     l2cap_emit_channel_opened(channel, 0);  // success
720                 }
721                 break;
722 
723             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
724                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
725                 channel->state = L2CAP_STATE_INVALID;
726                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
727                 // 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 :)
728                 l2cap_finialize_channel_close(channel);  // -- remove from list
729                 break;
730 
731             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
732                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
733                 channel->local_sig_id = l2cap_next_sig_id();
734                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
735                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
736                 break;
737             default:
738                 break;
739         }
740     }
741 #endif
742 
743 #ifdef ENABLE_LE_DATA_CHANNELS
744     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
745     while (btstack_linked_list_iterator_has_next(&it)){
746         uint8_t  * acl_buffer;
747         uint8_t  * l2cap_payload;
748         uint16_t pos;
749         uint16_t payload_size;
750         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
751         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
752         switch (channel->state){
753             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
754                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
755                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
756                 // le psm, source cid, mtu, mps, initial credits
757                 channel->local_sig_id = l2cap_next_sig_id();
758                 channel->credits_incoming =  channel->new_credits_incoming;
759                 channel->new_credits_incoming = 0;
760                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming);
761                 break;
762             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
763                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
764                 // TODO: support larger MPS
765                 channel->state = L2CAP_STATE_OPEN;
766                 channel->credits_incoming =  channel->new_credits_incoming;
767                 channel->new_credits_incoming = 0;
768                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0);
769                 // notify client
770                 l2cap_emit_le_channel_opened(channel, 0);
771                 break;
772             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
773                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
774                 channel->state = L2CAP_STATE_INVALID;
775                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
776                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
777                 l2cap_stop_rtx(channel);
778                 btstack_linked_list_iterator_remove(&it);
779                 btstack_memory_l2cap_channel_free(channel);
780                 break;
781             case L2CAP_STATE_OPEN:
782                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
783 
784                 // send credits
785                 if (channel->new_credits_incoming){
786                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
787                     channel->local_sig_id = l2cap_next_sig_id();
788                     uint16_t new_credits = channel->new_credits_incoming;
789                     channel->new_credits_incoming = 0;
790                     channel->credits_incoming += new_credits;
791                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
792                     break;
793                 }
794 
795                 // send data
796                 if (!channel->send_sdu_buffer) break;
797                 if (!channel->credits_outgoing) break;
798 
799                 // send part of SDU
800                 hci_reserve_packet_buffer();
801                 acl_buffer = hci_get_outgoing_packet_buffer();
802                 l2cap_payload = acl_buffer + 8;
803                 pos = 0;
804                 if (!channel->send_sdu_pos){
805                     // store SDU len
806                     channel->send_sdu_pos += 2;
807                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
808                     pos += 2;
809                 }
810                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
811                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
812                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
813                 pos += payload_size;
814                 channel->send_sdu_pos += payload_size;
815                 l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, pos);
816                 // done
817 
818                 channel->credits_outgoing--;
819 
820                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
821                     channel->send_sdu_buffer = NULL;
822                     // send done event
823                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
824                     // inform about can send now
825                     l2cap_le_notify_channel_can_send(channel);
826                 }
827                 hci_send_acl_packet_buffer(8 + pos);
828                 break;
829             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
830                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
831                 channel->local_sig_id = l2cap_next_sig_id();
832                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
833                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
834                 break;
835             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
836                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
837                 channel->state = L2CAP_STATE_INVALID;
838                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
839                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
840                 break;
841             default:
842                 break;
843         }
844     }
845 #endif
846 
847 #ifdef ENABLE_BLE
848     // send l2cap con paramter update if necessary
849     hci_connections_get_iterator(&it);
850     while(btstack_linked_list_iterator_has_next(&it)){
851         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
852         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
853         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
854         switch (connection->le_con_parameter_update_state){
855             case CON_PARAMETER_UPDATE_SEND_REQUEST:
856                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
857                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
858                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
859                 break;
860             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
861                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
862                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
863                 break;
864             case CON_PARAMETER_UPDATE_DENY:
865                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
866                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
867                 break;
868             default:
869                 break;
870         }
871     }
872 #endif
873 
874     // log_info("l2cap_run: exit");
875 }
876 
877 #ifdef ENABLE_CLASSIC
878 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
879     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
880         log_info("l2cap_handle_connection_complete expected state");
881         // success, start l2cap handshake
882         channel->con_handle = con_handle;
883         // check remote SSP feature first
884         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
885     }
886 }
887 
888 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
889     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
890 
891     // we have been waiting for remote supported features, if both support SSP,
892     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));
893     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
894         // request security level 2
895         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
896         gap_request_security_level(channel->con_handle, LEVEL_2);
897         return;
898     }
899     // fine, go ahead
900     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
901 }
902 #endif
903 
904 #ifdef L2CAP_USES_CHANNELS
905 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
906     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
907 
908     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
909     if (!channel) {
910         return NULL;
911     }
912 
913      // Init memory (make valgrind happy)
914     memset(channel, 0, sizeof(l2cap_channel_t));
915 
916     // fill in
917     channel->packet_handler = packet_handler;
918     bd_addr_copy(channel->address, address);
919     channel->address_type = address_type;
920     channel->psm = psm;
921     channel->local_mtu  = local_mtu;
922     channel->remote_mtu = L2CAP_MINIMAL_MTU;
923     channel->required_security_level = security_level;
924 
925     //
926     channel->local_cid = l2cap_next_local_cid();
927     channel->con_handle = 0;
928 
929     // set initial state
930     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
931     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
932     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
933     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
934     return channel;
935 }
936 #endif
937 
938 #ifdef ENABLE_CLASSIC
939 
940 /**
941  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
942  * @param packet_handler
943  * @param address
944  * @param psm
945  * @param mtu
946  * @param local_cid
947  */
948 
949 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t local_mtu, uint16_t * out_local_cid){
950     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, local_mtu);
951 
952     if (local_mtu > l2cap_max_mtu()) {
953         local_mtu = l2cap_max_mtu();
954     }
955 
956     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
957     if (!channel) {
958         return BTSTACK_MEMORY_ALLOC_FAILED;
959     }
960 
961     // add to connections list
962     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
963 
964     // store local_cid
965     if (out_local_cid){
966        *out_local_cid = channel->local_cid;
967     }
968 
969     // check if hci connection is already usable
970     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
971     if (conn){
972         log_info("l2cap_create_channel, hci connection already exists");
973         l2cap_handle_connection_complete(conn->con_handle, channel);
974         // check if remote supported fearures are already received
975         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
976             l2cap_handle_remote_supported_features_received(channel);
977         }
978     }
979 
980     l2cap_run();
981 
982     return 0;
983 }
984 
985 void
986 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
987     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
988     // find channel for local_cid
989     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
990     if (channel) {
991         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
992     }
993     // process
994     l2cap_run();
995 }
996 
997 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
998     btstack_linked_list_iterator_t it;
999     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1000     while (btstack_linked_list_iterator_has_next(&it)){
1001         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1002         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1003         // channel for this address found
1004         switch (channel->state){
1005             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1006             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1007                 // failure, forward error code
1008                 l2cap_emit_channel_opened(channel, status);
1009                 // discard channel
1010                 l2cap_stop_rtx(channel);
1011                 btstack_linked_list_iterator_remove(&it);
1012                 btstack_memory_l2cap_channel_free(channel);
1013                 break;
1014             default:
1015                 break;
1016         }
1017     }
1018 }
1019 
1020 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1021     btstack_linked_list_iterator_t it;
1022     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1023     while (btstack_linked_list_iterator_has_next(&it)){
1024         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1025         if ( ! bd_addr_cmp( channel->address, address) ){
1026             l2cap_handle_connection_complete(handle, channel);
1027         }
1028     }
1029     // process
1030     l2cap_run();
1031 }
1032 #endif
1033 
1034 static void l2cap_notify_channel_can_send(void){
1035 
1036 #ifdef ENABLE_CLASSIC
1037     btstack_linked_list_iterator_t it;
1038     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1039     while (btstack_linked_list_iterator_has_next(&it)){
1040         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1041         if (!channel->waiting_for_can_send_now) continue;
1042         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1043         channel->waiting_for_can_send_now = 0;
1044         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1045     }
1046 #endif
1047 
1048     int i;
1049     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1050         if (!fixed_channels[i].callback) continue;
1051         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1052         int can_send;
1053         if (l2cap_fixed_channel_table_index_is_le(i)){
1054             can_send = hci_can_send_acl_le_packet_now();
1055         } else {
1056             can_send = hci_can_send_acl_classic_packet_now();
1057         }
1058         if (!can_send) continue;
1059         fixed_channels[i].waiting_for_can_send_now = 0;
1060         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1061     }
1062 }
1063 
1064 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1065 
1066     bd_addr_t address;
1067     hci_con_handle_t handle;
1068     int hci_con_used;
1069     btstack_linked_list_iterator_t it;
1070 
1071     // avoid unused warnings
1072     (void) address;
1073     (void) hci_con_used;
1074     (void) it;
1075 
1076     switch(hci_event_packet_get_type(packet)){
1077 
1078         // Notify channel packet handler if they can send now
1079         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1080         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1081             l2cap_run();    // try sending signaling packets first
1082             l2cap_notify_channel_can_send();
1083             break;
1084 
1085         case HCI_EVENT_COMMAND_STATUS:
1086             l2cap_run();    // try sending signaling packets first
1087             break;
1088 
1089 #ifdef ENABLE_CLASSIC
1090         // handle connection complete events
1091         case HCI_EVENT_CONNECTION_COMPLETE:
1092             reverse_bd_addr(&packet[5], address);
1093             if (packet[2] == 0){
1094                 handle = little_endian_read_16(packet, 3);
1095                 l2cap_handle_connection_success_for_addr(address, handle);
1096             } else {
1097                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1098             }
1099             break;
1100 
1101         // handle successful create connection cancel command
1102         case HCI_EVENT_COMMAND_COMPLETE:
1103             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1104                 if (packet[5] == 0){
1105                     reverse_bd_addr(&packet[6], address);
1106                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1107                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1108                 }
1109             }
1110             l2cap_run();    // try sending signaling packets first
1111             break;
1112 #endif
1113 
1114         // handle disconnection complete events
1115         case HCI_EVENT_DISCONNECTION_COMPLETE:
1116             // send l2cap disconnect events for all channels on this handle and free them
1117             handle = little_endian_read_16(packet, 3);
1118 #ifdef ENABLE_CLASSIC
1119             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1120             while (btstack_linked_list_iterator_has_next(&it)){
1121                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1122                 if (channel->con_handle != handle) continue;
1123                 l2cap_emit_channel_closed(channel);
1124                 l2cap_stop_rtx(channel);
1125                 btstack_linked_list_iterator_remove(&it);
1126                 btstack_memory_l2cap_channel_free(channel);
1127             }
1128 #endif
1129 #ifdef ENABLE_LE_DATA_CHANNELS
1130             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1131             while (btstack_linked_list_iterator_has_next(&it)){
1132                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1133                 if (channel->con_handle != handle) continue;
1134                 l2cap_emit_channel_closed(channel);
1135                 btstack_linked_list_iterator_remove(&it);
1136                 btstack_memory_l2cap_channel_free(channel);
1137             }
1138 #endif
1139             break;
1140 
1141         // HCI Connection Timeouts
1142 #ifdef ENABLE_CLASSIC
1143         case L2CAP_EVENT_TIMEOUT_CHECK:
1144             handle = little_endian_read_16(packet, 2);
1145             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1146             if (hci_authentication_active_for_handle(handle)) break;
1147             hci_con_used = 0;
1148             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1149             while (btstack_linked_list_iterator_has_next(&it)){
1150                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1151                 if (channel->con_handle != handle) continue;
1152                 hci_con_used = 1;
1153                 break;
1154             }
1155             if (hci_con_used) break;
1156             if (!hci_can_send_command_packet_now()) break;
1157             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1158             break;
1159 
1160         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1161             handle = little_endian_read_16(packet, 3);
1162             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1163             while (btstack_linked_list_iterator_has_next(&it)){
1164                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1165                 if (channel->con_handle != handle) continue;
1166                 l2cap_handle_remote_supported_features_received(channel);
1167                 break;
1168             }
1169             break;
1170 
1171         case GAP_EVENT_SECURITY_LEVEL:
1172             handle = little_endian_read_16(packet, 2);
1173             log_info("l2cap - security level update");
1174             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1175             while (btstack_linked_list_iterator_has_next(&it)){
1176                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1177                 if (channel->con_handle != handle) continue;
1178 
1179                 log_info("l2cap - state %u", channel->state);
1180 
1181                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1182                 gap_security_level_t required_level = channel->required_security_level;
1183 
1184                 switch (channel->state){
1185                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1186                         if (actual_level >= required_level){
1187                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1188                             l2cap_emit_incoming_connection(channel);
1189                         } else {
1190                             channel->reason = 0x0003; // security block
1191                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1192                         }
1193                         break;
1194 
1195                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1196                         if (actual_level >= required_level){
1197                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1198                         } else {
1199                             // disconnnect, authentication not good enough
1200                             hci_disconnect_security_block(handle);
1201                         }
1202                         break;
1203 
1204                     default:
1205                         break;
1206                 }
1207             }
1208             break;
1209 #endif
1210 
1211         default:
1212             break;
1213     }
1214 
1215     l2cap_run();
1216 }
1217 
1218 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
1219     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1220     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1221         signaling_responses[signaling_responses_pending].handle = handle;
1222         signaling_responses[signaling_responses_pending].code = code;
1223         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1224         signaling_responses[signaling_responses_pending].data = data;
1225         signaling_responses_pending++;
1226         l2cap_run();
1227     }
1228 }
1229 
1230 #ifdef ENABLE_CLASSIC
1231 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1232     channel->remote_sig_id = identifier;
1233     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1234     l2cap_run();
1235 }
1236 
1237 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1238 
1239     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1240     l2cap_service_t *service = l2cap_get_service(psm);
1241     if (!service) {
1242         // 0x0002 PSM not supported
1243         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1244         return;
1245     }
1246 
1247     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1248     if (!hci_connection) {
1249         //
1250         log_error("no hci_connection for handle %u", handle);
1251         return;
1252     }
1253 
1254     // alloc structure
1255     // log_info("l2cap_handle_connection_request register channel");
1256     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1257     psm, service->mtu, service->required_security_level);
1258     if (!channel){
1259         // 0x0004 No resources available
1260         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1261         return;
1262     }
1263 
1264     channel->con_handle = handle;
1265     channel->remote_cid = source_cid;
1266     channel->remote_sig_id = sig_id;
1267 
1268     // limit local mtu to max acl packet length - l2cap header
1269     if (channel->local_mtu > l2cap_max_mtu()) {
1270         channel->local_mtu = l2cap_max_mtu();
1271     }
1272 
1273     // set initial state
1274     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1275     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1276 
1277     // add to connections list
1278     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1279 
1280     // assert security requirements
1281     gap_request_security_level(handle, channel->required_security_level);
1282 }
1283 
1284 void l2cap_accept_connection(uint16_t local_cid){
1285     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1286     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1287     if (!channel) {
1288         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1289         return;
1290     }
1291 
1292     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1293 
1294     // process
1295     l2cap_run();
1296 }
1297 
1298 void l2cap_decline_connection(uint16_t local_cid){
1299     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1300     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1301     if (!channel) {
1302         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1303         return;
1304     }
1305     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1306     channel->reason = 0x04; // no resources available
1307     l2cap_run();
1308 }
1309 
1310 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1311 
1312     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1313 
1314     uint16_t flags = little_endian_read_16(command, 6);
1315     if (flags & 1) {
1316         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1317     }
1318 
1319     // accept the other's configuration options
1320     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1321     uint16_t pos     = 8;
1322     while (pos < end_pos){
1323         uint8_t option_hint = command[pos] >> 7;
1324         uint8_t option_type = command[pos] & 0x7f;
1325         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1326         pos++;
1327         uint8_t length = command[pos++];
1328         // MTU { type(8): 1, len(8):2, MTU(16) }
1329         if (option_type == 1 && length == 2){
1330             channel->remote_mtu = little_endian_read_16(command, pos);
1331             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1332             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1333         }
1334         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1335         if (option_type == 2 && length == 2){
1336             channel->flush_timeout = little_endian_read_16(command, pos);
1337         }
1338         // check for unknown options
1339         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1340             log_info("l2cap cid %u, unknown options", channel->local_cid);
1341             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1342         }
1343         pos += length;
1344     }
1345 }
1346 
1347 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1348     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1349     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1350     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1351     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1352     if (channel->state == L2CAP_STATE_OPEN) return 0;
1353     return 1;
1354 }
1355 
1356 
1357 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1358 
1359     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1360     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1361     uint16_t result = 0;
1362 
1363     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1364 
1365     // handle DISCONNECT REQUESTS seperately
1366     if (code == DISCONNECTION_REQUEST){
1367         switch (channel->state){
1368             case L2CAP_STATE_CONFIG:
1369             case L2CAP_STATE_OPEN:
1370             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1371             case L2CAP_STATE_WAIT_DISCONNECT:
1372                 l2cap_handle_disconnect_request(channel, identifier);
1373                 break;
1374 
1375             default:
1376                 // ignore in other states
1377                 break;
1378         }
1379         return;
1380     }
1381 
1382     // @STATEMACHINE(l2cap)
1383     switch (channel->state) {
1384 
1385         case L2CAP_STATE_WAIT_CONNECT_RSP:
1386             switch (code){
1387                 case CONNECTION_RESPONSE:
1388                     l2cap_stop_rtx(channel);
1389                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1390                     switch (result) {
1391                         case 0:
1392                             // successful connection
1393                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1394                             channel->state = L2CAP_STATE_CONFIG;
1395                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1396                             break;
1397                         case 1:
1398                             // connection pending. get some coffee, but start the ERTX
1399                             l2cap_start_ertx(channel);
1400                             break;
1401                         default:
1402                             // channel closed
1403                             channel->state = L2CAP_STATE_CLOSED;
1404                             // map l2cap connection response result to BTstack status enumeration
1405                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1406 
1407                             // drop link key if security block
1408                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1409                                 gap_drop_link_key_for_bd_addr(channel->address);
1410                             }
1411 
1412                             // discard channel
1413                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1414                             btstack_memory_l2cap_channel_free(channel);
1415                             break;
1416                     }
1417                     break;
1418 
1419                 default:
1420                     //@TODO: implement other signaling packets
1421                     break;
1422             }
1423             break;
1424 
1425         case L2CAP_STATE_CONFIG:
1426             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1427             switch (code) {
1428                 case CONFIGURE_REQUEST:
1429                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1430                     l2cap_signaling_handle_configure_request(channel, command);
1431                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1432                         // only done if continuation not set
1433                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1434                     }
1435                     break;
1436                 case CONFIGURE_RESPONSE:
1437                     l2cap_stop_rtx(channel);
1438                     switch (result){
1439                         case 0: // success
1440                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1441                             break;
1442                         case 4: // pending
1443                             l2cap_start_ertx(channel);
1444                             break;
1445                         default:
1446                             // retry on negative result
1447                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1448                             break;
1449                     }
1450                     break;
1451                 default:
1452                     break;
1453             }
1454             if (l2cap_channel_ready_for_open(channel)){
1455                 // for open:
1456                 channel->state = L2CAP_STATE_OPEN;
1457                 l2cap_emit_channel_opened(channel, 0);
1458             }
1459             break;
1460 
1461         case L2CAP_STATE_WAIT_DISCONNECT:
1462             switch (code) {
1463                 case DISCONNECTION_RESPONSE:
1464                     l2cap_finialize_channel_close(channel);
1465                     break;
1466                 default:
1467                     //@TODO: implement other signaling packets
1468                     break;
1469             }
1470             break;
1471 
1472         case L2CAP_STATE_CLOSED:
1473             // @TODO handle incoming requests
1474             break;
1475 
1476         case L2CAP_STATE_OPEN:
1477             //@TODO: implement other signaling packets, e.g. re-configure
1478             break;
1479         default:
1480             break;
1481     }
1482     // log_info("new state %u", channel->state);
1483 }
1484 
1485 
1486 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1487 
1488     // get code, signalind identifier and command len
1489     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1490     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1491 
1492     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1493     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1494         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1495         return;
1496     }
1497 
1498     // general commands without an assigned channel
1499     switch(code) {
1500 
1501         case CONNECTION_REQUEST: {
1502             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1503             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1504             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1505             return;
1506         }
1507 
1508         case ECHO_REQUEST:
1509             l2cap_register_signaling_response(handle, code, sig_id, 0);
1510             return;
1511 
1512         case INFORMATION_REQUEST: {
1513             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1514             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1515             return;
1516         }
1517 
1518         default:
1519             break;
1520     }
1521 
1522 
1523     // Get potential destination CID
1524     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1525 
1526     // Find channel for this sig_id and connection handle
1527     btstack_linked_list_iterator_t it;
1528     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1529     while (btstack_linked_list_iterator_has_next(&it)){
1530         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1531         if (channel->con_handle != handle) continue;
1532         if (code & 1) {
1533             // match odd commands (responses) by previous signaling identifier
1534             if (channel->local_sig_id == sig_id) {
1535                 l2cap_signaling_handler_channel(channel, command);
1536                 break;
1537             }
1538         } else {
1539             // match even commands (requests) by local channel id
1540             if (channel->local_cid == dest_cid) {
1541                 l2cap_signaling_handler_channel(channel, command);
1542                 break;
1543             }
1544         }
1545     }
1546 }
1547 #endif
1548 
1549 #ifdef ENABLE_BLE
1550 
1551 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
1552     uint8_t event[6];
1553     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
1554     event[1] = 4;
1555     little_endian_store_16(event, 2, con_handle);
1556     little_endian_store_16(event, 4, result);
1557     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1558     if (!l2cap_event_packet_handler) return;
1559     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
1560 }
1561 
1562 // @returns valid
1563 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1564     hci_connection_t * connection;
1565     uint16_t result;
1566     uint8_t  event[10];
1567 
1568 #ifdef ENABLE_LE_DATA_CHANNELS
1569     btstack_linked_list_iterator_t it;
1570     l2cap_channel_t * channel;
1571     uint16_t local_cid;
1572     uint16_t le_psm;
1573     uint16_t new_credits;
1574     uint16_t credits_before;
1575     l2cap_service_t * service;
1576 #endif
1577 
1578     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1579     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1580 
1581     switch (code){
1582 
1583         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1584             result = little_endian_read_16(command, 4);
1585             l2cap_emit_connection_parameter_update_response(handle, result);
1586             break;
1587 
1588         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1589             connection = hci_connection_for_handle(handle);
1590             if (connection){
1591                 if (connection->role != HCI_ROLE_MASTER){
1592                     // reject command without notifying upper layer when not in master role
1593                     return 0;
1594                 }
1595                 int update_parameter = 1;
1596                 le_connection_parameter_range_t existing_range;
1597                 gap_get_connection_parameter_range(&existing_range);
1598                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1599                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1600                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1601                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1602 
1603                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1604                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1605 
1606                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1607                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1608 
1609                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1610                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1611 
1612                 if (update_parameter){
1613                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1614                     connection->le_conn_interval_min = le_conn_interval_min;
1615                     connection->le_conn_interval_max = le_conn_interval_max;
1616                     connection->le_conn_latency = le_conn_latency;
1617                     connection->le_supervision_timeout = le_supervision_timeout;
1618                 } else {
1619                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1620                 }
1621                 connection->le_con_param_update_identifier = sig_id;
1622             }
1623 
1624             if (!l2cap_event_packet_handler) break;
1625 
1626             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1627             event[1] = 8;
1628             memcpy(&event[2], &command[4], 8);
1629             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1630             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1631             break;
1632 
1633 #ifdef ENABLE_LE_DATA_CHANNELS
1634 
1635         case COMMAND_REJECT:
1636             // Find channel for this sig_id and connection handle
1637             channel = NULL;
1638             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1639             while (btstack_linked_list_iterator_has_next(&it)){
1640                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1641                 if (a_channel->con_handle   != handle) continue;
1642                 if (a_channel->local_sig_id != sig_id) continue;
1643                 channel = a_channel;
1644                 break;
1645             }
1646             if (!channel) break;
1647 
1648             // if received while waiting for le connection response, assume legacy device
1649             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1650                 channel->state = L2CAP_STATE_CLOSED;
1651                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1652                 l2cap_emit_le_channel_opened(channel, 0x0002);
1653 
1654                 // discard channel
1655                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1656                 btstack_memory_l2cap_channel_free(channel);
1657                 break;
1658             }
1659             break;
1660 
1661         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1662 
1663             // get hci connection, bail if not found (must not happen)
1664             connection = hci_connection_for_handle(handle);
1665             if (!connection) return 0;
1666 
1667             // check if service registered
1668             le_psm  = little_endian_read_16(command, 4);
1669             service = l2cap_le_get_service(le_psm);
1670 
1671             if (service){
1672 
1673                 uint16_t source_cid = little_endian_read_16(command, 6);
1674                 if (source_cid < 0x40){
1675                     // 0x0009 Connection refused - Invalid Source CID
1676                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0009);
1677                     return 1;
1678                 }
1679 
1680                 // go through list of channels for this ACL connection and check if we get a match
1681                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1682                 while (btstack_linked_list_iterator_has_next(&it)){
1683                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1684                     if (a_channel->con_handle != handle) continue;
1685                     if (a_channel->remote_cid != source_cid) continue;
1686                     // 0x000a Connection refused - Source CID already allocated
1687                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x000a);
1688                     return 1;
1689                 }
1690 
1691                 // security: check encryption
1692                 if (service->required_security_level >= LEVEL_2){
1693                     if (sm_encryption_key_size(handle) == 0){
1694                         // 0x0008 Connection refused - insufficient encryption
1695                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0008);
1696                         return 1;
1697                     }
1698                     // anything less than 16 byte key size is insufficient
1699                     if (sm_encryption_key_size(handle) < 16){
1700                         // 0x0007 Connection refused – insufficient encryption key size
1701                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0007);
1702                         return 1;
1703                     }
1704                 }
1705 
1706                 // security: check authencation
1707                 if (service->required_security_level >= LEVEL_3){
1708                     if (!sm_authenticated(handle)){
1709                         // 0x0005 Connection refused – insufficient authentication
1710                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0005);
1711                         return 1;
1712                     }
1713                 }
1714 
1715                 // security: check authorization
1716                 if (service->required_security_level >= LEVEL_4){
1717                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1718                         // 0x0006 Connection refused – insufficient authorization
1719                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0006);
1720                         return 1;
1721                     }
1722                 }
1723 
1724                 // allocate channel
1725                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1726                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1727                 if (!channel){
1728                     // 0x0004 Connection refused – no resources available
1729                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0004);
1730                     return 1;
1731                 }
1732 
1733                 channel->con_handle = handle;
1734                 channel->remote_cid = source_cid;
1735                 channel->remote_sig_id = sig_id;
1736                 channel->remote_mtu = little_endian_read_16(command, 8);
1737                 channel->remote_mps = little_endian_read_16(command, 10);
1738                 channel->credits_outgoing = little_endian_read_16(command, 12);
1739 
1740                 // set initial state
1741                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1742                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
1743 
1744                 // add to connections list
1745                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1746 
1747                 // post connection request event
1748                 l2cap_emit_le_incoming_connection(channel);
1749 
1750             } else {
1751                 // Connection refused – LE_PSM not supported
1752                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0002);
1753             }
1754             break;
1755 
1756         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1757             // Find channel for this sig_id and connection handle
1758             channel = NULL;
1759             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1760             while (btstack_linked_list_iterator_has_next(&it)){
1761                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1762                 if (a_channel->con_handle   != handle) continue;
1763                 if (a_channel->local_sig_id != sig_id) continue;
1764                 channel = a_channel;
1765                 break;
1766             }
1767             if (!channel) break;
1768 
1769             // cid + 0
1770             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1771             if (result){
1772                 channel->state = L2CAP_STATE_CLOSED;
1773                 // map l2cap connection response result to BTstack status enumeration
1774                 l2cap_emit_le_channel_opened(channel, result);
1775 
1776                 // discard channel
1777                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1778                 btstack_memory_l2cap_channel_free(channel);
1779                 break;
1780             }
1781 
1782             // success
1783             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1784             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1785             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1786             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1787             channel->state = L2CAP_STATE_OPEN;
1788             l2cap_emit_le_channel_opened(channel, result);
1789             break;
1790 
1791         case LE_FLOW_CONTROL_CREDIT:
1792             // find channel
1793             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1794             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1795             if (!channel) {
1796                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1797                 break;
1798             }
1799             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1800             credits_before = channel->credits_outgoing;
1801             channel->credits_outgoing += new_credits;
1802             // check for credit overrun
1803             if (credits_before > channel->credits_outgoing){
1804                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1805                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1806                 break;
1807             }
1808             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1809             break;
1810 
1811         case DISCONNECTION_REQUEST:
1812             // find channel
1813             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1814             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1815             if (!channel) {
1816                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1817                 break;
1818             }
1819             channel->remote_sig_id = sig_id;
1820             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1821             break;
1822 
1823 #endif
1824 
1825         case DISCONNECTION_RESPONSE:
1826             break;
1827 
1828         default:
1829             // command unknown -> reject command
1830             return 0;
1831     }
1832     return 1;
1833 }
1834 #endif
1835 
1836 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1837 
1838     l2cap_channel_t * l2cap_channel;
1839     (void) l2cap_channel;
1840 
1841     // Get Channel ID
1842     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1843     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1844 
1845     switch (channel_id) {
1846 
1847 #ifdef ENABLE_CLASSIC
1848         case L2CAP_CID_SIGNALING: {
1849             uint16_t command_offset = 8;
1850             while (command_offset < size) {
1851                 // handle signaling commands
1852                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1853 
1854                 // increment command_offset
1855                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1856             }
1857             break;
1858         }
1859 #endif
1860 
1861 #ifdef ENABLE_BLE
1862         case L2CAP_CID_SIGNALING_LE: {
1863             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1864             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1865             if (!valid){
1866                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1867             }
1868             break;
1869         }
1870 #endif
1871 
1872         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1873             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1874                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1875             }
1876             break;
1877 
1878         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1879             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1880                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1881             }
1882             break;
1883 
1884         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1885             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1886                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1887             }
1888             break;
1889 
1890         default:
1891 #ifdef ENABLE_CLASSIC
1892             // Find channel for this channel_id and connection handle
1893             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1894             if (l2cap_channel) {
1895                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1896             }
1897 #endif
1898 #ifdef ENABLE_LE_DATA_CHANNELS
1899             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1900             if (l2cap_channel) {
1901                 // credit counting
1902                 if (l2cap_channel->credits_incoming == 0){
1903                     log_error("LE Data Channel packet received but no incoming credits");
1904                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1905                     break;
1906                 }
1907                 l2cap_channel->credits_incoming--;
1908 
1909                 // automatic credits
1910                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
1911                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
1912                 }
1913 
1914                 // first fragment
1915                 uint16_t pos = 0;
1916                 if (!l2cap_channel->receive_sdu_len){
1917                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
1918                     l2cap_channel->receive_sdu_pos = 0;
1919                     pos  += 2;
1920                     size -= 2;
1921                 }
1922                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
1923                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
1924                 // done?
1925                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
1926                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
1927                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
1928                     l2cap_channel->receive_sdu_len = 0;
1929                 }
1930             } else {
1931                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
1932             }
1933 #endif
1934             break;
1935     }
1936 
1937     l2cap_run();
1938 }
1939 
1940 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1941 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1942     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
1943     if (index < 0) return;
1944     fixed_channels[index].callback = the_packet_handler;
1945 }
1946 
1947 #ifdef ENABLE_CLASSIC
1948 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1949 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
1950     channel->state = L2CAP_STATE_CLOSED;
1951     l2cap_emit_channel_closed(channel);
1952     // discard channel
1953     l2cap_stop_rtx(channel);
1954     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1955     btstack_memory_l2cap_channel_free(channel);
1956 }
1957 
1958 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1959     btstack_linked_list_iterator_t it;
1960     btstack_linked_list_iterator_init(&it, services);
1961     while (btstack_linked_list_iterator_has_next(&it)){
1962         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
1963         if ( service->psm == psm){
1964             return service;
1965         };
1966     }
1967     return NULL;
1968 }
1969 
1970 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1971     return l2cap_get_service_internal(&l2cap_services, psm);
1972 }
1973 
1974 
1975 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1976 
1977     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
1978 
1979     // check for alread registered psm
1980     l2cap_service_t *service = l2cap_get_service(psm);
1981     if (service) {
1982         log_error("l2cap_register_service: PSM %u already registered", psm);
1983         return L2CAP_SERVICE_ALREADY_REGISTERED;
1984     }
1985 
1986     // alloc structure
1987     service = btstack_memory_l2cap_service_get();
1988     if (!service) {
1989         log_error("l2cap_register_service: no memory for l2cap_service_t");
1990         return BTSTACK_MEMORY_ALLOC_FAILED;
1991     }
1992 
1993     // fill in
1994     service->psm = psm;
1995     service->mtu = mtu;
1996     service->packet_handler = service_packet_handler;
1997     service->required_security_level = security_level;
1998 
1999     // add to services list
2000     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2001 
2002     // enable page scan
2003     gap_connectable_control(1);
2004 
2005     return 0;
2006 }
2007 
2008 uint8_t l2cap_unregister_service(uint16_t psm){
2009 
2010     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2011 
2012     l2cap_service_t *service = l2cap_get_service(psm);
2013     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2014     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2015     btstack_memory_l2cap_service_free(service);
2016 
2017     // disable page scan when no services registered
2018     if (btstack_linked_list_empty(&l2cap_services)) {
2019         gap_connectable_control(0);
2020     }
2021     return 0;
2022 }
2023 #endif
2024 
2025 
2026 #ifdef ENABLE_LE_DATA_CHANNELS
2027 
2028 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2029     if (!channel->waiting_for_can_send_now) return;
2030     if (channel->send_sdu_buffer) return;
2031     channel->waiting_for_can_send_now = 0;
2032     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2033     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2034 }
2035 
2036 // 1BH2222
2037 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2038     log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
2039              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2040     uint8_t event[19];
2041     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2042     event[1] = sizeof(event) - 2;
2043     event[2] = channel->address_type;
2044     reverse_bd_addr(channel->address, &event[3]);
2045     little_endian_store_16(event,  9, channel->con_handle);
2046     little_endian_store_16(event, 11, channel->psm);
2047     little_endian_store_16(event, 13, channel->local_cid);
2048     little_endian_store_16(event, 15, channel->remote_cid);
2049     little_endian_store_16(event, 17, channel->remote_mtu);
2050     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2051     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2052 }
2053 // 11BH22222
2054 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2055     log_info("L2CAP_EVENT_LE_CHANNEL_OPENED status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
2056              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2057              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2058     uint8_t event[23];
2059     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2060     event[1] = sizeof(event) - 2;
2061     event[2] = status;
2062     event[3] = channel->address_type;
2063     reverse_bd_addr(channel->address, &event[4]);
2064     little_endian_store_16(event, 10, channel->con_handle);
2065     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2066     little_endian_store_16(event, 13, channel->psm);
2067     little_endian_store_16(event, 15, channel->local_cid);
2068     little_endian_store_16(event, 17, channel->remote_cid);
2069     little_endian_store_16(event, 19, channel->local_mtu);
2070     little_endian_store_16(event, 21, channel->remote_mtu);
2071     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2072     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2073 }
2074 
2075 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2076     btstack_linked_list_iterator_t it;
2077     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2078     while (btstack_linked_list_iterator_has_next(&it)){
2079         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2080         if ( channel->local_cid == local_cid) {
2081             return channel;
2082         }
2083     }
2084     return NULL;
2085 }
2086 
2087 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2088 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2089     channel->state = L2CAP_STATE_CLOSED;
2090     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2091     // discard channel
2092     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2093     btstack_memory_l2cap_channel_free(channel);
2094 }
2095 
2096 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2097     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2098 }
2099 
2100 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2101 
2102     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2103 
2104     // check for alread registered psm
2105     l2cap_service_t *service = l2cap_le_get_service(psm);
2106     if (service) {
2107         return L2CAP_SERVICE_ALREADY_REGISTERED;
2108     }
2109 
2110     // alloc structure
2111     service = btstack_memory_l2cap_service_get();
2112     if (!service) {
2113         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2114         return BTSTACK_MEMORY_ALLOC_FAILED;
2115     }
2116 
2117     // fill in
2118     service->psm = psm;
2119     service->mtu = 0;
2120     service->packet_handler = packet_handler;
2121     service->required_security_level = security_level;
2122 
2123     // add to services list
2124     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2125 
2126     // done
2127     return 0;
2128 }
2129 
2130 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2131     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2132     l2cap_service_t *service = l2cap_le_get_service(psm);
2133     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2134 
2135     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2136     btstack_memory_l2cap_service_free(service);
2137     return 0;
2138 }
2139 
2140 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2141     // get channel
2142     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2143     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2144 
2145     // validate state
2146     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2147         return ERROR_CODE_COMMAND_DISALLOWED;
2148     }
2149 
2150     // set state accept connection
2151     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2152     channel->receive_sdu_buffer = receive_sdu_buffer;
2153     channel->local_mtu = mtu;
2154     channel->new_credits_incoming = initial_credits;
2155     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2156 
2157     // test
2158     // channel->new_credits_incoming = 1;
2159 
2160     // go
2161     l2cap_run();
2162     return 0;
2163 }
2164 
2165 /**
2166  * @brief Deny incoming LE Data Channel connection due to resource constraints
2167  * @param local_cid             L2CAP LE Data Channel Identifier
2168  */
2169 
2170 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2171     // get channel
2172     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2173     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2174 
2175     // validate state
2176     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2177         return ERROR_CODE_COMMAND_DISALLOWED;
2178     }
2179 
2180     // set state decline connection
2181     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2182     channel->reason = 0x04; // no resources available
2183     l2cap_run();
2184     return 0;
2185 }
2186 
2187 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2188     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2189     uint16_t * out_local_cid) {
2190 
2191     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2192 
2193 
2194     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2195     if (!connection) {
2196         log_error("no hci_connection for handle 0x%04x", con_handle);
2197         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2198     }
2199 
2200     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2201     if (!channel) {
2202         return BTSTACK_MEMORY_ALLOC_FAILED;
2203     }
2204     log_info("l2cap_le_create_channel %p", channel);
2205 
2206     // store local_cid
2207     if (out_local_cid){
2208        *out_local_cid = channel->local_cid;
2209     }
2210 
2211     // provide buffer
2212     channel->con_handle = con_handle;
2213     channel->receive_sdu_buffer = receive_sdu_buffer;
2214     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2215     channel->new_credits_incoming = initial_credits;
2216     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2217 
2218     // add to connections list
2219     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2220 
2221     // go
2222     l2cap_run();
2223     return 0;
2224 }
2225 
2226 /**
2227  * @brief Provide credtis for LE Data Channel
2228  * @param local_cid             L2CAP LE Data Channel Identifier
2229  * @param credits               Number additional credits for peer
2230  */
2231 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2232 
2233     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2234     if (!channel) {
2235         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2236         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2237     }
2238 
2239     // check state
2240     if (channel->state != L2CAP_STATE_OPEN){
2241         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2242     }
2243 
2244     // assert incoming credits + credits <= 0xffff
2245     uint32_t total_credits = channel->credits_incoming;
2246     total_credits += channel->new_credits_incoming;
2247     total_credits += credits;
2248     if (total_credits > 0xffff){
2249         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2250             channel->new_credits_incoming, credits);
2251     }
2252 
2253     // set credits_granted
2254     channel->new_credits_incoming += credits;
2255 
2256     // go
2257     l2cap_run();
2258     return 0;
2259 }
2260 
2261 /**
2262  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2263  * @param local_cid             L2CAP LE Data Channel Identifier
2264  */
2265 int l2cap_le_can_send_now(uint16_t local_cid){
2266     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2267     if (!channel) {
2268         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2269         return 0;
2270     }
2271 
2272     // check state
2273     if (channel->state != L2CAP_STATE_OPEN) return 0;
2274 
2275     // check queue
2276     if (channel->send_sdu_buffer) return 0;
2277 
2278     // fine, go ahead
2279     return 1;
2280 }
2281 
2282 /**
2283  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2284  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2285  *       so packet handler should be ready to handle it
2286  * @param local_cid             L2CAP LE Data Channel Identifier
2287  */
2288 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2289     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2290     if (!channel) {
2291         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
2292         return 0;
2293     }
2294     channel->waiting_for_can_send_now = 1;
2295     l2cap_le_notify_channel_can_send(channel);
2296     return 0;
2297 }
2298 
2299 /**
2300  * @brief Send data via LE Data Channel
2301  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2302  * @param local_cid             L2CAP LE Data Channel Identifier
2303  * @param data                  data to send
2304  * @param size                  data size
2305  */
2306 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2307 
2308     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2309     if (!channel) {
2310         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2311         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2312     }
2313 
2314     if (len > channel->remote_mtu){
2315         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2316         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2317     }
2318 
2319     if (channel->send_sdu_buffer){
2320         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2321         return BTSTACK_ACL_BUFFERS_FULL;
2322     }
2323 
2324     channel->send_sdu_buffer = data;
2325     channel->send_sdu_len    = len;
2326     channel->send_sdu_pos    = 0;
2327 
2328     l2cap_run();
2329     return 0;
2330 }
2331 
2332 /**
2333  * @brief Disconnect from LE Data Channel
2334  * @param local_cid             L2CAP LE Data Channel Identifier
2335  */
2336 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2337 {
2338     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2339     if (!channel) {
2340         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2341         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2342     }
2343 
2344     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2345     l2cap_run();
2346     return 0;
2347 }
2348 
2349 #endif
2350