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