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