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