xref: /btstack/src/l2cap.c (revision 76115249e2829495b353960e8cc13a125936c03f)
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 #include "btstack_memory.h"
45 
46 #include <stdarg.h>
47 #include <string.h>
48 
49 #include <stdio.h>
50 
51 // nr of buffered acl packets in outgoing queue to get max performance
52 #define NR_BUFFERED_ACL_PACKETS 3
53 
54 // used to cache l2cap rejects, echo, and informational requests
55 #define NR_PENDING_SIGNALING_RESPONSES 5
56 
57 // offsets for L2CAP SIGNALING COMMANDS
58 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
59 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
60 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
61 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
62 
63 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
64 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
65 
66 // used to cache l2cap rejects, echo, and informational requests
67 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
68 static int signaling_responses_pending;
69 
70 static linked_list_t l2cap_channels = NULL;
71 static linked_list_t l2cap_services = NULL;
72 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
73 static int new_credits_blocked = 0;
74 
75 // prototypes
76 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
77 static l2cap_service_t * l2cap_get_service(uint16_t psm);
78 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
79 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
80 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
81 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
82 
83 
84 void l2cap_init(){
85 
86     new_credits_blocked = 0;
87     signaling_responses_pending = 0;
88 
89     //
90     // register callback with HCI
91     //
92     hci_register_packet_handler(&l2cap_packet_handler);
93 }
94 
95 
96 /** Register L2CAP packet handlers */
97 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
98 }
99 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
100     packet_handler = handler;
101 }
102 
103 //  notify client/protocol handler
104 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
105     if (channel->packet_handler) {
106         (* (channel->packet_handler))(type, channel->local_cid, data, size);
107     } else {
108         (*packet_handler)(channel->connection, type, channel->local_cid, data, size);
109     }
110 }
111 
112 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
113     uint8_t event[21];
114     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
115     event[1] = sizeof(event) - 2;
116     event[2] = status;
117     bt_flip_addr(&event[3], channel->address);
118     bt_store_16(event,  9, channel->handle);
119     bt_store_16(event, 11, channel->psm);
120     bt_store_16(event, 13, channel->local_cid);
121     bt_store_16(event, 15, channel->remote_cid);
122     bt_store_16(event, 17, channel->local_mtu);
123     bt_store_16(event, 19, channel->remote_mtu);
124     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
125     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
126 }
127 
128 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
129     uint8_t event[4];
130     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
131     event[1] = sizeof(event) - 2;
132     bt_store_16(event, 2, channel->local_cid);
133     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
134     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
135 }
136 
137 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
138     uint8_t event[16];
139     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
140     event[1] = sizeof(event) - 2;
141     bt_flip_addr(&event[2], channel->address);
142     bt_store_16(event,  8, channel->handle);
143     bt_store_16(event, 10, channel->psm);
144     bt_store_16(event, 12, channel->local_cid);
145     bt_store_16(event, 14, channel->remote_cid);
146     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
147     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
148 }
149 
150 void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) {
151     // track credits
152     channel->packets_granted += credits;
153     // log_info("l2cap_emit_credits for cid %u, credits given: %u (+%u)\n", channel->local_cid, channel->packets_granted, credits);
154 
155     uint8_t event[5];
156     event[0] = L2CAP_EVENT_CREDITS;
157     event[1] = sizeof(event) - 2;
158     bt_store_16(event, 2, channel->local_cid);
159     event[4] = credits;
160     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
161     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
162 }
163 
164 void l2cap_block_new_credits(uint8_t blocked){
165     new_credits_blocked = blocked;
166 }
167 
168 void l2cap_hand_out_credits(void){
169 
170     if (new_credits_blocked) return;    // we're told not to. used by daemon
171 
172     linked_item_t *it;
173     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
174         if (!hci_number_free_acl_slots()) return;
175         l2cap_channel_t * channel = (l2cap_channel_t *) it;
176         if (channel->state != L2CAP_STATE_OPEN) continue;
177         if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) {
178             l2cap_emit_credits(channel, 1);
179         }
180     }
181 }
182 
183 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
184     linked_item_t *it;
185     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
186         l2cap_channel_t * channel = (l2cap_channel_t *) it;
187         if ( channel->local_cid == local_cid) {
188             return channel;
189         }
190     }
191     return NULL;
192 }
193 
194 int  l2cap_can_send_packet_now(uint16_t local_cid){
195     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
196     if (!channel) return 0;
197     if (!channel->packets_granted) return 0;
198     return hci_can_send_packet_now(HCI_ACL_DATA_PACKET);
199 }
200 
201 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
202     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
203     if (channel) {
204         return channel->remote_mtu;
205     }
206     return 0;
207 }
208 
209 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
210 
211     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
212         log_info("l2cap_send_signaling_packet, cannot send\n");
213         return BTSTACK_ACL_BUFFERS_FULL;
214     }
215 
216     // log_info("l2cap_send_signaling_packet type %u\n", cmd);
217     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
218     va_list argptr;
219     va_start(argptr, identifier);
220     uint16_t len = l2cap_create_signaling_internal(acl_buffer, handle, cmd, identifier, argptr);
221     va_end(argptr);
222     // log_info("l2cap_send_signaling_packet con %u!\n", handle);
223     return hci_send_acl_packet(acl_buffer, len);
224 }
225 
226 uint8_t *l2cap_get_outgoing_buffer(void){
227     return hci_get_outgoing_acl_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
228 }
229 
230 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
231 
232     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
233         log_info("l2cap_send_internal cid %u, cannot send\n", local_cid);
234         return BTSTACK_ACL_BUFFERS_FULL;
235     }
236 
237     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
238     if (!channel) {
239         log_error("l2cap_send_internal no channel for cid %u\n", local_cid);
240         return -1;   // TODO: define error
241     }
242 
243     if (channel->packets_granted == 0){
244         log_error("l2cap_send_internal cid %u, no credits!\n", local_cid);
245         return -1;  // TODO: define error
246     }
247 
248     --channel->packets_granted;
249 
250     log_debug("l2cap_send_internal cid %u, handle %u, 1 credit used, credits left %u;\n",
251                   local_cid, channel->handle, channel->packets_granted);
252 
253     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
254 
255     // 0 - Connection handle : PB=10 : BC=00
256     bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14));
257     // 2 - ACL length
258     bt_store_16(acl_buffer, 2,  len + 4);
259     // 4 - L2CAP packet length
260     bt_store_16(acl_buffer, 4,  len + 0);
261     // 6 - L2CAP channel DEST
262     bt_store_16(acl_buffer, 6, channel->remote_cid);
263     // send
264     int err = hci_send_acl_packet(acl_buffer, len+8);
265 
266     l2cap_hand_out_credits();
267 
268     return err;
269 }
270 
271 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
272 
273     if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)){
274         log_info("l2cap_send_internal cid %u, cannot send\n", local_cid);
275         return BTSTACK_ACL_BUFFERS_FULL;
276     }
277 
278     uint8_t *acl_buffer = hci_get_outgoing_acl_packet_buffer();
279 
280     memcpy(&acl_buffer[8], data, len);
281 
282     return l2cap_send_prepared(local_cid, len);
283 }
284 
285 
286 // MARK: L2CAP_RUN
287 // process outstanding signaling tasks
288 void l2cap_run(void){
289 
290     // check pending signaling responses
291     while (signaling_responses_pending){
292 
293         if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break;
294 
295         hci_con_handle_t handle = signaling_responses[0].handle;
296         uint8_t sig_id = signaling_responses[0].sig_id;
297         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
298         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST
299 
300         switch (signaling_responses[0].code){
301             case CONNECTION_REQUEST:
302                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
303                 break;
304             case ECHO_REQUEST:
305                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
306                 break;
307             case INFORMATION_REQUEST:
308                 if (infoType == 2) {
309                     uint32_t features = 0;
310                     // extended features request supported, however no features present
311                     l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
312                 } else {
313                     // all other types are not supported
314                     l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
315                 }
316                 break;
317             default:
318                 // should not happen
319                 break;
320         }
321 
322         // remove first item
323         signaling_responses_pending--;
324         int i;
325         for (i=0; i < signaling_responses_pending; i++){
326             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
327         }
328     }
329 
330     uint8_t  config_options[4];
331     linked_item_t *it;
332     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
333 
334         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break;
335         if (!hci_can_send_packet_now(HCI_ACL_DATA_PACKET)) break;
336 
337         l2cap_channel_t * channel = (l2cap_channel_t *) it;
338 
339         // log_info("l2cap_run: state %u, var 0x%02x\n", channel->state, channel->state_var);
340 
341         switch (channel->state){
342 
343             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
344                 // send connection request - set state first
345                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
346                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
347                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
348                 break;
349 
350             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
351                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, channel->reason, 0);
352                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
353                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
354                 btstack_memory_l2cap_channel_free(channel);
355                 break;
356 
357             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
358                 channel->state = L2CAP_STATE_CONFIG;
359                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
360                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
361                 break;
362 
363             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
364                 // success, start l2cap handshake
365                 channel->local_sig_id = l2cap_next_sig_id();
366                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
367                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
368                 break;
369 
370             case L2CAP_STATE_CONFIG:
371                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
372                     channel->state_var &= ~L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP;
373                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP;
374                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, 0, 0, 0, NULL);
375                 }
376                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
377                     channel->state_var &= ~L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
378                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ;
379                     channel->local_sig_id = l2cap_next_sig_id();
380                     config_options[0] = 1; // MTU
381                     config_options[1] = 2; // len param
382                     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
383                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
384                 }
385                 if (l2cap_channel_ready_for_open(channel)){
386                     channel->state = L2CAP_STATE_OPEN;
387                     l2cap_emit_channel_opened(channel, 0);  // success
388                     l2cap_emit_credits(channel, 1);
389                 }
390                 break;
391 
392             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
393                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
394                 l2cap_finialize_channel_close(channel);
395                 break;
396 
397             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
398                 channel->local_sig_id = l2cap_next_sig_id();
399                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
400                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
401                 break;
402             default:
403                 break;
404         }
405     }
406 }
407 
408 uint16_t l2cap_max_mtu(void){
409     return hci_max_acl_data_packet_length() - L2CAP_HEADER_SIZE;
410 }
411 
412 // open outgoing L2CAP channel
413 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler,
414                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
415 
416     // alloc structure
417     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
418     if (!chan) {
419         // emit error event
420         l2cap_channel_t dummy_channel;
421         BD_ADDR_COPY(dummy_channel.address, address);
422         dummy_channel.psm = psm;
423         l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED);
424         return;
425     }
426     // limit local mtu to max acl packet length
427     if (mtu > l2cap_max_mtu()) {
428         mtu = l2cap_max_mtu();
429     }
430 
431     // fill in
432     BD_ADDR_COPY(chan->address, address);
433     chan->psm = psm;
434     chan->handle = 0;
435     chan->connection = connection;
436     chan->packet_handler = packet_handler;
437     chan->remote_mtu = L2CAP_MINIMAL_MTU;
438     chan->local_mtu = mtu;
439     chan->packets_granted = 0;
440 
441     // set initial state
442     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
443     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
444     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
445     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
446 
447     // add to connections list
448     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
449 
450     l2cap_run();
451 }
452 
453 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
454     // find channel for local_cid
455     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
456     if (channel) {
457         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
458     }
459     // process
460     l2cap_run();
461 }
462 
463 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
464     linked_item_t *it = (linked_item_t *) &l2cap_channels;
465     while (it->next){
466         l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
467         if ( ! BD_ADDR_CMP( channel->address, address) ){
468             if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
469                 // failure, forward error code
470                 l2cap_emit_channel_opened(channel, status);
471                 // discard channel
472                 it->next = it->next->next;
473                 btstack_memory_l2cap_channel_free(channel);
474             }
475         } else {
476             it = it->next;
477         }
478     }
479 }
480 
481 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
482     linked_item_t *it;
483     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
484         l2cap_channel_t * channel = (l2cap_channel_t *) it;
485         if ( ! BD_ADDR_CMP( channel->address, address) ){
486             if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
487                 // success, start l2cap handshake
488                 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
489                 channel->handle = handle;
490                 channel->local_cid = l2cap_next_local_cid();
491             }
492         }
493     }
494     // process
495     l2cap_run();
496 }
497 
498 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
499 
500     bd_addr_t address;
501     hci_con_handle_t handle;
502     l2cap_channel_t * channel;
503     linked_item_t *it;
504     int hci_con_used;
505 
506     switch(packet[0]){
507 
508         // handle connection complete events
509         case HCI_EVENT_CONNECTION_COMPLETE:
510             bt_flip_addr(address, &packet[5]);
511             if (packet[2] == 0){
512                 handle = READ_BT_16(packet, 3);
513                 l2cap_handle_connection_success_for_addr(address, handle);
514             } else {
515                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
516             }
517             break;
518 
519         // handle successful create connection cancel command
520         case HCI_EVENT_COMMAND_COMPLETE:
521             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
522                 if (packet[5] == 0){
523                     bt_flip_addr(address, &packet[6]);
524                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
525                     l2cap_handle_connection_failed_for_addr(address, 0x16);
526                 }
527             }
528             l2cap_run();    // try sending signaling packets first
529             break;
530 
531         case HCI_EVENT_COMMAND_STATUS:
532             l2cap_run();    // try sending signaling packets first
533             break;
534 
535         // handle disconnection complete events
536         case HCI_EVENT_DISCONNECTION_COMPLETE:
537             // send l2cap disconnect events for all channels on this handle
538             handle = READ_BT_16(packet, 3);
539             it = (linked_item_t *) &l2cap_channels;
540             while (it->next){
541                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
542                 if ( channel->handle == handle ){
543                     // update prev item before free'ing next element - don't call l2cap_finalize_channel_close
544                     it->next = it->next->next;
545                     l2cap_emit_channel_closed(channel);
546                     btstack_memory_l2cap_channel_free(channel);
547                 } else {
548                     it = it->next;
549                 }
550             }
551             break;
552 
553         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
554             l2cap_run();    // try sending signaling packets first
555             l2cap_hand_out_credits();
556             break;
557 
558         // HCI Connection Timeouts
559         case L2CAP_EVENT_TIMEOUT_CHECK:
560             handle = READ_BT_16(packet, 2);
561             if (hci_authentication_active_for_handle(handle)) break;
562             hci_con_used = 0;
563             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
564                 channel = (l2cap_channel_t *) it;
565                 if (channel->handle == handle) {
566                     hci_con_used = 1;
567                 }
568             }
569             if (hci_con_used) break;
570             if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) break;
571             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
572             break;
573 
574         case DAEMON_EVENT_HCI_PACKET_SENT:
575             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
576                 channel = (l2cap_channel_t *) it;
577                 if (channel->packet_handler) {
578                     (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
579                 }
580             }
581             break;
582 
583         default:
584             break;
585     }
586 
587     // pass on
588     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
589 }
590 
591 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
592     channel->remote_sig_id = identifier;
593     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
594     l2cap_run();
595 }
596 
597 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
598     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
599         signaling_responses[signaling_responses_pending].handle = handle;
600         signaling_responses[signaling_responses_pending].code = code;
601         signaling_responses[signaling_responses_pending].sig_id = sig_id;
602         signaling_responses[signaling_responses_pending].data = data;
603         signaling_responses_pending++;
604         l2cap_run();
605     }
606 }
607 
608 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
609 
610     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
611     l2cap_service_t *service = l2cap_get_service(psm);
612     if (!service) {
613         // 0x0002 PSM not supported
614         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
615         return;
616     }
617 
618     hci_connection_t * hci_connection = connection_for_handle( handle );
619     if (!hci_connection) {
620         //
621         log_error("no hci_connection for handle %u\n", handle);
622         return;
623     }
624     // alloc structure
625     // log_info("l2cap_handle_connection_request register channel\n");
626     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
627     if (!channel){
628         // 0x0004 No resources available
629         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
630         return;
631     }
632 
633     // fill in
634     BD_ADDR_COPY(channel->address, hci_connection->address);
635     channel->psm = psm;
636     channel->handle = handle;
637     channel->connection = service->connection;
638     channel->packet_handler = service->packet_handler;
639     channel->local_cid  = l2cap_next_local_cid();
640     channel->remote_cid = source_cid;
641     channel->local_mtu  = service->mtu;
642     channel->remote_mtu = L2CAP_DEFAULT_MTU;
643     channel->packets_granted = 0;
644     channel->remote_sig_id = sig_id;
645 
646     // limit local mtu to max acl packet length
647     if (channel->local_mtu > l2cap_max_mtu()) {
648         channel->local_mtu = l2cap_max_mtu();
649     }
650 
651     // set initial state
652     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
653     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
654 
655     // add to connections list
656     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
657 
658     // emit incoming connection request
659     l2cap_emit_connection_request(channel);
660 }
661 
662 void l2cap_accept_connection_internal(uint16_t local_cid){
663     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
664     if (!channel) {
665         log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
666         return;
667     }
668 
669     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
670 
671     // process
672     l2cap_run();
673 }
674 
675 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
676     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
677     if (!channel) {
678         log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
679         return;
680     }
681     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
682     channel->reason = reason;
683     l2cap_run();
684 }
685 
686 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
687 
688     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
689 
690     // accept the other's configuration options
691     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
692     uint16_t pos     = 8;
693     while (pos < end_pos){
694         uint8_t type   = command[pos++];
695         uint8_t length = command[pos++];
696         // MTU { type(8): 1, len(8):2, MTU(16) }
697         if ((type & 0x7f) == 1 && length == 2){
698             channel->remote_mtu = READ_BT_16(command, pos);
699             // log_info("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
700         }
701         pos += length;
702     }
703 }
704 
705 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
706     // log_info("l2cap_channel_ready_for_open 0x%02x\n", channel->state_var);
707     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
708     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
709     return 1;
710 }
711 
712 
713 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
714 
715     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
716     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
717     uint16_t result = 0;
718 
719     log_info("signaling handler code %u, state %u\n", code, channel->state);
720 
721     // handle DISCONNECT REQUESTS seperately
722     if (code == DISCONNECTION_REQUEST){
723         switch (channel->state){
724             case L2CAP_STATE_CONFIG:
725             case L2CAP_STATE_OPEN:
726             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
727             case L2CAP_STATE_WAIT_DISCONNECT:
728                 l2cap_handle_disconnect_request(channel, identifier);
729                 break;
730 
731             default:
732                 // ignore in other states
733                 break;
734         }
735         return;
736     }
737 
738     switch (channel->state) {
739 
740         case L2CAP_STATE_WAIT_CONNECT_RSP:
741             switch (code){
742                 case CONNECTION_RESPONSE:
743                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
744                     switch (result) {
745                         case 0:
746                             // successful connection
747                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
748                             channel->state = L2CAP_STATE_CONFIG;
749                             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ;
750                             break;
751                         case 1:
752                             // connection pending. get some coffee
753                             break;
754                         default:
755                             // channel closed
756                             channel->state = L2CAP_STATE_CLOSED;
757 
758                             // map l2cap connection response result to BTstack status enumeration
759                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
760 
761                             // drop link key if security block
762                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
763                                 hci_drop_link_key_for_bd_addr(&channel->address);
764                             }
765 
766                             // discard channel
767                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
768                             btstack_memory_l2cap_channel_free(channel);
769                             break;
770                     }
771                     break;
772 
773                 default:
774                     //@TODO: implement other signaling packets
775                     break;
776             }
777             break;
778 
779         case L2CAP_STATE_CONFIG:
780             switch (code) {
781                 case CONFIGURE_REQUEST:
782                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ;
783                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP;
784                     l2cap_signaling_handle_configure_request(channel, command);
785                     break;
786                 case CONFIGURE_RESPONSE:
787                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP;
788                     break;
789                 default:
790                     break;
791             }
792             if (l2cap_channel_ready_for_open(channel)){
793                 // for open:
794                 channel->state = L2CAP_STATE_OPEN;
795                 l2cap_emit_channel_opened(channel, 0);
796                 l2cap_emit_credits(channel, 1);
797             }
798             break;
799 
800         case L2CAP_STATE_WAIT_DISCONNECT:
801             switch (code) {
802                 case DISCONNECTION_RESPONSE:
803                     l2cap_finialize_channel_close(channel);
804                     break;
805                 default:
806                     //@TODO: implement other signaling packets
807                     break;
808             }
809             break;
810 
811         case L2CAP_STATE_CLOSED:
812             // @TODO handle incoming requests
813             break;
814 
815         case L2CAP_STATE_OPEN:
816             //@TODO: implement other signaling packets, e.g. re-configure
817             break;
818         default:
819             break;
820     }
821     // log_info("new state %u\n", channel->state);
822 }
823 
824 
825 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
826 
827     // get code, signalind identifier and command len
828     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
829     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
830 
831     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
832     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
833         return;
834     }
835 
836     // general commands without an assigned channel
837     switch(code) {
838 
839         case CONNECTION_REQUEST: {
840             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
841             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
842             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
843             return;
844         }
845 
846         case ECHO_REQUEST:
847             l2cap_register_signaling_response(handle, code, sig_id, 0);
848             return;
849 
850         case INFORMATION_REQUEST: {
851             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
852             l2cap_register_signaling_response(handle, code, sig_id, infoType);
853             return;
854         }
855 
856         default:
857             break;
858     }
859 
860 
861     // Get potential destination CID
862     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
863 
864     // Find channel for this sig_id and connection handle
865     linked_item_t *it;
866     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
867         l2cap_channel_t * channel = (l2cap_channel_t *) it;
868         if (channel->handle == handle) {
869             if (code & 1) {
870                 // match odd commands (responses) by previous signaling identifier
871                 if (channel->local_sig_id == sig_id) {
872                     l2cap_signaling_handler_channel(channel, command);
873                     break;
874                 }
875             } else {
876                 // match even commands (requests) by local channel id
877                 if (channel->local_cid == dest_cid) {
878                     l2cap_signaling_handler_channel(channel, command);
879                     break;
880                 }
881             }
882         }
883     }
884 }
885 
886 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
887 
888     // Get Channel ID
889     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
890 
891     // Signaling Packet?
892     if (channel_id == 1) {
893 
894         // Get Connection
895         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
896 
897         uint16_t command_offset = 8;
898         while (command_offset < size) {
899 
900             // handle signaling commands
901             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
902 
903             // increment command_offset
904             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
905         }
906 
907         l2cap_run();
908 
909         return;
910     }
911 
912     // Find channel for this channel_id and connection handle
913     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
914     if (channel) {
915         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
916     }
917 }
918 
919 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
920     switch (packet_type) {
921         case HCI_EVENT_PACKET:
922             l2cap_event_handler(packet, size);
923             break;
924         case HCI_ACL_DATA_PACKET:
925             l2cap_acl_handler(packet, size);
926             break;
927         default:
928             break;
929     }
930 }
931 
932 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
933 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
934     channel->state = L2CAP_STATE_CLOSED;
935     l2cap_emit_channel_closed(channel);
936     // discard channel
937     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
938     btstack_memory_l2cap_channel_free(channel);
939 }
940 
941 l2cap_service_t * l2cap_get_service(uint16_t psm){
942     linked_item_t *it;
943 
944     // close open channels
945     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
946         l2cap_service_t * service = ((l2cap_service_t *) it);
947         if ( service->psm == psm){
948             return service;
949         };
950     }
951     return NULL;
952 }
953 
954 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
955     // check for alread registered psm
956     // TODO: emit error event
957     l2cap_service_t *service = l2cap_get_service(psm);
958     if (service) {
959         log_error("l2cap_register_service_internal: PSM %u already registered\n", psm);
960         return;
961     }
962 
963     // alloc structure
964     // TODO: emit error event
965     service = btstack_memory_l2cap_service_get();
966     if (!service) {
967         log_error("l2cap_register_service_internal: no memory for l2cap_service_t\n");
968         return;
969     }
970 
971     // fill in
972     service->psm = psm;
973     service->mtu = mtu;
974     service->connection = connection;
975     service->packet_handler = packet_handler;
976 
977     // add to services list
978     linked_list_add(&l2cap_services, (linked_item_t *) service);
979 }
980 
981 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
982     l2cap_service_t *service = l2cap_get_service(psm);
983     if (!service) return;
984     linked_list_remove(&l2cap_services, (linked_item_t *) service);
985     btstack_memory_l2cap_service_free(service);
986 }
987 
988 //
989 void l2cap_close_connection(void *connection){
990     linked_item_t *it;
991 
992     // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks
993     l2cap_channel_t * channel;
994     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
995         channel = (l2cap_channel_t *) it;
996         if (channel->connection == connection) {
997             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
998         }
999     }
1000 
1001     // unregister services
1002     it = (linked_item_t *) &l2cap_services;
1003     while (it->next) {
1004         l2cap_service_t * service = (l2cap_service_t *) it->next;
1005         if (service->connection == connection){
1006             it->next = it->next->next;
1007             btstack_memory_l2cap_service_free(service);
1008         } else {
1009             it = it->next;
1010         }
1011     }
1012 
1013     // process
1014     l2cap_run();
1015 }
1016