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