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