xref: /btstack/src/l2cap.c (revision ae280e7320c91fb5b97eb4d6f04f07f064d41e94)
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     uint8_t  config_options[4];
248     linked_item_t *it;
249     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
250 
251         // can send?
252 
253         l2cap_channel_t * channel = (l2cap_channel_t *) it;
254         switch (channel->state){
255 
256             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
257                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, 0, 0, channel->reason, 0);
258                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
259                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
260                 free (channel);
261                 break;
262 
263             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
264                 // success, start l2cap handshake
265                 channel->sig_id = l2cap_next_sig_id();
266                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->sig_id, channel->psm, channel->local_cid);
267                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
268                 break;
269 
270             case L2CAP_STATE_WAIT_CONFIG_REQ_OR_SEND_CONFIG_REQ:
271                 // after connection response was received
272                 channel->sig_id = l2cap_next_sig_id();
273                 config_options[0] = 1; // MTU
274                 config_options[1] = 2; // len param
275                 bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
276                 l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
277                 channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
278                 break;
279 
280             case L2CAP_STATE_WILL_SEND_CONFIG_REQ_AND_CONFIG_REQ_RSP:
281                 channel->sig_id = l2cap_next_sig_id();
282                 config_options[0] = 1; // MTU
283                 config_options[1] = 2; // len param
284                 bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
285                 l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
286                 channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP;
287                 break;
288 
289             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
290                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid);
291                 l2cap_finialize_channel_close(channel);
292                 break;
293 
294             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
295                 channel->sig_id = l2cap_next_sig_id();
296                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
297                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
298                 break;
299             default:
300                 break;
301         }
302     }
303 }
304 
305 // open outgoing L2CAP channel
306 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler,
307                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
308 
309     // alloc structure
310     l2cap_channel_t * chan = malloc(sizeof(l2cap_channel_t));
311     // TODO: emit error event
312     if (!chan) return;
313 
314     // limit local mtu to max acl packet length
315     if (mtu > hci_max_acl_data_packet_length()) {
316         mtu = hci_max_acl_data_packet_length();
317     }
318 
319     // fill in
320     BD_ADDR_COPY(chan->address, address);
321     chan->psm = psm;
322     chan->handle = 0;
323     chan->connection = connection;
324     chan->packet_handler = packet_handler;
325     chan->remote_mtu = L2CAP_MINIMAL_MTU;
326     chan->local_mtu = mtu;
327     chan->packets_granted = 0;
328 
329     // set initial state
330     chan->state = L2CAP_STATE_CLOSED;
331     chan->sig_id = L2CAP_SIG_ID_INVALID;
332 
333     // add to connections list
334     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
335 
336     // send connection request
337     // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
338     hci_send_cmd(&hci_create_connection, address, 0xcc18, 0, 0, 0, 1);
339 }
340 
341 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
342     // find channel for local_cid
343     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
344     if (channel) {
345         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
346     }
347     // process
348     l2cap_run();
349 }
350 
351 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
352     linked_item_t *it = (linked_item_t *) &l2cap_channels;
353     while (it->next){
354         l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
355         if ( ! BD_ADDR_CMP( channel->address, address) ){
356             if (channel->state == L2CAP_STATE_CLOSED) {
357                 // failure, forward error code
358                 l2cap_emit_channel_opened(channel, status);
359                 // discard channel
360                 it->next = it->next->next;
361                 free (channel);
362             }
363         } else {
364             it = it->next;
365         }
366     }
367 }
368 
369 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
370     linked_item_t *it;
371     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
372         l2cap_channel_t * channel = (l2cap_channel_t *) it;
373         if ( ! BD_ADDR_CMP( channel->address, address) ){
374             if (channel->state == L2CAP_STATE_CLOSED) {
375                 // success, start l2cap handshake
376                 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
377                 channel->handle = handle;
378                 channel->local_cid = l2cap_next_local_cid();
379             }
380         }
381     }
382     // process
383     l2cap_run();
384 }
385 
386 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
387 
388     bd_addr_t address;
389     hci_con_handle_t handle;
390     linked_item_t *it;
391 
392     switch(packet[0]){
393 
394         // handle connection complete events
395         case HCI_EVENT_CONNECTION_COMPLETE:
396             bt_flip_addr(address, &packet[5]);
397             if (packet[2] == 0){
398                 handle = READ_BT_16(packet, 3);
399                 l2cap_handle_connection_success_for_addr(address, handle);
400             } else {
401                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
402             }
403             break;
404 
405         // handle successful create connection cancel command
406         case HCI_EVENT_COMMAND_COMPLETE:
407             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
408                 if (packet[5] == 0){
409                     bt_flip_addr(address, &packet[6]);
410                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
411                     l2cap_handle_connection_failed_for_addr(address, 0x16);
412                 }
413             }
414             break;
415 
416         // handle disconnection complete events
417         case HCI_EVENT_DISCONNECTION_COMPLETE:
418             // send l2cap disconnect events for all channels on this handle
419             handle = READ_BT_16(packet, 3);
420             it = (linked_item_t *) &l2cap_channels;
421             while (it->next){
422                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
423                 if ( channel->handle == handle ){
424                     // update prev item before free'ing next element - don't call l2cap_finalize_channel_close
425                     it->next = it->next->next;
426                     l2cap_emit_channel_closed(channel);
427                     free (channel);
428                 } else {
429                     it = it->next;
430                 }
431             }
432             break;
433 
434         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
435             l2cap_hand_out_credits();
436             break;
437 
438         // HCI Connection Timeouts
439         case L2CAP_EVENT_TIMEOUT_CHECK:
440             handle = READ_BT_16(packet, 2);
441             if (hci_authentication_active_for_handle(handle)) break;
442             l2cap_channel_t * channel;
443             int used = 0;
444             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
445                 channel = (l2cap_channel_t *) it;
446                 if (channel->handle == handle) {
447                     used = 1;
448                 }
449             }
450             if (!used) {
451                 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
452             }
453             break;
454 
455         default:
456             break;
457     }
458 
459     // pass on
460     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
461 }
462 
463 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
464     channel->sig_id = identifier;
465     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
466     l2cap_run();
467 }
468 
469 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
470 
471     // log_dbg("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
472     l2cap_service_t *service = l2cap_get_service(psm);
473     if (!service) {
474         // 0x0002 PSM not supported
475         // log_dbg("l2cap_handle_connection_request no PSM for psm %u/n", psm);
476         l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, 0x0002, 0);
477         return;
478     }
479 
480     hci_connection_t * hci_connection = connection_for_handle( handle );
481     if (!hci_connection) {
482         log_err("no hci_connection for handle %u\n", handle);
483         // TODO: emit error
484         return;
485     }
486     // alloc structure
487     // log_dbg("l2cap_handle_connection_request register channel\n");
488     l2cap_channel_t * channel = malloc(sizeof(l2cap_channel_t));
489     // TODO: emit error event
490     if (!channel) return;
491 
492     // fill in
493     BD_ADDR_COPY(channel->address, hci_connection->address);
494     channel->psm = psm;
495     channel->handle = handle;
496     channel->connection = service->connection;
497     channel->packet_handler = service->packet_handler;
498     channel->local_cid  = l2cap_next_local_cid();
499     channel->remote_cid = source_cid;
500     channel->local_mtu  = service->mtu;
501     channel->remote_mtu = L2CAP_DEFAULT_MTU;
502     channel->packets_granted = 0;
503 
504     // limit local mtu to max acl packet length
505     if (channel->local_mtu > hci_max_acl_data_packet_length()) {
506         channel->local_mtu = hci_max_acl_data_packet_length();
507     }
508 
509     // set initial state
510     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
511 
512     // temp. store req sig id
513     channel->sig_id = sig_id;
514 
515     // add to connections list
516     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
517 
518     // emit incoming connection request
519     l2cap_emit_connection_request(channel);
520 }
521 
522 void l2cap_accept_connection_internal(uint16_t local_cid){
523     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
524     if (!channel) {
525         log_err("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
526         return;
527     }
528 
529     // accept connection
530     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid, 0, 0);
531 
532     // set real sig and state and start config
533     channel->sig_id = l2cap_next_sig_id();
534     channel->state  = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
535     uint8_t config_options[4];
536     config_options[0] = 1; // MTU
537     config_options[1] = 2; // len param
538     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
539     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
540 
541     // log_dbg("new state %u\n", channel->state);
542 }
543 
544 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
545     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
546     if (!channel) {
547         log_err( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
548         return;
549     }
550     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
551     channel->reason = reason;
552     l2cap_run();
553 }
554 
555 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
556     // accept the other's configuration options
557     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
558     uint16_t pos     = 8;
559     while (pos < end_pos){
560         uint8_t type   = command[pos++];
561         uint8_t length = command[pos++];
562         // MTU { type(8): 1, len(8):2, MTU(16) }
563         if ((type & 0x7f) == 1 && length == 2){
564             channel->remote_mtu = READ_BT_16(command, pos);
565             // log_dbg("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
566         }
567         pos += length;
568     }
569     uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
570     // send back OK
571     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, identifier, channel->remote_cid, 0, 0, 0, NULL);
572 }
573 
574 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
575 
576     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
577     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
578     uint16_t result = 0;
579 
580     // log_dbg("signaling handler code %u\n", code);
581 
582     switch (channel->state) {
583 
584         case L2CAP_STATE_WAIT_CONNECT_RSP:
585             switch (code){
586                 case CONNECTION_RESPONSE:
587                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
588                     switch (result) {
589                         case 0:
590                             // successful connection
591                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
592                             channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_OR_SEND_CONFIG_REQ;
593 #if 0
594     channel->state = L2CAP_STATE_OPEN;
595     l2cap_emit_channel_opened(channel, 0);  // success
596     l2cap_emit_credits(channel, 1);
597 #endif
598                             break;
599                         case 1:
600                             // connection pending. get some coffee
601                             break;
602                         default:
603                             // channel closed
604                             channel->state = L2CAP_STATE_CLOSED;
605 
606                             // map l2cap connection response result to BTstack status enumeration
607                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
608 
609                             // drop link key if security block
610                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
611                                 hci_drop_link_key_for_bd_addr(&channel->address);
612                             }
613 
614                             // discard channel
615                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
616                             free (channel);
617                             break;
618                     }
619                     break;
620 
621                 case DISCONNECTION_REQUEST:
622                     l2cap_handle_disconnect_request(channel, identifier);
623                     break;
624 
625                 default:
626                     //@TODO: implement other signaling packets
627                     break;
628             }
629             break;
630 
631         case L2CAP_STATE_WAIT_CONFIG_REQ_OR_SEND_CONFIG_REQ:
632             switch (code) {
633                 case CONFIGURE_REQUEST:
634                     l2cap_signaling_handle_configure_request(channel, command);
635                     channel->state = L2CAP_STATE_WILL_SEND_CONFIG_REQ_AND_CONFIG_REQ_RSP;
636                     break;
637                 case DISCONNECTION_REQUEST:
638                     l2cap_handle_disconnect_request(channel, identifier);
639                     break;
640                 default:
641                     //@TODO: implement other signaling packets
642                     break;
643             }
644             break;
645 
646         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ:
647             switch (code) {
648                 case CONFIGURE_RESPONSE:
649                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ;
650                     break;
651                 case CONFIGURE_REQUEST:
652                     l2cap_signaling_handle_configure_request(channel, command);
653                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP;
654                     break;
655                 case DISCONNECTION_REQUEST:
656                     l2cap_handle_disconnect_request(channel, identifier);
657                     break;
658                 default:
659                     //@TODO: implement other signaling packets
660                     break;
661             }
662             break;
663 
664         case L2CAP_STATE_WAIT_CONFIG_REQ:
665             switch (code) {
666                 case CONFIGURE_REQUEST:
667                     l2cap_signaling_handle_configure_request(channel, command);
668                     channel->state = L2CAP_STATE_OPEN;
669                     l2cap_emit_channel_opened(channel, 0);  // success
670                     l2cap_emit_credits(channel, 1);
671                     break;
672                 case DISCONNECTION_REQUEST:
673                     l2cap_handle_disconnect_request(channel, identifier);
674                     break;
675                 default:
676                     //@TODO: implement other signaling packets
677                     break;
678             }
679             break;
680 
681         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP:
682             switch (code) {
683                 case CONFIGURE_RESPONSE:
684                     channel->state = L2CAP_STATE_OPEN;
685                     l2cap_emit_channel_opened(channel, 0);  // success
686                     l2cap_emit_credits(channel, 1);
687                     break;
688                 case DISCONNECTION_REQUEST:
689                     l2cap_handle_disconnect_request(channel, identifier);
690                     break;
691                 default:
692                     //@TODO: implement other signaling packets
693                     break;
694             }
695             break;
696 
697         case L2CAP_STATE_WAIT_DISCONNECT:
698             switch (code) {
699                 case DISCONNECTION_RESPONSE:
700                     l2cap_finialize_channel_close(channel);
701                     break;
702                 case DISCONNECTION_REQUEST:
703                     l2cap_handle_disconnect_request(channel, identifier);
704                     break;
705                 default:
706                     //@TODO: implement other signaling packets
707                     break;
708             }
709             break;
710 
711         case L2CAP_STATE_CLOSED:
712             // @TODO handle incoming requests
713             break;
714 
715         case L2CAP_STATE_OPEN:
716             switch (code) {
717                 case DISCONNECTION_REQUEST:
718                     l2cap_handle_disconnect_request(channel, identifier);
719                     break;
720                 default:
721                     //@TODO: implement other signaling packets, e.g. re-configure
722                     break;
723             }
724             break;
725         default:
726             break;
727     }
728     // log_dbg("new state %u\n", channel->state);
729 }
730 
731 
732 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
733 
734     // get code, signalind identifier and command len
735     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
736     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
737     uint16_t len   = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
738 
739     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
740     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
741         return;
742     }
743 
744     // general commands without an assigned channel
745     switch(code) {
746 
747         case CONNECTION_REQUEST: {
748             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
749             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
750             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
751             break;
752         }
753 
754         case ECHO_REQUEST: {
755             // send back packet
756             l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, len, &command[L2CAP_SIGNALING_COMMAND_DATA_OFFSET]);
757             break;
758         }
759 
760         case INFORMATION_REQUEST: {
761             // we neither support connectionless L2CAP data nor support any flow control modes yet
762             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
763             if (infoType == 2) {
764                 uint32_t features = 0;
765                 // extended features request supported, however no features present
766                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
767             } else {
768                 // all other types are not supported
769                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
770             }
771             break;;
772         }
773 
774         default:
775             break;
776     }
777 
778 
779     // Get potential destination CID
780     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
781 
782     // Find channel for this sig_id and connection handle
783     linked_item_t *it;
784     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
785         l2cap_channel_t * channel = (l2cap_channel_t *) it;
786         if (channel->handle == handle) {
787             if (code & 1) {
788                 // match odd commands by previous signaling identifier
789                 if (channel->sig_id == sig_id) {
790                     l2cap_signaling_handler_channel(channel, command);
791                     break;
792                 }
793             } else {
794                 // match even commands by local channel id
795                 if (channel->local_cid == dest_cid) {
796                     l2cap_signaling_handler_channel(channel, command);
797                     break;
798                 }
799             }
800         }
801     }
802 }
803 
804 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
805 
806     // Get Channel ID
807     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
808 
809     // Signaling Packet?
810     if (channel_id == 1) {
811 
812         // Get Connection
813         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
814 
815         uint16_t command_offset = 8;
816         while (command_offset < size) {
817 
818             // handle signaling commands
819             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
820 
821             // increment command_offset
822             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
823         }
824         return;
825     }
826 
827     // Find channel for this channel_id and connection handle
828     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
829     if (channel) {
830         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
831     }
832 }
833 
834 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
835     switch (packet_type) {
836         case HCI_EVENT_PACKET:
837             l2cap_event_handler(packet, size);
838             break;
839         case HCI_ACL_DATA_PACKET:
840             l2cap_acl_handler(packet, size);
841             break;
842         default:
843             break;
844     }
845 }
846 
847 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
848 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
849     channel->state = L2CAP_STATE_CLOSED;
850     l2cap_emit_channel_closed(channel);
851     // discard channel
852     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
853     free (channel);
854 }
855 
856 l2cap_service_t * l2cap_get_service(uint16_t psm){
857     linked_item_t *it;
858 
859     // close open channels
860     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
861         l2cap_service_t * service = ((l2cap_service_t *) it);
862         if ( service->psm == psm){
863             return service;
864         };
865     }
866     return NULL;
867 }
868 
869 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
870     // check for alread registered psm // TODO: emit error event
871     l2cap_service_t *service = l2cap_get_service(psm);
872     if (service) return;
873 
874     // alloc structure     // TODO: emit error event
875     service = malloc(sizeof(l2cap_service_t));
876     if (!service) return;
877 
878     // fill in
879     service->psm = psm;
880     service->mtu = mtu;
881     service->connection = connection;
882     service->packet_handler = packet_handler;
883 
884     // add to services list
885     linked_list_add(&l2cap_services, (linked_item_t *) service);
886 }
887 
888 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
889     l2cap_service_t *service = l2cap_get_service(psm);
890     if (!service) return;
891     linked_list_remove(&l2cap_services, (linked_item_t *) service);
892     free(service);
893 }
894 
895 //
896 void l2cap_close_connection(void *connection){
897     linked_item_t *it;
898 
899     // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks
900     l2cap_channel_t * channel;
901     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
902         channel = (l2cap_channel_t *) it;
903         if (channel->connection == connection) {
904             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
905         }
906     }
907 
908     // unregister services
909     it = (linked_item_t *) &l2cap_services;
910     while (it->next) {
911         l2cap_service_t * service = (l2cap_service_t *) it->next;
912         if (service->connection == connection){
913             it->next = it->next->next;
914             free(service);
915         } else {
916             it = it->next;
917         }
918     }
919 
920     // process
921     l2cap_run();
922 }
923