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 <base/logging.h>
19 #include <sys/ioctl.h>
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <cstdint>
25 #include <cstring>
26
27 #include "bta/include/bta_jv_api.h"
28 #include "btif/include/btif_metrics_logging.h"
29 #include "btif/include/btif_sock.h"
30 #include "btif/include/btif_sock_thread.h"
31 #include "btif/include/btif_sock_util.h"
32 #include "btif/include/btif_uid.h"
33 #include "include/hardware/bluetooth.h"
34 #include "internal_include/bt_target.h"
35 #include "osi/include/allocator.h"
36 #include "osi/include/log.h"
37 #include "osi/include/osi.h"
38 #include "stack/btm/security_device_record.h"
39 #include "stack/include/bt_hdr.h"
40 #include "stack/include/bt_types.h"
41 #include "types/raw_address.h"
42
43 struct packet {
44 struct packet *next, *prev;
45 uint32_t len;
46 uint8_t* data;
47 };
48
49 typedef struct l2cap_socket {
50 struct l2cap_socket* prev; // link to prev list item
51 struct l2cap_socket* next; // link to next list item
52 RawAddress addr; // other side's address
53 char name[256]; // user-friendly name of the service
54 uint32_t id; // just a tag to find this struct
55 int app_uid; // The UID of the app who requested this socket
56 int handle; // handle from lower layers
57 unsigned security; // security flags
58 int channel; // PSM
59 int our_fd; // fd from our side
60 int app_fd; // fd from app's side
61
62 unsigned bytes_buffered;
63 struct packet* first_packet; // fist packet to be delivered to app
64 struct packet* last_packet; // last packet to be delivered to app
65
66 unsigned server : 1; // is a server? (or connecting?)
67 unsigned connected : 1; // is connected?
68 unsigned outgoing_congest : 1; // should we hold?
69 unsigned server_psm_sent : 1; // The server shall only send PSM once.
70 bool is_le_coc; // is le connection oriented channel?
71 uint16_t rx_mtu;
72 uint16_t tx_mtu;
73 // Cumulative number of bytes transmitted on this socket
74 int64_t tx_bytes;
75 // Cumulative number of bytes received on this socket
76 int64_t rx_bytes;
77 } l2cap_socket;
78
79 static void btsock_l2cap_server_listen(l2cap_socket* sock);
80
81 static std::mutex state_lock;
82
83 l2cap_socket* socks = NULL;
84 static uint32_t last_sock_id = 0;
85 static uid_set_t* uid_set = NULL;
86 static int pth = -1;
87
88 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data,
89 uint32_t l2cap_socket_id);
90
91 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well,
92 * and we risk
93 * a buffer overflow with this implementation if the socket data is not
94 * read from
95 * JAVA for a while. In such a case we should use flow control to tell the
96 * sender to
97 * back off.
98 * BUT remember we need to avoid blocking the BTA task execution - hence
99 * we cannot
100 * directly write to the socket.
101 * we should be able to change to store the data pointer here, and just
102 * wait
103 * confirming the l2cap_ind until we have more space in the buffer. */
104
105 /* 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)106 static char packet_get_head_l(l2cap_socket* sock, uint8_t** data,
107 uint32_t* len) {
108 struct packet* p = sock->first_packet;
109
110 if (!p) return false;
111
112 if (data) *data = sock->first_packet->data;
113 if (len) *len = sock->first_packet->len;
114 sock->first_packet = p->next;
115 if (sock->first_packet)
116 sock->first_packet->prev = NULL;
117 else
118 sock->last_packet = NULL;
119
120 if (len) sock->bytes_buffered -= *len;
121
122 osi_free(p);
123
124 return true;
125 }
126
packet_alloc(const uint8_t * data,uint32_t len)127 static struct packet* packet_alloc(const uint8_t* data, uint32_t len) {
128 struct packet* p = (struct packet*)osi_calloc(sizeof(*p));
129 uint8_t* buf = (uint8_t*)osi_malloc(len);
130
131 p->data = buf;
132 p->len = len;
133 memcpy(p->data, data, len);
134 return p;
135 }
136
137 /* makes a copy of the data, returns true on success */
packet_put_head_l(l2cap_socket * sock,const void * data,uint32_t len)138 static char packet_put_head_l(l2cap_socket* sock, const void* data,
139 uint32_t len) {
140 struct packet* p = packet_alloc((const uint8_t*)data, len);
141
142 /*
143 * We do not check size limits here since this is used to undo "getting" a
144 * packet that the user read incompletely. That is to say the packet was
145 * already in the queue. We do check thos elimits in packet_put_tail_l() since
146 * that function is used to put new data into the queue.
147 */
148
149 if (!p) return false;
150
151 p->prev = NULL;
152 p->next = sock->first_packet;
153 sock->first_packet = p;
154 if (p->next)
155 p->next->prev = p;
156 else
157 sock->last_packet = p;
158
159 sock->bytes_buffered += len;
160
161 return true;
162 }
163
164 /* makes a copy of the data, returns true on success */
packet_put_tail_l(l2cap_socket * sock,const void * data,uint32_t len)165 static char packet_put_tail_l(l2cap_socket* sock, const void* data,
166 uint32_t len) {
167 if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
168 LOG_ERROR("Unable to add to buffer due to buffer overflow socket_id:%u",
169 sock->id);
170 return false;
171 }
172
173 struct packet* p = packet_alloc((const uint8_t*)data, len);
174 p->next = NULL;
175 p->prev = sock->last_packet;
176 sock->last_packet = p;
177 if (p->prev)
178 p->prev->next = p;
179 else
180 sock->first_packet = p;
181
182 sock->bytes_buffered += len;
183
184 return true;
185 }
186
is_inited(void)187 static char is_inited(void) {
188 std::unique_lock<std::mutex> lock(state_lock);
189 return pth != -1;
190 }
191
192 /* only call with std::mutex taken */
btsock_l2cap_find_by_id_l(uint32_t id)193 static l2cap_socket* btsock_l2cap_find_by_id_l(uint32_t id) {
194 l2cap_socket* sock = socks;
195
196 while (sock && sock->id != id) sock = sock->next;
197
198 return sock;
199 }
200
btsock_l2cap_free_l(l2cap_socket * sock)201 static void btsock_l2cap_free_l(l2cap_socket* sock) {
202 uint8_t* buf;
203 l2cap_socket* t = socks;
204
205 while (t && t != sock) t = t->next;
206
207 if (!t) /* prever double-frees */
208 return;
209
210 btif_sock_connection_logger(
211 SOCKET_CONNECTION_STATE_DISCONNECTED,
212 sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->addr);
213
214 // Whenever a socket is freed, the connection must be dropped
215 log_socket_connection_state(
216 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
217 android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTED, sock->tx_bytes,
218 sock->rx_bytes, sock->app_uid, sock->channel,
219 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
220 : android::bluetooth::SOCKET_ROLE_CONNECTION);
221
222 if (sock->next) sock->next->prev = sock->prev;
223
224 if (sock->prev)
225 sock->prev->next = sock->next;
226 else
227 socks = sock->next;
228
229 shutdown(sock->our_fd, SHUT_RDWR);
230 close(sock->our_fd);
231 if (sock->app_fd != -1) {
232 close(sock->app_fd);
233 } else {
234 LOG_INFO("Application has already closed l2cap socket socket_id:%u",
235 sock->id);
236 }
237
238 while (packet_get_head_l(sock, &buf, NULL)) osi_free(buf);
239
240 // lower-level close() should be idempotent... so let's call it and see...
241 if (sock->is_le_coc) {
242 // Only call if we are non server connections
243 if (sock->handle >= 0 && (!sock->server)) {
244 BTA_JvL2capClose(sock->handle);
245 }
246 if ((sock->channel >= 0) && (sock->server)) {
247 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
248 LOG_INFO("Stopped L2CAP LE COC server socket_id:%u channel:%u", sock->id,
249 sock->channel);
250 BTA_JvL2capStopServer(sock->channel, sock->id);
251 }
252 } else {
253 // Only call if we are non server connections
254 if ((sock->handle >= 0) && (!sock->server)) {
255 BTA_JvL2capClose(sock->handle);
256 }
257 if ((sock->channel >= 0) && (sock->server)) {
258 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
259 BTA_JvL2capStopServer(sock->channel, sock->id);
260 }
261 }
262
263 osi_free(sock);
264 }
265
btsock_l2cap_alloc_l(const char * name,const RawAddress * addr,char is_server,int flags)266 static l2cap_socket* btsock_l2cap_alloc_l(const char* name,
267 const RawAddress* addr,
268 char is_server, int flags) {
269 unsigned security = 0;
270 int fds[2];
271 l2cap_socket* sock = (l2cap_socket*)osi_calloc(sizeof(*sock));
272 int sock_type = SOCK_SEQPACKET;
273
274 if (flags & BTSOCK_FLAG_ENCRYPT)
275 security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
276 if (flags & BTSOCK_FLAG_AUTH)
277 security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
278 if (flags & BTSOCK_FLAG_AUTH_MITM)
279 security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
280 if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
281 security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
282
283 // For Floss, set socket as SOCK_STREAM
284 // TODO(b:271828292): Set SOCK_STREAM for everyone after verification tests
285 #if TARGET_FLOSS
286 sock_type = SOCK_STREAM;
287 #endif
288 if (socketpair(AF_LOCAL, sock_type, 0, fds)) {
289 LOG_ERROR("socketpair failed:%s", strerror(errno));
290 goto fail_sockpair;
291 }
292
293 sock->our_fd = fds[0];
294 sock->app_fd = fds[1];
295 sock->security = security;
296 sock->server = is_server;
297 sock->connected = false;
298 sock->handle = 0;
299 sock->server_psm_sent = false;
300 sock->app_uid = -1;
301
302 if (name) strncpy(sock->name, name, sizeof(sock->name) - 1);
303 if (addr) sock->addr = *addr;
304
305 sock->first_packet = NULL;
306 sock->last_packet = NULL;
307
308 sock->tx_mtu = L2CAP_LE_MIN_MTU;
309
310 sock->next = socks;
311 sock->prev = NULL;
312 if (socks) socks->prev = sock;
313 sock->id = last_sock_id + 1;
314 sock->tx_bytes = 0;
315 sock->rx_bytes = 0;
316 socks = sock;
317 /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed
318 */
319 while (1) {
320 l2cap_socket* t;
321 t = socks->next;
322 while (t && t->id != sock->id) {
323 t = t->next;
324 }
325 if (!t && sock->id) /* non-zeor handle is unique -> we're done */
326 break;
327 /* if we're here, we found a duplicate */
328 if (!++sock->id) /* no zero IDs allowed */
329 sock->id++;
330 }
331 last_sock_id = sock->id;
332 LOG_INFO("Allocated l2cap socket structure socket_id:%u", sock->id);
333 return sock;
334
335 fail_sockpair:
336 osi_free(sock);
337 return NULL;
338 }
339
btsock_l2cap_init(int handle,uid_set_t * set)340 bt_status_t btsock_l2cap_init(int handle, uid_set_t* set) {
341 std::unique_lock<std::mutex> lock(state_lock);
342 pth = handle;
343 socks = NULL;
344 uid_set = set;
345 return BT_STATUS_SUCCESS;
346 }
347
btsock_l2cap_cleanup()348 bt_status_t btsock_l2cap_cleanup() {
349 std::unique_lock<std::mutex> lock(state_lock);
350 pth = -1;
351 while (socks) btsock_l2cap_free_l(socks);
352 return BT_STATUS_SUCCESS;
353 }
354
send_app_psm_or_chan_l(l2cap_socket * sock)355 static inline bool send_app_psm_or_chan_l(l2cap_socket* sock) {
356 LOG_INFO("Sending l2cap socket socket_id:%u channel:%d", sock->id,
357 sock->channel);
358 return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel,
359 sizeof(sock->channel)) == sizeof(sock->channel);
360 }
361
send_app_err_code(l2cap_socket * sock,tBTA_JV_L2CAP_REASON code)362 static bool send_app_err_code(l2cap_socket* sock, tBTA_JV_L2CAP_REASON code) {
363 LOG_INFO("Sending l2cap failure reason socket_id:%u reason code:%d", sock->id,
364 code);
365 int err_channel = 0;
366 if (sock_send_all(sock->our_fd, (const uint8_t*)&err_channel,
367 sizeof(err_channel)) != sizeof(err_channel)) {
368 return false;
369 }
370 return sock_send_all(sock->our_fd, (const uint8_t*)&code, sizeof(code)) ==
371 sizeof(code);
372 }
373
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd,uint16_t rx_mtu,uint16_t tx_mtu)374 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel,
375 int status, int send_fd, uint16_t rx_mtu,
376 uint16_t tx_mtu) {
377 sock_connect_signal_t cs;
378 cs.size = sizeof(cs);
379 cs.bd_addr = *addr;
380 cs.channel = channel;
381 cs.status = status;
382 cs.max_rx_packet_size = rx_mtu;
383 cs.max_tx_packet_size = tx_mtu;
384 if (send_fd != -1) {
385 if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) ==
386 sizeof(cs))
387 return true;
388 } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
389 return true;
390 }
391
392 LOG_ERROR("Unable to send data to socket fd:%d send_fd:%d", fd, send_fd);
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) {
403 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
404 return;
405 }
406
407 if (p_start->status != BTA_JV_SUCCESS) {
408 LOG_ERROR("Unable to start l2cap server socket_id:%u", sock->id);
409 btsock_l2cap_free_l(sock);
410 return;
411 }
412
413 sock->handle = p_start->handle;
414
415 btif_sock_connection_logger(
416 SOCKET_CONNECTION_STATE_LISTENING,
417 sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->addr);
418
419 log_socket_connection_state(
420 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
421 android::bluetooth::SocketConnectionstateEnum::
422 SOCKET_CONNECTION_STATE_LISTENING,
423 0, 0, sock->app_uid, sock->channel,
424 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
425 : android::bluetooth::SOCKET_ROLE_CONNECTION);
426
427 if (!sock->server_psm_sent) {
428 if (!send_app_psm_or_chan_l(sock)) {
429 // closed
430 LOG_INFO("Unable to send socket to application socket_id:%u", sock->id);
431 btsock_l2cap_free_l(sock);
432 } else {
433 sock->server_psm_sent = true;
434 }
435 }
436 }
437
on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT * p_init,uint32_t id)438 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT* p_init, uint32_t id) {
439 l2cap_socket* sock;
440
441 std::unique_lock<std::mutex> lock(state_lock);
442 sock = btsock_l2cap_find_by_id_l(id);
443 if (!sock) {
444 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
445 return;
446 }
447
448 if (p_init->status != BTA_JV_SUCCESS) {
449 LOG_ERROR("Initialization status failed socket_id:%u", id);
450 btsock_l2cap_free_l(sock);
451 return;
452 }
453
454 sock->handle = p_init->handle;
455 }
456
457 /**
458 * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket
459 * will be a clone of the sock representing the BluetoothServerSocket.
460 * */
on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)461 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open,
462 l2cap_socket* sock) {
463 // std::mutex locked by caller
464 l2cap_socket* accept_rs =
465 btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0);
466 accept_rs->connected = true;
467 accept_rs->security = sock->security;
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 btif_sock_connection_logger(
483 SOCKET_CONNECTION_STATE_CONNECTED,
484 accept_rs->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
485 accept_rs->addr);
486
487 log_socket_connection_state(
488 accept_rs->addr, accept_rs->id,
489 accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
490 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
491 accept_rs->app_uid, accept_rs->channel,
492 accept_rs->server ? android::bluetooth::SOCKET_ROLE_LISTEN
493 : android::bluetooth::SOCKET_ROLE_CONNECTION);
494
495 // start monitor the socket
496 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
497 SOCK_THREAD_FD_EXCEPTION, sock->id);
498 btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
499 accept_rs->id);
500 send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
501 accept_rs->app_fd, sock->rx_mtu, p_open->tx_mtu);
502 accept_rs->app_fd =
503 -1; // The fd is closed after sent to app in send_app_connect_signal()
504 // But for some reason we still leak a FD - either the server socket
505 // one or the accept socket one.
506 btsock_l2cap_server_listen(sock);
507 }
508
on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)509 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open,
510 l2cap_socket* sock) {
511 sock->addr = p_open->rem_bda;
512 sock->tx_mtu = p_open->tx_mtu;
513
514 if (!send_app_psm_or_chan_l(sock)) {
515 LOG_ERROR("Unable to send l2cap socket to application socket_id:%u",
516 sock->id);
517 return;
518 }
519
520 if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1,
521 sock->rx_mtu, p_open->tx_mtu)) {
522 LOG_ERROR("Unable to connect l2cap socket to application socket_id:%u",
523 sock->id);
524 return;
525 }
526
527 btif_sock_connection_logger(
528 SOCKET_CONNECTION_STATE_CONNECTED,
529 sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->addr);
530
531 log_socket_connection_state(
532 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
533 android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
534 sock->app_uid, sock->channel,
535 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
536 : android::bluetooth::SOCKET_ROLE_CONNECTION);
537
538 // start monitoring the socketpair to get call back when app writing data
539 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
540 sock->id);
541 LOG_INFO("Connected l2cap socket socket_id:%u", sock->id);
542 sock->connected = true;
543 }
544
on_l2cap_connect(tBTA_JV * p_data,uint32_t id)545 static void on_l2cap_connect(tBTA_JV* p_data, uint32_t id) {
546 l2cap_socket* sock;
547 tBTA_JV_L2CAP_OPEN* psm_open = &p_data->l2c_open;
548 tBTA_JV_L2CAP_LE_OPEN* le_open = &p_data->l2c_le_open;
549
550 std::unique_lock<std::mutex> lock(state_lock);
551 sock = btsock_l2cap_find_by_id_l(id);
552 if (!sock) {
553 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
554 return;
555 }
556
557 sock->tx_mtu = le_open->tx_mtu;
558 if (psm_open->status == BTA_JV_SUCCESS) {
559 if (!sock->server) {
560 on_cl_l2cap_psm_connect_l(psm_open, sock);
561 } else {
562 on_srv_l2cap_psm_connect_l(psm_open, sock);
563 }
564 } else {
565 LOG_ERROR("Unable to open socket after receiving connection socket_id:%u",
566 sock->id);
567 btsock_l2cap_free_l(sock);
568 }
569 }
570
on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close,uint32_t id)571 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE* p_close, uint32_t id) {
572 l2cap_socket* sock;
573
574 std::unique_lock<std::mutex> lock(state_lock);
575 sock = btsock_l2cap_find_by_id_l(id);
576 if (!sock) {
577 LOG_INFO(
578 "Unable to find probably already closed l2cap socket with socket_id:%u",
579 id);
580 return;
581 }
582
583 btif_sock_connection_logger(
584 SOCKET_CONNECTION_STATE_DISCONNECTING,
585 sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->addr);
586
587 log_socket_connection_state(
588 sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
589 android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0,
590 sock->app_uid, sock->channel,
591 sock->server ? android::bluetooth::SOCKET_ROLE_LISTEN
592 : android::bluetooth::SOCKET_ROLE_CONNECTION);
593
594 if (!send_app_err_code(sock, p_close->reason)) {
595 LOG_ERROR("Unable to send l2cap socket to application socket_id:%u",
596 sock->id);
597 }
598 // TODO: This does not seem to be called...
599 // I'm not sure if this will be called for non-server sockets?
600 if (sock->server) {
601 BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
602 }
603 btsock_l2cap_free_l(sock);
604 }
605
on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG * p,uint32_t id)606 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG* p, uint32_t id) {
607 l2cap_socket* sock;
608
609 std::unique_lock<std::mutex> lock(state_lock);
610 sock = btsock_l2cap_find_by_id_l(id);
611 if (!sock) {
612 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
613 return;
614 }
615
616 sock->outgoing_congest = p->cong ? 1 : 0;
617
618 if (!sock->outgoing_congest) {
619 LOG_VERBOSE("Monitoring l2cap socket for outgoing data socket_id:%u",
620 sock->id);
621 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
622 sock->id);
623 }
624 }
625
on_l2cap_write_done(uint16_t len,uint32_t id)626 static void on_l2cap_write_done(uint16_t len, uint32_t id) {
627 std::unique_lock<std::mutex> lock(state_lock);
628 l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
629 if (!sock) {
630 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
631 return;
632 }
633
634 int app_uid = sock->app_uid;
635 if (!sock->outgoing_congest) {
636 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
637 sock->id);
638 } else {
639 LOG_INFO("Socket congestion on socket_id:%u", sock->id);
640 }
641
642 sock->tx_bytes += len;
643 uid_set_add_tx(uid_set, app_uid, len);
644 }
645
on_l2cap_data_ind(tBTA_JV * evt,uint32_t id)646 static void on_l2cap_data_ind(tBTA_JV* evt, uint32_t id) {
647 l2cap_socket* sock;
648
649 int app_uid = -1;
650 uint32_t bytes_read = 0;
651
652 std::unique_lock<std::mutex> lock(state_lock);
653 sock = btsock_l2cap_find_by_id_l(id);
654 if (!sock) {
655 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
656 return;
657 }
658
659 app_uid = sock->app_uid;
660
661 uint32_t count;
662
663 if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
664 std::vector<uint8_t> buffer(count);
665 if (BTA_JvL2capRead(sock->handle, sock->id, buffer.data(), count) ==
666 BTA_JV_SUCCESS) {
667 if (packet_put_tail_l(sock, buffer.data(), count)) {
668 bytes_read = count;
669 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
670 sock->id);
671 } else { // connection must be dropped
672 LOG_WARN("Closing socket as unable to push data to socket socket_id:%u",
673 sock->id);
674 BTA_JvL2capClose(sock->handle);
675 btsock_l2cap_free_l(sock);
676 return;
677 }
678 }
679 }
680
681 sock->rx_bytes += bytes_read;
682 uid_set_add_rx(uid_set, app_uid, bytes_read);
683 }
684
btsock_l2cap_cbk(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t l2cap_socket_id)685 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data,
686 uint32_t l2cap_socket_id) {
687 switch (event) {
688 case BTA_JV_L2CAP_START_EVT:
689 on_srv_l2cap_listen_started(&p_data->l2c_start, l2cap_socket_id);
690 break;
691
692 case BTA_JV_L2CAP_CL_INIT_EVT:
693 on_cl_l2cap_init(&p_data->l2c_cl_init, l2cap_socket_id);
694 break;
695
696 case BTA_JV_L2CAP_OPEN_EVT:
697 on_l2cap_connect(p_data, l2cap_socket_id);
698 BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1,
699 BTA_JV_CONN_OPEN);
700 break;
701
702 case BTA_JV_L2CAP_CLOSE_EVT:
703 on_l2cap_close(&p_data->l2c_close, l2cap_socket_id);
704 break;
705
706 case BTA_JV_L2CAP_DATA_IND_EVT:
707 on_l2cap_data_ind(p_data, l2cap_socket_id);
708 break;
709
710 case BTA_JV_L2CAP_READ_EVT:
711 break;
712
713 case BTA_JV_L2CAP_WRITE_EVT:
714 on_l2cap_write_done(p_data->l2c_write.len, l2cap_socket_id);
715 break;
716
717 case BTA_JV_L2CAP_CONG_EVT:
718 on_l2cap_outgoing_congest(&p_data->l2c_cong, l2cap_socket_id);
719 break;
720
721 default:
722 LOG_ERROR("Unhandled event:%hu l2cap_socket_id:%u", event,
723 l2cap_socket_id);
724 break;
725 }
726 }
727
728 const tL2CAP_ERTM_INFO obex_l2c_etm_opt = {L2CAP_FCR_ERTM_MODE,
729 /* Mandatory for OBEX over l2cap */};
730
731 /**
732 * When using a dynamic PSM, a PSM allocation is requested from
733 * btsock_l2cap_listen_or_connect().
734 * The PSM allocation event is refeived in the JV-callback - currently located
735 * in RFC-code -
736 * and this function is called with the newly allocated PSM.
737 */
on_l2cap_psm_assigned(int id,int psm)738 void on_l2cap_psm_assigned(int id, int psm) {
739 /* Setup ETM settings:
740 * mtu will be set below */
741 std::unique_lock<std::mutex> lock(state_lock);
742 l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
743 if (!sock) {
744 LOG_ERROR("Unable to find l2cap socket with socket_id:%u", id);
745 return;
746 }
747
748 sock->channel = psm;
749
750 btsock_l2cap_server_listen(sock);
751 }
752
btsock_l2cap_server_listen(l2cap_socket * sock)753 static void btsock_l2cap_server_listen(l2cap_socket* sock) {
754 int connection_type =
755 sock->is_le_coc ? BTA_JV_CONN_TYPE_L2CAP_LE : BTA_JV_CONN_TYPE_L2CAP;
756
757 /* If we have a channel specified in the request, just start the server,
758 * else we request a PSM and start the server after we receive a PSM. */
759 if (sock->channel <= 0) {
760 BTA_JvGetChannelId(connection_type, sock->id, 0);
761 return;
762 }
763
764 /* Setup ETM settings: mtu will be set below */
765 std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
766 tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions});
767
768 std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
769 if (!sock->is_le_coc) {
770 ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
771 }
772
773 BTA_JvL2capStartServer(connection_type, sock->security, 0,
774 std::move(ertm_info), sock->channel, sock->rx_mtu,
775 std::move(cfg), btsock_l2cap_cbk, sock->id);
776 }
777
btsock_l2cap_listen_or_connect(const char * name,const RawAddress * addr,int channel,int * sock_fd,int flags,char listen,int app_uid)778 static bt_status_t btsock_l2cap_listen_or_connect(const char* name,
779 const RawAddress* addr,
780 int channel, int* sock_fd,
781 int flags, char listen,
782 int app_uid) {
783 bool is_le_coc = (flags & BTSOCK_FLAG_LE_COC) != 0;
784
785 if (!sock_fd) {
786 LOG_INFO("Invalid socket descriptor");
787 return BT_STATUS_PARM_INVALID;
788 }
789
790 if (!is_inited()) return BT_STATUS_NOT_READY;
791
792 // TODO: This is kind of bad to lock here, but it is needed for the current
793 // design.
794 std::unique_lock<std::mutex> lock(state_lock);
795 l2cap_socket* sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
796 if (!sock) {
797 return BT_STATUS_NOMEM;
798 }
799
800 sock->channel = channel;
801 sock->app_uid = app_uid;
802 sock->is_le_coc = is_le_coc;
803 sock->rx_mtu = is_le_coc ? L2CAP_SDU_LENGTH_LE_MAX : L2CAP_SDU_LENGTH_MAX;
804
805 /* "role" is never initialized in rfcomm code */
806 if (listen) {
807 btsock_l2cap_server_listen(sock);
808 } else {
809 int connection_type =
810 sock->is_le_coc ? BTA_JV_CONN_TYPE_L2CAP_LE : BTA_JV_CONN_TYPE_L2CAP;
811
812 /* Setup ETM settings: mtu will be set below */
813 std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
814 tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions});
815
816 std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
817 if (!sock->is_le_coc) {
818 ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
819 }
820
821 BTA_JvL2capConnect(
822 connection_type, sock->security, 0, std::move(ertm_info), channel,
823 sock->rx_mtu, std::move(cfg), sock->addr, btsock_l2cap_cbk, sock->id);
824 }
825
826 *sock_fd = sock->app_fd;
827 /* We pass the FD to JAVA, but since it runs in another process, we need to
828 * also close it in native, either straight away, as done when accepting an
829 * incoming connection, or when doing cleanup after this socket */
830 sock->app_fd = -1;
831 /*This leaks the file descriptor. The FD should be closed in JAVA but it
832 * apparently do not work */
833 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP,
834 SOCK_THREAD_FD_EXCEPTION, sock->id);
835
836 return BT_STATUS_SUCCESS;
837 }
838
btsock_l2cap_listen(const char * name,int channel,int * sock_fd,int flags,int app_uid)839 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd,
840 int flags, int app_uid) {
841 return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1,
842 app_uid);
843 }
844
btsock_l2cap_connect(const RawAddress * bd_addr,int channel,int * sock_fd,int flags,int app_uid)845 bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel,
846 int* sock_fd, int flags, int app_uid) {
847 return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags,
848 0, app_uid);
849 }
850
851 /* return true if we have more to send and should wait for user readiness, false
852 * else
853 * (for example: unrecoverable error or no data)
854 */
flush_incoming_que_on_wr_signal_l(l2cap_socket * sock)855 static bool flush_incoming_que_on_wr_signal_l(l2cap_socket* sock) {
856 uint8_t* buf;
857 uint32_t len;
858
859 while (packet_get_head_l(sock, &buf, &len)) {
860 ssize_t sent;
861 OSI_NO_INTR(sent = send(sock->our_fd, buf, len, MSG_DONTWAIT));
862 int saved_errno = errno;
863
864 if (sent == (signed)len)
865 osi_free(buf);
866 else if (sent >= 0) {
867 packet_put_head_l(sock, buf + sent, len - sent);
868 osi_free(buf);
869 if (!sent) /* special case if other end not keeping up */
870 return true;
871 } else {
872 packet_put_head_l(sock, buf, len);
873 osi_free(buf);
874 return saved_errno == EWOULDBLOCK || saved_errno == EAGAIN;
875 }
876 }
877
878 return false;
879 }
880
malloc_l2cap_buf(uint16_t len)881 inline BT_HDR* malloc_l2cap_buf(uint16_t len) {
882 // We need FCS only for L2CAP_FCR_ERTM_MODE, but it's just 2 bytes so it's ok
883 BT_HDR* msg = (BT_HDR*)osi_malloc(BT_HDR_SIZE + L2CAP_MIN_OFFSET + len +
884 L2CAP_FCS_LENGTH);
885 msg->offset = L2CAP_MIN_OFFSET;
886 msg->len = len;
887 return msg;
888 }
889
get_l2cap_sdu_start_ptr(BT_HDR * msg)890 inline uint8_t* get_l2cap_sdu_start_ptr(BT_HDR* msg) {
891 return (uint8_t*)(msg) + BT_HDR_SIZE + msg->offset;
892 }
893
btsock_l2cap_signaled(int fd,int flags,uint32_t user_id)894 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) {
895 char drop_it = false;
896
897 /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to
898 * hold the lock. */
899 std::unique_lock<std::mutex> lock(state_lock);
900 l2cap_socket* sock = btsock_l2cap_find_by_id_l(user_id);
901 if (!sock) return;
902
903 if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
904 // app sending data
905 if (sock->connected) {
906 int size = 0;
907 bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0;
908 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl_success && size)) {
909 /* FIONREAD return number of bytes that are immediately available for
910 reading, might be bigger than awaiting packet.
911
912 BluetoothSocket.write(...) guarantees that any packet send to this
913 socket is broken into pieces no bigger than MTU bytes (as requested
914 by BT spec). */
915 size = std::min(size, (int)sock->tx_mtu);
916
917 BT_HDR* buffer = malloc_l2cap_buf(size);
918 /* The socket is created with SOCK_SEQPACKET, hence we read one message
919 * at the time. */
920 ssize_t count;
921 OSI_NO_INTR(count = recv(fd, get_l2cap_sdu_start_ptr(buffer), size,
922 MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
923 if (count > sock->tx_mtu) {
924 /* This can't happen thanks to check in BluetoothSocket.java but leave
925 * this in case this socket is ever used anywhere else*/
926 LOG(ERROR) << "recv more than MTU. Data will be lost: " << count;
927 count = sock->tx_mtu;
928 }
929
930 /* When multiple packets smaller than MTU are flushed to the socket, the
931 size of the single packet read could be smaller than the ioctl
932 reported total size of awaiting packets. Hence, we adjust the buffer
933 length. */
934 buffer->len = count;
935 DVLOG(2) << __func__ << ": bytes received from socket: " << count;
936
937 // will take care of freeing buffer
938 BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, user_id);
939 }
940 } else
941 drop_it = true;
942 }
943 if (flags & SOCK_THREAD_FD_WR) {
944 // app is ready to receive more data, tell stack to enable the data flow
945 if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
946 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
947 sock->id);
948 }
949 if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
950 int size = 0;
951 if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
952 btsock_l2cap_free_l(sock);
953 }
954 }
955