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