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