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