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