1 /*
2 * Copyright 2014 Samsung System LSI
3 * Copyright 2013 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include "btif_sock_l2cap.h"
19
20 #include <base/logging.h>
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <vector>
28
29 #include <mutex>
30
31 #include <frameworks/base/core/proto/android/bluetooth/enums.pb.h>
32 #include <hardware/bt_sock.h>
33
34 #include "osi/include/allocator.h"
35
36 #include "bt_common.h"
37 #include "bt_target.h"
38 #include "bta_api.h"
39 #include "bta_jv_api.h"
40 #include "bta_jv_co.h"
41 #include "btif_common.h"
42 #include "btif_sock_sdp.h"
43 #include "btif_sock_thread.h"
44 #include "btif_sock_util.h"
45 #include "btif_uid.h"
46 #include "btif_util.h"
47 #include "btm_api.h"
48 #include "btm_int.h"
49 #include "btu.h"
50 #include "common/metrics.h"
51 #include "hcimsgs.h"
52 #include "l2c_api.h"
53 #include "l2c_int.h"
54 #include "l2cdefs.h"
55 #include "port_api.h"
56 #include "sdp_api.h"
57
58 struct packet {
59 struct packet *next, *prev;
60 uint32_t len;
61 uint8_t* data;
62 };
63
64 typedef struct l2cap_socket {
65 struct l2cap_socket* prev; // link to prev list item
66 struct l2cap_socket* next; // link to next list item
67 RawAddress addr; // other side's address
68 char name[256]; // user-friendly name of the service
69 uint32_t id; // just a tag to find this struct
70 int app_uid; // The UID of the app who requested this socket
71 int handle; // handle from lower layers
72 unsigned security; // security flags
73 int channel; // channel (fixed_chan) or PSM (!fixed_chan)
74 int our_fd; // fd from our side
75 int app_fd; // fd from app's side
76
77 unsigned bytes_buffered;
78 struct packet* first_packet; // fist packet to be delivered to app
79 struct packet* last_packet; // last packet to be delivered to app
80
81 unsigned fixed_chan : 1; // fixed channel (or psm?)
82 unsigned server : 1; // is a server? (or connecting?)
83 unsigned connected : 1; // is connected?
84 unsigned outgoing_congest : 1; // should we hold?
85 unsigned server_psm_sent : 1; // The server shall only send PSM once.
86 bool is_le_coc; // is le connection oriented channel?
87 uint16_t rx_mtu;
88 uint16_t tx_mtu;
89 // Cumulative number of bytes transmitted on this socket
90 int64_t tx_bytes;
91 // Cumulative number of bytes received on this socket
92 int64_t rx_bytes;
93 } l2cap_socket;
94
95 static void btsock_l2cap_server_listen(l2cap_socket* sock);
96
97 static std::mutex state_lock;
98
99 l2cap_socket* socks = NULL;
100 static uint32_t last_sock_id = 0;
101 static uid_set_t* uid_set = NULL;
102 static int pth = -1;
103
104 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data,
105 uint32_t l2cap_socket_id);
106
107 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well,
108 * and we risk
109 * a buffer overflow with this implementation if the socket data is not
110 * read from
111 * JAVA for a while. In such a case we should use flow control to tell the
112 * sender to
113 * back off.
114 * BUT remember we need to avoid blocking the BTA task execution - hence
115 * we cannot
116 * directly write to the socket.
117 * we should be able to change to store the data pointer here, and just
118 * wait
119 * confirming the l2cap_ind until we have more space in the buffer. */
120
121 /* returns false if none - caller must free "data" memory when done with it */
packet_get_head_l(l2cap_socket * sock,uint8_t ** data,uint32_t * len)122 static char packet_get_head_l(l2cap_socket* sock, uint8_t** data,
123 uint32_t* len) {
124 struct packet* p = sock->first_packet;
125
126 if (!p) return false;
127
128 if (data) *data = sock->first_packet->data;
129 if (len) *len = sock->first_packet->len;
130 sock->first_packet = p->next;
131 if (sock->first_packet)
132 sock->first_packet->prev = NULL;
133 else
134 sock->last_packet = NULL;
135
136 if (len) sock->bytes_buffered -= *len;
137
138 osi_free(p);
139
140 return true;
141 }
142
packet_alloc(const uint8_t * data,uint32_t len)143 static struct packet* packet_alloc(const uint8_t* data, uint32_t len) {
144 struct packet* p = (struct packet*)osi_calloc(sizeof(*p));
145 uint8_t* buf = (uint8_t*)osi_malloc(len);
146
147 p->data = buf;
148 p->len = len;
149 memcpy(p->data, data, len);
150 return p;
151 }
152
153 /* makes a copy of the data, returns true on success */
packet_put_head_l(l2cap_socket * sock,const void * data,uint32_t len)154 static char packet_put_head_l(l2cap_socket* sock, const void* data,
155 uint32_t len) {
156 struct packet* p = packet_alloc((const uint8_t*)data, len);
157
158 /*
159 * We do not check size limits here since this is used to undo "getting" a
160 * packet that the user read incompletely. That is to say the packet was
161 * already in the queue. We do check thos elimits in packet_put_tail_l() since
162 * that function is used to put new data into the queue.
163 */
164
165 if (!p) return false;
166
167 p->prev = NULL;
168 p->next = sock->first_packet;
169 sock->first_packet = p;
170 if (p->next)
171 p->next->prev = p;
172 else
173 sock->last_packet = p;
174
175 sock->bytes_buffered += len;
176
177 return true;
178 }
179
180 /* makes a copy of the data, returns true on success */
packet_put_tail_l(l2cap_socket * sock,const void * data,uint32_t len)181 static char packet_put_tail_l(l2cap_socket* sock, const void* data,
182 uint32_t len) {
183 if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
184 LOG(ERROR) << __func__ << ": buffer overflow";
185 return false;
186 }
187
188 struct packet* p = packet_alloc((const uint8_t*)data, len);
189 p->next = NULL;
190 p->prev = sock->last_packet;
191 sock->last_packet = p;
192 if (p->prev)
193 p->prev->next = p;
194 else
195 sock->first_packet = p;
196
197 sock->bytes_buffered += len;
198
199 return true;
200 }
201
is_inited(void)202 static char is_inited(void) {
203 std::unique_lock<std::mutex> lock(state_lock);
204 return pth != -1;
205 }
206
207 /* only call with std::mutex taken */
btsock_l2cap_find_by_id_l(uint32_t id)208 static l2cap_socket* btsock_l2cap_find_by_id_l(uint32_t id) {
209 l2cap_socket* sock = socks;
210
211 while (sock && sock->id != id) sock = sock->next;
212
213 return sock;
214 }
215
btsock_l2cap_free_l(l2cap_socket * sock)216 static void btsock_l2cap_free_l(l2cap_socket* sock) {
217 uint8_t* buf;
218 l2cap_socket* t = socks;
219
220 while (t && t != sock) t = t->next;
221
222 if (!t) /* prever double-frees */
223 return;
224
225 // Whenever a socket is freed, the connection must be dropped
226 bluetooth::common::LogSocketConnectionState(
227 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
228 android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTED, sock->tx_bytes,
229 sock->rx_bytes, sock->app_uid, sock->channel,
230 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
231 : android::bluetooth::SOCKET_ROLE_CONNECTION);
232
233 if (sock->next) sock->next->prev = sock->prev;
234
235 if (sock->prev)
236 sock->prev->next = sock->next;
237 else
238 socks = sock->next;
239
240 shutdown(sock->our_fd, SHUT_RDWR);
241 close(sock->our_fd);
242 if (sock->app_fd != -1) {
243 close(sock->app_fd);
244 } else {
245 LOG(ERROR) << "SOCK_LIST: free(id = " << sock->id << ") - NO app_fd!";
246 }
247
248 while (packet_get_head_l(sock, &buf, NULL)) osi_free(buf);
249
250 // lower-level close() should be idempotent... so let's call it and see...
251 if (sock->is_le_coc) {
252 // Only call if we are non server connections
253 if (sock->handle >= 0 && (!sock->server)) {
254 BTA_JvL2capClose(sock->handle);
255 }
256 if ((sock->channel >= 0) && (sock->server)) {
257 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
258 if (!sock->fixed_chan) {
259 VLOG(2) << __func__ << ": stopping L2CAP LE COC server channel "
260 << sock->channel;
261 BTA_JvL2capStopServer(sock->channel, sock->id);
262 }
263 }
264 } else {
265 // Only call if we are non server connections
266 if ((sock->handle >= 0) && (!sock->server)) {
267 if (sock->fixed_chan)
268 BTA_JvL2capCloseLE(sock->handle);
269 else
270 BTA_JvL2capClose(sock->handle);
271 }
272 if ((sock->channel >= 0) && (sock->server)) {
273 if (sock->fixed_chan)
274 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
275 else
276 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
277
278 if (!sock->fixed_chan) {
279 DVLOG(2) << __func__ << ": stopping L2CAP server channel "
280 << sock->channel;
281 BTA_JvL2capStopServer(sock->channel, sock->id);
282 }
283 }
284 }
285
286 DVLOG(2) << __func__ << ": free id:" << sock->id;
287 osi_free(sock);
288 }
289
btsock_l2cap_alloc_l(const char * name,const RawAddress * addr,char is_server,int flags)290 static l2cap_socket* btsock_l2cap_alloc_l(const char* name,
291 const RawAddress* addr,
292 char is_server, int flags) {
293 unsigned security = 0;
294 int fds[2];
295 l2cap_socket* sock = (l2cap_socket*)osi_calloc(sizeof(*sock));
296
297 if (flags & BTSOCK_FLAG_ENCRYPT)
298 security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
299 if (flags & BTSOCK_FLAG_AUTH)
300 security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
301 if (flags & BTSOCK_FLAG_AUTH_MITM)
302 security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
303 if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
304 security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
305
306 if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, fds)) {
307 LOG(ERROR) << "socketpair failed, errno:" << errno;
308 goto fail_sockpair;
309 }
310
311 sock->our_fd = fds[0];
312 sock->app_fd = fds[1];
313 sock->security = security;
314 sock->server = is_server;
315 sock->connected = false;
316 sock->handle = 0;
317 sock->server_psm_sent = false;
318 sock->app_uid = -1;
319
320 if (name) strncpy(sock->name, name, sizeof(sock->name) - 1);
321 if (addr) sock->addr = *addr;
322
323 sock->first_packet = NULL;
324 sock->last_packet = NULL;
325
326 sock->tx_mtu = L2CAP_LE_MIN_MTU;
327
328 sock->next = socks;
329 sock->prev = NULL;
330 if (socks) socks->prev = sock;
331 sock->id = last_sock_id + 1;
332 sock->tx_bytes = 0;
333 sock->rx_bytes = 0;
334 socks = sock;
335 /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed
336 */
337 while (1) {
338 l2cap_socket* t;
339 t = socks->next;
340 while (t && t->id != sock->id) {
341 t = t->next;
342 }
343 if (!t && sock->id) /* non-zeor handle is unique -> we're done */
344 break;
345 /* if we're here, we found a duplicate */
346 if (!++sock->id) /* no zero IDs allowed */
347 sock->id++;
348 }
349 last_sock_id = sock->id;
350 DVLOG(2) << __func__ << " SOCK_LIST: alloc id:" << sock->id;
351 return sock;
352
353 fail_sockpair:
354 osi_free(sock);
355 return NULL;
356 }
357
btsock_l2cap_init(int handle,uid_set_t * set)358 bt_status_t btsock_l2cap_init(int handle, uid_set_t* set) {
359 DVLOG(2) << __func__ << ": handle: " << handle;
360 std::unique_lock<std::mutex> lock(state_lock);
361 pth = handle;
362 socks = NULL;
363 uid_set = set;
364 return BT_STATUS_SUCCESS;
365 }
366
btsock_l2cap_cleanup()367 bt_status_t btsock_l2cap_cleanup() {
368 std::unique_lock<std::mutex> lock(state_lock);
369 pth = -1;
370 while (socks) btsock_l2cap_free_l(socks);
371 return BT_STATUS_SUCCESS;
372 }
373
send_app_psm_or_chan_l(l2cap_socket * sock)374 static inline bool send_app_psm_or_chan_l(l2cap_socket* sock) {
375 DVLOG(2) << __func__ << ": channel: " << sock->channel;
376 return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel,
377 sizeof(sock->channel)) == sizeof(sock->channel);
378 }
379
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd,uint16_t rx_mtu,uint16_t tx_mtu)380 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel,
381 int status, int send_fd, uint16_t rx_mtu,
382 uint16_t tx_mtu) {
383 sock_connect_signal_t cs;
384 cs.size = sizeof(cs);
385 cs.bd_addr = *addr;
386 cs.channel = channel;
387 cs.status = status;
388 cs.max_rx_packet_size = rx_mtu;
389 cs.max_tx_packet_size = tx_mtu;
390 if (send_fd != -1) {
391 if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) ==
392 sizeof(cs))
393 return true;
394 else
395 LOG(ERROR) << "sock_send_fd failed, fd: " << fd
396 << ", send_fd:" << send_fd;
397 } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
398 return true;
399 }
400 return false;
401 }
402
on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START * p_start,uint32_t id)403 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START* p_start,
404 uint32_t id) {
405 l2cap_socket* sock;
406
407 std::unique_lock<std::mutex> lock(state_lock);
408 sock = btsock_l2cap_find_by_id_l(id);
409 if (!sock) return;
410
411 if (p_start->status != BTA_JV_SUCCESS) {
412 LOG(ERROR) << "Error starting l2cap_listen - status: "
413 << loghex(p_start->status);
414 btsock_l2cap_free_l(sock);
415 return;
416 }
417
418 sock->handle = p_start->handle;
419 DVLOG(2) << __func__ << ": sock->handle: " << sock->handle
420 << ", id: " << sock->id;
421
422 bluetooth::common::LogSocketConnectionState(
423 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
424 android::bluetooth::SocketConnectionstateEnum::
425 SOCKET_CONNECTION_STATE_LISTENING,
426 0, 0, sock->app_uid, sock->channel,
427 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
428 : android::bluetooth::SOCKET_ROLE_CONNECTION);
429
430 if (!sock->server_psm_sent) {
431 if (!send_app_psm_or_chan_l(sock)) {
432 // closed
433 DVLOG(2) << "send_app_psm() failed, close rs->id: " << sock->id;
434 btsock_l2cap_free_l(sock);
435 } else {
436 sock->server_psm_sent = true;
437 }
438 }
439 }
440
on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT * p_init,uint32_t id)441 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT* p_init, uint32_t id) {
442 l2cap_socket* sock;
443
444 std::unique_lock<std::mutex> lock(state_lock);
445 sock = btsock_l2cap_find_by_id_l(id);
446 if (!sock) return;
447
448 if (p_init->status != BTA_JV_SUCCESS) {
449 btsock_l2cap_free_l(sock);
450 return;
451 }
452
453 sock->handle = p_init->handle;
454 }
455
456 /**
457 * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket
458 * will be a clone of the sock representing the BluetoothServerSocket.
459 * */
on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)460 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open,
461 l2cap_socket* sock) {
462 // std::mutex locked by caller
463 l2cap_socket* accept_rs =
464 btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0);
465 accept_rs->connected = true;
466 accept_rs->security = sock->security;
467 accept_rs->fixed_chan = sock->fixed_chan;
468 accept_rs->channel = sock->channel;
469 accept_rs->handle = sock->handle;
470 accept_rs->app_uid = sock->app_uid;
471 sock->handle =
472 -1; /* We should no longer associate this handle with the server socket */
473 accept_rs->is_le_coc = sock->is_le_coc;
474 accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu;
475
476 /* Swap IDs to hand over the GAP connection to the accepted socket, and start
477 a new server on the newly create socket ID. */
478 uint32_t new_listen_id = accept_rs->id;
479 accept_rs->id = sock->id;
480 sock->id = new_listen_id;
481
482 bluetooth::common::LogSocketConnectionState(
483 accept_rs->addr, accept_rs->id,
484 accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
485 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
486 accept_rs->app_uid, accept_rs->channel,
487 accept_rs->server ? android::bluetooth::SOCKET_ROLE_LISTEN
488 : android::bluetooth::SOCKET_ROLE_CONNECTION);
489
490 // start monitor the socket
491 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
492 SOCK_THREAD_FD_EXCEPTION, sock->id);
493 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
494 accept_rs->id);
495 DVLOG(2) << "sending connect signal & app fd: " << accept_rs->app_fd
496 << " to app server to accept() the connection";
497 DVLOG(2) << "server fd: << " << sock->our_fd << ", scn:" << sock->channel;
498 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
499 accept_rs->app_fd, sock->rx_mtu, p_open->tx_mtu);
500 accept_rs->app_fd =
501 -1; // The fd is closed after sent to app in send_app_connect_signal()
502 // But for some reason we still leak a FD - either the server socket
503 // one or the accept socket one.
504 btsock_l2cap_server_listen(sock);
505 }
506
on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN * p_open,l2cap_socket * sock)507 static void on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN* p_open,
508 l2cap_socket* sock) {
509 // std::mutex locked by caller
510 l2cap_socket* accept_rs =
511 btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0);
512 if (!accept_rs) return;
513
514 // swap IDs
515 uint32_t new_listen_id = accept_rs->id;
516 accept_rs->id = sock->id;
517 sock->id = new_listen_id;
518
519 accept_rs->handle = p_open->handle;
520 accept_rs->connected = true;
521 accept_rs->security = sock->security;
522 accept_rs->fixed_chan = sock->fixed_chan;
523 accept_rs->channel = sock->channel;
524 accept_rs->app_uid = sock->app_uid;
525 accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu;
526
527 // if we do not set a callback, this socket will be dropped */
528 *(p_open->p_p_cback) = (void*)btsock_l2cap_cbk;
529 *(p_open->p_user_data) = UINT_TO_PTR(accept_rs->id);
530
531 bluetooth::common::LogSocketConnectionState(
532 accept_rs->addr, accept_rs->id,
533 accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
534 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
535 accept_rs->app_uid, accept_rs->channel,
536 accept_rs->server ? android::bluetooth::SOCKET_ROLE_LISTEN
537 : android::bluetooth::SOCKET_ROLE_CONNECTION);
538
539 // start monitor the socket
540 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
541 SOCK_THREAD_FD_EXCEPTION, sock->id);
542 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
543 accept_rs->id);
544 DVLOG(2) << "sending connect signal & app fd: " << accept_rs->app_fd
545 << " to app server to accept() the connection";
546 DVLOG(2) << "server fd: << " << sock->our_fd << ", scn:" << sock->channel;
547 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
548 accept_rs->app_fd, sock->rx_mtu, p_open->tx_mtu);
549 accept_rs->app_fd = -1; // the fd is closed after sent to app
550 }
551
on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)552 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open,
553 l2cap_socket* sock) {
554 sock->addr = p_open->rem_bda;
555 sock->tx_mtu = p_open->tx_mtu;
556
557 if (!send_app_psm_or_chan_l(sock)) {
558 LOG(ERROR) << "send_app_psm_or_chan_l failed";
559 return;
560 }
561
562 if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1,
563 sock->rx_mtu, p_open->tx_mtu)) {
564 LOG(ERROR) << "send_app_connect_signal failed";
565 return;
566 }
567
568 bluetooth::common::LogSocketConnectionState(
569 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
570 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
571 sock->app_uid, sock->channel,
572 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
573 : android::bluetooth::SOCKET_ROLE_CONNECTION);
574
575 // start monitoring the socketpair to get call back when app writing data
576 DVLOG(2) << " connect signal sent, slot id: " << sock->id
577 << ", chan: " << sock->channel << ", server: " << sock->server;
578 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
579 sock->id);
580 sock->connected = true;
581 }
582
on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN * p_open,l2cap_socket * sock)583 static void on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN* p_open,
584 l2cap_socket* sock) {
585 sock->addr = p_open->rem_bda;
586 sock->tx_mtu = p_open->tx_mtu;
587
588 if (!send_app_psm_or_chan_l(sock)) {
589 LOG(ERROR) << "send_app_psm_or_chan_l failed";
590 return;
591 }
592
593 if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1,
594 sock->rx_mtu, p_open->tx_mtu)) {
595 LOG(ERROR) << "send_app_connect_signal failed";
596 return;
597 }
598
599 bluetooth::common::LogSocketConnectionState(
600 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
601 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
602 sock->app_uid, sock->channel,
603 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
604 : android::bluetooth::SOCKET_ROLE_CONNECTION);
605
606 // start monitoring the socketpair to get call back when app writing data
607 DVLOG(2) << " connect signal sent, slot id: " << sock->id
608 << ", chan: " << sock->channel << ", server: " << sock->server;
609 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
610 sock->id);
611 sock->connected = true;
612 }
613
on_l2cap_connect(tBTA_JV * p_data,uint32_t id)614 static void on_l2cap_connect(tBTA_JV* p_data, uint32_t id) {
615 l2cap_socket* sock;
616 tBTA_JV_L2CAP_OPEN* psm_open = &p_data->l2c_open;
617 tBTA_JV_L2CAP_LE_OPEN* le_open = &p_data->l2c_le_open;
618
619 std::unique_lock<std::mutex> lock(state_lock);
620 sock = btsock_l2cap_find_by_id_l(id);
621 if (!sock) {
622 LOG(ERROR) << __func__ << ": unknown socket";
623 return;
624 }
625
626 sock->tx_mtu = le_open->tx_mtu;
627 if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
628 if (!sock->server) {
629 on_cl_l2cap_le_connect_l(le_open, sock);
630 } else {
631 on_srv_l2cap_le_connect_l(le_open, sock);
632 }
633 } else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
634 if (!sock->server) {
635 on_cl_l2cap_psm_connect_l(psm_open, sock);
636 } else {
637 on_srv_l2cap_psm_connect_l(psm_open, sock);
638 }
639 } else {
640 btsock_l2cap_free_l(sock);
641 }
642 }
643
on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close,uint32_t id)644 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE* p_close, uint32_t id) {
645 l2cap_socket* sock;
646
647 std::unique_lock<std::mutex> lock(state_lock);
648 sock = btsock_l2cap_find_by_id_l(id);
649 if (!sock) return;
650
651 bluetooth::common::LogSocketConnectionState(
652 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
653 android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0,
654 sock->app_uid, sock->channel,
655 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
656 : android::bluetooth::SOCKET_ROLE_CONNECTION);
657
658 DVLOG(2) << __func__ << ": slot id: " << sock->id << ", fd: " << sock->our_fd
659 << (sock->fixed_chan ? ", fixed_chan:" : ", PSM: ") << sock->channel
660 << ", server:" << sock->server;
661 // TODO: This does not seem to be called...
662 // I'm not sure if this will be called for non-server sockets?
663 if (!sock->fixed_chan && (sock->server)) {
664 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
665 }
666 btsock_l2cap_free_l(sock);
667 }
668
on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG * p,uint32_t id)669 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG* p, uint32_t id) {
670 l2cap_socket* sock;
671
672 std::unique_lock<std::mutex> lock(state_lock);
673 sock = btsock_l2cap_find_by_id_l(id);
674 if (!sock) return;
675
676 sock->outgoing_congest = p->cong ? 1 : 0;
677 // mointer the fd for any outgoing data
678 if (!sock->outgoing_congest) {
679 DVLOG(2) << __func__ << ": adding fd to btsock_thread...";
680 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
681 sock->id);
682 }
683 }
684
on_l2cap_write_done(uint16_t len,uint32_t id)685 static void on_l2cap_write_done(uint16_t len, uint32_t id) {
686 std::unique_lock<std::mutex> lock(state_lock);
687 l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
688 if (!sock) return;
689
690 int app_uid = sock->app_uid;
691 if (!sock->outgoing_congest) {
692 // monitor the fd for any outgoing data
693 DVLOG(2) << __func__ << ": adding fd to btsock_thread...";
694 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
695 sock->id);
696 }
697
698 sock->tx_bytes += len;
699 uid_set_add_tx(uid_set, app_uid, len);
700 }
701
on_l2cap_data_ind(tBTA_JV * evt,uint32_t id)702 static void on_l2cap_data_ind(tBTA_JV* evt, uint32_t id) {
703 l2cap_socket* sock;
704
705 int app_uid = -1;
706 uint32_t bytes_read = 0;
707
708 std::unique_lock<std::mutex> lock(state_lock);
709 sock = btsock_l2cap_find_by_id_l(id);
710 if (!sock) return;
711
712 app_uid = sock->app_uid;
713
714 if (sock->fixed_chan) { /* we do these differently */
715
716 tBTA_JV_LE_DATA_IND* p_le_data_ind = &evt->le_data_ind;
717 BT_HDR* p_buf = p_le_data_ind->p_buf;
718 uint8_t* data = (uint8_t*)(p_buf + 1) + p_buf->offset;
719
720 if (packet_put_tail_l(sock, data, p_buf->len)) {
721 bytes_read = p_buf->len;
722 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
723 sock->id);
724 } else { // connection must be dropped
725 DVLOG(2) << __func__
726 << ": unable to push data to socket - closing fixed channel";
727 BTA_JvL2capCloseLE(sock->handle);
728 btsock_l2cap_free_l(sock);
729 }
730
731 } else {
732 uint32_t count;
733
734 if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
735 std::vector<uint8_t> buffer(count);
736 if (BTA_JvL2capRead(sock->handle, sock->id, buffer.data(), count) ==
737 BTA_JV_SUCCESS) {
738 if (packet_put_tail_l(sock, buffer.data(), count)) {
739 bytes_read = count;
740 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
741 SOCK_THREAD_FD_WR, sock->id);
742 } else { // connection must be dropped
743 DVLOG(2) << __func__
744 << ": unable to push data to socket - closing channel";
745 BTA_JvL2capClose(sock->handle);
746 btsock_l2cap_free_l(sock);
747 }
748 }
749 }
750 }
751
752 sock->rx_bytes += bytes_read;
753 uid_set_add_rx(uid_set, app_uid, bytes_read);
754 }
755
btsock_l2cap_cbk(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t l2cap_socket_id)756 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data,
757 uint32_t l2cap_socket_id) {
758 switch (event) {
759 case BTA_JV_L2CAP_START_EVT:
760 on_srv_l2cap_listen_started(&p_data->l2c_start, l2cap_socket_id);
761 break;
762
763 case BTA_JV_L2CAP_CL_INIT_EVT:
764 on_cl_l2cap_init(&p_data->l2c_cl_init, l2cap_socket_id);
765 break;
766
767 case BTA_JV_L2CAP_OPEN_EVT:
768 on_l2cap_connect(p_data, l2cap_socket_id);
769 BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1,
770 BTA_JV_CONN_OPEN);
771 break;
772
773 case BTA_JV_L2CAP_CLOSE_EVT:
774 DVLOG(2) << "BTA_JV_L2CAP_CLOSE_EVT: id: " << l2cap_socket_id;
775 on_l2cap_close(&p_data->l2c_close, l2cap_socket_id);
776 break;
777
778 case BTA_JV_L2CAP_DATA_IND_EVT:
779 on_l2cap_data_ind(p_data, l2cap_socket_id);
780 DVLOG(2) << "BTA_JV_L2CAP_DATA_IND_EVT";
781 break;
782
783 case BTA_JV_L2CAP_READ_EVT:
784 DVLOG(2) << "BTA_JV_L2CAP_READ_EVT not used";
785 break;
786
787 case BTA_JV_L2CAP_WRITE_EVT:
788 DVLOG(2) << "BTA_JV_L2CAP_WRITE_EVT: id: " << l2cap_socket_id;
789 on_l2cap_write_done(p_data->l2c_write.len, l2cap_socket_id);
790 break;
791
792 case BTA_JV_L2CAP_WRITE_FIXED_EVT:
793 DVLOG(2) << "BTA_JV_L2CAP_WRITE_FIXED_EVT: id: " << l2cap_socket_id;
794 on_l2cap_write_done(p_data->l2c_write.len, l2cap_socket_id);
795 break;
796
797 case BTA_JV_L2CAP_CONG_EVT:
798 on_l2cap_outgoing_congest(&p_data->l2c_cong, l2cap_socket_id);
799 break;
800
801 default:
802 LOG(ERROR) << "unhandled event: " << event
803 << ", slot id: " << l2cap_socket_id;
804 break;
805 }
806 }
807
808 /* L2CAP default options for OBEX socket connections */
809 const tL2CAP_FCR_OPTS obex_l2c_fcr_opts_def = {
810 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
811 OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR, /* Tx window size */
812 OBX_FCR_OPT_MAX_TX_B4_DISCNT, /* Maximum transmissions before
813 disconnecting */
814 OBX_FCR_OPT_RETX_TOUT, /* Retransmission timeout (2 secs) */
815 OBX_FCR_OPT_MONITOR_TOUT, /* Monitor timeout (12 secs) */
816 OBX_FCR_OPT_MAX_PDU_SIZE /* MPS segment size */
817 };
818 const tL2CAP_ERTM_INFO obex_l2c_etm_opt = {
819 L2CAP_FCR_ERTM_MODE, /* Mandatory for OBEX over l2cap */
820 L2CAP_FCR_CHAN_OPT_ERTM, /* Mandatory for OBEX over l2cap */
821 OBX_USER_RX_BUF_SIZE, OBX_USER_TX_BUF_SIZE,
822 OBX_FCR_RX_BUF_SIZE, OBX_FCR_TX_BUF_SIZE};
823
824 /**
825 * When using a dynamic PSM, a PSM allocation is requested from
826 * btsock_l2cap_listen_or_connect().
827 * The PSM allocation event is refeived in the JV-callback - currently located
828 * in RFC-code -
829 * and this function is called with the newly allocated PSM.
830 */
on_l2cap_psm_assigned(int id,int psm)831 void on_l2cap_psm_assigned(int id, int psm) {
832 /* Setup ETM settings:
833 * mtu will be set below */
834 std::unique_lock<std::mutex> lock(state_lock);
835 l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
836 if (!sock) {
837 LOG(ERROR) << __func__ << ": sock is null";
838 return;
839 }
840
841 sock->channel = psm;
842
843 btsock_l2cap_server_listen(sock);
844 }
845
btsock_l2cap_server_listen(l2cap_socket * sock)846 static void btsock_l2cap_server_listen(l2cap_socket* sock) {
847 DVLOG(2) << __func__ << ": fixed_chan: " << sock->fixed_chan
848 << ", channel: " << sock->channel
849 << ", is_le_coc: " << sock->is_le_coc;
850
851 if (sock->fixed_chan) {
852 BTA_JvL2capStartServerLE(sock->channel, btsock_l2cap_cbk, sock->id);
853 return;
854 }
855
856 int connection_type =
857 sock->is_le_coc ? BTA_JV_CONN_TYPE_L2CAP_LE : BTA_JV_CONN_TYPE_L2CAP;
858
859 /* If we have a channel specified in the request, just start the server,
860 * else we request a PSM and start the server after we receive a PSM. */
861 if (sock->channel <= 0) {
862 BTA_JvGetChannelId(connection_type, sock->id, 0);
863 return;
864 }
865
866 /* Setup ETM settings: mtu will be set below */
867 std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
868 tL2CAP_CFG_INFO{.fcr_present = true, .fcr = obex_l2c_fcr_opts_def});
869
870 std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
871 if (!sock->is_le_coc) {
872 ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
873 }
874
875 BTA_JvL2capStartServer(connection_type, sock->security, 0,
876 std::move(ertm_info), sock->channel, sock->rx_mtu,
877 std::move(cfg), btsock_l2cap_cbk, sock->id);
878 }
879
btsock_l2cap_listen_or_connect(const char * name,const RawAddress * addr,int channel,int * sock_fd,int flags,char listen,int app_uid)880 static bt_status_t btsock_l2cap_listen_or_connect(const char* name,
881 const RawAddress* addr,
882 int channel, int* sock_fd,
883 int flags, char listen,
884 int app_uid) {
885 int fixed_chan = 1;
886 bool is_le_coc = false;
887
888 if (!sock_fd) return BT_STATUS_PARM_INVALID;
889
890 if (channel < 0) {
891 // We need to auto assign a PSM
892 fixed_chan = 0;
893 } else {
894 is_le_coc = (flags & BTSOCK_FLAG_LE_COC) != 0;
895 fixed_chan = (channel & L2CAP_MASK_FIXED_CHANNEL) != 0;
896 channel &= ~L2CAP_MASK_FIXED_CHANNEL;
897 }
898
899 if (!is_inited()) return BT_STATUS_NOT_READY;
900
901 // TODO: This is kind of bad to lock here, but it is needed for the current
902 // design.
903 std::unique_lock<std::mutex> lock(state_lock);
904 l2cap_socket* sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
905 if (!sock) {
906 return BT_STATUS_NOMEM;
907 }
908
909 sock->fixed_chan = fixed_chan;
910 sock->channel = channel;
911 sock->app_uid = app_uid;
912 sock->is_le_coc = is_le_coc;
913 sock->rx_mtu = is_le_coc ? L2CAP_SDU_LENGTH_LE_MAX : L2CAP_SDU_LENGTH_MAX;
914
915 /* "role" is never initialized in rfcomm code */
916 if (listen) {
917 btsock_l2cap_server_listen(sock);
918 } else {
919 if (fixed_chan) {
920 BTA_JvL2capConnectLE(channel, sock->addr, btsock_l2cap_cbk, sock->id);
921 } else {
922 int connection_type =
923 sock->is_le_coc ? BTA_JV_CONN_TYPE_L2CAP_LE : BTA_JV_CONN_TYPE_L2CAP;
924
925 /* Setup ETM settings: mtu will be set below */
926 std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
927 tL2CAP_CFG_INFO{.fcr_present = true, .fcr = obex_l2c_fcr_opts_def});
928
929 std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
930 if (!sock->is_le_coc) {
931 ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
932 }
933
934 BTA_JvL2capConnect(
935 connection_type, sock->security, 0, std::move(ertm_info), channel,
936 sock->rx_mtu, std::move(cfg), sock->addr, btsock_l2cap_cbk, sock->id);
937 }
938 }
939
940 *sock_fd = sock->app_fd;
941 /* We pass the FD to JAVA, but since it runs in another process, we need to
942 * also close it in native, either straight away, as done when accepting an
943 * incoming connection, or when doing cleanup after this socket */
944 sock->app_fd = -1;
945 /*This leaks the file descriptor. The FD should be closed in JAVA but it
946 * apparently do not work */
947 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
948 SOCK_THREAD_FD_EXCEPTION, sock->id);
949
950 return BT_STATUS_SUCCESS;
951 }
952
btsock_l2cap_listen(const char * name,int channel,int * sock_fd,int flags,int app_uid)953 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd,
954 int flags, int app_uid) {
955 return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1,
956 app_uid);
957 }
958
btsock_l2cap_connect(const RawAddress * bd_addr,int channel,int * sock_fd,int flags,int app_uid)959 bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel,
960 int* sock_fd, int flags, int app_uid) {
961 return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags,
962 0, app_uid);
963 }
964
965 /* return true if we have more to send and should wait for user readiness, false
966 * else
967 * (for example: unrecoverable error or no data)
968 */
flush_incoming_que_on_wr_signal_l(l2cap_socket * sock)969 static bool flush_incoming_que_on_wr_signal_l(l2cap_socket* sock) {
970 uint8_t* buf;
971 uint32_t len;
972
973 while (packet_get_head_l(sock, &buf, &len)) {
974 ssize_t sent;
975 OSI_NO_INTR(sent = send(sock->our_fd, buf, len, MSG_DONTWAIT));
976 int saved_errno = errno;
977
978 if (sent == (signed)len)
979 osi_free(buf);
980 else if (sent >= 0) {
981 packet_put_head_l(sock, buf + sent, len - sent);
982 osi_free(buf);
983 if (!sent) /* special case if other end not keeping up */
984 return true;
985 } else {
986 packet_put_head_l(sock, buf, len);
987 osi_free(buf);
988 return saved_errno == EWOULDBLOCK || saved_errno == EAGAIN;
989 }
990 }
991
992 return false;
993 }
994
malloc_l2cap_buf(uint16_t len)995 inline BT_HDR* malloc_l2cap_buf(uint16_t len) {
996 // We need FCS only for L2CAP_FCR_ERTM_MODE, but it's just 2 bytes so it's ok
997 BT_HDR* msg = (BT_HDR*)osi_malloc(BT_HDR_SIZE + L2CAP_MIN_OFFSET + len +
998 L2CAP_FCS_LENGTH);
999 msg->offset = L2CAP_MIN_OFFSET;
1000 msg->len = len;
1001 return msg;
1002 }
1003
get_l2cap_sdu_start_ptr(BT_HDR * msg)1004 inline uint8_t* get_l2cap_sdu_start_ptr(BT_HDR* msg) {
1005 return (uint8_t*)(msg) + BT_HDR_SIZE + msg->offset;
1006 }
1007
btsock_l2cap_signaled(int fd,int flags,uint32_t user_id)1008 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) {
1009 char drop_it = false;
1010
1011 /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to
1012 * hold the lock. */
1013 std::unique_lock<std::mutex> lock(state_lock);
1014 l2cap_socket* sock = btsock_l2cap_find_by_id_l(user_id);
1015 if (!sock) return;
1016
1017 if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1018 // app sending data
1019 if (sock->connected) {
1020 int size = 0;
1021 bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0;
1022 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl_success && size)) {
1023 /* FIONREAD return number of bytes that are immediately available for
1024 reading, might be bigger than awaiting packet.
1025
1026 BluetoothSocket.write(...) guarantees that any packet send to this
1027 socket is broken into pieces no bigger than MTU bytes (as requested
1028 by BT spec). */
1029 size = std::min(size, (int)sock->tx_mtu);
1030
1031 BT_HDR* buffer = malloc_l2cap_buf(size);
1032 /* The socket is created with SOCK_SEQPACKET, hence we read one message
1033 * at the time. */
1034 ssize_t count;
1035 OSI_NO_INTR(count = recv(fd, get_l2cap_sdu_start_ptr(buffer), size,
1036 MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
1037 if (count > sock->tx_mtu) {
1038 /* This can't happen thanks to check in BluetoothSocket.java but leave
1039 * this in case this socket is ever used anywhere else*/
1040 LOG(ERROR) << "recv more than MTU. Data will be lost: " << count;
1041 count = sock->tx_mtu;
1042 }
1043
1044 /* When multiple packets smaller than MTU are flushed to the socket, the
1045 size of the single packet read could be smaller than the ioctl
1046 reported total size of awaiting packets. Hence, we adjust the buffer
1047 length. */
1048 buffer->len = count;
1049 DVLOG(2) << __func__ << ": bytes received from socket: " << count;
1050
1051 if (sock->fixed_chan) {
1052 // will take care of freeing buffer
1053 BTA_JvL2capWriteFixed(sock->channel, sock->addr, PTR_TO_UINT(buffer),
1054 btsock_l2cap_cbk, buffer, user_id);
1055 } else {
1056 // will take care of freeing buffer
1057 BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, user_id);
1058 }
1059 }
1060 } else
1061 drop_it = true;
1062 }
1063 if (flags & SOCK_THREAD_FD_WR) {
1064 // app is ready to receive more data, tell stack to enable the data flow
1065 if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
1066 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
1067 sock->id);
1068 }
1069 if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1070 int size = 0;
1071 if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
1072 btsock_l2cap_free_l(sock);
1073 }
1074 }
1075