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