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