xref: /btstack/src/l2cap.c (revision cb8eb7e69eaaca409db0b901afd8f7cbee8b1ee3)
1 /*
2  * Copyright (C) 2009 by Matthias Ringwald
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  l2cap.c
34  *
35  *  Logical Link Control and Adaption Protocl (L2CAP)
36  *
37  *  Created by Matthias Ringwald on 5/16/09.
38  */
39 
40 #include "l2cap.h"
41 #include "hci.h"
42 #include "hci_dump.h"
43 #include "debug.h"
44 
45 #include <stdarg.h>
46 #include <string.h>
47 
48 #include <stdio.h>
49 
50 // size of HCI ACL + L2CAP Header for regular data packets
51 #define COMPLETE_L2CAP_HEADER 8
52 
53 // minimum signaling MTU
54 #define L2CAP_MINIMAL_MTU 48
55 #define L2CAP_DEFAULT_MTU 672
56 
57 // nr of buffered acl packets in outgoing queue to get max performance
58 #define NR_BUFFERED_ACL_PACKETS 3
59 
60 // offsets for L2CAP SIGNALING COMMANDS
61 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
62 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
63 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
64 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
65 
66 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
67 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
68 
69 static uint8_t * sig_buffer = NULL;
70 static linked_list_t l2cap_channels = NULL;
71 static linked_list_t l2cap_services = NULL;
72 static uint8_t * acl_buffer = NULL;
73 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
74 static int new_credits_blocked = 0;
75 
76 void l2cap_init(){
77     sig_buffer = malloc( L2CAP_MINIMAL_MTU );
78     acl_buffer = malloc( HCI_ACL_3DH5_SIZE);
79 
80     new_credits_blocked = 0;
81 
82     //
83     // register callback with HCI
84     //
85     hci_register_packet_handler(&l2cap_packet_handler);
86 }
87 
88 
89 /** Register L2CAP packet handlers */
90 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
91 }
92 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
93     packet_handler = handler;
94 }
95 
96 //  notify client/protocol handler
97 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
98     if (channel->packet_handler) {
99         (* (channel->packet_handler))(type, channel->local_cid, data, size);
100     } else {
101         (*packet_handler)(channel->connection, type, channel->local_cid, data, size);
102     }
103 }
104 
105 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
106     uint8_t event[21];
107     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
108     event[1] = sizeof(event) - 2;
109     event[2] = status;
110     bt_flip_addr(&event[3], channel->address);
111     bt_store_16(event,  9, channel->handle);
112     bt_store_16(event, 11, channel->psm);
113     bt_store_16(event, 13, channel->local_cid);
114     bt_store_16(event, 15, channel->remote_cid);
115     bt_store_16(event, 17, channel->local_mtu);
116     bt_store_16(event, 19, channel->remote_mtu);
117     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
118     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
119 }
120 
121 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
122     uint8_t event[4];
123     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
124     event[1] = sizeof(event) - 2;
125     bt_store_16(event, 2, channel->local_cid);
126     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
127     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
128 }
129 
130 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
131     uint8_t event[16];
132     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
133     event[1] = sizeof(event) - 2;
134     bt_flip_addr(&event[2], channel->address);
135     bt_store_16(event,  8, channel->handle);
136     bt_store_16(event, 10, channel->psm);
137     bt_store_16(event, 12, channel->local_cid);
138     bt_store_16(event, 14, channel->remote_cid);
139     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
140     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
141 }
142 
143 void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) {
144     // track credits
145     channel->packets_granted += credits;
146     // log_dbg("l2cap_emit_credits for cid %u, credits given: %u (+%u)\n", channel->local_cid, channel->packets_granted, credits);
147 
148     uint8_t event[5];
149     event[0] = L2CAP_EVENT_CREDITS;
150     event[1] = sizeof(event) - 2;
151     bt_store_16(event, 2, channel->local_cid);
152     event[4] = credits;
153     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
154     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
155 }
156 
157 void l2cap_block_new_credits(uint8_t blocked){
158     new_credits_blocked = blocked;
159 }
160 
161 void l2cap_hand_out_credits(void){
162 
163     if (new_credits_blocked) return;    // we're told not to. used by daemon
164 
165     linked_item_t *it;
166     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
167         if (!hci_number_free_acl_slots()) return;
168         l2cap_channel_t * channel = (l2cap_channel_t *) it;
169         if (channel->state != L2CAP_STATE_OPEN) continue;
170         if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) {
171             l2cap_emit_credits(channel, 1);
172         }
173     }
174 }
175 
176 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
177     linked_item_t *it;
178     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
179         l2cap_channel_t * channel = (l2cap_channel_t *) it;
180         if ( channel->local_cid == local_cid) {
181             return channel;
182         }
183     }
184     return NULL;
185 }
186 
187 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
188     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
189     if (channel) {
190         return channel->remote_mtu;
191     }
192     return 0;
193 }
194 
195 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
196     // log_dbg("l2cap_send_signaling_packet type %u\n", cmd);
197     va_list argptr;
198     va_start(argptr, identifier);
199     uint16_t len = l2cap_create_signaling_internal(sig_buffer, handle, cmd, identifier, argptr);
200     va_end(argptr);
201     // log_dbg("l2cap_send_signaling_packet con %u!\n", handle);
202     return hci_send_acl_packet(sig_buffer, len);
203 }
204 
205 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){
206 
207     // check for free places on BT module
208     if (!hci_number_free_acl_slots()) {
209         log_dbg("l2cap_send_internal cid %u, BT module full <-----\n", local_cid);
210         return BTSTACK_ACL_BUFFERS_FULL;
211     }
212     int err = 0;
213 
214     // find channel for local_cid, construct l2cap packet and send
215     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
216     if (channel) {
217         if (channel->packets_granted > 0){
218             --channel->packets_granted;
219             // log_dbg("l2cap_send_internal cid %u, handle %u, 1 credit used, credits left %u;\n",
220             //        local_cid, channel->handle, channel->packets_granted);
221         } else {
222             log_err("l2cap_send_internal cid %u, no credits!\n", local_cid);
223         }
224 
225         // 0 - Connection handle : PB=10 : BC=00
226         bt_store_16(acl_buffer, 0, channel->handle | (2 << 12) | (0 << 14));
227         // 2 - ACL length
228         bt_store_16(acl_buffer, 2,  len + 4);
229         // 4 - L2CAP packet length
230         bt_store_16(acl_buffer, 4,  len + 0);
231         // 6 - L2CAP channel DEST
232         bt_store_16(acl_buffer, 6, channel->remote_cid);
233         // 8 - data
234         memcpy(&acl_buffer[8], data, len);
235 
236         // send
237         err = hci_send_acl_packet(acl_buffer, len+8);
238     }
239 
240     l2cap_hand_out_credits();
241 
242     return err;
243 }
244 
245 // process outstanding signaling tasks
246 void l2cap_run(void){
247     linked_item_t *it;
248     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
249 
250         // can send?
251 
252         l2cap_channel_t * channel = (l2cap_channel_t *) it;
253         switch (channel->state){
254 
255             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
256                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, 0, 0, channel->reason, 0);
257                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
258                 linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
259                 free (channel);
260                 break;
261 
262             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
263                 // success, start l2cap handshake
264                 channel->sig_id = l2cap_next_sig_id();
265                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->sig_id, channel->psm, channel->local_cid);
266                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
267                 break;
268 
269             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
270                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid);
271                 l2cap_finialize_channel_close(channel);
272                 break;
273 
274             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
275                 channel->sig_id = l2cap_next_sig_id();
276                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->sig_id, channel->remote_cid, channel->local_cid);
277                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
278                 break;
279             default:
280                 break;
281         }
282     }
283 }
284 
285 // open outgoing L2CAP channel
286 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler,
287                                    bd_addr_t address, uint16_t psm, uint16_t mtu){
288 
289     // alloc structure
290     l2cap_channel_t * chan = malloc(sizeof(l2cap_channel_t));
291     // TODO: emit error event
292     if (!chan) return;
293 
294     // limit local mtu to max acl packet length
295     if (mtu > hci_max_acl_data_packet_length()) {
296         mtu = hci_max_acl_data_packet_length();
297     }
298 
299     // fill in
300     BD_ADDR_COPY(chan->address, address);
301     chan->psm = psm;
302     chan->handle = 0;
303     chan->connection = connection;
304     chan->packet_handler = packet_handler;
305     chan->remote_mtu = L2CAP_MINIMAL_MTU;
306     chan->local_mtu = mtu;
307     chan->packets_granted = 0;
308 
309     // set initial state
310     chan->state = L2CAP_STATE_CLOSED;
311     chan->sig_id = L2CAP_SIG_ID_INVALID;
312 
313     // add to connections list
314     linked_list_add(&l2cap_channels, (linked_item_t *) chan);
315 
316     // send connection request
317     // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
318     hci_send_cmd(&hci_create_connection, address, 0xcc18, 0, 0, 0, 1);
319 }
320 
321 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){
322     // find channel for local_cid
323     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
324     if (channel) {
325         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
326     }
327     // process
328     l2cap_run();
329 }
330 
331 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
332     linked_item_t *it = (linked_item_t *) &l2cap_channels;
333     while (it->next){
334         l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
335         if ( ! BD_ADDR_CMP( channel->address, address) ){
336             if (channel->state == L2CAP_STATE_CLOSED) {
337                 // failure, forward error code
338                 l2cap_emit_channel_opened(channel, status);
339                 // discard channel
340                 it->next = it->next->next;
341                 free (channel);
342             }
343         } else {
344             it = it->next;
345         }
346     }
347 }
348 
349 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
350     linked_item_t *it;
351     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
352         l2cap_channel_t * channel = (l2cap_channel_t *) it;
353         if ( ! BD_ADDR_CMP( channel->address, address) ){
354             if (channel->state == L2CAP_STATE_CLOSED) {
355                 // success, start l2cap handshake
356                 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
357                 channel->handle = handle;
358                 channel->local_cid = l2cap_next_local_cid();
359             }
360         }
361     }
362     // process
363     l2cap_run();
364 }
365 
366 void l2cap_event_handler( uint8_t *packet, uint16_t size ){
367 
368     bd_addr_t address;
369     hci_con_handle_t handle;
370     linked_item_t *it;
371 
372     switch(packet[0]){
373 
374         // handle connection complete events
375         case HCI_EVENT_CONNECTION_COMPLETE:
376             bt_flip_addr(address, &packet[5]);
377             if (packet[2] == 0){
378                 handle = READ_BT_16(packet, 3);
379                 l2cap_handle_connection_success_for_addr(address, handle);
380             } else {
381                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
382             }
383             break;
384 
385         // handle successful create connection cancel command
386         case HCI_EVENT_COMMAND_COMPLETE:
387             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
388                 if (packet[5] == 0){
389                     bt_flip_addr(address, &packet[6]);
390                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
391                     l2cap_handle_connection_failed_for_addr(address, 0x16);
392                 }
393             }
394             break;
395 
396         // handle disconnection complete events
397         case HCI_EVENT_DISCONNECTION_COMPLETE:
398             // send l2cap disconnect events for all channels on this handle
399             handle = READ_BT_16(packet, 3);
400             it = (linked_item_t *) &l2cap_channels;
401             while (it->next){
402                 l2cap_channel_t * channel = (l2cap_channel_t *) it->next;
403                 if ( channel->handle == handle ){
404                     // update prev item before free'ing next element - don't call l2cap_finalize_channel_close
405                     it->next = it->next->next;
406                     l2cap_emit_channel_closed(channel);
407                     free (channel);
408                 } else {
409                     it = it->next;
410                 }
411             }
412             break;
413 
414         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
415             l2cap_hand_out_credits();
416             break;
417 
418         // HCI Connection Timeouts
419         case L2CAP_EVENT_TIMEOUT_CHECK:
420             handle = READ_BT_16(packet, 2);
421             if (hci_authentication_active_for_handle(handle)) break;
422             l2cap_channel_t * channel;
423             int used = 0;
424             for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
425                 channel = (l2cap_channel_t *) it;
426                 if (channel->handle == handle) {
427                     used = 1;
428                 }
429             }
430             if (!used) {
431                 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
432             }
433             break;
434 
435         default:
436             break;
437     }
438 
439     // pass on
440     (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size);
441 }
442 
443 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
444     channel->sig_id = identifier;
445     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
446     l2cap_run();
447 }
448 
449 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
450 
451     // log_dbg("l2cap_handle_connection_request for handle %u, psm %u cid %u\n", handle, psm, source_cid);
452     l2cap_service_t *service = l2cap_get_service(psm);
453     if (!service) {
454         // 0x0002 PSM not supported
455         // log_dbg("l2cap_handle_connection_request no PSM for psm %u/n", psm);
456         l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, 0x0002, 0);
457         return;
458     }
459 
460     hci_connection_t * hci_connection = connection_for_handle( handle );
461     if (!hci_connection) {
462         log_err("no hci_connection for handle %u\n", handle);
463         // TODO: emit error
464         return;
465     }
466     // alloc structure
467     // log_dbg("l2cap_handle_connection_request register channel\n");
468     l2cap_channel_t * channel = malloc(sizeof(l2cap_channel_t));
469     // TODO: emit error event
470     if (!channel) return;
471 
472     // fill in
473     BD_ADDR_COPY(channel->address, hci_connection->address);
474     channel->psm = psm;
475     channel->handle = handle;
476     channel->connection = service->connection;
477     channel->packet_handler = service->packet_handler;
478     channel->local_cid  = l2cap_next_local_cid();
479     channel->remote_cid = source_cid;
480     channel->local_mtu  = service->mtu;
481     channel->remote_mtu = L2CAP_DEFAULT_MTU;
482     channel->packets_granted = 0;
483 
484     // limit local mtu to max acl packet length
485     if (channel->local_mtu > hci_max_acl_data_packet_length()) {
486         channel->local_mtu = hci_max_acl_data_packet_length();
487     }
488 
489     // set initial state
490     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
491 
492     // temp. store req sig id
493     channel->sig_id = sig_id;
494 
495     // add to connections list
496     linked_list_add(&l2cap_channels, (linked_item_t *) channel);
497 
498     // emit incoming connection request
499     l2cap_emit_connection_request(channel);
500 }
501 
502 void l2cap_accept_connection_internal(uint16_t local_cid){
503     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
504     if (!channel) {
505         log_err("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid);
506         return;
507     }
508 
509     // accept connection
510     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->sig_id, channel->local_cid, channel->remote_cid, 0, 0);
511 
512     // set real sig and state and start config
513     channel->sig_id = l2cap_next_sig_id();
514     channel->state  = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
515     uint8_t config_options[4];
516     config_options[0] = 1; // MTU
517     config_options[1] = 2; // len param
518     bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
519     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
520 
521     // log_dbg("new state %u\n", channel->state);
522 }
523 
524 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){
525     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
526     if (!channel) {
527         log_err( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid);
528         return;
529     }
530     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
531     channel->reason = reason;
532     l2cap_run();
533 }
534 
535 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
536     // accept the other's configuration options
537     uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
538     uint16_t pos     = 8;
539     while (pos < end_pos){
540         uint8_t type   = command[pos++];
541         uint8_t length = command[pos++];
542         // MTU { type(8): 1, len(8):2, MTU(16) }
543         if ((type & 0x7f) == 1 && length == 2){
544             channel->remote_mtu = READ_BT_16(command, pos);
545             // log_dbg("l2cap cid %u, remote mtu %u\n", channel->local_cid, channel->remote_mtu);
546         }
547         pos += length;
548     }
549     uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
550     // send back OK
551     l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, identifier, channel->remote_cid, 0, 0, 0, NULL);
552 }
553 
554 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
555 
556     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
557     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
558     uint16_t result = 0;
559     uint8_t  config_options[4];
560 
561     // log_dbg("signaling handler code %u\n", code);
562 
563     switch (channel->state) {
564 
565         case L2CAP_STATE_WAIT_CONNECT_RSP:
566             switch (code){
567                 case CONNECTION_RESPONSE:
568                     result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
569                     switch (result) {
570                         case 0:
571                             // successful connection
572                             channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
573 
574 
575                             channel->sig_id = l2cap_next_sig_id();
576                             config_options[0] = 1; // MTU
577                             config_options[1] = 2; // len param
578                             bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
579                             l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->sig_id, channel->remote_cid, 0, 4, &config_options);
580                             channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ;
581 
582 #if 0
583     channel->state = L2CAP_STATE_OPEN;
584     l2cap_emit_channel_opened(channel, 0);  // success
585     l2cap_emit_credits(channel, 1);
586 #endif
587                             break;
588                         case 1:
589                             // connection pending. get some coffee
590                             break;
591                         default:
592                             // channel closed
593                             channel->state = L2CAP_STATE_CLOSED;
594 
595                             // map l2cap connection response result to BTstack status enumeration
596                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
597 
598                             // drop link key if security block
599                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
600                                 hci_drop_link_key_for_bd_addr(&channel->address);
601                             }
602 
603                             // discard channel
604                             linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
605                             free (channel);
606                             break;
607                     }
608                     break;
609 
610                 case DISCONNECTION_REQUEST:
611                     l2cap_handle_disconnect_request(channel, identifier);
612                     break;
613 
614                 default:
615                     //@TODO: implement other signaling packets
616                     break;
617             }
618             break;
619 
620         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP_OR_CONFIG_REQ:
621             switch (code) {
622                 case CONFIGURE_RESPONSE:
623                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ;
624                     break;
625                 case CONFIGURE_REQUEST:
626                     l2cap_signaling_handle_configure_request(channel, command);
627                     channel->state = L2CAP_STATE_WAIT_CONFIG_REQ_RSP;
628                     break;
629                 case DISCONNECTION_REQUEST:
630                     l2cap_handle_disconnect_request(channel, identifier);
631                     break;
632                 default:
633                     //@TODO: implement other signaling packets
634                     break;
635             }
636             break;
637 
638         case L2CAP_STATE_WAIT_CONFIG_REQ:
639             switch (code) {
640                 case CONFIGURE_REQUEST:
641                     l2cap_signaling_handle_configure_request(channel, command);
642                     channel->state = L2CAP_STATE_OPEN;
643                     l2cap_emit_channel_opened(channel, 0);  // success
644                     l2cap_emit_credits(channel, 1);
645                     break;
646                 case DISCONNECTION_REQUEST:
647                     l2cap_handle_disconnect_request(channel, identifier);
648                     break;
649                 default:
650                     //@TODO: implement other signaling packets
651                     break;
652             }
653             break;
654 
655         case L2CAP_STATE_WAIT_CONFIG_REQ_RSP:
656             switch (code) {
657                 case CONFIGURE_RESPONSE:
658                     channel->state = L2CAP_STATE_OPEN;
659                     l2cap_emit_channel_opened(channel, 0);  // success
660                     l2cap_emit_credits(channel, 1);
661                     break;
662                 case DISCONNECTION_REQUEST:
663                     l2cap_handle_disconnect_request(channel, identifier);
664                     break;
665                 default:
666                     //@TODO: implement other signaling packets
667                     break;
668             }
669             break;
670 
671         case L2CAP_STATE_WAIT_DISCONNECT:
672             switch (code) {
673                 case DISCONNECTION_RESPONSE:
674                     l2cap_finialize_channel_close(channel);
675                     break;
676                 case DISCONNECTION_REQUEST:
677                     l2cap_handle_disconnect_request(channel, identifier);
678                     break;
679                 default:
680                     //@TODO: implement other signaling packets
681                     break;
682             }
683             break;
684 
685         case L2CAP_STATE_CLOSED:
686             // @TODO handle incoming requests
687             break;
688 
689         case L2CAP_STATE_OPEN:
690             switch (code) {
691                 case DISCONNECTION_REQUEST:
692                     l2cap_handle_disconnect_request(channel, identifier);
693                     break;
694                 default:
695                     //@TODO: implement other signaling packets, e.g. re-configure
696                     break;
697             }
698             break;
699         default:
700             break;
701     }
702     // log_dbg("new state %u\n", channel->state);
703 }
704 
705 
706 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
707 
708     // get code, signalind identifier and command len
709     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
710     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
711     uint16_t len   = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
712 
713     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
714     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
715         return;
716     }
717 
718     // general commands without an assigned channel
719     switch(code) {
720 
721         case CONNECTION_REQUEST: {
722             uint16_t psm =        READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
723             uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
724             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
725             break;
726         }
727 
728         case ECHO_REQUEST: {
729             // send back packet
730             l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, len, &command[L2CAP_SIGNALING_COMMAND_DATA_OFFSET]);
731             break;
732         }
733 
734         case INFORMATION_REQUEST: {
735             // we neither support connectionless L2CAP data nor support any flow control modes yet
736             uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
737             if (infoType == 2) {
738                 uint32_t features = 0;
739                 // extended features request supported, however no features present
740                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, 4, &features);
741             } else {
742                 // all other types are not supported
743                 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
744             }
745             break;;
746         }
747 
748         default:
749             break;
750     }
751 
752 
753     // Get potential destination CID
754     uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
755 
756     // Find channel for this sig_id and connection handle
757     linked_item_t *it;
758     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
759         l2cap_channel_t * channel = (l2cap_channel_t *) it;
760         if (channel->handle == handle) {
761             if (code & 1) {
762                 // match odd commands by previous signaling identifier
763                 if (channel->sig_id == sig_id) {
764                     l2cap_signaling_handler_channel(channel, command);
765                     break;
766                 }
767             } else {
768                 // match even commands by local channel id
769                 if (channel->local_cid == dest_cid) {
770                     l2cap_signaling_handler_channel(channel, command);
771                     break;
772                 }
773             }
774         }
775     }
776 }
777 
778 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
779 
780     // Get Channel ID
781     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
782 
783     // Signaling Packet?
784     if (channel_id == 1) {
785 
786         // Get Connection
787         hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
788 
789         uint16_t command_offset = 8;
790         while (command_offset < size) {
791 
792             // handle signaling commands
793             l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
794 
795             // increment command_offset
796             command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
797         }
798         return;
799     }
800 
801     // Find channel for this channel_id and connection handle
802     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
803     if (channel) {
804         l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
805     }
806 }
807 
808 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
809     switch (packet_type) {
810         case HCI_EVENT_PACKET:
811             l2cap_event_handler(packet, size);
812             break;
813         case HCI_ACL_DATA_PACKET:
814             l2cap_acl_handler(packet, size);
815             break;
816         default:
817             break;
818     }
819 }
820 
821 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
822 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
823     channel->state = L2CAP_STATE_CLOSED;
824     l2cap_emit_channel_closed(channel);
825     // discard channel
826     linked_list_remove(&l2cap_channels, (linked_item_t *) channel);
827     free (channel);
828 }
829 
830 l2cap_service_t * l2cap_get_service(uint16_t psm){
831     linked_item_t *it;
832 
833     // close open channels
834     for (it = (linked_item_t *) l2cap_services; it ; it = it->next){
835         l2cap_service_t * service = ((l2cap_service_t *) it);
836         if ( service->psm == psm){
837             return service;
838         };
839     }
840     return NULL;
841 }
842 
843 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu){
844     // check for alread registered psm // TODO: emit error event
845     l2cap_service_t *service = l2cap_get_service(psm);
846     if (service) return;
847 
848     // alloc structure     // TODO: emit error event
849     service = malloc(sizeof(l2cap_service_t));
850     if (!service) return;
851 
852     // fill in
853     service->psm = psm;
854     service->mtu = mtu;
855     service->connection = connection;
856     service->packet_handler = packet_handler;
857 
858     // add to services list
859     linked_list_add(&l2cap_services, (linked_item_t *) service);
860 }
861 
862 void l2cap_unregister_service_internal(void *connection, uint16_t psm){
863     l2cap_service_t *service = l2cap_get_service(psm);
864     if (!service) return;
865     linked_list_remove(&l2cap_services, (linked_item_t *) service);
866     free(service);
867 }
868 
869 //
870 void l2cap_close_connection(void *connection){
871     linked_item_t *it;
872 
873     // close open channels - note to myself: no channel is freed, so no new for fancy iterator tricks
874     l2cap_channel_t * channel;
875     for (it = (linked_item_t *) l2cap_channels; it ; it = it->next){
876         channel = (l2cap_channel_t *) it;
877         if (channel->connection == connection) {
878             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
879         }
880     }
881 
882     // unregister services
883     it = (linked_item_t *) &l2cap_services;
884     while (it->next) {
885         l2cap_service_t * service = (l2cap_service_t *) it->next;
886         if (service->connection == connection){
887             it->next = it->next->next;
888             free(service);
889         } else {
890             it = it->next;
891         }
892     }
893 
894     // process
895     l2cap_run();
896 }
897