xref: /btstack/src/l2cap.c (revision e7ff783c33345b844f175b5df7c58252307efed7)
1 /*
2  * Copyright (C) 2009 by Matthias Ringwald
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  l2cap.c
34  *
35  *  Logical Link Control and Adaption Protocl (L2CAP)
36  *
37  *  Created by Matthias Ringwald on 5/16/09.
38  */
39 
40 #include "l2cap.h"
41 #include "hci.h"
42 #include "hci_dump.h"
43 #include "debug.h"
44 
45 #include <stdarg.h>
46 #include <string.h>
47 
48 #include <stdio.h>
49 
50 // size of HCI ACL + L2CAP Header for regular data packets
51 #define COMPLETE_L2CAP_HEADER 8
52 
53 // minimum signaling MTU
54 #define L2CAP_MINIMAL_MTU 48
55 #define L2CAP_DEFAULT_MTU 672
56 
57 // nr of buffered acl packets in outgoing queue to get max performance
58 #define NR_BUFFERED_ACL_PACKETS 3
59 
60 // offsets for L2CAP SIGNALING COMMANDS
61 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
62 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
63 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
64 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
65 
66 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
67 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
68 
69 static uint8_t * sig_buffer = NULL;
70 static linked_list_t l2cap_channels = NULL;
71 static linked_list_t l2cap_services = NULL;
72 static uint8_t * acl_buffer = NULL;
73 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
74 static int new_credits_blocked = 0;
75 
76 void l2cap_init(){
77     sig_buffer = malloc( L2CAP_MINIMAL_MTU );
78     acl_buffer = malloc( HCI_ACL_3DH5_SIZE);
79 
80     new_credits_blocked = 0;
81 
82     //
83     // register callback with HCI
84     //
85     hci_register_packet_handler(&l2cap_packet_handler);
86 }
87 
88 
89 /** Register L2CAP packet handlers */
90 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
91 }
92 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
93     packet_handler = handler;
94 }
95 
96 //  notify client/protocol handler
97 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
98     if (channel->packet_handler) {
99         (* (channel->packet_handler))(type, channel->local_cid, data, size);
100     } else {
101         (*packet_handler)(channel->connection, type, channel->local_cid, data, size);
102     }
103 }
104 
105 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
106     uint8_t event[21];
107     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
108     event[1] = sizeof(event) - 2;
109     event[2] = status;
110     bt_flip_addr(&event[3], channel->address);
111     bt_store_16(event,  9, channel->handle);
112     bt_store_16(event, 11, channel->psm);
113     bt_store_16(event, 13, channel->local_cid);
114     bt_store_16(event, 15, channel->remote_cid);
115     bt_store_16(event, 17, channel->local_mtu);
116     bt_store_16(event, 19, channel->remote_mtu);
117     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
118     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
119 }
120 
121 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
122     uint8_t event[4];
123     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
124     event[1] = sizeof(event) - 2;
125     bt_store_16(event, 2, channel->local_cid);
126     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
127     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
128 }
129 
130 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
131     uint8_t event[16];
132     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
133     event[1] = sizeof(event) - 2;
134     bt_flip_addr(&event[2], channel->address);
135     bt_store_16(event,  8, channel->handle);
136     bt_store_16(event, 10, channel->psm);
137     bt_store_16(event, 12, channel->local_cid);
138     bt_store_16(event, 14, channel->remote_cid);
139     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
140     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
141 }
142 
143 void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) {
144     // track credits
145     channel->packets_granted += credits;
146     // log_dbg("l2cap_emit_credits for cid %u, credits given: %u (+%u)\n", channel->local_cid, channel->packets_granted, credits);
147 
148     uint8_t event[5];
149     event[0] = L2CAP_EVENT_CREDITS;
150     event[1] = sizeof(event) - 2;
151     bt_store_16(event, 2, channel->local_cid);
152     event[4] = credits;
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_block_new_credits(uint8_t blocked){
158     new_credits_blocked = blocked;
159 }
160 
161 void l2cap_hand_out_credits(void){
162 
163     if (new_credits_blocked) return;    // we're told not to. used by daemon
164 
165     linked_item_t *it;
166     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
167         if (!hci_number_free_acl_slots()) return;
168         l2cap_channel_t * channel = (l2cap_channel_t *) it;
169         if (channel->state != L2CAP_STATE_OPEN) continue;
170         if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) {
171             l2cap_emit_credits(channel, 1);
172         }
173     }
174 }
175 
176 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
177     linked_item_t *it;
178     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
179         l2cap_channel_t * channel = (l2cap_channel_t *) it;
180         if ( channel->local_cid == local_cid) {
181             return channel;
182         }
183     }
184     return NULL;
185 }
186 
187 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
188     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
189     if (channel) {
190         return channel->remote_mtu;
191     }
192     return 0;
193 }
194 
195 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
196     // log_dbg("l2cap_send_signaling_packet type %u\n", cmd);
197     va_list argptr;
198     va_start(argptr, identifier);
199     uint16_t len = l2cap_create_signaling_internal(sig_buffer, handle, cmd, identifier, argptr);
200     va_end(argptr);
201     // log_dbg("l2cap_send_signaling_packet con %u!\n", handle);
202     return hci_send_acl_packet(sig_buffer, len);
203 }
204 
205 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
206 
207     // check for free places on BT module
208     if (!hci_number_free_acl_slots()) {
209         log_dbg("l2cap_send_internal cid %u, BT module full <-----\n", local_cid);
210         return BTSTACK_ACL_BUFFERS_FULL;
211     }
212     int err = 0;
213 
214     // find channel for local_cid, construct l2cap packet and send
215     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
216     if (channel) {
217         if (channel->packets_granted > 0){
218             --channel->packets_granted;
219             // log_dbg("l2cap_send_internal cid %u, handle %u, 1 credit used, credits left %u;\n",
220             //        local_cid, channel->handle, channel->packets_granted);
221         } else {
222             log_err("l2cap_send_internal cid %u, no credits!\n", local_cid);
223         }
224 
225         // 0 - Connection handle : PB=10 : BC=00
226         bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14));
227         // 2 - ACL length
228         bt_store_16(acl_buffer, 2,  len + 4);
229         // 4 - L2CAP packet length
230         bt_store_16(acl_buffer, 4,  len + 0);
231         // 6 - L2CAP channel DEST
232         bt_store_16(acl_buffer, 6, channel->remote_cid);
233         // 8 - data
234         memcpy(&acl_buffer[8], data, len);
235 
236         // send
237         err = hci_send_acl_packet(acl_buffer, len+8);
238     }
239 
240     l2cap_hand_out_credits();
241 
242     return err;
243 }
244 
245 // process outstanding signaling tasks
246 void l2cap_run(void){
247     linked_item_t *it;
248     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
249 
250         // can send?
251 
252         l2cap_channel_t * channel = (l2cap_channel_t *) it;
253         switch (channel->state){
254 
255             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
256                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, 0, 0, channel->reason, 0);
257                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
258                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
259                 free (channel);
260                 break;
261 
262             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
263                 // success, start l2cap handshake
264                 channel->sig_id = l2cap_next_sig_id();
265                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->sig_id, channel->psm, channel->local_cid);
266                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
267                 break;
268 
269             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
270                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid);
271                 l2cap_finialize_channel_close(channel);
272                 break;
273 
274             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
275                 channel->sig_id = l2cap_next_sig_id();
276                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
277                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
278                 break;
279             default:
280                 break;
281         }
282     }
283 }
284 
285 // open outgoing L2CAP channel
286 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler,
287                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
288 
289     // alloc structure
290     l2cap_channel_t * chan = malloc(sizeof(l2cap_channel_t));
291     // TODO: emit error event
292     if (!chan) return;
293 
294     // limit local mtu to max acl packet length
295     if (mtu > hci_max_acl_data_packet_length()) {
296         mtu = hci_max_acl_data_packet_length();
297     }
298 
299     // fill in
300     BD_ADDR_COPY(chan->address, address);
301     chan->psm = psm;
302     chan->handle = 0;
303     chan->connection = connection;
304     chan->packet_handler = packet_handler;
305     chan->remote_mtu = L2CAP_MINIMAL_MTU;
306     chan->local_mtu = mtu;
307     chan->packets_granted = 0;
308 
309     // set initial state
310     chan->state = L2CAP_STATE_CLOSED;
311     chan->sig_id = L2CAP_SIG_ID_INVALID;
312 
313     // add to connections list
314     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
315 
316     // send connection request
317     // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
318     hci_send_cmd(&hci_create_connection, address, 0xcc18, 0, 0, 0, 1);
319 }
320 
321 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
322     // find channel for local_cid
323     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
324     if (channel) {
325         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
326     }
327     // process
328     l2cap_run();
329 }
330 
331 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
332     linked_item_t *it = (linked_item_t *) &l2cap_channels;
333     while (it->next){
334         l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
335         if ( ! BD_ADDR_CMP( channel->address, address) ){
336             if (channel->state == L2CAP_STATE_CLOSED) {
337                 // failure, forward error code
338                 l2cap_emit_channel_opened(channel, status);
339                 // discard channel
340                 it->next = it->next->next;
341                 free (channel);
342             }
343         } else {
344             it = it->next;
345         }
346     }
347 }
348 
349 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
350     linked_item_t *it;
351     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
352         l2cap_channel_t * channel = (l2cap_channel_t *) it;
353         if ( ! BD_ADDR_CMP( channel->address, address) ){
354             if (channel->state == L2CAP_STATE_CLOSED) {
355                 // success, start l2cap handshake
356                 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
357                 channel->handle = handle;
358                 channel->local_cid = l2cap_next_local_cid();
359             }
360         }
361     }
362     // process
363     l2cap_run();
364 }
365 
366 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
367 
368     bd_addr_t address;
369     hci_con_handle_t handle;
370     linked_item_t *it;
371 
372     switch(packet[0]){
373 
374         // handle connection complete events
375         case HCI_EVENT_CONNECTION_COMPLETE:
376             bt_flip_addr(address, &packet[5]);
377             if (packet[2] == 0){
378                 handle = READ_BT_16(packet, 3);
379                 l2cap_handle_connection_success_for_addr(address, handle);
380             } else {
381                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
382             }
383             break;
384 
385         // handle successful create connection cancel command
386         case HCI_EVENT_COMMAND_COMPLETE:
387             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
388                 if (packet[5] == 0){
389                     bt_flip_addr(address, &packet[6]);
390                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
391                     l2cap_handle_connection_failed_for_addr(address, 0x16);
392                 }
393             }
394             break;
395 
396         // handle disconnection complete events
397         case HCI_EVENT_DISCONNECTION_COMPLETE:
398             // send l2cap disconnect events for all channels on this handle
399             handle = READ_BT_16(packet, 3);
400             it = (linked_item_t *) &l2cap_channels;
401             while (it->next){
402                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
403                 if ( channel->handle == handle ){
404                     // update prev item before free'ing next element - don't call l2cap_finalize_channel_close
405                     it->next = it->next->next;
406                     l2cap_emit_channel_closed(channel);
407                     free (channel);
408                 } else {
409                     it = it->next;
410                 }
411             }
412             break;
413 
414         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
415             l2cap_hand_out_credits();
416             break;
417 
418         // HCI Connection Timeouts
419         case L2CAP_EVENT_TIMEOUT_CHECK:
420             handle = READ_BT_16(packet, 2);
421             if (hci_authentication_active_for_handle(handle)) break;
422             l2cap_channel_t * channel;
423             int used = 0;
424             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
425                 channel = (l2cap_channel_t *) it;
426                 if (channel->handle == handle) {
427                     used = 1;
428                 }
429             }
430             if (!used) {
431                 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
432             }
433             break;
434 
435         default:
436             break;
437     }
438 
439     // pass on
440     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
441 }
442 
443 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
444     channel->sig_id = identifier;
445     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
446     l2cap_run();
447 }
448 
449 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
450 
451     // log_dbg("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
452     l2cap_service_t *service = l2cap_get_service(psm);
453     if (!service) {
454         // 0x0002 PSM not supported
455         // log_dbg("l2cap_handle_connection_request no PSM for psm %u/n", psm);
456         l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, 0x0002, 0);
457         return;
458     }
459 
460     hci_connection_t * hci_connection = connection_for_handle( handle );
461     if (!hci_connection) {
462         log_err("no hci_connection for handle %u\n", handle);
463         // TODO: emit error
464         return;
465     }
466     // alloc structure
467     // log_dbg("l2cap_handle_connection_request register channel\n");
468     l2cap_channel_t * channel = malloc(sizeof(l2cap_channel_t));
469     // TODO: emit error event
470     if (!channel) return;
471 
472     // fill in
473     BD_ADDR_COPY(channel->address, hci_connection->address);
474     channel->psm = psm;
475     channel->handle = handle;
476     channel->connection = service->connection;
477     channel->packet_handler = service->packet_handler;
478     channel->local_cid  = l2cap_next_local_cid();
479     channel->remote_cid = source_cid;
480     channel->local_mtu  = service->mtu;
481     channel->remote_mtu = L2CAP_DEFAULT_MTU;
482     channel->packets_granted = 0;
483 
484     // limit local mtu to max acl packet length
485     if (channel->local_mtu > hci_max_acl_data_packet_length()) {
486         channel->local_mtu = hci_max_acl_data_packet_length();
487     }
488 
489     // set initial state
490     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
491 
492     // temp. store req sig id
493     channel->sig_id = sig_id;
494 
495     // add to connections list
496     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
497 
498     // emit incoming connection request
499     l2cap_emit_connection_request(channel);
500 }
501 
502 void l2cap_accept_connection_internal(uint16_t local_cid){
503     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
504     if (!channel) {
505         log_err("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
506         return;
507     }
508 
509     // accept connection
510     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid, 0, 0);
511 
512     // set real sig and state and start config
513     channel->sig_id = l2cap_next_sig_id();
514     channel->state  = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
515     uint8_t config_options[4];
516     config_options[0] = 1; // MTU
517     config_options[1] = 2; // len param
518     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
519     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
520 
521     // log_dbg("new state %u\n", channel->state);
522 }
523 
524 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
525     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
526     if (!channel) {
527         log_err( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
528         return;
529     }
530     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
531     channel->reason = reason;
532     l2cap_run();
533 }
534 
535 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
536     // accept the other's configuration options
537     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
538     uint16_t pos     = 8;
539     while (pos < end_pos){
540         uint8_t type   = command[pos++];
541         uint8_t length = command[pos++];
542         // MTU { type(8): 1, len(8):2, MTU(16) }
543         if ((type & 0x7f) == 1 && length == 2){
544             channel->remote_mtu = READ_BT_16(command, pos);
545             // log_dbg("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
546         }
547         pos += length;
548     }
549     uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
550     // send back OK
551     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, identifier, channel->remote_cid, 0, 0, 0, NULL);
552 }
553 
554 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
555 
556     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
557     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
558     uint16_t result = 0;
559     uint8_t  config_options[4];
560 
561     // log_dbg("signaling handler code %u\n", code);
562 
563     switch (channel->state) {
564 
565         case L2CAP_STATE_WAIT_CONNECT_RSP:
566             switch (code){
567                 case CONNECTION_RESPONSE:
568                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
569                     switch (result) {
570                         case 0:
571                             // successful connection
572                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
573                             channel->sig_id = l2cap_next_sig_id();
574                             config_options[0] = 1; // MTU
575                             config_options[1] = 2; // len param
576                             bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
577                             l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
578                             channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
579 
580 #if 0
581     channel->state = L2CAP_STATE_OPEN;
582     l2cap_emit_channel_opened(channel, 0);  // success
583     l2cap_emit_credits(channel, 1);
584 #endif
585                             break;
586                         case 1:
587                             // connection pending. get some coffee
588                             break;
589                         default:
590                             // channel closed
591                             channel->state = L2CAP_STATE_CLOSED;
592 
593                             // map l2cap connection response result to BTstack status enumeration
594                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
595 
596                             // drop link key if security block
597                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
598                                 hci_drop_link_key_for_bd_addr(&channel->address);
599                             }
600 
601                             // discard channel
602                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
603                             free (channel);
604                             break;
605                     }
606                     break;
607 
608                 case DISCONNECTION_REQUEST:
609                     l2cap_handle_disconnect_request(channel, identifier);
610                     break;
611 
612                 default:
613                     //@TODO: implement other signaling packets
614                     break;
615             }
616             break;
617 
618         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ:
619             switch (code) {
620                 case CONFIGURE_RESPONSE:
621                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ;
622                     break;
623                 case CONFIGURE_REQUEST:
624                     l2cap_signaling_handle_configure_request(channel, command);
625                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP;
626                     break;
627                 case DISCONNECTION_REQUEST:
628                     l2cap_handle_disconnect_request(channel, identifier);
629                     break;
630                 default:
631                     //@TODO: implement other signaling packets
632                     break;
633             }
634             break;
635 
636         case L2CAP_STATE_WAIT_CONFIG_REQ:
637             switch (code) {
638                 case CONFIGURE_REQUEST:
639                     l2cap_signaling_handle_configure_request(channel, command);
640                     channel->state = L2CAP_STATE_OPEN;
641                     l2cap_emit_channel_opened(channel, 0);  // success
642                     l2cap_emit_credits(channel, 1);
643                     break;
644                 case DISCONNECTION_REQUEST:
645                     l2cap_handle_disconnect_request(channel, identifier);
646                     break;
647                 default:
648                     //@TODO: implement other signaling packets
649                     break;
650             }
651             break;
652 
653         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP:
654             switch (code) {
655                 case CONFIGURE_RESPONSE:
656                     channel->state = L2CAP_STATE_OPEN;
657                     l2cap_emit_channel_opened(channel, 0);  // success
658                     l2cap_emit_credits(channel, 1);
659                     break;
660                 case DISCONNECTION_REQUEST:
661                     l2cap_handle_disconnect_request(channel, identifier);
662                     break;
663                 default:
664                     //@TODO: implement other signaling packets
665                     break;
666             }
667             break;
668 
669         case L2CAP_STATE_WAIT_DISCONNECT:
670             switch (code) {
671                 case DISCONNECTION_RESPONSE:
672                     l2cap_finialize_channel_close(channel);
673                     break;
674                 case DISCONNECTION_REQUEST:
675                     l2cap_handle_disconnect_request(channel, identifier);
676                     break;
677                 default:
678                     //@TODO: implement other signaling packets
679                     break;
680             }
681             break;
682 
683         case L2CAP_STATE_CLOSED:
684             // @TODO handle incoming requests
685             break;
686 
687         case L2CAP_STATE_OPEN:
688             switch (code) {
689                 case DISCONNECTION_REQUEST:
690                     l2cap_handle_disconnect_request(channel, identifier);
691                     break;
692                 default:
693                     //@TODO: implement other signaling packets, e.g. re-configure
694                     break;
695             }
696             break;
697         default:
698             break;
699     }
700     // log_dbg("new state %u\n", channel->state);
701 }
702 
703 
704 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
705 
706     // get code, signalind identifier and command len
707     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
708     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
709     uint16_t len   = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
710 
711     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
712     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
713         return;
714     }
715 
716     // general commands without an assigned channel
717     switch(code) {
718 
719         case CONNECTION_REQUEST: {
720             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
721             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
722             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
723             break;
724         }
725 
726         case ECHO_REQUEST: {
727             // send back packet
728             l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, len, &command[L2CAP_SIGNALING_COMMAND_DATA_OFFSET]);
729             break;
730         }
731 
732         case INFORMATION_REQUEST: {
733             // we neither support connectionless L2CAP data nor support any flow control modes yet
734             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
735             if (infoType == 2) {
736                 uint32_t features = 0;
737                 // extended features request supported, however no features present
738                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
739             } else {
740                 // all other types are not supported
741                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
742             }
743             break;;
744         }
745 
746         default:
747             break;
748     }
749 
750 
751     // Get potential destination CID
752     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
753 
754     // Find channel for this sig_id and connection handle
755     linked_item_t *it;
756     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
757         l2cap_channel_t * channel = (l2cap_channel_t *) it;
758         if (channel->handle == handle) {
759             if (code & 1) {
760                 // match odd commands by previous signaling identifier
761                 if (channel->sig_id == sig_id) {
762                     l2cap_signaling_handler_channel(channel, command);
763                     break;
764                 }
765             } else {
766                 // match even commands by local channel id
767                 if (channel->local_cid == dest_cid) {
768                     l2cap_signaling_handler_channel(channel, command);
769                     break;
770                 }
771             }
772         }
773     }
774 }
775 
776 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
777 
778     // Get Channel ID
779     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
780 
781     // Signaling Packet?
782     if (channel_id == 1) {
783 
784         // Get Connection
785         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
786 
787         uint16_t command_offset = 8;
788         while (command_offset < size) {
789 
790             // handle signaling commands
791             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
792 
793             // increment command_offset
794             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
795         }
796         return;
797     }
798 
799     // Find channel for this channel_id and connection handle
800     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
801     if (channel) {
802         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
803     }
804 }
805 
806 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
807     switch (packet_type) {
808         case HCI_EVENT_PACKET:
809             l2cap_event_handler(packet, size);
810             break;
811         case HCI_ACL_DATA_PACKET:
812             l2cap_acl_handler(packet, size);
813             break;
814         default:
815             break;
816     }
817 }
818 
819 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
820 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
821     channel->state = L2CAP_STATE_CLOSED;
822     l2cap_emit_channel_closed(channel);
823     // discard channel
824     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
825     free (channel);
826 }
827 
828 l2cap_service_t * l2cap_get_service(uint16_t psm){
829     linked_item_t *it;
830 
831     // close open channels
832     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
833         l2cap_service_t * service = ((l2cap_service_t *) it);
834         if ( service->psm == psm){
835             return service;
836         };
837     }
838     return NULL;
839 }
840 
841 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
842     // check for alread registered psm // TODO: emit error event
843     l2cap_service_t *service = l2cap_get_service(psm);
844     if (service) return;
845 
846     // alloc structure     // TODO: emit error event
847     service = malloc(sizeof(l2cap_service_t));
848     if (!service) return;
849 
850     // fill in
851     service->psm = psm;
852     service->mtu = mtu;
853     service->connection = connection;
854     service->packet_handler = packet_handler;
855 
856     // add to services list
857     linked_list_add(&l2cap_services, (linked_item_t *) service);
858 }
859 
860 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
861     l2cap_service_t *service = l2cap_get_service(psm);
862     if (!service) return;
863     linked_list_remove(&l2cap_services, (linked_item_t *) service);
864     free(service);
865 }
866 
867 //
868 void l2cap_close_connection(void *connection){
869     linked_item_t *it;
870 
871     // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks
872     l2cap_channel_t * channel;
873     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
874         channel = (l2cap_channel_t *) it;
875         if (channel->connection == connection) {
876             channel->sig_id = l2cap_next_sig_id();
877             l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
878             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
879         }
880     }
881 
882     // unregister services
883     it = (linked_item_t *) &l2cap_services;
884     while (it->next) {
885         l2cap_service_t * service = (l2cap_service_t *) it->next;
886         if (service->connection == connection){
887             it->next = it->next->next;
888             free(service);
889         } else {
890             it = it->next;
891         }
892     }
893 }
894