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